~ntt-pf-lab/nova/monkey_patch_notification

« back to all changes in this revision

Viewing changes to vendor/Twisted-10.0.0/twisted/names/dns.py

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- test-case-name: twisted.names.test.test_dns -*-
 
2
# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
 
3
# See LICENSE for details.
 
4
 
 
5
 
 
6
"""
 
7
DNS protocol implementation.
 
8
 
 
9
Future Plans:
 
10
    - Get rid of some toplevels, maybe.
 
11
    - Put in a better lookupRecordType implementation.
 
12
 
 
13
@author: Moshe Zadka
 
14
@author: Jp Calderone
 
15
"""
 
16
 
 
17
# System imports
 
18
import warnings
 
19
 
 
20
import struct, random, types, socket
 
21
 
 
22
try:
 
23
    import cStringIO as StringIO
 
24
except ImportError:
 
25
    import StringIO
 
26
 
 
27
AF_INET6 = socket.AF_INET6
 
28
 
 
29
from zope.interface import implements, Interface, Attribute
 
30
 
 
31
 
 
32
# Twisted imports
 
33
from twisted.internet import protocol, defer
 
34
from twisted.internet.error import CannotListenError
 
35
from twisted.python import log, failure
 
36
from twisted.python import util as tputil
 
37
from twisted.python import randbytes
 
38
 
 
39
 
 
40
def randomSource():
 
41
    """
 
42
    Wrapper around L{randbytes.secureRandom} to return 2 random chars.
 
43
    """
 
44
    return struct.unpack('H', randbytes.secureRandom(2, fallback=True))[0]
 
45
 
 
46
 
 
47
PORT = 53
 
48
 
 
49
(A, NS, MD, MF, CNAME, SOA, MB, MG, MR, NULL, WKS, PTR, HINFO, MINFO, MX, TXT,
 
50
 RP, AFSDB) = range(1, 19)
 
51
AAAA = 28
 
52
SRV = 33
 
53
NAPTR = 35
 
54
A6 = 38
 
55
DNAME = 39
 
56
 
 
57
QUERY_TYPES = {
 
58
    A: 'A',
 
59
    NS: 'NS',
 
60
    MD: 'MD',
 
61
    MF: 'MF',
 
62
    CNAME: 'CNAME',
 
63
    SOA: 'SOA',
 
64
    MB: 'MB',
 
65
    MG: 'MG',
 
66
    MR: 'MR',
 
67
    NULL: 'NULL',
 
68
    WKS: 'WKS',
 
69
    PTR: 'PTR',
 
70
    HINFO: 'HINFO',
 
71
    MINFO: 'MINFO',
 
72
    MX: 'MX',
 
73
    TXT: 'TXT',
 
74
    RP: 'RP',
 
75
    AFSDB: 'AFSDB',
 
76
 
 
77
    # 19 through 27?  Eh, I'll get to 'em.
 
78
 
 
79
    AAAA: 'AAAA',
 
80
    SRV: 'SRV',
 
81
    NAPTR: 'NAPTR',
 
82
    A6: 'A6',
 
83
    DNAME: 'DNAME'
 
84
}
 
85
 
 
86
IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = range(251, 256)
 
87
 
 
88
# "Extended" queries (Hey, half of these are deprecated, good job)
 
89
EXT_QUERIES = {
 
90
    IXFR: 'IXFR',
 
91
    AXFR: 'AXFR',
 
92
    MAILB: 'MAILB',
 
93
    MAILA: 'MAILA',
 
94
    ALL_RECORDS: 'ALL_RECORDS'
 
95
}
 
96
 
 
97
REV_TYPES = dict([
 
98
    (v, k) for (k, v) in QUERY_TYPES.items() + EXT_QUERIES.items()
 
99
])
 
100
 
 
101
IN, CS, CH, HS = range(1, 5)
 
102
ANY = 255
 
103
 
 
104
QUERY_CLASSES = {
 
105
    IN: 'IN',
 
106
    CS: 'CS',
 
107
    CH: 'CH',
 
108
    HS: 'HS',
 
109
    ANY: 'ANY'
 
110
}
 
111
REV_CLASSES = dict([
 
112
    (v, k) for (k, v) in QUERY_CLASSES.items()
 
113
])
 
114
 
 
115
 
 
116
# Opcodes
 
117
OP_QUERY, OP_INVERSE, OP_STATUS = range(3)
 
118
OP_NOTIFY = 4 # RFC 1996
 
119
OP_UPDATE = 5 # RFC 2136
 
120
 
 
121
 
 
122
# Response Codes
 
123
OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = range(6)
 
124
 
 
125
class IRecord(Interface):
 
126
    """
 
127
    An single entry in a zone of authority.
 
128
    """
 
129
 
 
130
    TYPE = Attribute("An indicator of what kind of record this is.")
 
131
 
 
132
 
 
133
# Backwards compatibility aliases - these should be deprecated or something I
 
134
# suppose. -exarkun
 
135
from twisted.names.error import DomainError, AuthoritativeDomainError
 
136
from twisted.names.error import DNSQueryTimeoutError
 
137
 
 
138
 
 
139
def str2time(s):
 
140
    suffixes = (
 
141
        ('S', 1), ('M', 60), ('H', 60 * 60), ('D', 60 * 60 * 24),
 
142
        ('W', 60 * 60 * 24 * 7), ('Y', 60 * 60 * 24 * 365)
 
143
    )
 
144
    if isinstance(s, types.StringType):
 
145
        s = s.upper().strip()
 
146
        for (suff, mult) in suffixes:
 
147
            if s.endswith(suff):
 
148
                return int(float(s[:-1]) * mult)
 
149
        try:
 
150
            s = int(s)
 
151
        except ValueError:
 
152
            raise ValueError, "Invalid time interval specifier: " + s
 
153
    return s
 
154
 
 
155
 
 
156
def readPrecisely(file, l):
 
157
    buff = file.read(l)
 
158
    if len(buff) < l:
 
159
        raise EOFError
 
160
    return buff
 
161
 
 
162
 
 
163
class IEncodable(Interface):
 
164
    """
 
165
    Interface for something which can be encoded to and decoded
 
166
    from a file object.
 
167
    """
 
168
 
 
169
    def encode(strio, compDict = None):
 
170
        """
 
171
        Write a representation of this object to the given
 
172
        file object.
 
173
 
 
174
        @type strio: File-like object
 
175
        @param strio: The stream to which to write bytes
 
176
 
 
177
        @type compDict: C{dict} or C{None}
 
178
        @param compDict: A dictionary of backreference addresses that have
 
179
        have already been written to this stream and that may be used for
 
180
        compression.
 
181
        """
 
182
 
 
183
    def decode(strio, length = None):
 
184
        """
 
185
        Reconstruct an object from data read from the given
 
186
        file object.
 
187
 
 
188
        @type strio: File-like object
 
189
        @param strio: The stream from which bytes may be read
 
190
 
 
191
        @type length: C{int} or C{None}
 
192
        @param length: The number of bytes in this RDATA field.  Most
 
193
        implementations can ignore this value.  Only in the case of
 
194
        records similar to TXT where the total length is in no way
 
195
        encoded in the data is it necessary.
 
196
        """
 
197
 
 
198
 
 
199
 
 
200
class Charstr(object):
 
201
    implements(IEncodable)
 
202
 
 
203
    def __init__(self, string=''):
 
204
        if not isinstance(string, str):
 
205
            raise ValueError("%r is not a string" % (string,))
 
206
        self.string = string
 
207
 
 
208
 
 
209
    def encode(self, strio, compDict=None):
 
210
        """
 
211
        Encode this Character string into the appropriate byte format.
 
212
 
 
213
        @type strio: file
 
214
        @param strio: The byte representation of this Charstr will be written
 
215
            to this file.
 
216
        """
 
217
        string = self.string
 
218
        ind = len(string)
 
219
        strio.write(chr(ind))
 
220
        strio.write(string)
 
221
 
 
222
 
 
223
    def decode(self, strio, length=None):
 
224
        """
 
225
        Decode a byte string into this Name.
 
226
 
 
227
        @type strio: file
 
228
        @param strio: Bytes will be read from this file until the full string
 
229
            is decoded.
 
230
 
 
231
        @raise EOFError: Raised when there are not enough bytes available from
 
232
            C{strio}.
 
233
        """
 
234
        self.string = ''
 
235
        l = ord(readPrecisely(strio, 1))
 
236
        self.string = readPrecisely(strio, l)
 
237
 
 
238
 
 
239
    def __eq__(self, other):
 
240
        if isinstance(other, Charstr):
 
241
            return self.string == other.string
 
242
        return False
 
243
 
 
244
 
 
245
    def __hash__(self):
 
246
        return hash(self.string)
 
247
 
 
248
 
 
249
    def __str__(self):
 
250
        return self.string
 
251
 
 
252
 
 
253
 
 
254
class Name:
 
255
    implements(IEncodable)
 
256
 
 
257
    def __init__(self, name=''):
 
258
        assert isinstance(name, types.StringTypes), "%r is not a string" % (name,)
 
259
        self.name = name
 
260
 
 
261
    def encode(self, strio, compDict=None):
 
262
        """
 
263
        Encode this Name into the appropriate byte format.
 
264
 
 
265
        @type strio: file
 
266
        @param strio: The byte representation of this Name will be written to
 
267
        this file.
 
268
 
 
269
        @type compDict: dict
 
270
        @param compDict: dictionary of Names that have already been encoded
 
271
        and whose addresses may be backreferenced by this Name (for the purpose
 
272
        of reducing the message size).
 
273
        """
 
274
        name = self.name
 
275
        while name:
 
276
            if compDict is not None:
 
277
                if name in compDict:
 
278
                    strio.write(
 
279
                        struct.pack("!H", 0xc000 | compDict[name]))
 
280
                    return
 
281
                else:
 
282
                    compDict[name] = strio.tell() + Message.headerSize
 
283
            ind = name.find('.')
 
284
            if ind > 0:
 
285
                label, name = name[:ind], name[ind + 1:]
 
286
            else:
 
287
                label, name = name, ''
 
288
                ind = len(label)
 
289
            strio.write(chr(ind))
 
290
            strio.write(label)
 
291
        strio.write(chr(0))
 
292
 
 
293
 
 
294
    def decode(self, strio, length=None):
 
295
        """
 
296
        Decode a byte string into this Name.
 
297
 
 
298
        @type strio: file
 
299
        @param strio: Bytes will be read from this file until the full Name
 
300
        is decoded.
 
301
 
 
302
        @raise EOFError: Raised when there are not enough bytes available
 
303
        from C{strio}.
 
304
        """
 
305
        self.name = ''
 
306
        off = 0
 
307
        while 1:
 
308
            l = ord(readPrecisely(strio, 1))
 
309
            if l == 0:
 
310
                if off > 0:
 
311
                    strio.seek(off)
 
312
                return
 
313
            if (l >> 6) == 3:
 
314
                new_off = ((l&63) << 8
 
315
                            | ord(readPrecisely(strio, 1)))
 
316
                if off == 0:
 
317
                    off = strio.tell()
 
318
                strio.seek(new_off)
 
319
                continue
 
320
            label = readPrecisely(strio, l)
 
321
            if self.name == '':
 
322
                self.name = label
 
323
            else:
 
324
                self.name = self.name + '.' + label
 
325
 
 
326
    def __eq__(self, other):
 
327
        if isinstance(other, Name):
 
328
            return str(self) == str(other)
 
329
        return 0
 
330
 
 
331
 
 
332
    def __hash__(self):
 
333
        return hash(str(self))
 
334
 
 
335
 
 
336
    def __str__(self):
 
337
        return self.name
 
338
 
 
339
class Query:
 
340
    """
 
341
    Represent a single DNS query.
 
342
 
 
343
    @ivar name: The name about which this query is requesting information.
 
344
    @ivar type: The query type.
 
345
    @ivar cls: The query class.
 
346
    """
 
347
 
 
348
    implements(IEncodable)
 
349
 
 
350
    name = None
 
351
    type = None
 
352
    cls = None
 
353
 
 
354
    def __init__(self, name='', type=A, cls=IN):
 
355
        """
 
356
        @type name: C{str}
 
357
        @param name: The name about which to request information.
 
358
 
 
359
        @type type: C{int}
 
360
        @param type: The query type.
 
361
 
 
362
        @type cls: C{int}
 
363
        @param cls: The query class.
 
364
        """
 
365
        self.name = Name(name)
 
366
        self.type = type
 
367
        self.cls = cls
 
368
 
 
369
 
 
370
    def encode(self, strio, compDict=None):
 
371
        self.name.encode(strio, compDict)
 
372
        strio.write(struct.pack("!HH", self.type, self.cls))
 
373
 
 
374
 
 
375
    def decode(self, strio, length = None):
 
376
        self.name.decode(strio)
 
377
        buff = readPrecisely(strio, 4)
 
378
        self.type, self.cls = struct.unpack("!HH", buff)
 
379
 
 
380
 
 
381
    def __hash__(self):
 
382
        return hash((str(self.name).lower(), self.type, self.cls))
 
383
 
 
384
 
 
385
    def __cmp__(self, other):
 
386
        return isinstance(other, Query) and cmp(
 
387
            (str(self.name).lower(), self.type, self.cls),
 
388
            (str(other.name).lower(), other.type, other.cls)
 
389
        ) or cmp(self.__class__, other.__class__)
 
390
 
 
391
 
 
392
    def __str__(self):
 
393
        t = QUERY_TYPES.get(self.type, EXT_QUERIES.get(self.type, 'UNKNOWN (%d)' % self.type))
 
394
        c = QUERY_CLASSES.get(self.cls, 'UNKNOWN (%d)' % self.cls)
 
395
        return '<Query %s %s %s>' % (self.name, t, c)
 
396
 
 
397
 
 
398
    def __repr__(self):
 
399
        return 'Query(%r, %r, %r)' % (str(self.name), self.type, self.cls)
 
400
 
 
401
 
 
402
class RRHeader(tputil.FancyEqMixin):
 
403
    """
 
404
    A resource record header.
 
405
 
 
406
    @cvar fmt: C{str} specifying the byte format of an RR.
 
407
 
 
408
    @ivar name: The name about which this reply contains information.
 
409
    @ivar type: The query type of the original request.
 
410
    @ivar cls: The query class of the original request.
 
411
    @ivar ttl: The time-to-live for this record.
 
412
    @ivar payload: An object that implements the IEncodable interface
 
413
    @ivar auth: Whether this header is authoritative or not.
 
414
    """
 
415
 
 
416
    implements(IEncodable)
 
417
 
 
418
    compareAttributes = ('name', 'type', 'cls', 'ttl', 'payload', 'auth')
 
419
 
 
420
    fmt = "!HHIH"
 
421
 
 
422
    name = None
 
423
    type = None
 
424
    cls = None
 
425
    ttl = None
 
426
    payload = None
 
427
    rdlength = None
 
428
 
 
429
    cachedResponse = None
 
430
 
 
431
    def __init__(self, name='', type=A, cls=IN, ttl=0, payload=None, auth=False):
 
432
        """
 
433
        @type name: C{str}
 
434
        @param name: The name about which this reply contains information.
 
435
 
 
436
        @type type: C{int}
 
437
        @param type: The query type.
 
438
 
 
439
        @type cls: C{int}
 
440
        @param cls: The query class.
 
441
 
 
442
        @type ttl: C{int}
 
443
        @param ttl: Time to live for this record.
 
444
 
 
445
        @type payload: An object implementing C{IEncodable}
 
446
        @param payload: A Query Type specific data object.
 
447
        """
 
448
        assert (payload is None) or (payload.TYPE == type)
 
449
 
 
450
        self.name = Name(name)
 
451
        self.type = type
 
452
        self.cls = cls
 
453
        self.ttl = ttl
 
454
        self.payload = payload
 
455
        self.auth = auth
 
456
 
 
457
 
 
458
    def encode(self, strio, compDict=None):
 
459
        self.name.encode(strio, compDict)
 
460
        strio.write(struct.pack(self.fmt, self.type, self.cls, self.ttl, 0))
 
461
        if self.payload:
 
462
            prefix = strio.tell()
 
463
            self.payload.encode(strio, compDict)
 
464
            aft = strio.tell()
 
465
            strio.seek(prefix - 2, 0)
 
466
            strio.write(struct.pack('!H', aft - prefix))
 
467
            strio.seek(aft, 0)
 
468
 
 
469
 
 
470
    def decode(self, strio, length = None):
 
471
        self.name.decode(strio)
 
472
        l = struct.calcsize(self.fmt)
 
473
        buff = readPrecisely(strio, l)
 
474
        r = struct.unpack(self.fmt, buff)
 
475
        self.type, self.cls, self.ttl, self.rdlength = r
 
476
 
 
477
 
 
478
    def isAuthoritative(self):
 
479
        return self.auth
 
480
 
 
481
 
 
482
    def __str__(self):
 
483
        t = QUERY_TYPES.get(self.type, EXT_QUERIES.get(self.type, 'UNKNOWN (%d)' % self.type))
 
484
        c = QUERY_CLASSES.get(self.cls, 'UNKNOWN (%d)' % self.cls)
 
485
        return '<RR name=%s type=%s class=%s ttl=%ds auth=%s>' % (self.name, t, c, self.ttl, self.auth and 'True' or 'False')
 
486
 
 
487
 
 
488
    __repr__ = __str__
 
489
 
 
490
 
 
491
 
 
492
class SimpleRecord(tputil.FancyStrMixin, tputil.FancyEqMixin):
 
493
    """
 
494
    A Resource Record which consists of a single RFC 1035 domain-name.
 
495
 
 
496
    @type name: L{Name}
 
497
    @ivar name: The name associated with this record.
 
498
 
 
499
    @type ttl: C{int}
 
500
    @ivar ttl: The maximum number of seconds which this record should be
 
501
        cached.
 
502
    """
 
503
    implements(IEncodable, IRecord)
 
504
 
 
505
    showAttributes = (('name', 'name', '%s'), 'ttl')
 
506
    compareAttributes = ('name', 'ttl')
 
507
 
 
508
    TYPE = None
 
509
    name = None
 
510
 
 
511
    def __init__(self, name='', ttl=None):
 
512
        self.name = Name(name)
 
513
        self.ttl = str2time(ttl)
 
514
 
 
515
 
 
516
    def encode(self, strio, compDict = None):
 
517
        self.name.encode(strio, compDict)
 
518
 
 
519
 
 
520
    def decode(self, strio, length = None):
 
521
        self.name = Name()
 
522
        self.name.decode(strio)
 
523
 
 
524
 
 
525
    def __hash__(self):
 
526
        return hash(self.name)
 
527
 
 
528
 
 
529
# Kinds of RRs - oh my!
 
530
class Record_NS(SimpleRecord):
 
531
    """
 
532
    An authoritative nameserver.
 
533
    """
 
534
    TYPE = NS
 
535
    fancybasename = 'NS'
 
536
 
 
537
 
 
538
 
 
539
class Record_MD(SimpleRecord):
 
540
    """
 
541
    A mail destination.
 
542
 
 
543
    This record type is obsolete.
 
544
 
 
545
    @see: L{Record_MX}
 
546
    """
 
547
    TYPE = MD
 
548
    fancybasename = 'MD'
 
549
 
 
550
 
 
551
 
 
552
class Record_MF(SimpleRecord):
 
553
    """
 
554
    A mail forwarder.
 
555
 
 
556
    This record type is obsolete.
 
557
 
 
558
    @see: L{Record_MX}
 
559
    """
 
560
    TYPE = MF
 
561
    fancybasename = 'MF'
 
562
 
 
563
 
 
564
 
 
565
class Record_CNAME(SimpleRecord):
 
566
    """
 
567
    The canonical name for an alias.
 
568
    """
 
569
    TYPE = CNAME
 
570
    fancybasename = 'CNAME'
 
571
 
 
572
 
 
573
 
 
574
class Record_MB(SimpleRecord):
 
575
    """
 
576
    A mailbox domain name.
 
577
 
 
578
    This is an experimental record type.
 
579
    """
 
580
    TYPE = MB
 
581
    fancybasename = 'MB'
 
582
 
 
583
 
 
584
 
 
585
class Record_MG(SimpleRecord):
 
586
    """
 
587
    A mail group member.
 
588
 
 
589
    This is an experimental record type.
 
590
    """
 
591
    TYPE = MG
 
592
    fancybasename = 'MG'
 
593
 
 
594
 
 
595
 
 
596
class Record_MR(SimpleRecord):
 
597
    """
 
598
    A mail rename domain name.
 
599
 
 
600
    This is an experimental record type.
 
601
    """
 
602
    TYPE = MR
 
603
    fancybasename = 'MR'
 
604
 
 
605
 
 
606
 
 
607
class Record_PTR(SimpleRecord):
 
608
    """
 
609
    A domain name pointer.
 
610
    """
 
611
    TYPE = PTR
 
612
    fancybasename = 'PTR'
 
613
 
 
614
 
 
615
 
 
616
class Record_DNAME(SimpleRecord):
 
617
    """
 
618
    A non-terminal DNS name redirection.
 
619
 
 
620
    This record type provides the capability to map an entire subtree of the
 
621
    DNS name space to another domain.  It differs from the CNAME record which
 
622
    maps a single node of the name space.
 
623
 
 
624
    @see: U{http://www.faqs.org/rfcs/rfc2672.html}
 
625
    @see: U{http://www.faqs.org/rfcs/rfc3363.html}
 
626
    """
 
627
    TYPE = DNAME
 
628
    fancybasename = 'DNAME'
 
629
 
 
630
 
 
631
 
 
632
class Record_A(tputil.FancyEqMixin):
 
633
    """
 
634
    An IPv4 host address.
 
635
 
 
636
    @type address: C{str}
 
637
    @ivar address: The packed network-order representation of the IPv4 address
 
638
        associated with this record.
 
639
 
 
640
    @type ttl: C{int}
 
641
    @ivar ttl: The maximum number of seconds which this record should be
 
642
        cached.
 
643
    """
 
644
    implements(IEncodable, IRecord)
 
645
 
 
646
    compareAttributes = ('address', 'ttl')
 
647
 
 
648
    TYPE = A
 
649
    address = None
 
650
 
 
651
    def __init__(self, address='0.0.0.0', ttl=None):
 
652
        address = socket.inet_aton(address)
 
653
        self.address = address
 
654
        self.ttl = str2time(ttl)
 
655
 
 
656
 
 
657
    def encode(self, strio, compDict = None):
 
658
        strio.write(self.address)
 
659
 
 
660
 
 
661
    def decode(self, strio, length = None):
 
662
        self.address = readPrecisely(strio, 4)
 
663
 
 
664
 
 
665
    def __hash__(self):
 
666
        return hash(self.address)
 
667
 
 
668
 
 
669
    def __str__(self):
 
670
        return '<A address=%s ttl=%s>' % (self.dottedQuad(), self.ttl)
 
671
    __repr__ = __str__
 
672
 
 
673
 
 
674
    def dottedQuad(self):
 
675
        return socket.inet_ntoa(self.address)
 
676
 
 
677
 
 
678
 
 
679
class Record_SOA(tputil.FancyEqMixin, tputil.FancyStrMixin):
 
680
    """
 
681
    Marks the start of a zone of authority.
 
682
 
 
683
    This record describes parameters which are shared by all records within a
 
684
    particular zone.
 
685
 
 
686
    @type mname: L{Name}
 
687
    @ivar mname: The domain-name of the name server that was the original or
 
688
        primary source of data for this zone.
 
689
 
 
690
    @type rname: L{Name}
 
691
    @ivar rname: A domain-name which specifies the mailbox of the person
 
692
        responsible for this zone.
 
693
 
 
694
    @type serial: C{int}
 
695
    @ivar serial: The unsigned 32 bit version number of the original copy of
 
696
        the zone.  Zone transfers preserve this value.  This value wraps and
 
697
        should be compared using sequence space arithmetic.
 
698
 
 
699
    @type refresh: C{int}
 
700
    @ivar refresh: A 32 bit time interval before the zone should be refreshed.
 
701
 
 
702
    @type minimum: C{int}
 
703
    @ivar minimum: The unsigned 32 bit minimum TTL field that should be
 
704
        exported with any RR from this zone.
 
705
 
 
706
    @type expire: C{int}
 
707
    @ivar expire: A 32 bit time value that specifies the upper limit on the
 
708
        time interval that can elapse before the zone is no longer
 
709
        authoritative.
 
710
 
 
711
    @type retry: C{int}
 
712
    @ivar retry: A 32 bit time interval that should elapse before a failed
 
713
        refresh should be retried.
 
714
 
 
715
    @type ttl: C{int}
 
716
    @ivar ttl: The default TTL to use for records served from this zone.
 
717
    """
 
718
    implements(IEncodable, IRecord)
 
719
 
 
720
    fancybasename = 'SOA'
 
721
    compareAttributes = ('serial', 'mname', 'rname', 'refresh', 'expire', 'retry', 'minimum', 'ttl')
 
722
    showAttributes = (('mname', 'mname', '%s'), ('rname', 'rname', '%s'), 'serial', 'refresh', 'retry', 'expire', 'minimum', 'ttl')
 
723
 
 
724
    TYPE = SOA
 
725
 
 
726
    def __init__(self, mname='', rname='', serial=0, refresh=0, retry=0, expire=0, minimum=0, ttl=None):
 
727
        self.mname, self.rname = Name(mname), Name(rname)
 
728
        self.serial, self.refresh = str2time(serial), str2time(refresh)
 
729
        self.minimum, self.expire = str2time(minimum), str2time(expire)
 
730
        self.retry = str2time(retry)
 
731
        self.ttl = str2time(ttl)
 
732
 
 
733
 
 
734
    def encode(self, strio, compDict = None):
 
735
        self.mname.encode(strio, compDict)
 
736
        self.rname.encode(strio, compDict)
 
737
        strio.write(
 
738
            struct.pack(
 
739
                '!LlllL',
 
740
                self.serial, self.refresh, self.retry, self.expire,
 
741
                self.minimum
 
742
            )
 
743
        )
 
744
 
 
745
 
 
746
    def decode(self, strio, length = None):
 
747
        self.mname, self.rname = Name(), Name()
 
748
        self.mname.decode(strio)
 
749
        self.rname.decode(strio)
 
750
        r = struct.unpack('!LlllL', readPrecisely(strio, 20))
 
751
        self.serial, self.refresh, self.retry, self.expire, self.minimum = r
 
752
 
 
753
 
 
754
    def __hash__(self):
 
755
        return hash((
 
756
            self.serial, self.mname, self.rname,
 
757
            self.refresh, self.expire, self.retry
 
758
        ))
 
759
 
 
760
 
 
761
 
 
762
class Record_NULL(tputil.FancyStrMixin, tputil.FancyEqMixin):
 
763
    """
 
764
    A null record.
 
765
 
 
766
    This is an experimental record type.
 
767
 
 
768
    @type ttl: C{int}
 
769
    @ivar ttl: The maximum number of seconds which this record should be
 
770
        cached.
 
771
    """
 
772
    implements(IEncodable, IRecord)
 
773
 
 
774
    fancybasename = 'NULL'
 
775
    showAttributes = compareAttributes = ('payload', 'ttl')
 
776
 
 
777
    TYPE = NULL
 
778
 
 
779
    def __init__(self, payload=None, ttl=None):
 
780
        self.payload = payload
 
781
        self.ttl = str2time(ttl)
 
782
 
 
783
 
 
784
    def encode(self, strio, compDict = None):
 
785
        strio.write(self.payload)
 
786
 
 
787
 
 
788
    def decode(self, strio, length = None):
 
789
        self.payload = readPrecisely(strio, length)
 
790
 
 
791
 
 
792
    def __hash__(self):
 
793
        return hash(self.payload)
 
794
 
 
795
 
 
796
 
 
797
class Record_WKS(tputil.FancyEqMixin, tputil.FancyStrMixin):
 
798
    """
 
799
    A well known service description.
 
800
 
 
801
    This record type is obsolete.  See L{Record_SRV}.
 
802
 
 
803
    @type address: C{str}
 
804
    @ivar address: The packed network-order representation of the IPv4 address
 
805
        associated with this record.
 
806
 
 
807
    @type protocol: C{int}
 
808
    @ivar protocol: The 8 bit IP protocol number for which this service map is
 
809
        relevant.
 
810
 
 
811
    @type map: C{str}
 
812
    @ivar map: A bitvector indicating the services available at the specified
 
813
        address.
 
814
 
 
815
    @type ttl: C{int}
 
816
    @ivar ttl: The maximum number of seconds which this record should be
 
817
        cached.
 
818
    """
 
819
    implements(IEncodable, IRecord)
 
820
 
 
821
    fancybasename = "WKS"
 
822
    compareAttributes = ('address', 'protocol', 'map', 'ttl')
 
823
    showAttributes = [('_address', 'address', '%s'), 'protocol', 'ttl']
 
824
 
 
825
    TYPE = WKS
 
826
 
 
827
    _address = property(lambda self: socket.inet_ntoa(self.address))
 
828
 
 
829
    def __init__(self, address='0.0.0.0', protocol=0, map='', ttl=None):
 
830
        self.address = socket.inet_aton(address)
 
831
        self.protocol, self.map = protocol, map
 
832
        self.ttl = str2time(ttl)
 
833
 
 
834
 
 
835
    def encode(self, strio, compDict = None):
 
836
        strio.write(self.address)
 
837
        strio.write(struct.pack('!B', self.protocol))
 
838
        strio.write(self.map)
 
839
 
 
840
 
 
841
    def decode(self, strio, length = None):
 
842
        self.address = readPrecisely(strio, 4)
 
843
        self.protocol = struct.unpack('!B', readPrecisely(strio, 1))[0]
 
844
        self.map = readPrecisely(strio, length - 5)
 
845
 
 
846
 
 
847
    def __hash__(self):
 
848
        return hash((self.address, self.protocol, self.map))
 
849
 
 
850
 
 
851
 
 
852
class Record_AAAA(tputil.FancyEqMixin, tputil.FancyStrMixin):
 
853
    """
 
854
    An IPv6 host address.
 
855
 
 
856
    @type address: C{str}
 
857
    @ivar address: The packed network-order representation of the IPv6 address
 
858
        associated with this record.
 
859
 
 
860
    @type ttl: C{int}
 
861
    @ivar ttl: The maximum number of seconds which this record should be
 
862
        cached.
 
863
 
 
864
    @see: U{http://www.faqs.org/rfcs/rfc1886.html}
 
865
    """
 
866
    implements(IEncodable, IRecord)
 
867
    TYPE = AAAA
 
868
 
 
869
    fancybasename = 'AAAA'
 
870
    showAttributes = (('_address', 'address', '%s'), 'ttl')
 
871
    compareAttributes = ('address', 'ttl')
 
872
 
 
873
    _address = property(lambda self: socket.inet_ntop(AF_INET6, self.address))
 
874
 
 
875
    def __init__(self, address = '::', ttl=None):
 
876
        self.address = socket.inet_pton(AF_INET6, address)
 
877
        self.ttl = str2time(ttl)
 
878
 
 
879
 
 
880
    def encode(self, strio, compDict = None):
 
881
        strio.write(self.address)
 
882
 
 
883
 
 
884
    def decode(self, strio, length = None):
 
885
        self.address = readPrecisely(strio, 16)
 
886
 
 
887
 
 
888
    def __hash__(self):
 
889
        return hash(self.address)
 
890
 
 
891
 
 
892
 
 
893
class Record_A6(tputil.FancyStrMixin, tputil.FancyEqMixin):
 
894
    """
 
895
    An IPv6 address.
 
896
 
 
897
    This is an experimental record type.
 
898
 
 
899
    @type prefixLen: C{int}
 
900
    @ivar prefixLen: The length of the suffix.
 
901
 
 
902
    @type suffix: C{str}
 
903
    @ivar suffix: An IPv6 address suffix in network order.
 
904
 
 
905
    @type prefix: L{Name}
 
906
    @ivar prefix: If specified, a name which will be used as a prefix for other
 
907
        A6 records.
 
908
 
 
909
    @type bytes: C{int}
 
910
    @ivar bytes: The length of the prefix.
 
911
 
 
912
    @type ttl: C{int}
 
913
    @ivar ttl: The maximum number of seconds which this record should be
 
914
        cached.
 
915
 
 
916
    @see: U{http://www.faqs.org/rfcs/rfc2874.html}
 
917
    @see: U{http://www.faqs.org/rfcs/rfc3363.html}
 
918
    @see: U{http://www.faqs.org/rfcs/rfc3364.html}
 
919
    """
 
920
    implements(IEncodable, IRecord)
 
921
    TYPE = A6
 
922
 
 
923
    fancybasename = 'A6'
 
924
    showAttributes = (('_suffix', 'suffix', '%s'), ('prefix', 'prefix', '%s'), 'ttl')
 
925
    compareAttributes = ('prefixLen', 'prefix', 'suffix', 'ttl')
 
926
 
 
927
    _suffix = property(lambda self: socket.inet_ntop(AF_INET6, self.suffix))
 
928
 
 
929
    def __init__(self, prefixLen=0, suffix='::', prefix='', ttl=None):
 
930
        self.prefixLen = prefixLen
 
931
        self.suffix = socket.inet_pton(AF_INET6, suffix)
 
932
        self.prefix = Name(prefix)
 
933
        self.bytes = int((128 - self.prefixLen) / 8.0)
 
934
        self.ttl = str2time(ttl)
 
935
 
 
936
 
 
937
    def encode(self, strio, compDict = None):
 
938
        strio.write(struct.pack('!B', self.prefixLen))
 
939
        if self.bytes:
 
940
            strio.write(self.suffix[-self.bytes:])
 
941
        if self.prefixLen:
 
942
            # This may not be compressed
 
943
            self.prefix.encode(strio, None)
 
944
 
 
945
 
 
946
    def decode(self, strio, length = None):
 
947
        self.prefixLen = struct.unpack('!B', readPrecisely(strio, 1))[0]
 
948
        self.bytes = int((128 - self.prefixLen) / 8.0)
 
949
        if self.bytes:
 
950
            self.suffix = '\x00' * (16 - self.bytes) + readPrecisely(strio, self.bytes)
 
951
        if self.prefixLen:
 
952
            self.prefix.decode(strio)
 
953
 
 
954
 
 
955
    def __eq__(self, other):
 
956
        if isinstance(other, Record_A6):
 
957
            return (self.prefixLen == other.prefixLen and
 
958
                    self.suffix[-self.bytes:] == other.suffix[-self.bytes:] and
 
959
                    self.prefix == other.prefix and
 
960
                    self.ttl == other.ttl)
 
961
        return NotImplemented
 
962
 
 
963
 
 
964
    def __hash__(self):
 
965
        return hash((self.prefixLen, self.suffix[-self.bytes:], self.prefix))
 
966
 
 
967
 
 
968
    def __str__(self):
 
969
        return '<A6 %s %s (%d) ttl=%s>' % (
 
970
            self.prefix,
 
971
            socket.inet_ntop(AF_INET6, self.suffix),
 
972
            self.prefixLen, self.ttl
 
973
        )
 
974
 
 
975
 
 
976
 
 
977
class Record_SRV(tputil.FancyEqMixin, tputil.FancyStrMixin):
 
978
    """
 
979
    The location of the server(s) for a specific protocol and domain.
 
980
 
 
981
    This is an experimental record type.
 
982
 
 
983
    @type priority: C{int}
 
984
    @ivar priority: The priority of this target host.  A client MUST attempt to
 
985
        contact the target host with the lowest-numbered priority it can reach;
 
986
        target hosts with the same priority SHOULD be tried in an order defined
 
987
        by the weight field.
 
988
 
 
989
    @type weight: C{int}
 
990
    @ivar weight: Specifies a relative weight for entries with the same
 
991
        priority. Larger weights SHOULD be given a proportionately higher
 
992
        probability of being selected.
 
993
 
 
994
    @type port: C{int}
 
995
    @ivar port: The port on this target host of this service.
 
996
 
 
997
    @type target: L{Name}
 
998
    @ivar target: The domain name of the target host.  There MUST be one or
 
999
        more address records for this name, the name MUST NOT be an alias (in
 
1000
        the sense of RFC 1034 or RFC 2181).  Implementors are urged, but not
 
1001
        required, to return the address record(s) in the Additional Data
 
1002
        section.  Unless and until permitted by future standards action, name
 
1003
        compression is not to be used for this field.
 
1004
 
 
1005
    @type ttl: C{int}
 
1006
    @ivar ttl: The maximum number of seconds which this record should be
 
1007
        cached.
 
1008
 
 
1009
    @see: U{http://www.faqs.org/rfcs/rfc2782.html}
 
1010
    """
 
1011
    implements(IEncodable, IRecord)
 
1012
    TYPE = SRV
 
1013
 
 
1014
    fancybasename = 'SRV'
 
1015
    compareAttributes = ('priority', 'weight', 'target', 'port', 'ttl')
 
1016
    showAttributes = ('priority', 'weight', ('target', 'target', '%s'), 'port', 'ttl')
 
1017
 
 
1018
    def __init__(self, priority=0, weight=0, port=0, target='', ttl=None):
 
1019
        self.priority = int(priority)
 
1020
        self.weight = int(weight)
 
1021
        self.port = int(port)
 
1022
        self.target = Name(target)
 
1023
        self.ttl = str2time(ttl)
 
1024
 
 
1025
 
 
1026
    def encode(self, strio, compDict = None):
 
1027
        strio.write(struct.pack('!HHH', self.priority, self.weight, self.port))
 
1028
        # This can't be compressed
 
1029
        self.target.encode(strio, None)
 
1030
 
 
1031
 
 
1032
    def decode(self, strio, length = None):
 
1033
        r = struct.unpack('!HHH', readPrecisely(strio, struct.calcsize('!HHH')))
 
1034
        self.priority, self.weight, self.port = r
 
1035
        self.target = Name()
 
1036
        self.target.decode(strio)
 
1037
 
 
1038
 
 
1039
    def __hash__(self):
 
1040
        return hash((self.priority, self.weight, self.port, self.target))
 
1041
 
 
1042
 
 
1043
 
 
1044
class Record_NAPTR(tputil.FancyEqMixin, tputil.FancyStrMixin):
 
1045
    """
 
1046
    The location of the server(s) for a specific protocol and domain.
 
1047
 
 
1048
    @type order: C{int}
 
1049
    @ivar order: An integer specifying the order in which the NAPTR records
 
1050
        MUST be processed to ensure the correct ordering of rules.  Low numbers
 
1051
        are processed before high numbers.
 
1052
 
 
1053
    @type preference: C{int}
 
1054
    @ivar preference: An integer that specifies the order in which NAPTR
 
1055
        records with equal "order" values SHOULD be processed, low numbers
 
1056
        being processed before high numbers.
 
1057
 
 
1058
    @type flag: L{Charstr}
 
1059
    @ivar flag: A <character-string> containing flags to control aspects of the
 
1060
        rewriting and interpretation of the fields in the record.  Flags
 
1061
        aresingle characters from the set [A-Z0-9].  The case of the alphabetic
 
1062
        characters is not significant.
 
1063
 
 
1064
        At this time only four flags, "S", "A", "U", and "P", are defined.
 
1065
 
 
1066
    @type service: L{Charstr}
 
1067
    @ivar service: Specifies the service(s) available down this rewrite path.
 
1068
        It may also specify the particular protocol that is used to talk with a
 
1069
        service.  A protocol MUST be specified if the flags field states that
 
1070
        the NAPTR is terminal.
 
1071
 
 
1072
    @type regexp: L{Charstr}
 
1073
    @ivar regexp: A STRING containing a substitution expression that is applied
 
1074
        to the original string held by the client in order to construct the
 
1075
        next domain name to lookup.
 
1076
 
 
1077
    @type replacement: L{Name}
 
1078
    @ivar replacement: The next NAME to query for NAPTR, SRV, or address
 
1079
        records depending on the value of the flags field.  This MUST be a
 
1080
        fully qualified domain-name.
 
1081
 
 
1082
    @type ttl: C{int}
 
1083
    @ivar ttl: The maximum number of seconds which this record should be
 
1084
        cached.
 
1085
 
 
1086
    @see: U{http://www.faqs.org/rfcs/rfc2915.html}
 
1087
    """
 
1088
    implements(IEncodable, IRecord)
 
1089
    TYPE = NAPTR
 
1090
 
 
1091
    compareAttributes = ('order', 'preference', 'flags', 'service', 'regexp',
 
1092
                         'replacement')
 
1093
    fancybasename = 'NAPTR'
 
1094
    showAttributes = ('order', 'preference', ('flags', 'flags', '%s'),
 
1095
                      ('service', 'service', '%s'), ('regexp', 'regexp', '%s'),
 
1096
                      ('replacement', 'replacement', '%s'), 'ttl')
 
1097
 
 
1098
    def __init__(self, order=0, preference=0, flags='', service='', regexp='',
 
1099
                 replacement='', ttl=None):
 
1100
        self.order = int(order)
 
1101
        self.preference = int(preference)
 
1102
        self.flags = Charstr(flags)
 
1103
        self.service = Charstr(service)
 
1104
        self.regexp = Charstr(regexp)
 
1105
        self.replacement = Name(replacement)
 
1106
        self.ttl = str2time(ttl)
 
1107
 
 
1108
 
 
1109
    def encode(self, strio, compDict=None):
 
1110
        strio.write(struct.pack('!HH', self.order, self.preference))
 
1111
        # This can't be compressed
 
1112
        self.flags.encode(strio, None)
 
1113
        self.service.encode(strio, None)
 
1114
        self.regexp.encode(strio, None)
 
1115
        self.replacement.encode(strio, None)
 
1116
 
 
1117
 
 
1118
    def decode(self, strio, length=None):
 
1119
        r = struct.unpack('!HH', readPrecisely(strio, struct.calcsize('!HH')))
 
1120
        self.order, self.preference = r
 
1121
        self.flags = Charstr()
 
1122
        self.service = Charstr()
 
1123
        self.regexp = Charstr()
 
1124
        self.replacement = Name()
 
1125
        self.flags.decode(strio)
 
1126
        self.service.decode(strio)
 
1127
        self.regexp.decode(strio)
 
1128
        self.replacement.decode(strio)
 
1129
 
 
1130
 
 
1131
    def __hash__(self):
 
1132
        return hash((
 
1133
            self.order, self.preference, self.flags,
 
1134
            self.service, self.regexp, self.replacement))
 
1135
 
 
1136
 
 
1137
 
 
1138
class Record_AFSDB(tputil.FancyStrMixin, tputil.FancyEqMixin):
 
1139
    """
 
1140
    Map from a domain name to the name of an AFS cell database server.
 
1141
 
 
1142
    @type subtype: C{int}
 
1143
    @ivar subtype: In the case of subtype 1, the host has an AFS version 3.0
 
1144
        Volume Location Server for the named AFS cell.  In the case of subtype
 
1145
        2, the host has an authenticated name server holding the cell-root
 
1146
        directory node for the named DCE/NCA cell.
 
1147
 
 
1148
    @type hostname: L{Name}
 
1149
    @ivar hostname: The domain name of a host that has a server for the cell
 
1150
        named by this record.
 
1151
 
 
1152
    @type ttl: C{int}
 
1153
    @ivar ttl: The maximum number of seconds which this record should be
 
1154
        cached.
 
1155
 
 
1156
    @see: U{http://www.faqs.org/rfcs/rfc1183.html}
 
1157
    """
 
1158
    implements(IEncodable, IRecord)
 
1159
    TYPE = AFSDB
 
1160
 
 
1161
    fancybasename = 'AFSDB'
 
1162
    compareAttributes = ('subtype', 'hostname', 'ttl')
 
1163
    showAttributes = ('subtype', ('hostname', 'hostname', '%s'), 'ttl')
 
1164
 
 
1165
    def __init__(self, subtype=0, hostname='', ttl=None):
 
1166
        self.subtype = int(subtype)
 
1167
        self.hostname = Name(hostname)
 
1168
        self.ttl = str2time(ttl)
 
1169
 
 
1170
 
 
1171
    def encode(self, strio, compDict = None):
 
1172
        strio.write(struct.pack('!H', self.subtype))
 
1173
        self.hostname.encode(strio, compDict)
 
1174
 
 
1175
 
 
1176
    def decode(self, strio, length = None):
 
1177
        r = struct.unpack('!H', readPrecisely(strio, struct.calcsize('!H')))
 
1178
        self.subtype, = r
 
1179
        self.hostname.decode(strio)
 
1180
 
 
1181
 
 
1182
    def __hash__(self):
 
1183
        return hash((self.subtype, self.hostname))
 
1184
 
 
1185
 
 
1186
 
 
1187
class Record_RP(tputil.FancyEqMixin, tputil.FancyStrMixin):
 
1188
    """
 
1189
    The responsible person for a domain.
 
1190
 
 
1191
    @type mbox: L{Name}
 
1192
    @ivar mbox: A domain name that specifies the mailbox for the responsible
 
1193
        person.
 
1194
 
 
1195
    @type txt: L{Name}
 
1196
    @ivar txt: A domain name for which TXT RR's exist (indirection through
 
1197
        which allows information sharing about the contents of this RP record).
 
1198
 
 
1199
    @type ttl: C{int}
 
1200
    @ivar ttl: The maximum number of seconds which this record should be
 
1201
        cached.
 
1202
 
 
1203
    @see: U{http://www.faqs.org/rfcs/rfc1183.html}
 
1204
    """
 
1205
    implements(IEncodable, IRecord)
 
1206
    TYPE = RP
 
1207
 
 
1208
    fancybasename = 'RP'
 
1209
    compareAttributes = ('mbox', 'txt', 'ttl')
 
1210
    showAttributes = (('mbox', 'mbox', '%s'), ('txt', 'txt', '%s'), 'ttl')
 
1211
 
 
1212
    def __init__(self, mbox='', txt='', ttl=None):
 
1213
        self.mbox = Name(mbox)
 
1214
        self.txt = Name(txt)
 
1215
        self.ttl = str2time(ttl)
 
1216
 
 
1217
 
 
1218
    def encode(self, strio, compDict = None):
 
1219
        self.mbox.encode(strio, compDict)
 
1220
        self.txt.encode(strio, compDict)
 
1221
 
 
1222
 
 
1223
    def decode(self, strio, length = None):
 
1224
        self.mbox = Name()
 
1225
        self.txt = Name()
 
1226
        self.mbox.decode(strio)
 
1227
        self.txt.decode(strio)
 
1228
 
 
1229
 
 
1230
    def __hash__(self):
 
1231
        return hash((self.mbox, self.txt))
 
1232
 
 
1233
 
 
1234
 
 
1235
class Record_HINFO(tputil.FancyStrMixin, tputil.FancyEqMixin):
 
1236
    """
 
1237
    Host information.
 
1238
 
 
1239
    @type cpu: C{str}
 
1240
    @ivar cpu: Specifies the CPU type.
 
1241
 
 
1242
    @type os: C{str}
 
1243
    @ivar os: Specifies the OS.
 
1244
 
 
1245
    @type ttl: C{int}
 
1246
    @ivar ttl: The maximum number of seconds which this record should be
 
1247
        cached.
 
1248
    """
 
1249
    implements(IEncodable, IRecord)
 
1250
    TYPE = HINFO
 
1251
 
 
1252
    fancybasename = 'HINFO'
 
1253
    showAttributes = compareAttributes = ('cpu', 'os', 'ttl')
 
1254
 
 
1255
    def __init__(self, cpu='', os='', ttl=None):
 
1256
        self.cpu, self.os = cpu, os
 
1257
        self.ttl = str2time(ttl)
 
1258
 
 
1259
 
 
1260
    def encode(self, strio, compDict = None):
 
1261
        strio.write(struct.pack('!B', len(self.cpu)) + self.cpu)
 
1262
        strio.write(struct.pack('!B', len(self.os)) + self.os)
 
1263
 
 
1264
 
 
1265
    def decode(self, strio, length = None):
 
1266
        cpu = struct.unpack('!B', readPrecisely(strio, 1))[0]
 
1267
        self.cpu = readPrecisely(strio, cpu)
 
1268
        os = struct.unpack('!B', readPrecisely(strio, 1))[0]
 
1269
        self.os = readPrecisely(strio, os)
 
1270
 
 
1271
 
 
1272
    def __eq__(self, other):
 
1273
        if isinstance(other, Record_HINFO):
 
1274
            return (self.os.lower() == other.os.lower() and
 
1275
                    self.cpu.lower() == other.cpu.lower() and
 
1276
                    self.ttl == other.ttl)
 
1277
        return NotImplemented
 
1278
 
 
1279
 
 
1280
    def __hash__(self):
 
1281
        return hash((self.os.lower(), self.cpu.lower()))
 
1282
 
 
1283
 
 
1284
 
 
1285
class Record_MINFO(tputil.FancyEqMixin, tputil.FancyStrMixin):
 
1286
    """
 
1287
    Mailbox or mail list information.
 
1288
 
 
1289
    This is an experimental record type.
 
1290
 
 
1291
    @type rmailbx: L{Name}
 
1292
    @ivar rmailbx: A domain-name which specifies a mailbox which is responsible
 
1293
        for the mailing list or mailbox.  If this domain name names the root,
 
1294
        the owner of the MINFO RR is responsible for itself.
 
1295
 
 
1296
    @type emailbx: L{Name}
 
1297
    @ivar emailbx: A domain-name which specifies a mailbox which is to receive
 
1298
        error messages related to the mailing list or mailbox specified by the
 
1299
        owner of the MINFO record.  If this domain name names the root, errors
 
1300
        should be returned to the sender of the message.
 
1301
 
 
1302
    @type ttl: C{int}
 
1303
    @ivar ttl: The maximum number of seconds which this record should be
 
1304
        cached.
 
1305
    """
 
1306
    implements(IEncodable, IRecord)
 
1307
    TYPE = MINFO
 
1308
 
 
1309
    rmailbx = None
 
1310
    emailbx = None
 
1311
 
 
1312
    fancybasename = 'MINFO'
 
1313
    compareAttributes = ('rmailbx', 'emailbx', 'ttl')
 
1314
    showAttributes = (('rmailbx', 'responsibility', '%s'),
 
1315
                      ('emailbx', 'errors', '%s'),
 
1316
                      'ttl')
 
1317
 
 
1318
    def __init__(self, rmailbx='', emailbx='', ttl=None):
 
1319
        self.rmailbx, self.emailbx = Name(rmailbx), Name(emailbx)
 
1320
        self.ttl = str2time(ttl)
 
1321
 
 
1322
 
 
1323
    def encode(self, strio, compDict = None):
 
1324
        self.rmailbx.encode(strio, compDict)
 
1325
        self.emailbx.encode(strio, compDict)
 
1326
 
 
1327
 
 
1328
    def decode(self, strio, length = None):
 
1329
        self.rmailbx, self.emailbx = Name(), Name()
 
1330
        self.rmailbx.decode(strio)
 
1331
        self.emailbx.decode(strio)
 
1332
 
 
1333
 
 
1334
    def __hash__(self):
 
1335
        return hash((self.rmailbx, self.emailbx))
 
1336
 
 
1337
 
 
1338
 
 
1339
class Record_MX(tputil.FancyStrMixin, tputil.FancyEqMixin):
 
1340
    """
 
1341
    Mail exchange.
 
1342
 
 
1343
    @type preference: C{int}
 
1344
    @ivar preference: Specifies the preference given to this RR among others at
 
1345
        the same owner.  Lower values are preferred.
 
1346
 
 
1347
    @type name: L{Name}
 
1348
    @ivar name: A domain-name which specifies a host willing to act as a mail
 
1349
        exchange.
 
1350
 
 
1351
    @type ttl: C{int}
 
1352
    @ivar ttl: The maximum number of seconds which this record should be
 
1353
        cached.
 
1354
    """
 
1355
    implements(IEncodable, IRecord)
 
1356
    TYPE = MX
 
1357
 
 
1358
    fancybasename = 'MX'
 
1359
    compareAttributes = ('preference', 'name', 'ttl')
 
1360
    showAttributes = ('preference', ('name', 'name', '%s'), 'ttl')
 
1361
 
 
1362
    def __init__(self, preference=0, name='', ttl=None, **kwargs):
 
1363
        self.preference, self.name = int(preference), Name(kwargs.get('exchange', name))
 
1364
        self.ttl = str2time(ttl)
 
1365
 
 
1366
    def encode(self, strio, compDict = None):
 
1367
        strio.write(struct.pack('!H', self.preference))
 
1368
        self.name.encode(strio, compDict)
 
1369
 
 
1370
 
 
1371
    def decode(self, strio, length = None):
 
1372
        self.preference = struct.unpack('!H', readPrecisely(strio, 2))[0]
 
1373
        self.name = Name()
 
1374
        self.name.decode(strio)
 
1375
 
 
1376
    def exchange(self):
 
1377
        warnings.warn("use Record_MX.name instead", DeprecationWarning, stacklevel=2)
 
1378
        return self.name
 
1379
 
 
1380
    exchange = property(exchange)
 
1381
 
 
1382
    def __hash__(self):
 
1383
        return hash((self.preference, self.name))
 
1384
 
 
1385
 
 
1386
 
 
1387
# Oh god, Record_TXT how I hate thee.
 
1388
class Record_TXT(tputil.FancyEqMixin, tputil.FancyStrMixin):
 
1389
    """
 
1390
    Freeform text.
 
1391
 
 
1392
    @type data: C{list} of C{str}
 
1393
    @ivar data: Freeform text which makes up this record.
 
1394
    """
 
1395
    implements(IEncodable, IRecord)
 
1396
 
 
1397
    TYPE = TXT
 
1398
 
 
1399
    fancybasename = 'TXT'
 
1400
    showAttributes = compareAttributes = ('data', 'ttl')
 
1401
 
 
1402
    def __init__(self, *data, **kw):
 
1403
        self.data = list(data)
 
1404
        # arg man python sucks so bad
 
1405
        self.ttl = str2time(kw.get('ttl', None))
 
1406
 
 
1407
 
 
1408
    def encode(self, strio, compDict = None):
 
1409
        for d in self.data:
 
1410
            strio.write(struct.pack('!B', len(d)) + d)
 
1411
 
 
1412
 
 
1413
    def decode(self, strio, length = None):
 
1414
        soFar = 0
 
1415
        self.data = []
 
1416
        while soFar < length:
 
1417
            L = struct.unpack('!B', readPrecisely(strio, 1))[0]
 
1418
            self.data.append(readPrecisely(strio, L))
 
1419
            soFar += L + 1
 
1420
        if soFar != length:
 
1421
            log.msg(
 
1422
                "Decoded %d bytes in TXT record, but rdlength is %d" % (
 
1423
                    soFar, length
 
1424
                )
 
1425
            )
 
1426
 
 
1427
 
 
1428
    def __hash__(self):
 
1429
        return hash(tuple(self.data))
 
1430
 
 
1431
 
 
1432
 
 
1433
class Message:
 
1434
    headerFmt = "!H2B4H"
 
1435
    headerSize = struct.calcsize(headerFmt)
 
1436
 
 
1437
    # Question, answer, additional, and nameserver lists
 
1438
    queries = answers = add = ns = None
 
1439
 
 
1440
    def __init__(self, id=0, answer=0, opCode=0, recDes=0, recAv=0,
 
1441
                       auth=0, rCode=OK, trunc=0, maxSize=512):
 
1442
        self.maxSize = maxSize
 
1443
        self.id = id
 
1444
        self.answer = answer
 
1445
        self.opCode = opCode
 
1446
        self.auth = auth
 
1447
        self.trunc = trunc
 
1448
        self.recDes = recDes
 
1449
        self.recAv = recAv
 
1450
        self.rCode = rCode
 
1451
        self.queries = []
 
1452
        self.answers = []
 
1453
        self.authority = []
 
1454
        self.additional = []
 
1455
 
 
1456
 
 
1457
    def addQuery(self, name, type=ALL_RECORDS, cls=IN):
 
1458
        """
 
1459
        Add another query to this Message.
 
1460
 
 
1461
        @type name: C{str}
 
1462
        @param name: The name to query.
 
1463
 
 
1464
        @type type: C{int}
 
1465
        @param type: Query type
 
1466
 
 
1467
        @type cls: C{int}
 
1468
        @param cls: Query class
 
1469
        """
 
1470
        self.queries.append(Query(name, type, cls))
 
1471
 
 
1472
 
 
1473
    def encode(self, strio):
 
1474
        compDict = {}
 
1475
        body_tmp = StringIO.StringIO()
 
1476
        for q in self.queries:
 
1477
            q.encode(body_tmp, compDict)
 
1478
        for q in self.answers:
 
1479
            q.encode(body_tmp, compDict)
 
1480
        for q in self.authority:
 
1481
            q.encode(body_tmp, compDict)
 
1482
        for q in self.additional:
 
1483
            q.encode(body_tmp, compDict)
 
1484
        body = body_tmp.getvalue()
 
1485
        size = len(body) + self.headerSize
 
1486
        if self.maxSize and size > self.maxSize:
 
1487
            self.trunc = 1
 
1488
            body = body[:self.maxSize - self.headerSize]
 
1489
        byte3 = (( ( self.answer & 1 ) << 7 )
 
1490
                 | ((self.opCode & 0xf ) << 3 )
 
1491
                 | ((self.auth & 1 ) << 2 )
 
1492
                 | ((self.trunc & 1 ) << 1 )
 
1493
                 | ( self.recDes & 1 ) )
 
1494
        byte4 = ( ( (self.recAv & 1 ) << 7 )
 
1495
                  | (self.rCode & 0xf ) )
 
1496
 
 
1497
        strio.write(struct.pack(self.headerFmt, self.id, byte3, byte4,
 
1498
                                len(self.queries), len(self.answers),
 
1499
                                len(self.authority), len(self.additional)))
 
1500
        strio.write(body)
 
1501
 
 
1502
 
 
1503
    def decode(self, strio, length=None):
 
1504
        self.maxSize = 0
 
1505
        header = readPrecisely(strio, self.headerSize)
 
1506
        r = struct.unpack(self.headerFmt, header)
 
1507
        self.id, byte3, byte4, nqueries, nans, nns, nadd = r
 
1508
        self.answer = ( byte3 >> 7 ) & 1
 
1509
        self.opCode = ( byte3 >> 3 ) & 0xf
 
1510
        self.auth = ( byte3 >> 2 ) & 1
 
1511
        self.trunc = ( byte3 >> 1 ) & 1
 
1512
        self.recDes = byte3 & 1
 
1513
        self.recAv = ( byte4 >> 7 ) & 1
 
1514
        self.rCode = byte4 & 0xf
 
1515
 
 
1516
        self.queries = []
 
1517
        for i in range(nqueries):
 
1518
            q = Query()
 
1519
            try:
 
1520
                q.decode(strio)
 
1521
            except EOFError:
 
1522
                return
 
1523
            self.queries.append(q)
 
1524
 
 
1525
        items = ((self.answers, nans), (self.authority, nns), (self.additional, nadd))
 
1526
        for (l, n) in items:
 
1527
            self.parseRecords(l, n, strio)
 
1528
 
 
1529
 
 
1530
    def parseRecords(self, list, num, strio):
 
1531
        for i in range(num):
 
1532
            header = RRHeader()
 
1533
            try:
 
1534
                header.decode(strio)
 
1535
            except EOFError:
 
1536
                return
 
1537
            t = self.lookupRecordType(header.type)
 
1538
            if not t:
 
1539
                continue
 
1540
            header.payload = t(ttl=header.ttl)
 
1541
            try:
 
1542
                header.payload.decode(strio, header.rdlength)
 
1543
            except EOFError:
 
1544
                return
 
1545
            list.append(header)
 
1546
 
 
1547
 
 
1548
    def lookupRecordType(self, type):
 
1549
        return globals().get('Record_' + QUERY_TYPES.get(type, ''), None)
 
1550
 
 
1551
 
 
1552
    def toStr(self):
 
1553
        strio = StringIO.StringIO()
 
1554
        self.encode(strio)
 
1555
        return strio.getvalue()
 
1556
 
 
1557
 
 
1558
    def fromStr(self, str):
 
1559
        strio = StringIO.StringIO(str)
 
1560
        self.decode(strio)
 
1561
 
 
1562
class DNSMixin(object):
 
1563
    """
 
1564
    DNS protocol mixin shared by UDP and TCP implementations.
 
1565
 
 
1566
    @ivar _reactor: A L{IReactorTime} and L{IReactorUDP} provider which will
 
1567
        be used to issue DNS queries and manage request timeouts.
 
1568
    """
 
1569
    id = None
 
1570
    liveMessages = None
 
1571
 
 
1572
    def __init__(self, controller, reactor=None):
 
1573
        self.controller = controller
 
1574
        self.id = random.randrange(2 ** 10, 2 ** 15)
 
1575
        if reactor is None:
 
1576
            from twisted.internet import reactor
 
1577
        self._reactor = reactor
 
1578
 
 
1579
 
 
1580
    def pickID(self):
 
1581
        """
 
1582
        Return a unique ID for queries.
 
1583
        """
 
1584
        while True:
 
1585
            id = randomSource()
 
1586
            if id not in self.liveMessages:
 
1587
                return id
 
1588
 
 
1589
 
 
1590
    def callLater(self, period, func, *args):
 
1591
        """
 
1592
        Wrapper around reactor.callLater, mainly for test purpose.
 
1593
        """
 
1594
        return self._reactor.callLater(period, func, *args)
 
1595
 
 
1596
 
 
1597
    def _query(self, queries, timeout, id, writeMessage):
 
1598
        """
 
1599
        Send out a message with the given queries.
 
1600
 
 
1601
        @type queries: C{list} of C{Query} instances
 
1602
        @param queries: The queries to transmit
 
1603
 
 
1604
        @type timeout: C{int} or C{float}
 
1605
        @param timeout: How long to wait before giving up
 
1606
 
 
1607
        @type id: C{int}
 
1608
        @param id: Unique key for this request
 
1609
 
 
1610
        @type writeMessage: C{callable}
 
1611
        @param writeMessage: One-parameter callback which writes the message
 
1612
 
 
1613
        @rtype: C{Deferred}
 
1614
        @return: a C{Deferred} which will be fired with the result of the
 
1615
            query, or errbacked with any errors that could happen (exceptions
 
1616
            during writing of the query, timeout errors, ...).
 
1617
        """
 
1618
        m = Message(id, recDes=1)
 
1619
        m.queries = queries
 
1620
 
 
1621
        try:
 
1622
            writeMessage(m)
 
1623
        except:
 
1624
            return defer.fail()
 
1625
 
 
1626
        resultDeferred = defer.Deferred()
 
1627
        cancelCall = self.callLater(timeout, self._clearFailed, resultDeferred, id)
 
1628
        self.liveMessages[id] = (resultDeferred, cancelCall)
 
1629
 
 
1630
        return resultDeferred
 
1631
 
 
1632
    def _clearFailed(self, deferred, id):
 
1633
        """
 
1634
        Clean the Deferred after a timeout.
 
1635
        """
 
1636
        try:
 
1637
            del self.liveMessages[id]
 
1638
        except KeyError:
 
1639
            pass
 
1640
        deferred.errback(failure.Failure(DNSQueryTimeoutError(id)))
 
1641
 
 
1642
 
 
1643
class DNSDatagramProtocol(DNSMixin, protocol.DatagramProtocol):
 
1644
    """
 
1645
    DNS protocol over UDP.
 
1646
    """
 
1647
    resends = None
 
1648
 
 
1649
    def stopProtocol(self):
 
1650
        """
 
1651
        Stop protocol: reset state variables.
 
1652
        """
 
1653
        self.liveMessages = {}
 
1654
        self.resends = {}
 
1655
        self.transport = None
 
1656
 
 
1657
    def startProtocol(self):
 
1658
        """
 
1659
        Upon start, reset internal state.
 
1660
        """
 
1661
        self.liveMessages = {}
 
1662
        self.resends = {}
 
1663
 
 
1664
    def writeMessage(self, message, address):
 
1665
        """
 
1666
        Send a message holding DNS queries.
 
1667
 
 
1668
        @type message: L{Message}
 
1669
        """
 
1670
        self.transport.write(message.toStr(), address)
 
1671
 
 
1672
    def startListening(self):
 
1673
        self._reactor.listenUDP(0, self, maxPacketSize=512)
 
1674
 
 
1675
    def datagramReceived(self, data, addr):
 
1676
        """
 
1677
        Read a datagram, extract the message in it and trigger the associated
 
1678
        Deferred.
 
1679
        """
 
1680
        m = Message()
 
1681
        try:
 
1682
            m.fromStr(data)
 
1683
        except EOFError:
 
1684
            log.msg("Truncated packet (%d bytes) from %s" % (len(data), addr))
 
1685
            return
 
1686
        except:
 
1687
            # Nothing should trigger this, but since we're potentially
 
1688
            # invoking a lot of different decoding methods, we might as well
 
1689
            # be extra cautious.  Anything that triggers this is itself
 
1690
            # buggy.
 
1691
            log.err(failure.Failure(), "Unexpected decoding error")
 
1692
            return
 
1693
 
 
1694
        if m.id in self.liveMessages:
 
1695
            d, canceller = self.liveMessages[m.id]
 
1696
            del self.liveMessages[m.id]
 
1697
            canceller.cancel()
 
1698
            # XXX we shouldn't need this hack of catching exception on callback()
 
1699
            try:
 
1700
                d.callback(m)
 
1701
            except:
 
1702
                log.err()
 
1703
        else:
 
1704
            if m.id not in self.resends:
 
1705
                self.controller.messageReceived(m, self, addr)
 
1706
 
 
1707
 
 
1708
    def removeResend(self, id):
 
1709
        """
 
1710
        Mark message ID as no longer having duplication suppression.
 
1711
        """
 
1712
        try:
 
1713
            del self.resends[id]
 
1714
        except KeyError:
 
1715
            pass
 
1716
 
 
1717
    def query(self, address, queries, timeout=10, id=None):
 
1718
        """
 
1719
        Send out a message with the given queries.
 
1720
 
 
1721
        @type address: C{tuple} of C{str} and C{int}
 
1722
        @param address: The address to which to send the query
 
1723
 
 
1724
        @type queries: C{list} of C{Query} instances
 
1725
        @param queries: The queries to transmit
 
1726
 
 
1727
        @rtype: C{Deferred}
 
1728
        """
 
1729
        if not self.transport:
 
1730
            # XXX transport might not get created automatically, use callLater?
 
1731
            try:
 
1732
                self.startListening()
 
1733
            except CannotListenError:
 
1734
                return defer.fail()
 
1735
 
 
1736
        if id is None:
 
1737
            id = self.pickID()
 
1738
        else:
 
1739
            self.resends[id] = 1
 
1740
 
 
1741
        def writeMessage(m):
 
1742
            self.writeMessage(m, address)
 
1743
 
 
1744
        return self._query(queries, timeout, id, writeMessage)
 
1745
 
 
1746
 
 
1747
class DNSProtocol(DNSMixin, protocol.Protocol):
 
1748
    """
 
1749
    DNS protocol over TCP.
 
1750
    """
 
1751
    length = None
 
1752
    buffer = ''
 
1753
 
 
1754
    def writeMessage(self, message):
 
1755
        """
 
1756
        Send a message holding DNS queries.
 
1757
 
 
1758
        @type message: L{Message}
 
1759
        """
 
1760
        s = message.toStr()
 
1761
        self.transport.write(struct.pack('!H', len(s)) + s)
 
1762
 
 
1763
    def connectionMade(self):
 
1764
        """
 
1765
        Connection is made: reset internal state, and notify the controller.
 
1766
        """
 
1767
        self.liveMessages = {}
 
1768
        self.controller.connectionMade(self)
 
1769
 
 
1770
 
 
1771
    def connectionLost(self, reason):
 
1772
        """
 
1773
        Notify the controller that this protocol is no longer
 
1774
        connected.
 
1775
        """
 
1776
        self.controller.connectionLost(self)
 
1777
 
 
1778
 
 
1779
    def dataReceived(self, data):
 
1780
        self.buffer += data
 
1781
 
 
1782
        while self.buffer:
 
1783
            if self.length is None and len(self.buffer) >= 2:
 
1784
                self.length = struct.unpack('!H', self.buffer[:2])[0]
 
1785
                self.buffer = self.buffer[2:]
 
1786
 
 
1787
            if len(self.buffer) >= self.length:
 
1788
                myChunk = self.buffer[:self.length]
 
1789
                m = Message()
 
1790
                m.fromStr(myChunk)
 
1791
 
 
1792
                try:
 
1793
                    d, canceller = self.liveMessages[m.id]
 
1794
                except KeyError:
 
1795
                    self.controller.messageReceived(m, self)
 
1796
                else:
 
1797
                    del self.liveMessages[m.id]
 
1798
                    canceller.cancel()
 
1799
                    # XXX we shouldn't need this hack
 
1800
                    try:
 
1801
                        d.callback(m)
 
1802
                    except:
 
1803
                        log.err()
 
1804
 
 
1805
                self.buffer = self.buffer[self.length:]
 
1806
                self.length = None
 
1807
            else:
 
1808
                break
 
1809
 
 
1810
 
 
1811
    def query(self, queries, timeout=60):
 
1812
        """
 
1813
        Send out a message with the given queries.
 
1814
 
 
1815
        @type queries: C{list} of C{Query} instances
 
1816
        @param queries: The queries to transmit
 
1817
 
 
1818
        @rtype: C{Deferred}
 
1819
        """
 
1820
        id = self.pickID()
 
1821
        return self._query(queries, timeout, id, self.writeMessage)
 
1822