forked from twisted/twisted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdns.py
3355 lines (2697 loc) · 96.7 KB
/
dns.py
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- test-case-name: twisted.names.test.test_dns -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
DNS protocol implementation.
Future Plans:
- Get rid of some toplevels, maybe.
"""
# System imports
import inspect
import random
import socket
import struct
from itertools import chain
from io import BytesIO
from typing import Optional, SupportsInt, Union
from zope.interface import implementer, Interface, Attribute
# Twisted imports
from twisted.internet import protocol, defer
from twisted.internet.error import CannotListenError
from twisted.python import log, failure
from twisted.python import util as tputil
from twisted.python import randbytes
from twisted.python.compat import comparable, cmp, nativeString
__all__ = [
"IEncodable",
"IRecord",
"IEncodableRecord",
"A",
"A6",
"AAAA",
"AFSDB",
"CNAME",
"DNAME",
"HINFO",
"MAILA",
"MAILB",
"MB",
"MD",
"MF",
"MG",
"MINFO",
"MR",
"MX",
"NAPTR",
"NS",
"NULL",
"OPT",
"PTR",
"RP",
"SOA",
"SPF",
"SRV",
"TXT",
"SSHFP",
"TSIG",
"WKS",
"ANY",
"CH",
"CS",
"HS",
"IN",
"ALL_RECORDS",
"AXFR",
"IXFR",
"EFORMAT",
"ENAME",
"ENOTIMP",
"EREFUSED",
"ESERVER",
"EBADVERSION",
"EBADSIG",
"EBADKEY",
"EBADTIME",
"Record_A",
"Record_A6",
"Record_AAAA",
"Record_AFSDB",
"Record_CNAME",
"Record_DNAME",
"Record_HINFO",
"Record_MB",
"Record_MD",
"Record_MF",
"Record_MG",
"Record_MINFO",
"Record_MR",
"Record_MX",
"Record_NAPTR",
"Record_NS",
"Record_NULL",
"Record_PTR",
"Record_RP",
"Record_SOA",
"Record_SPF",
"Record_SRV",
"Record_SSHFP",
"Record_TSIG",
"Record_TXT",
"Record_WKS",
"UnknownRecord",
"QUERY_CLASSES",
"QUERY_TYPES",
"REV_CLASSES",
"REV_TYPES",
"EXT_QUERIES",
"Charstr",
"Message",
"Name",
"Query",
"RRHeader",
"SimpleRecord",
"DNSDatagramProtocol",
"DNSMixin",
"DNSProtocol",
"OK",
"OP_INVERSE",
"OP_NOTIFY",
"OP_QUERY",
"OP_STATUS",
"OP_UPDATE",
"PORT",
"AuthoritativeDomainError",
"DNSQueryTimeoutError",
"DomainError",
]
AF_INET6 = socket.AF_INET6
def _ord2bytes(ordinal):
"""
Construct a bytes object representing a single byte with the given
ordinal value.
@type ordinal: L{int}
@rtype: L{bytes}
"""
return bytes([ordinal])
def _nicebytes(bytes):
"""
Represent a mostly textful bytes object in a way suitable for
presentation to an end user.
@param bytes: The bytes to represent.
@rtype: L{str}
"""
return repr(bytes)[1:]
def _nicebyteslist(list):
"""
Represent a list of mostly textful bytes objects in a way suitable for
presentation to an end user.
@param list: The list of bytes to represent.
@rtype: L{str}
"""
return "[{}]".format(", ".join([_nicebytes(b) for b in list]))
def randomSource():
"""
Wrapper around L{twisted.python.randbytes.RandomFactory.secureRandom} to
return 2 random bytes.
@rtype: L{bytes}
"""
return struct.unpack("H", randbytes.secureRandom(2, fallback=True))[0]
PORT = 53
(
A,
NS,
MD,
MF,
CNAME,
SOA,
MB,
MG,
MR,
NULL,
WKS,
PTR,
HINFO,
MINFO,
MX,
TXT,
RP,
AFSDB,
) = range(1, 19)
AAAA = 28
SRV = 33
NAPTR = 35
A6 = 38
DNAME = 39
OPT = 41
SSHFP = 44
SPF = 99
# These record types do not exist in zones, but are transferred in
# messages the same way normal RRs are.
TKEY = 249
TSIG = 250
QUERY_TYPES = {
A: "A",
NS: "NS",
MD: "MD",
MF: "MF",
CNAME: "CNAME",
SOA: "SOA",
MB: "MB",
MG: "MG",
MR: "MR",
NULL: "NULL",
WKS: "WKS",
PTR: "PTR",
HINFO: "HINFO",
MINFO: "MINFO",
MX: "MX",
TXT: "TXT",
RP: "RP",
AFSDB: "AFSDB",
# 19 through 27? Eh, I'll get to 'em.
AAAA: "AAAA",
SRV: "SRV",
NAPTR: "NAPTR",
A6: "A6",
DNAME: "DNAME",
OPT: "OPT",
SSHFP: "SSHFP",
SPF: "SPF",
TKEY: "TKEY",
TSIG: "TSIG",
}
IXFR, AXFR, MAILB, MAILA, ALL_RECORDS = range(251, 256)
# "Extended" queries (Hey, half of these are deprecated, good job)
EXT_QUERIES = {
IXFR: "IXFR",
AXFR: "AXFR",
MAILB: "MAILB",
MAILA: "MAILA",
ALL_RECORDS: "ALL_RECORDS",
}
REV_TYPES = {v: k for (k, v) in chain(QUERY_TYPES.items(), EXT_QUERIES.items())}
IN, CS, CH, HS = range(1, 5)
ANY = 255
QUERY_CLASSES = {IN: "IN", CS: "CS", CH: "CH", HS: "HS", ANY: "ANY"}
REV_CLASSES = {v: k for (k, v) in QUERY_CLASSES.items()}
# Opcodes
OP_QUERY, OP_INVERSE, OP_STATUS = range(3)
OP_NOTIFY = 4 # RFC 1996
OP_UPDATE = 5 # RFC 2136
# Response Codes
OK, EFORMAT, ESERVER, ENAME, ENOTIMP, EREFUSED = range(6)
# https://tools.ietf.org/html/rfc6891#section-9
EBADVERSION = 16
# RFC 2845
EBADSIG, EBADKEY, EBADTIME = range(16, 19)
class IRecord(Interface):
"""
A single entry in a zone of authority.
"""
TYPE = Attribute("An indicator of what kind of record this is.")
# Backwards compatibility aliases - these should be deprecated or something I
# suppose. -exarkun
from twisted.names.error import DomainError, AuthoritativeDomainError
from twisted.names.error import DNSQueryTimeoutError
def _nameToLabels(name):
"""
Split a domain name into its constituent labels.
@type name: L{bytes}
@param name: A fully qualified domain name (with or without a
trailing dot).
@return: A L{list} of labels ending with an empty label
representing the DNS root zone.
@rtype: L{list} of L{bytes}
"""
if name in (b"", b"."):
return [b""]
labels = name.split(b".")
if labels[-1] != b"":
labels.append(b"")
return labels
def domainString(domain):
"""
Coerce a domain name string to bytes.
L{twisted.names} represents domain names as L{bytes}, but many interfaces
accept L{bytes} or a text string (L{unicode} on Python 2, L{str} on Python
3). This function coerces text strings using IDNA encoding --- see
L{encodings.idna}.
Note that DNS is I{case insensitive} but I{case preserving}. This function
doesn't normalize case, so you'll still need to do that whenever comparing
the strings it returns.
@param domain: A domain name. If passed as a text string it will be
C{idna} encoded.
@type domain: L{bytes} or L{str}
@returns: L{bytes} suitable for network transmission.
@rtype: L{bytes}
@since: Twisted 20.3.0
"""
if isinstance(domain, str):
domain = domain.encode("idna")
if not isinstance(domain, bytes):
raise TypeError(
"Expected {} or {} but found {!r} of type {}".format(
type(b"").__name__, type("").__name__, domain, type(domain)
)
)
return domain
def _isSubdomainOf(descendantName, ancestorName):
"""
Test whether C{descendantName} is equal to or is a I{subdomain} of
C{ancestorName}.
The names are compared case-insensitively.
The names are treated as byte strings containing one or more
DNS labels separated by B{.}.
C{descendantName} is considered equal if its sequence of labels
exactly matches the labels of C{ancestorName}.
C{descendantName} is considered a I{subdomain} if its sequence of
labels ends with the labels of C{ancestorName}.
@type descendantName: L{bytes}
@param descendantName: The DNS subdomain name.
@type ancestorName: L{bytes}
@param ancestorName: The DNS parent or ancestor domain name.
@return: C{True} if C{descendantName} is equal to or if it is a
subdomain of C{ancestorName}. Otherwise returns C{False}.
"""
descendantLabels = _nameToLabels(descendantName.lower())
ancestorLabels = _nameToLabels(ancestorName.lower())
return descendantLabels[-len(ancestorLabels) :] == ancestorLabels
def str2time(s):
"""
Parse a string description of an interval into an integer number of seconds.
@param s: An interval definition constructed as an interval duration
followed by an interval unit. An interval duration is a base ten
representation of an integer. An interval unit is one of the following
letters: S (seconds), M (minutes), H (hours), D (days), W (weeks), or Y
(years). For example: C{"3S"} indicates an interval of three seconds;
C{"5D"} indicates an interval of five days. Alternatively, C{s} may be
any non-string and it will be returned unmodified.
@type s: text string (L{bytes} or L{str}) for parsing; anything else
for passthrough.
@return: an L{int} giving the interval represented by the string C{s}, or
whatever C{s} is if it is not a string.
"""
suffixes = (
("S", 1),
("M", 60),
("H", 60 * 60),
("D", 60 * 60 * 24),
("W", 60 * 60 * 24 * 7),
("Y", 60 * 60 * 24 * 365),
)
if isinstance(s, bytes):
s = s.decode("ascii")
if isinstance(s, str):
s = s.upper().strip()
for (suff, mult) in suffixes:
if s.endswith(suff):
return int(float(s[:-1]) * mult)
try:
s = int(s)
except ValueError:
raise ValueError("Invalid time interval specifier: " + s)
return s
def readPrecisely(file, l):
buff = file.read(l)
if len(buff) < l:
raise EOFError
return buff
class IEncodable(Interface):
"""
Interface for something which can be encoded to and decoded
to the DNS wire format.
A binary-mode file object (such as L{io.BytesIO}) is used as a buffer when
encoding or decoding.
"""
def encode(strio, compDict=None):
"""
Write a representation of this object to the given
file object.
@type strio: File-like object
@param strio: The buffer to write to. It must have a C{tell()} method.
@type compDict: L{dict} of L{bytes} to L{int} r L{None}
@param compDict: A mapping of names to byte offsets that have already
been written to the buffer, which may be used for compression (see RFC
1035 section 4.1.4). When L{None}, encode without compression.
"""
def decode(strio, length=None):
"""
Reconstruct an object from data read from the given
file object.
@type strio: File-like object
@param strio: A seekable buffer from which bytes may be read.
@type length: L{int} or L{None}
@param length: The number of bytes in this RDATA field. Most
implementations can ignore this value. Only in the case of
records similar to TXT where the total length is in no way
encoded in the data is it necessary.
"""
class IEncodableRecord(IEncodable, IRecord):
"""
Interface for DNS records that can be encoded and decoded.
@since: Twisted 21.2.0
"""
@implementer(IEncodable)
class Charstr:
def __init__(self, string=b""):
if not isinstance(string, bytes):
raise ValueError(f"{string!r} is not a byte string")
self.string = string
def encode(self, strio, compDict=None):
"""
Encode this Character string into the appropriate byte format.
@type strio: file
@param strio: The byte representation of this Charstr will be written
to this file.
"""
string = self.string
ind = len(string)
strio.write(_ord2bytes(ind))
strio.write(string)
def decode(self, strio, length=None):
"""
Decode a byte string into this Charstr.
@type strio: file
@param strio: Bytes will be read from this file until the full string
is decoded.
@raise EOFError: Raised when there are not enough bytes available from
C{strio}.
"""
self.string = b""
l = ord(readPrecisely(strio, 1))
self.string = readPrecisely(strio, l)
def __eq__(self, other: object) -> bool:
if isinstance(other, Charstr):
return self.string == other.string
return NotImplemented
def __hash__(self):
return hash(self.string)
def __str__(self) -> str:
"""
Represent this L{Charstr} instance by its string value.
"""
return nativeString(self.string)
@implementer(IEncodable)
class Name:
"""
A name in the domain name system, made up of multiple labels. For example,
I{twistedmatrix.com}.
@ivar name: A byte string giving the name.
@type name: L{bytes}
"""
def __init__(self, name=b""):
"""
@param name: A name.
@type name: L{bytes} or L{str}
"""
self.name = domainString(name)
def encode(self, strio, compDict=None):
"""
Encode this Name into the appropriate byte format.
@type strio: file
@param strio: The byte representation of this Name will be written to
this file.
@type compDict: dict
@param compDict: dictionary of Names that have already been encoded
and whose addresses may be backreferenced by this Name (for the purpose
of reducing the message size).
"""
name = self.name
while name:
if compDict is not None:
if name in compDict:
strio.write(struct.pack("!H", 0xC000 | compDict[name]))
return
else:
compDict[name] = strio.tell() + Message.headerSize
ind = name.find(b".")
if ind > 0:
label, name = name[:ind], name[ind + 1 :]
else:
# This is the last label, end the loop after handling it.
label = name
name = None
ind = len(label)
strio.write(_ord2bytes(ind))
strio.write(label)
strio.write(b"\x00")
def decode(self, strio, length=None):
"""
Decode a byte string into this Name.
@type strio: file
@param strio: Bytes will be read from this file until the full Name
is decoded.
@raise EOFError: Raised when there are not enough bytes available
from C{strio}.
@raise ValueError: Raised when the name cannot be decoded (for example,
because it contains a loop).
"""
visited = set()
self.name = b""
off = 0
while 1:
l = ord(readPrecisely(strio, 1))
if l == 0:
if off > 0:
strio.seek(off)
return
if (l >> 6) == 3:
new_off = (l & 63) << 8 | ord(readPrecisely(strio, 1))
if new_off in visited:
raise ValueError("Compression loop in encoded name")
visited.add(new_off)
if off == 0:
off = strio.tell()
strio.seek(new_off)
continue
label = readPrecisely(strio, l)
if self.name == b"":
self.name = label
else:
self.name = self.name + b"." + label
def __eq__(self, other: object) -> bool:
if isinstance(other, Name):
return self.name.lower() == other.name.lower()
return NotImplemented
def __hash__(self):
return hash(self.name)
def __str__(self) -> str:
"""
Represent this L{Name} instance by its string name.
"""
return nativeString(self.name)
@comparable
@implementer(IEncodable)
class Query:
"""
Represent a single DNS query.
@ivar name: The name about which this query is requesting information.
@type name: L{Name}
@ivar type: The query type.
@type type: L{int}
@ivar cls: The query class.
@type cls: L{int}
"""
def __init__(self, name: Union[bytes, str] = b"", type: int = A, cls: int = IN):
"""
@type name: L{bytes} or L{str}
@param name: See L{Query.name}
@type type: L{int}
@param type: The query type.
@type cls: L{int}
@param cls: The query class.
"""
self.name = Name(name)
self.type = type
self.cls = cls
def encode(self, strio, compDict=None):
self.name.encode(strio, compDict)
strio.write(struct.pack("!HH", self.type, self.cls))
def decode(self, strio, length=None):
self.name.decode(strio)
buff = readPrecisely(strio, 4)
self.type, self.cls = struct.unpack("!HH", buff)
def __hash__(self):
return hash((self.name.name.lower(), self.type, self.cls))
def __cmp__(self, other):
if isinstance(other, Query):
return cmp(
(self.name.name.lower(), self.type, self.cls),
(other.name.name.lower(), other.type, other.cls),
)
return NotImplemented
def __str__(self) -> str:
t = QUERY_TYPES.get(
self.type, EXT_QUERIES.get(self.type, "UNKNOWN (%d)" % self.type)
)
c = QUERY_CLASSES.get(self.cls, "UNKNOWN (%d)" % self.cls)
return f"<Query {self.name} {t} {c}>"
def __repr__(self) -> str:
return f"Query({self.name.name!r}, {self.type!r}, {self.cls!r})"
@implementer(IEncodable)
class _OPTHeader(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
An OPT record header.
@ivar name: The DNS name associated with this record. Since this
is a pseudo record, the name is always an L{Name} instance
with value b'', which represents the DNS root zone. This
attribute is a readonly property.
@ivar type: The DNS record type. This is a fixed value of 41
C{dns.OPT} for OPT Record. This attribute is a readonly
property.
@see: L{_OPTHeader.__init__} for documentation of other public
instance attributes.
@see: U{https://tools.ietf.org/html/rfc6891#section-6.1.2}
@since: 13.2
"""
showAttributes = (
("name", lambda n: nativeString(n.name)),
"type",
"udpPayloadSize",
"extendedRCODE",
"version",
"dnssecOK",
"options",
)
compareAttributes = (
"name",
"type",
"udpPayloadSize",
"extendedRCODE",
"version",
"dnssecOK",
"options",
)
def __init__(
self,
udpPayloadSize=4096,
extendedRCODE=0,
version=0,
dnssecOK=False,
options=None,
):
"""
@type udpPayloadSize: L{int}
@param udpPayloadSize: The number of octets of the largest UDP
payload that can be reassembled and delivered in the
requestor's network stack.
@type extendedRCODE: L{int}
@param extendedRCODE: Forms the upper 8 bits of extended
12-bit RCODE (together with the 4 bits defined in
[RFC1035]. Note that EXTENDED-RCODE value 0 indicates
that an unextended RCODE is in use (values 0 through 15).
@type version: L{int}
@param version: Indicates the implementation level of the
setter. Full conformance with this specification is
indicated by version C{0}.
@type dnssecOK: L{bool}
@param dnssecOK: DNSSEC OK bit as defined by [RFC3225].
@type options: L{list}
@param options: A L{list} of 0 or more L{_OPTVariableOption}
instances.
"""
self.udpPayloadSize = udpPayloadSize
self.extendedRCODE = extendedRCODE
self.version = version
self.dnssecOK = dnssecOK
if options is None:
options = []
self.options = options
@property
def name(self):
"""
A readonly property for accessing the C{name} attribute of
this record.
@return: The DNS name associated with this record. Since this
is a pseudo record, the name is always an L{Name} instance
with value b'', which represents the DNS root zone.
"""
return Name(b"")
@property
def type(self):
"""
A readonly property for accessing the C{type} attribute of
this record.
@return: The DNS record type. This is a fixed value of 41
(C{dns.OPT} for OPT Record.
"""
return OPT
def encode(self, strio, compDict=None):
"""
Encode this L{_OPTHeader} instance to bytes.
@type strio: file
@param strio: the byte representation of this L{_OPTHeader}
will be written to this file.
@type compDict: L{dict} or L{None}
@param compDict: A dictionary of backreference addresses that
have already been written to this stream and that may
be used for DNS name compression.
"""
b = BytesIO()
for o in self.options:
o.encode(b)
optionBytes = b.getvalue()
RRHeader(
name=self.name.name,
type=self.type,
cls=self.udpPayloadSize,
ttl=(self.extendedRCODE << 24 | self.version << 16 | self.dnssecOK << 15),
payload=UnknownRecord(optionBytes),
).encode(strio, compDict)
def decode(self, strio, length=None):
"""
Decode bytes into an L{_OPTHeader} instance.
@type strio: file
@param strio: Bytes will be read from this file until the full
L{_OPTHeader} is decoded.
@type length: L{int} or L{None}
@param length: Not used.
"""
h = RRHeader()
h.decode(strio, length)
h.payload = UnknownRecord(readPrecisely(strio, h.rdlength))
newOptHeader = self.fromRRHeader(h)
for attrName in self.compareAttributes:
if attrName not in ("name", "type"):
setattr(self, attrName, getattr(newOptHeader, attrName))
@classmethod
def fromRRHeader(cls, rrHeader):
"""
A classmethod for constructing a new L{_OPTHeader} from the
attributes and payload of an existing L{RRHeader} instance.
@type rrHeader: L{RRHeader}
@param rrHeader: An L{RRHeader} instance containing an
L{UnknownRecord} payload.
@return: An instance of L{_OPTHeader}.
@rtype: L{_OPTHeader}
"""
options = None
if rrHeader.payload is not None:
options = []
optionsBytes = BytesIO(rrHeader.payload.data)
optionsBytesLength = len(rrHeader.payload.data)
while optionsBytes.tell() < optionsBytesLength:
o = _OPTVariableOption()
o.decode(optionsBytes)
options.append(o)
# Decode variable options if present
return cls(
udpPayloadSize=rrHeader.cls,
extendedRCODE=rrHeader.ttl >> 24,
version=rrHeader.ttl >> 16 & 0xFF,
dnssecOK=(rrHeader.ttl & 0xFFFF) >> 15,
options=options,
)
@implementer(IEncodable)
class _OPTVariableOption(tputil.FancyStrMixin, tputil.FancyEqMixin):
"""
A class to represent OPT record variable options.
@see: L{_OPTVariableOption.__init__} for documentation of public
instance attributes.
@see: U{https://tools.ietf.org/html/rfc6891#section-6.1.2}
@since: 13.2
"""
showAttributes = ("code", ("data", nativeString))
compareAttributes = ("code", "data")
_fmt = "!HH"
def __init__(self, code=0, data=b""):
"""
@type code: L{int}
@param code: The option code
@type data: L{bytes}
@param data: The option data
"""
self.code = code
self.data = data
def encode(self, strio, compDict=None):
"""
Encode this L{_OPTVariableOption} to bytes.
@type strio: file
@param strio: the byte representation of this
L{_OPTVariableOption} will be written to this file.
@type compDict: L{dict} or L{None}
@param compDict: A dictionary of backreference addresses that
have already been written to this stream and that may
be used for DNS name compression.
"""
strio.write(struct.pack(self._fmt, self.code, len(self.data)) + self.data)
def decode(self, strio, length=None):
"""
Decode bytes into an L{_OPTVariableOption} instance.
@type strio: file
@param strio: Bytes will be read from this file until the full
L{_OPTVariableOption} is decoded.
@type length: L{int} or L{None}
@param length: Not used.
"""
l = struct.calcsize(self._fmt)
buff = readPrecisely(strio, l)
self.code, length = struct.unpack(self._fmt, buff)
self.data = readPrecisely(strio, length)
@implementer(IEncodable)
class RRHeader(tputil.FancyEqMixin):
"""
A resource record header.
@cvar fmt: L{str} specifying the byte format of an RR.
@ivar name: The name about which this reply contains information.
@type name: L{Name}
@ivar type: The query type of the original request.
@type type: L{int}
@ivar cls: The query class of the original request.
@ivar ttl: The time-to-live for this record.
@type ttl: L{int}
@ivar payload: The record described by this header.
@type payload: L{IEncodableRecord} or L{None}
@ivar auth: A L{bool} indicating whether this C{RRHeader} was parsed from
an authoritative message.
"""
compareAttributes = ("name", "type", "cls", "ttl", "payload", "auth")
fmt = "!HHIH"
rdlength = None
cachedResponse = None
def __init__(
self,
name: Union[bytes, str] = b"",
type: int = A,
cls: int = IN,
ttl: SupportsInt = 0,
payload: Optional[IEncodableRecord] = None,
auth: bool = False,
):
"""
@type name: L{bytes} or L{str}
@param name: See L{RRHeader.name}
@type type: L{int}
@param type: The query type.
@type cls: L{int}
@param cls: The query class.
@type ttl: L{int}
@param ttl: Time to live for this record. This will be
converted to an L{int}.
@type payload: L{IEncodableRecord} or L{None}
@param payload: An optional Query Type specific data object.
@raises TypeError: if the ttl cannot be converted to an L{int}.
@raises ValueError: if the ttl is negative.