aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/dns/ParallelResolverImpl.java
blob: ca93ccebc378a8f5765fc56f99ff2e6e33f7239c (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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.dns;

import java.beans.*;
import java.io.*;
import java.net.*;
import java.util.*;

import net.java.sip.communicator.service.dns.*;
import net.java.sip.communicator.util.*;

import org.xbill.DNS.*;

/**
 * The purpose of this class is to help avoid the significant delays that occur
 * in networks where DNS servers would ignore SRV, NAPTR, and sometimes even
 * A/AAAA queries (i.e. without even sending an error response). We also try to
 * handle cases where DNS servers may return empty responses to some records.
 * <p>
 * We achieve this by entering a redundant mode whenever we detect an abnormal
 * delay (longer than <tt>DNS_PATIENCE</tt>)  while waiting for a DNS resonse,
 * or when that response is not considered satisfying.
 * <p>
 * Once we enter redundant mode, we start duplicating all queries and sending
 * them to both our primary and backup resolvers (in case we have any). We then
 * always return the first response we get, regardless of who sent it.
 * <p>
 * We exit redundant mode after receiving <tt>DNS_REDEMPTION</tt> consecutive
 * timely and correct responses from our primary resolver.
 *
 * @author Emil Ivov
 */
public class ParallelResolverImpl
    implements CustomResolver, PropertyChangeListener
{
    /**
     * The <tt>Logger</tt> used by the <tt>ParallelResolver</tt>
     * class and its instances for logging output.
     */
    private static final Logger logger = Logger
                    .getLogger(ParallelResolverImpl.class.getName());

    /**
     * Indicates whether we are currently in a mode where all DNS queries are
     * sent to both the primary and the backup DNS servers.
     */
    private static boolean redundantMode = false;

    /**
     * The currently configured number of milliseconds that we need to wait
     * before entering redundant mode.
     */
    private static long currentDnsPatience = DNS_PATIENCE;

    /**
     * The currently configured number of times that the primary DNS would have
     * to provide a faster response than the backup resolver before we consider
     * it safe enough to exit redundant mode.
     */
    public static int currentDnsRedemption = DNS_REDEMPTION;

    /**
     * The number of fast responses that we need to get from the primary
     * resolver before we exit redundant mode. <tt>0</tt> indicates that we are
     * no longer in redundant mode
     */
    private static int redemptionStatus = 0;

    /**
     * A lock that we use while determining whether we've completed redemption
     * and can exit redundant mode.
     */
    private final static Object redemptionLock = new Object();

    /**
     * The default resolver that we use if everything works properly.
     */
    private Resolver defaultResolver;

    /**
     * An extended resolver that would be encapsulating all backup resolvers.
     */
    private ExtendedResolver backupResolver;

    /**
     * Creates a new instance of this class.
     */
    ParallelResolverImpl()
    {
        try
        {
            defaultResolver = new ExtendedResolver();
        }
        catch (UnknownHostException e)
        {
            //should never happen
            throw new RuntimeException("Failed to initialize resolver");
        }

        DnsUtilActivator.getConfigurationService()
            .addPropertyChangeListener(this);
        initProperties();
        Lookup.setDefaultResolver(this);
    }

    private void initProperties()
    {
        String rslvrAddrStr
            = DnsUtilActivator.getConfigurationService().getString(
                DnsUtilActivator.PNAME_BACKUP_RESOLVER,
                DnsUtilActivator.DEFAULT_BACKUP_RESOLVER);
        String customResolverIP
            = DnsUtilActivator.getConfigurationService().getString(
                DnsUtilActivator.PNAME_BACKUP_RESOLVER_FALLBACK_IP,
                DnsUtilActivator.getResources().getSettingsString(
                    DnsUtilActivator.PNAME_BACKUP_RESOLVER_FALLBACK_IP));

        InetAddress resolverAddress = null;
        try
        {
            resolverAddress = NetworkUtils.getInetAddress(rslvrAddrStr);
        }
        catch(UnknownHostException exc)
        {
            logger.warn("Oh! Seems like our primary DNS is down!"
                        + "Don't panic! We'll try to fall back to "
                        + customResolverIP);
        }

        if(resolverAddress == null)
        {
            // name resolution failed for backup DNS resolver,
            // try with the IP address of the default backup resolver
            try
            {
                resolverAddress = NetworkUtils.getInetAddress(customResolverIP);
            }
            catch (UnknownHostException e)
            {
                // this shouldn't happen, but log anyway
                logger.error(e);
            }
        }

        int resolverPort = DnsUtilActivator.getConfigurationService().getInt(
            DnsUtilActivator.PNAME_BACKUP_RESOLVER_PORT,
            SimpleResolver.DEFAULT_PORT);

        InetSocketAddress resolverSockAddr
            = new InetSocketAddress(resolverAddress, resolverPort);

        setBackupServers(new InetSocketAddress[]{ resolverSockAddr });

        currentDnsPatience = DnsUtilActivator.getConfigurationService()
            .getLong(PNAME_DNS_PATIENCE, DNS_PATIENCE);

        currentDnsRedemption
            = DnsUtilActivator.getConfigurationService()
                .getInt(PNAME_DNS_REDEMPTION, DNS_REDEMPTION);
    }

    /**
     * Sets the specified array of <tt>backupServers</tt> used if the default
     * DNS doesn't seem to be doing that well.
     *
     * @param backupServers the list of backup DNS servers that we should use
     * if, and only if, the default servers don't seem to work that well.
     */
    private void setBackupServers(InetSocketAddress[] backupServers)
    {
        try
        {
            backupResolver = new ExtendedResolver(new SimpleResolver[]{});
            for(InetSocketAddress backupServer : backupServers )
            {
                SimpleResolver sr = new SimpleResolver();
                sr.setAddress(backupServer);
                backupResolver.addResolver(sr);
            }
        }
        catch (UnknownHostException e)
        {
            //this shouldn't be thrown since we don't do any DNS querying
            //in here. this is why we take an InetSocketAddress as a param.
            throw new IllegalStateException("The impossible just happened: "
                        +"we could not initialize our backup DNS resolver");
        }
    }

    /**
     * Sends a message and waits for a response.
     *
     * @param query The query to send.
     * @return The response
     *
     * @throws IOException An error occurred while sending or receiving.
     */
    public Message send(Message query)
        throws IOException
    {

        ParallelResolution resolution = new ParallelResolution(query);

        resolution.sendFirstQuery();

        //make a copy of the redundant mode variable in case we are currently
        //completed a redemption that started earlier.
        boolean redundantModeCopy;

        synchronized(redemptionLock)
        {
            redundantModeCopy = redundantMode;
        }

        //if we are not in redundant mode we should wait a bit and see how this
        //goes. if we get a reply we could return bravely.
        if(!redundantModeCopy)
        {
            if(resolution.waitForResponse(currentDnsPatience))
            {
                //we are done.
                return resolution.returnResponseOrThrowUp();
            }
            else
            {
                synchronized(redemptionLock)
                {
                    redundantMode = true;
                    redemptionStatus = currentDnsRedemption;
                    logger.info("Primary DNS seems laggy as we got no "
                                +"response for " + currentDnsPatience + "ms. "
                                + "Enabling redundant mode.");
                }
            }
        }

        //we are definitely in redundant mode now
        resolution.sendBackupQueries();

        resolution.waitForResponse(0);

        //check if it is time to end redundant mode.
        synchronized(redemptionLock)
        {
            if(!resolution.primaryResolverRespondedFirst)
            {
                //primary DNS is still feeling shaky. we reinit redemption
                //status in case we were about to cut the server some slack
                redemptionStatus = currentDnsRedemption;
            }
            else
            {
                //primary server replied first. we let him redeem some dignity
                redemptionStatus --;

                //yup, it's now time to end DNS redundant mode;
                if(redemptionStatus <= 0)
                {
                    redundantMode = false;
                    logger.info("Primary DNS seems back in biz. "
                                    + "Disabling redundant mode.");
                }
            }
        }

        return resolution.returnResponseOrThrowUp();
    }

    /**
     * Supposed to asynchronously send messages but not currently implemented.
     *
     * @param query The query to send
     * @param listener The object containing the callbacks.
     * @return An identifier, which is also a parameter in the callback
     */
    public Object sendAsync(final Message query, final ResolverListener listener)
    {
        return null;
    }

    /**
     * Sets the port to communicate on with the default servers.
     *
     * @param port The port to send messages to
     */
    public void setPort(int port)
    {
        defaultResolver.setPort(port);
    }

    /**
     * Sets whether TCP connections will be sent by default with the default
     * resolver. Backup servers would always be contacted the same way.
     *
     * @param flag Indicates whether TCP connections are made
     */
    public void setTCP(boolean flag)
    {
        defaultResolver.setTCP(flag);
    }

    /**
     * Sets whether truncated responses will be ignored.  If not, a truncated
     * response over UDP will cause a retransmission over TCP. Backup servers
     * would always be contacted the same way.
     *
     * @param flag Indicates whether truncated responses should be ignored.
     */
    public void setIgnoreTruncation(boolean flag)
    {
        defaultResolver.setIgnoreTruncation(flag);
    }

    /**
     * Sets the EDNS version used on outgoing messages.
     *
     * @param level The EDNS level to use.  0 indicates EDNS0 and -1 indicates no
     * EDNS.
     * @throws IllegalArgumentException An invalid level was indicated.
     */
    public void setEDNS(int level)
    {
        defaultResolver.setEDNS(level);
    }

    /**
     * Sets the EDNS information on outgoing messages.
     *
     * @param level The EDNS level to use.  0 indicates EDNS0 and -1 indicates no
     * EDNS.
     * @param payloadSize The maximum DNS packet size that this host is capable
     * of receiving over UDP.  If 0 is specified, the default (1280) is used.
     * @param flags EDNS extended flags to be set in the OPT record.
     * @param options EDNS options to be set in the OPT record, specified as a
     * List of OPTRecord.Option elements.
     *
     * @throws IllegalArgumentException An invalid field was specified.
     * @see OPTRecord
     */
    @SuppressWarnings("rawtypes") // that's the way it is in dnsjava
    public void setEDNS(int level, int payloadSize, int flags, List options)
    {
        defaultResolver.setEDNS(level, payloadSize, flags, options);
    }

    /**
     * Specifies the TSIG key that messages will be signed with
     * @param key The key
     */
    public void setTSIGKey(TSIG key)
    {
        defaultResolver.setTSIGKey(key);
    }

    /**
     * Sets the amount of time to wait for a response before giving up.
     *
     * @param secs The number of seconds to wait.
     * @param msecs The number of milliseconds to wait.
     */
    public void setTimeout(int secs, int msecs)
    {
        defaultResolver.setTimeout(secs, msecs);
    }

    /**
     * Sets the amount of time to wait for a response before giving up.
     *
     * @param secs The number of seconds to wait.
     */
    public void setTimeout(int secs)
    {
        defaultResolver.setTimeout(secs);
    }

    /**
     * Resets resolver configuration and populate our default resolver
     * with the newly configured servers.
     */
    public void reset()
    {
        Lookup.refreshDefault();
        ExtendedResolver resolver = (ExtendedResolver)defaultResolver;

        // remove old ones
        for(Resolver r : resolver.getResolvers())
        {
            resolver.deleteResolver(r);
        }

        // populate with new servers after refreshing configuration
        try
        {
            String [] servers = ResolverConfig.getCurrentConfig().servers();
            if (servers != null)
            {
                for (int i = 0; i < servers.length; i++)
                {
                    Resolver r = new SimpleResolver(servers[i]);
                    //r.setTimeout(quantum);
                    resolver.addResolver(r);
                }
            }
            else
            {
                resolver.addResolver(new SimpleResolver());
            }
        }
        catch (UnknownHostException e)
        {
            //should never happen
            throw new RuntimeException("Failed to initialize resolver");
        }
    }

    /**
     * Determines if <tt>response</tt> can be considered a satisfactory DNS
     * response and returns accordingly.
     * <p>
     * We consider non-satisfactory responses that may indicate that the local
     * DNS does not work properly and that we may hence need to fall back to
     * the backup resolver.
     * <p>
     * Basically the goal here is to be able to go into redundant mode when we
     * come across DNS servers that send empty responses to SRV and NAPTR
     * requests.
     *
     * @param response the dnsjava {@link Message} that we'd like to inspect.
     *
     * @return <tt>true</tt> if <tt>response</tt> appears as a satisfactory
     * response and <tt>false</tt> otherwise.
     */
    private boolean isResponseSatisfactory(Message response)
    {
        if ( response == null )
            return false;

        Record[] answerRR = response.getSectionArray(Section.ANSWER);
        Record[] authorityRR = response.getSectionArray(Section.AUTHORITY);
        Record[] additionalRR = response.getSectionArray(Section.ADDITIONAL);

        if (    (answerRR     != null && answerRR.length > 0)
             || (authorityRR  != null && authorityRR.length > 0)
             || (additionalRR != null && additionalRR.length > 0))
        {
            return true;
        }

        //we didn't find any responses and unless the answer is NXDOMAIN then
        //we may want to check with the backup resolver for a second opinion
        if(response.getRcode() == Rcode.NXDOMAIN)
            return true;

        //if we received NODATA (same as NOERROR and no response records) for
        // an AAAA or a NAPTR query then it makes sense since many existing
        //domains come without those two.
        if( response.getRcode() == Rcode.NOERROR
            && (response.getQuestion().getType() == Type.AAAA
                || response.getQuestion().getType() == Type.NAPTR))
        {
            return true;
        }

        //nope .. this doesn't make sense ...
        return false;
    }

    /**
     * The class that listens for responses to any of the queries we send to
     * our default and backup servers and returns as soon as we get one or until
     * our default resolver fails.
     */
    private class ParallelResolution extends Thread
    {
        /**
         * The query that we have sent to the default and backup DNS servers.
         */
        private final Message query;

        /**
         * The field where we would store the first incoming response to our
         * query.
         */
        public Message response;

        /**
         * The field where we would store the first error we receive from a DNS
         * or a backup resolver.
         */
        private Throwable exception;

        /**
         * Indicates whether we are still waiting for an answer from someone
         */
        private boolean done = false;

        /**
         * Indicates that a response was received from the primary resolver.
         */
        private boolean primaryResolverRespondedFirst = true;

        /**
         * Creates a {@link ParallelResolution} for the specified <tt>query</tt>
         *
         * @param query the DNS query that we'd like to send to our primary
         * and backup resolvers.
         */
        public ParallelResolution(final Message query)
        {
            super("ParallelResolutionThread");
            this.query = query;
        }

        /**
         * Starts this collector which would cause it to send its query to the
         * default resolver.
         */
        public void sendFirstQuery()
        {
            start();
        }

        /**
         * Sends this collector's query to the default resolver.
         */
        public void run()
        {
            Message localResponse = null;
            try
            {
                localResponse = defaultResolver.send(query);
            }
            catch (Throwable exc)
            {
                logger.info("Exception occurred during parallel DNS resolving" +
                        exc, exc);
                this.exception = exc;
            }
            synchronized(this)
            {
                //if the backup resolvers had already replied we ignore the
                //reply of the primary one whatever it was.
                if(done)
                    return;

                //if there was a response we're only done if it is satisfactory
                if(    localResponse != null
                    && isResponseSatisfactory(localResponse))
                {
                    response = localResponse;
                    done = true;
                }
                notify();
            }
        }

        /**
         * Asynchronously sends this collector's query to all backup resolvers.
         */
        public void sendBackupQueries()
        {
            logger.info("Send DNS queries to backup resolvers");

            //yes. a second thread in the thread ... it's ugly but it works
            //and i do want to keep code simple to read ... this whole parallel
            //resolving is complicated enough as it is.
            new Thread(){
                public void run()
                {
                    synchronized(ParallelResolution.this)
                    {
                        if (done)
                            return;
                        Message localResponse = null;
                        try
                        {
                            localResponse = backupResolver.send(query);
                        }
                        catch (Throwable exc)
                        {
                            logger.info("Exception occurred during backup "
                                        +"DNS resolving" + exc);

                            //keep this so that we can rethrow it
                            exception = exc;
                        }
                        //if the default resolver has already replied we
                        //ignore the reply of the backup ones.
                        if(done)
                            return;

                        //contrary to responses from the  primary resolver,
                        //in this case we don't care whether the response is
                        //satisfying: if it isn't, there's nothing we can do
                        response = localResponse;
                        done = true;

                        ParallelResolution.this.notify();
                    }
                }
            }.start();
        }

        /**
         * Waits for a response or an error to occur during <tt>waitFor</tt>
         * milliseconds.If neither happens, we return false.
         *
         * @param waitFor the number of milliseconds to wait for a response or
         * an error or <tt>0</tt> if we'd like to wait until either of these
         * happen.
         *
         * @return <tt>true</tt> if we returned because we received a response
         * from a resolver or errors from everywhere, and <tt>false</tt> that
         * didn't happen.
         */
        public boolean waitForResponse(long waitFor)
        {
            synchronized(this)
            {
                if(done)
                    return done;
                try
                {
                    wait(waitFor);
                }
                catch (InterruptedException e)
                {
                    //we don't care
                }

                return done;
            }
        }

        /**
         * Waits for resolution to complete (if necessary) and then either
         * returns the response we received or throws whatever exception we
         * saw.
         *
         * @return the response {@link Message} we received from the DNS.
         *
         * @throws IOException if this resolution ended badly because of a
         * network IO error
         * @throws RuntimeException if something unexpected happened
         * during resolution.
         * @throws IllegalArgumentException if something unexpected happened
         * during resolution or if there was no response.
         */
        public Message returnResponseOrThrowUp()
            throws IOException, RuntimeException, IllegalArgumentException
        {
            if(!done)
                waitForResponse(0);

            if(response != null)
            {
                return response;
            }
            else if (exception instanceof IOException)
            {
                logger.warn("IO exception while using DNS resolver", exception);
                throw (IOException) exception;
            }
            else if (exception instanceof RuntimeException)
            {
                logger.warn("RunTimeException while using DNS resolver",
                        exception);
                throw (RuntimeException) exception;
            }
            else if (exception instanceof Error)
            {
                logger.warn("Error while using DNS resolver", exception);
                throw (Error) exception;
            }
            else
            {
                logger.warn("Received a bad response from primary DNS resolver",
                        exception);
                throw new IllegalStateException("ExtendedResolver failure");
            }
        }
    }

    @SuppressWarnings("serial")
    private final Set<String> configNames = new HashSet<String>(5)
    {{
        add(DnsUtilActivator.PNAME_BACKUP_RESOLVER);
        add(DnsUtilActivator.PNAME_BACKUP_RESOLVER_FALLBACK_IP);
        add(DnsUtilActivator.PNAME_BACKUP_RESOLVER_PORT);
        add(CustomResolver.PNAME_DNS_PATIENCE);
        add(CustomResolver.PNAME_DNS_REDEMPTION);
    }};

    public void propertyChange(PropertyChangeEvent evt)
    {
        if (!configNames.contains(evt.getPropertyName()))
        {
            return;
        }

        initProperties();
    }
}