aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/main/org/apache/tools/ant/taskdefs/HostInfo.java
blob: 5cd433cade56a5217822877a7b965a1bdf082530 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.apache.tools.ant.taskdefs;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;

/**
 * Sets properties to the host provided, or localhost if no information is
 * provided. The default properties are NAME, FQDN, ADDR4, ADDR6;
 *
 * @since Ant 1.8
 * @ant.task category="utility"
 */


public class HostInfo extends Task {
    private static final String DEF_REM_ADDR6 = "::";

    private static final String DEF_REM_ADDR4 = "0.0.0.0";

    private static final String DEF_LOCAL_ADDR6 = "::1";

    private static final String DEF_LOCAL_ADDR4 = "127.0.0.1";

    private static final String DEF_LOCAL_NAME = "localhost";
    private static final String DEF_DOMAIN = "localdomain";

    private static final String DOMAIN = "DOMAIN";

    private static final String NAME = "NAME";

    private static final String ADDR4 = "ADDR4";

    private static final String ADDR6 = "ADDR6";

    private String prefix = "";

    private String host;

    private InetAddress nameAddr;

    private InetAddress best6;

    private InetAddress best4;

    private List<InetAddress> inetAddrs;

    /**
     * Set a prefix for the properties. If the prefix does not end with a "."
     * one is automatically added.
     *
     * @param aPrefix
     *            the prefix to use.
     * @since Ant 1.8
     */
    public void setPrefix(String aPrefix) {
        prefix = aPrefix;
        if (!prefix.endsWith(".")) {
            prefix += ".";
        }
    }

    /**
     * Set the host to be retrieved.
     *
     * @param aHost
     *            the name or the address of the host, data for the local host
     *            will be retrieved if omitted.
     * @since Ant 1.8
     */
    public void setHost(String aHost) {
        host = aHost;
    }

    /**
     * set the properties.
     *
     * @throws BuildException
     *             on error.
     */
    public void execute() throws BuildException {
        if (host == null || "".equals(host)) {
            executeLocal();
        } else {
            executeRemote();
        }
    }

    private void executeLocal() {
        try {
            inetAddrs = new LinkedList<InetAddress>();
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface currentif = interfaces.nextElement();
                Enumeration<InetAddress> addrs = currentif.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    inetAddrs.add(addrs.nextElement());
                }
            }
            selectAddresses();

            if (nameAddr != null && hasHostName(nameAddr)) {
                setDomainAndName(nameAddr.getCanonicalHostName());
            } else {
                setProperty(DOMAIN, DEF_DOMAIN);
                setProperty(NAME, DEF_LOCAL_NAME);
            }
            if (best4 != null) {
                setProperty(ADDR4, best4.getHostAddress());
            } else {
                setProperty(ADDR4, DEF_LOCAL_ADDR4);
            }
            if (best6 != null) {
                setProperty(ADDR6, best6.getHostAddress());
            } else {
                setProperty(ADDR6, DEF_LOCAL_ADDR6);
            }
        } catch (Exception e) {
            log("Error retrieving local host information", e, Project.MSG_WARN);
            setProperty(DOMAIN, DEF_DOMAIN);
            setProperty(NAME, DEF_LOCAL_NAME);
            setProperty(ADDR4, DEF_LOCAL_ADDR4);
            setProperty(ADDR6, DEF_LOCAL_ADDR6);
        }
    }

    private boolean hasHostName(InetAddress addr) {
        return !addr.getHostAddress().equals(addr.getCanonicalHostName());
    }

    private void selectAddresses() {
        for (InetAddress current : inetAddrs) {
            if (!current.isMulticastAddress()) {
                if (current instanceof Inet4Address) {
                    best4 = selectBestAddress(best4, current);
                } else if (current instanceof Inet6Address) {
                    best6 = selectBestAddress(best6, current);
                }
            }
        }

        nameAddr = selectBestAddress(best4, best6);
    }

    private InetAddress selectBestAddress(InetAddress bestSoFar,
            InetAddress current) {
        InetAddress best = bestSoFar;
        if (best == null) {
            // none selected so far, so this one is better.
            best = current;
        } else {
            if (current == null || current.isLoopbackAddress()) {
                // definitely not better than the previously selected address.
            } else if (current.isLinkLocalAddress()) {
                // link local considered better than loopback
                if (best.isLoopbackAddress()) {
                    best = current;
                }
            } else if (current.isSiteLocalAddress()) {
                // site local considered better than link local (and loopback)
                // address with hostname resolved considered better than
                // address without hostname
                if (best.isLoopbackAddress()
                        || best.isLinkLocalAddress()
                        || (best.isSiteLocalAddress() && !hasHostName(best))) {
                    best = current;
                }
            } else {
                // current is a "Global address", considered better than
                // site local (and better than link local, loopback)
                // address with hostname resolved considered better than
                // address without hostname
                if (best.isLoopbackAddress()
                        || best.isLinkLocalAddress()
                        || best.isSiteLocalAddress()
                        || !hasHostName(best)) {
                    best = current;
                }
            }
        }
        return best;
    }

    private void executeRemote() {
        try {
            inetAddrs = Arrays.asList(InetAddress.getAllByName(host));

            selectAddresses();

            if (nameAddr != null && hasHostName(nameAddr)) {
                setDomainAndName(nameAddr.getCanonicalHostName());
            } else {
                setDomainAndName(host);
            }
            if (best4 != null) {
                setProperty(ADDR4, best4.getHostAddress());
            } else {
                setProperty(ADDR4, DEF_REM_ADDR4);
            }
            if (best6 != null) {
                setProperty(ADDR6, best6.getHostAddress());
            } else {
                setProperty(ADDR6, DEF_REM_ADDR6);
            }
        } catch (Exception e) {
            log("Error retrieving remote host information for host:" + host
                    + ".", e, Project.MSG_WARN);
            setDomainAndName(host);
            setProperty(ADDR4, DEF_REM_ADDR4);
            setProperty(ADDR6, DEF_REM_ADDR6);
        }
    }

    private void setDomainAndName(String fqdn) {
        int idx = fqdn.indexOf('.');
        if (idx > 0) {
            setProperty(NAME, fqdn.substring(0, idx));
            setProperty(DOMAIN, fqdn.substring(idx+1));
        } else {
            setProperty(NAME, fqdn);
            setProperty(DOMAIN, DEF_DOMAIN);
        }
    }

    private void setProperty(String name, String value) {
        getProject().setNewProperty(prefix + name, value);
    }

}