aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/util/Resolver.java
blob: 03709a7c3e1b84e13749989712e7ea99dde6d309 (plain) (blame)
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
 This file is part of GNUnet.
 Copyright (C) 2011, 2012 Christian Grothoff (and other contributing authors)

 GNUnet is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 3, or (at your
 option) any later version.

 GNUnet is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNUnet; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 Boston, MA 02110-1301, USA.
 */

package org.gnunet.util;

import com.google.common.net.InetAddresses;
import org.gnunet.construct.*;
import org.gnunet.util.getopt.Argument;
import org.gnunet.util.getopt.ArgumentAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;

/**
 * Resolve hostnames asynchronously, using the gnunet resolver service if necessary.
 * <p/>
 * TODO: implement reverse lookup (already done in the C-API)
 */
public class Resolver {
    private static final Logger logger = LoggerFactory
            .getLogger(Resolver.class);

    private static Resolver singletonInstance;

    private Configuration cfg;

    private Client client;

    public static InetAddress getInetAddressFromString(String ipString) {
        try {
            return InetAddresses.forString(ipString);
        } catch (IllegalArgumentException e) {
            return null;
        }
    }

    @UnionCase(4)
    public static class GetMessage implements GnunetMessage.Body {
        static final int DIRECTION_GET_IP = 0;
        static final int DIRECTION_GET_NAME = 1;
        static final int AF_UNSPEC = 0;
        static final int AF_INET = 2;
        static final int AF_INET6 = 10;

        @UInt32
        public int direction;
        @UInt32
        public int domain;

        @Union(tag = "direction", optional = true)
        public Address addr;
    }

    public interface Address extends MessageUnion {
    }

    @UnionCase(GetMessage.DIRECTION_GET_IP)
    public static class TextualAddress implements Address {
        @ZeroTerminatedString
        public String addr;
    }

    @UnionCase(GetMessage.DIRECTION_GET_NAME)
    public static class NumericAddress implements Address {
        @FillWith @UInt8
        public byte[] addr;
    }


    @UnionCase(5)
    public static class ResolverResponse implements GnunetMessage.Body {
        @NestedMessage(optional = true)
        public ResponseBody responseBody;
    }


    public static class ResponseBody implements Message {
        @FillWith @UInt8
        public byte[] addr;
    }

    /**
     * Callback object for hostname resolution.
     */
    public interface AddressCallback {
        /**
         * Called for every address the requested hostname resolves to.
         *
         * @param addr address for the resolved name
         */
        public void onAddress(InetAddress addr);

        /**
         * Called after every result (if any) has been passed to onAddress.
         */
        public void onFinished();

        /**
         * Called when the resolve operation times out before returning every result.
         */
        void onTimeout();
    }


    /**
     * Configuration to use with the Resolver.
     * <p/>
     * Usually called by the entry points Program/Service.
     *
     * @param cfg configuration to use
     */
    public void setConfiguration(Configuration cfg) {
        this.cfg = cfg;
    }

    private void lazyConnect() {
        if (client == null) {
            if (cfg == null) {
                throw new AssertionError("Resolver has no Configuration");
            }
            client = new Client("resolver", cfg);
        }
    }


    private InetAddress getInet4Localhost() {
        try {
            return InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
        } catch (UnknownHostException e) {
            throw new RuntimeException();
        }
    }

    private InetAddress getInet6Localhost() {
        try {
            return InetAddress.getByAddress(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1});
        } catch (UnknownHostException e) {
            throw new RuntimeException();
        }
    }

    public class ResolveHandle implements Cancelable {
        private String hostname;
        private AbsoluteTime deadline;
        private AddressCallback cb;
        private boolean finished = false;
        private boolean canceled = false;
        private Cancelable transmitTask = null;

        public void cancel() {
            if (finished) {
                throw new AssertionError("Resolve already finished");
            }
            if (canceled) {
                throw new AssertionError("ResolveHandle canceled twice");
            }
            if (queuedRequests.contains(this)) {
                queuedRequests.remove(this);
            } else {
                if (transmitTask != null) {
                    transmitTask.cancel();
                }
            }
            canceled = true;
        }
    }

    private LinkedList<ResolveHandle> queuedRequests = new LinkedList<ResolveHandle>();

    private boolean resolveActive = false;

    /**
     * Resolve the hostname 'hostname'.
     *
     * @param hostname hostname to resolve
     * @param timeout  timeout, calls cb.onTimeout on expiratoin
     * @param cb       callback
     * @return a handle to onCancel the getRequestIdentifier, null if getRequestIdentifier could be satisfied immediately
     */
    public Cancelable resolveHostname(String hostname, RelativeTime timeout, final AddressCallback cb) {
        // try if hostname is numeric IP or loopback
        if (hostname.equalsIgnoreCase("localhost")) {
            logger.debug("resolving address locally");
            cb.onAddress(getInet6Localhost());
            cb.onAddress(getInet4Localhost());
            cb.onFinished();
            return null;
        }
        if (hostname.equalsIgnoreCase("ip6-localhost")) {
            cb.onAddress(getInet6Localhost());
            cb.onFinished();
            return null;
        }
        InetAddress inetAddr = getInetAddressFromString(hostname);

        if (inetAddr != null) {
            cb.onAddress(inetAddr);
            cb.onFinished();
            return null;
        }

        final ResolveHandle rh = new ResolveHandle();
        rh.hostname = hostname;
        rh.deadline = timeout.toAbsolute();
        rh.cb = cb;

        queuedRequests.addLast(rh);
        handleNextRequest();
        return rh;
    }

    private void handleNextRequest() {
        if (!resolveActive && !queuedRequests.isEmpty()) {
            ResolveHandle rh = queuedRequests.pollFirst();
            handleRequest(rh);
        }
    }

    private void handleRequest(final ResolveHandle rh) {
        if (resolveActive) {
            throw new AssertionError("resolveActive but new resolve started");
        }

        resolveActive = true;

        lazyConnect();

        final GetMessage req = new GetMessage();
        req.direction = GetMessage.DIRECTION_GET_IP;
        req.domain = GetMessage.AF_UNSPEC;

        TextualAddress textAddr = new TextualAddress();
        textAddr.addr = rh.hostname;

        req.addr = textAddr;

        final AbsoluteTime deadline = rh.deadline;

        logger.debug("deadline is " + deadline + " | now is " + AbsoluteTime.now());

        logger.debug("remaining is " + deadline.getRemaining());

        rh.transmitTask = client.notifyTransmitReady(
                deadline.getRemaining(), true,
                0, new MessageTransmitter() {
            @Override
            public void transmit(Connection.MessageSink sink) {
                if (sink == null) {
                    onTimeout(rh);
                    return;
                }
                sink.send(req);
                rh.transmitTask = null;

                logger.debug("recv in notifyTransmitReady cb");
                client.receiveOne(deadline.getRemaining(), new MessageReceiver() {
                    @Override
                    public void process(GnunetMessage.Body msg) {
                        ResolverResponse gmsg = (ResolverResponse) msg;
                        if (gmsg.responseBody != null) {
                            try {
                                InetAddress in_addr;
                                int len = gmsg.responseBody.addr.length;
                                if (len == 4 || len == 16) {
                                    in_addr = InetAddress.getByAddress(gmsg.responseBody.addr);
                                } else {
                                    throw new ProtocolViolationException("malformed address message");
                                }

                                rh.cb.onAddress(in_addr);
                                client.receiveOne(deadline.getRemaining(), this);
                            } catch (UnknownHostException e) {
                                throw new ProtocolViolationException("malformed address");
                            }
                        } else {
                            resolveActive = false;
                            rh.cb.onFinished();
                            handleNextRequest();
                        }
                    }

                    @Override
                    public void handleError() {
                        onTimeout(rh);
                    }
                });

            }

            @Override
            public void handleError() {
                rh.cb.onTimeout();
            }
        });
    }


    private void onTimeout(ResolveHandle h) {
        resolveActive = false;
        h.cb.onTimeout();
        handleNextRequest();
    }


    public static Resolver getInstance() {
        if (singletonInstance == null) {
            singletonInstance = new Resolver();
        }
        return singletonInstance;
    }


    /**
     * Return a textual representation of an InetAddress. Shortens IPv6 addresses.
     *
     * @param addr the address to convert
     * @return textual representation of the address
     */
    public static String ipToString(InetAddress addr) {
        byte[] a = addr.getAddress();
        if (a.length == 4) {
            return addr.getHostAddress();
        } else if (a.length == 16) {
            String s = addr.getHostAddress();
            // replace the first group of zeroes (not the longest) with ::
            return s.replaceFirst("[:]?0[:](0[:])+0?", "::");
        } else {
            throw new RuntimeException("unknown InetAddress format");
        }
    }


    public static void main(final String[] argv) {
        new Program() {
            @Argument(shortname = "r", longname = "reverse",
                    description = "do reverse dns lookup",
                    action = ArgumentAction.SET)
            boolean isReverse;

            @Override
            public void run() {
                if (isReverse) {
                    System.out.println("reverse lookup not supported");
                } else {
                    resolve();
                }
            }

            public void resolve() {
                final RelativeTime timeout = RelativeTime.SECOND;

                if (unprocessedArgs.length == 0) {
                    logger.warn("no hostname(s) given");
                } else {
                    logger.info("resolving hostname '" + unprocessedArgs[0] + "'");
                    Resolver.getInstance().resolveHostname(unprocessedArgs[0], timeout, new AddressCallback() {
                        int next = 1;

                        @Override
                        public void onAddress(InetAddress addr) {
                            System.out.println(ipToString(addr));
                        }

                        @Override
                        public void onFinished() {
                            logger.info("resolve finished");
                            next();
                        }

                        @Override
                        public void onTimeout() {
                            logger.warn("resolve timed out");
                            next();

                        }

                        public void next() {
                            if (unprocessedArgs.length > next) {
                                logger.info("resolving hostname '" + unprocessedArgs[next] + "'");
                                Resolver.getInstance().resolveHostname(unprocessedArgs[next], timeout, this);
                                next++;
                            }
                        }
                    });
                }

            }

            @Override
            protected String makeHelpText() {
                return "tool for forward and reverse DNS lookup";
            }
        }.start(argv);
    }
}