aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/zeroconf/jmdns/DNSRecord.java
blob: 673bbc48182e1f8075cd2279dcb1751ed260dad5 (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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright 2003-2005 Arthur van Hoff Rick Blair
 *
 * Licensed 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 net.java.sip.communicator.impl.protocol.zeroconf.jmdns;

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

/**
 * DNS record
 *
 * @version %I%, %G%
 * @author  Arthur van Hoff, Rick Blair, Werner Randelshofer, Pierre Frisch
 */
public abstract class DNSRecord extends DNSEntry
{
    private static Logger logger =
        Logger.getLogger(DNSRecord.class.toString());
    int ttl;
    private long created;

    /**
     * Create a DNSRecord with a name, type, clazz, and ttl.
     */
    DNSRecord(String name, int type, int clazz, int ttl)
    {
        super(name, type, clazz);
        this.ttl = ttl;
        this.created = System.currentTimeMillis();

        String SLevel = System.getProperty("jmdns.debug");
        if (SLevel == null) SLevel = "INFO";
        logger.setLevel(Level.parse(SLevel));
    }

    /**
     * True if this record is the same as some other record.
     * @param other obj to be compared to.
     */
    @Override
    public boolean equals(Object other)
    {
        return (other instanceof DNSRecord) && sameAs((DNSRecord) other);
    }

    /**
     * True if this record is the same as some other record.
     */
    boolean sameAs(DNSRecord other)
    {
        return super.equals(other) && sameValue(other);
    }

    /**
     * True if this record has the same value as some other record.
     */
    abstract boolean sameValue(DNSRecord other);

    /**
     * True if this record has the same type as some other record.
     */
    boolean sameType(DNSRecord other)
    {
        return type == other.type;
    }

    /**
     * Handles a query represented by this record.
     *
     * @return Returns true if a conflict with one of the services registered
     *         with JmDNS or with the hostname occured.
     */
    abstract boolean handleQuery(JmDNS dns, long expirationTime);

    /**
     * Handles a responserepresented by this record.
     *
     * @return Returns true if a conflict with one of the services registered
     *         with JmDNS or with the hostname occured.
     */
    abstract boolean handleResponse(JmDNS dns);

    /**
     * Adds this as an answer to the provided outgoing datagram.
     */
    abstract DNSOutgoing addAnswer(JmDNS dns, DNSIncoming in, InetAddress addr,
                                   int port, DNSOutgoing out)
        throws IOException;

    /**
     * True if this record is suppressed by the answers in a message.
     */
    boolean suppressedBy(DNSIncoming msg)
    {
        try
        {
            for (int i = msg.numAnswers; i-- > 0;)
            {
                if (suppressedBy(msg.answers.get(i)))
                {
                    return true;
                }
            }
            return false;
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            logger.log(Level.WARNING,
                "suppressedBy() message " + msg + " exception ", e);
            // msg.print(true);
            return false;
        }
    }

    /**
     * True if this record would be supressed by an answer.
     * This is the case if this record would not have a
     * significantly longer TTL.
     */
    boolean suppressedBy(DNSRecord other)
    {
        if (sameAs(other) && (other.ttl > ttl / 2))
        {
            return true;
        }
        return false;
    }

    /**
     * Get the expiration time of this record.
     */
    long getExpirationTime(int percent)
    {
        return created + (percent * ttl * 10L);
    }

    /**
     * Get the remaining TTL for this record.
     */
    int getRemainingTTL(long now)
    {
        return (int) Math.max(0, (getExpirationTime(100) - now) / 1000);
    }

    /**
     * Check if the record is expired.
     */
    boolean isExpired(long now)
    {
        return getExpirationTime(100) <= now;
    }

    /**
     * Check if the record is stale, ie it has outlived
     * more than half of its TTL.
     */
    boolean isStale(long now)
    {
        return getExpirationTime(50) <= now;
    }

    /**
     * Reset the TTL of a record. This avoids having to
     * update the entire record in the cache.
     */
    void resetTTL(DNSRecord other)
    {
        created = other.created;
        ttl = other.ttl;
    }

    /**
     * Write this record into an outgoing message.
     */
    abstract void write(DNSOutgoing out) throws IOException;

    /**
     * Address record.
     */
    static class Address extends DNSRecord
    {
        private static Logger logger =
            Logger.getLogger(Address.class.toString());
        InetAddress addr;

        Address(String name, int type, int clazz, int ttl, InetAddress addr)
        {
            super(name, type, clazz, ttl);
            this.addr = addr;

            String SLevel = System.getProperty("jmdns.debug");
            if (SLevel == null) SLevel = "INFO";
            logger.setLevel(Level.parse(SLevel));
        }

        Address(String name, int type, int clazz, int ttl, byte[] rawAddress)
        {
            super(name, type, clazz, ttl);
            try
            {
                this.addr = InetAddress.getByAddress(rawAddress);
            }
            catch (UnknownHostException exception)
            {
                logger.log(Level.WARNING, "Address() exception ", exception);
            }
        }

        @Override
        void write(DNSOutgoing out) throws IOException
        {
            if (addr != null)
            {
                byte[] buffer = addr.getAddress();
                if (DNSConstants.TYPE_A == type)
                {
                    // If we have a type A records we should
                    // answer with a IPv4 address
                    if (addr instanceof Inet4Address)
                    {
                        // All is good
                    }
                    else
                    {
                        // Get the last four bytes
                        byte[] tempbuffer = buffer;
                        buffer = new byte[4];
                        System.arraycopy(tempbuffer, 12, buffer, 0, 4);
                    }
                }
                else
                {
                    // If we have a type AAAA records we should
                    // answer with a IPv6 address
                    if (addr instanceof Inet4Address)
                    {
                        byte[] tempbuffer = buffer;
                        buffer = new byte[16];
                        for (int i = 0; i < 16; i++)
                        {
                            if (i < 11)
                            {
                                buffer[i] = tempbuffer[i - 12];
                            }
                            else
                            {
                                buffer[i] = 0;
                            }
                        }
                    }
                }
                int length = buffer.length;
                out.writeBytes(buffer, 0, length);
            }
        }

        boolean same(DNSRecord other)
        {
            return ((sameName(other)) && ((sameValue(other))));
        }

        boolean sameName(DNSRecord other)
        {
            return name.equalsIgnoreCase(((Address) other).name);
        }

        @Override
        boolean sameValue(DNSRecord other)
        {
            return addr.equals(((Address) other).getAddress());
        }

        InetAddress getAddress()
        {
            return addr;
        }

        /**
         * Creates a byte array representation of this record.
         * This is needed for tie-break tests according to
         * draft-cheshire-dnsext-multicastdns-04.txt chapter 9.2.
         */
        private byte[] toByteArray()
        {
            try
            {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                DataOutputStream dout = new DataOutputStream(bout);
                dout.write(name.getBytes("UTF8"));
                dout.writeShort(type);
                dout.writeShort(clazz);
                //dout.writeInt(len);
                byte[] buffer = addr.getAddress();
                for (int i = 0; i < buffer.length; i++)
                {
                    dout.writeByte(buffer[i]);
                }
                dout.close();
                return bout.toByteArray();
            }
            catch (IOException e)
            {
                throw new InternalError();
            }
        }

        /**
         * Does a lexicographic comparison of the byte array representation
         * of this record and that record.
         * This is needed for tie-break tests according to
         * draft-cheshire-dnsext-multicastdns-04.txt chapter 9.2.
         */
        private int lexCompare(DNSRecord.Address that)
        {
            byte[] thisBytes = this.toByteArray();
            byte[] thatBytes = that.toByteArray();
            for (   int i = 0, n = Math.min(thisBytes.length, thatBytes.length);
                    i < n;
                    i++)
            {
                if (thisBytes[i] > thatBytes[i])
                {
                    return 1;
                }
                else
                {
                    if (thisBytes[i] < thatBytes[i])
                    {
                        return -1;
                    }
                }
            }
            return thisBytes.length - thatBytes.length;
        }

        /**
         * Does the necessary actions, when this as a query.
         */
        @Override
        boolean handleQuery(JmDNS dns, long expirationTime)
        {
            DNSRecord.Address dnsAddress =
                dns.getLocalHost().getDNSAddressRecord(this);
            if (dnsAddress != null)
            {
                if (dnsAddress.sameType(this) &&
                    dnsAddress.sameName(this) &&
                    (!dnsAddress.sameValue(this)))
                {
                    logger.finer(
                        "handleQuery() Conflicting probe detected. dns state " +
                        dns.getState() +
                        " lex compare " + lexCompare(dnsAddress));
                    // Tie-breaker test
                    if (dns.getState().isProbing() && lexCompare(dnsAddress) >= 0)
                    {
                        // We lost the tie-break. We have to choose a different name.
                        dns.getLocalHost().incrementHostName();
                        dns.getCache().clear();
                        for (ServiceInfo info : dns.services.values())
                            info.revertState();
                    }
                    dns.revertState();
                    return true;
                }
            }
            return false;
        }

        /**
         * Does the necessary actions, when this as a response.
         */
        @Override
        boolean handleResponse(JmDNS dns)
        {
            DNSRecord.Address dnsAddress =
                dns.getLocalHost().getDNSAddressRecord(this);
            if (dnsAddress != null)
            {
                if (dnsAddress.sameType(this) &&
                    dnsAddress.sameName(this) &&
                    (!dnsAddress.sameValue(this)))
                {
                    logger.finer("handleResponse() Denial detected");

                    if (dns.getState().isProbing())
                    {
                        dns.getLocalHost().incrementHostName();
                        dns.getCache().clear();
                        for (ServiceInfo info : dns.services.values())
                            info.revertState();
                    }
                    dns.revertState();
                    return true;
                }
            }
            return false;
        }

        @Override
        DNSOutgoing addAnswer(JmDNS dns,
                              DNSIncoming in,
                              InetAddress addr,
                              int port,
                              DNSOutgoing out)
            throws IOException
        {
            return out;
        }

        @Override
        public String toString()
        {
            return toString(" address '" +
                (addr != null ? addr.getHostAddress() : "null") + "'");
        }

    }

    /**
     * Pointer record.
     */
    static class Pointer extends DNSRecord
    {
        private static Logger logger =
            Logger.getLogger(Pointer.class.toString());
        String alias;

        Pointer(String name, int type, int clazz, int ttl, String alias)
        {
            super(name, type, clazz, ttl);
            this.alias = alias;

            String SLevel = System.getProperty("jmdns.debug");
            if (SLevel == null) SLevel = "INFO";
            logger.setLevel(Level.parse(SLevel));
        }

        @Override
        void write(DNSOutgoing out) throws IOException
        {
            out.writeName(alias);
        }

        @Override
        boolean sameValue(DNSRecord other)
        {
            return alias.equals(((Pointer) other).alias);
        }

        @Override
        boolean handleQuery(JmDNS dns, long expirationTime)
        {
            // Nothing to do (?)
            // I think there is no possibility
            // for conflicts for this record type?
            return false;
        }

        @Override
        boolean handleResponse(JmDNS dns)
        {
            // Nothing to do (?)
            // I think there is no possibility for conflicts for this record type?
            return false;
        }

        String getAlias()
        {
            return alias;
        }

        @Override
        DNSOutgoing addAnswer(JmDNS dns,
                            DNSIncoming in,
                            InetAddress addr,
                            int port,
                            DNSOutgoing out)
            throws IOException
        {
            return out;
        }

        @Override
        public String toString()
        {
            return toString(alias);
        }
    }

    static class Text extends DNSRecord
    {
        private static Logger logger =
            Logger.getLogger(Text.class.toString());
        byte text[];

        Text(String name, int type, int clazz, int ttl, byte text[])
        {
            super(name, type, clazz, ttl);
            this.text = text;

            String SLevel = System.getProperty("jmdns.debug");
            if (SLevel == null) SLevel = "INFO";
            logger.setLevel(Level.parse(SLevel));
        }

        @Override
        void write(DNSOutgoing out) throws IOException
        {
            out.writeBytes(text, 0, text.length);
        }

        @Override
        boolean sameValue(DNSRecord other)
        {
            Text txt = (Text) other;
            if (txt.text.length != text.length)
            {
                return false;
            }
            for (int i = text.length; i-- > 0;)
            {
                if (txt.text[i] != text[i])
                {
                    return false;
                }
            }
            return true;
        }

        @Override
        boolean handleQuery(JmDNS dns, long expirationTime)
        {
            // Nothing to do (?)
            // I think there is no possibility for conflicts for this record type?
            return false;
        }

        @Override
        boolean handleResponse(JmDNS dns)
        {
            // Nothing to do (?)
            // Shouldn't we care if we get a conflict at this level?
            /*
                ServiceInfo info = (ServiceInfo) dns.services.get(name.toLowerCase());
                if (info != null)
                {
                    if (! Arrays.equals(text,info.text))
                    {
                        info.revertState();
                        return true;
                    }
                }
             */
            return false;
        }

        @Override
        DNSOutgoing addAnswer(JmDNS dns,
                              DNSIncoming in,
                              InetAddress addr,
                              int port,
                              DNSOutgoing out)
            throws IOException
        {
            return out;
        }

        @Override
        public String toString()
        {
            return toString((text.length > 10) ?
                    new String(text, 0, 7) + "..." :
                    new String(text));
        }
    }

    /**
     * Service record.
     */
    static class Service extends DNSRecord
    {
        private static Logger logger =
            Logger.getLogger(Service.class.toString());
        int priority;
        int weight;
        int port;
        String server;

        Service(String name,
                int type,
                int clazz,
                int ttl,
                int priority,
                int weight,
                int port,
                String server)
        {
            super(name, type, clazz, ttl);
            this.priority = priority;
            this.weight = weight;
            this.port = port;
            this.server = server;

            String SLevel = System.getProperty("jmdns.debug");
            if (SLevel == null) SLevel = "INFO";
            logger.setLevel(Level.parse(SLevel));
        }

        @Override
        void write(DNSOutgoing out) throws IOException
        {
            out.writeShort(priority);
            out.writeShort(weight);
            out.writeShort(port);
            out.writeName(server);
        }

        private byte[] toByteArray()
        {
            try
            {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                DataOutputStream dout = new DataOutputStream(bout);
                dout.write(name.getBytes("UTF8"));
                dout.writeShort(type);
                dout.writeShort(clazz);
                //dout.writeInt(len);
                dout.writeShort(priority);
                dout.writeShort(weight);
                dout.writeShort(port);
                dout.write(server.getBytes("UTF8"));
                dout.close();
                return bout.toByteArray();
            }
            catch (IOException e)
            {
                throw new InternalError();
            }
        }

        private int lexCompare(DNSRecord.Service that)
        {
            byte[] thisBytes = this.toByteArray();
            byte[] thatBytes = that.toByteArray();
            for (int i = 0, n = Math.min(thisBytes.length, thatBytes.length);
                i < n;
                i++)
            {
                if (thisBytes[i] > thatBytes[i])
                {
                    return 1;
                }
                else
                {
                    if (thisBytes[i] < thatBytes[i])
                    {
                        return -1;
                    }
                }
            }
            return thisBytes.length - thatBytes.length;
        }

        @Override
        boolean sameValue(DNSRecord other)
        {
            Service s = (Service) other;
            return (priority == s.priority) &&
                (weight == s.weight) &&
                (port == s.port) &&
                server.equals(s.server);
        }

        @Override
        boolean handleQuery(JmDNS dns, long expirationTime)
        {
            ServiceInfo info = dns.services.get(name.toLowerCase());
            if (info != null &&
                (port != info.port ||
                !server.equalsIgnoreCase(dns.getLocalHost().getName())))
            {
                logger.finer("handleQuery() Conflicting probe detected");

                // Tie breaker test
                if (info.getState().isProbing() &&
                    lexCompare(new DNSRecord.Service(
                        info.getQualifiedName(),
                        DNSConstants.TYPE_SRV,
                        DNSConstants.CLASS_IN | DNSConstants.CLASS_UNIQUE,
                        DNSConstants.DNS_TTL,
                        info.priority,
                        info.weight,
                        info.port,
                        dns.getLocalHost().getName())) >= 0)
                {
                    // We lost the tie break
                    String oldName = info.getQualifiedName().toLowerCase();
                    info.setName(dns.incrementName(info.getName()));
                    dns.services.remove(oldName);
                    dns.services.put(info.getQualifiedName().toLowerCase(), info);
                    logger.finer(
                        "handleQuery() Lost tie break: new unique name chosen:" + info.getName());

                }
                info.revertState();
                return true;

            }
            return false;
        }

        @Override
        boolean handleResponse(JmDNS dns)
        {
            ServiceInfo info = dns.services.get(name.toLowerCase());
            if (info != null &&
                (port != info.port || !server.equalsIgnoreCase(dns.getLocalHost().getName())))
            {
                logger.finer("handleResponse() Denial detected");

                if (info.getState().isProbing())
                {
                    String oldName = info.getQualifiedName().toLowerCase();
                    info.setName(dns.incrementName(info.getName()));
                    dns.services.remove(oldName);
                    dns.services.put(info.getQualifiedName().toLowerCase(), info);
                    logger.finer(
                        "handleResponse() New unique name chose:" + info.getName());

                }
                info.revertState();
                return true;
            }
            return false;
        }

        @Override
        DNSOutgoing addAnswer(JmDNS dns,
                              DNSIncoming in,
                              InetAddress addr,
                              int port,
                              DNSOutgoing out)
            throws IOException
        {
            ServiceInfo info = dns.services.get(name.toLowerCase());
            if (info != null)
            {
                if (this.port == info.port != server.equals(dns.getLocalHost().getName()))
                {
                    return dns.addAnswer(in, addr, port, out,
                        new DNSRecord.Service(
                                info.getQualifiedName(),
                                DNSConstants.TYPE_SRV,
                                DNSConstants.CLASS_IN | DNSConstants.CLASS_UNIQUE,
                                DNSConstants.DNS_TTL,
                                info.priority,
                                info.weight,
                                info.port,
                                dns.getLocalHost().getName()));
                }
            }
            return out;
        }

        @Override
        public String toString()
        {
            return toString(server + ":" + port);
        }
    }

    public String toString(String other)
    {
        return toString("record", ttl + "/" +
            getRemainingTTL(System.currentTimeMillis())
//            + "," + other
            );
    }
}