id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
22,100
wiredata.py
wummel_linkchecker/third_party/dnspython/dns/wiredata.py
# Copyright (C) 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Wire Data Helper""" import sys import dns.exception class WireData(str): # WireData is a string with stricter slicing def __getitem__(self, key): try: return WireData(super(WireData, self).__getitem__(key)) except IndexError: raise dns.exception.FormError def __getslice__(self, i, j): try: if j == sys.maxint: # handle the case where the right bound is unspecified j = len(self) if i < 0 or j < 0: raise dns.exception.FormError # If it's not an empty slice, access left and right bounds # to make sure they're valid if i != j: super(WireData, self).__getitem__(i) super(WireData, self).__getitem__(j - 1) return WireData(super(WireData, self).__getslice__(i, j)) except IndexError: raise dns.exception.FormError def __iter__(self): i = 0 while 1: try: yield self[i] i += 1 except dns.exception.FormError: raise StopIteration def unwrap(self): return str(self) def maybe_wrap(wire): if not isinstance(wire, WireData): return WireData(wire) else: return wire
2,100
Python
.py
54
31.12963
72
0.639392
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,101
set.py
wummel_linkchecker/third_party/dnspython/dns/set.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """A simple Set class.""" class Set(object): """A simple set class. Sets are not in Python until 2.3, and rdata are not immutable so we cannot use sets.Set anyway. This class implements subset of the 2.3 Set interface using a list as the container. @ivar items: A list of the items which are in the set @type items: list""" __slots__ = ['items'] def __init__(self, items=None): """Initialize the set. @param items: the initial set of items @type items: any iterable or None """ self.items = [] if not items is None: for item in items: self.add(item) def __repr__(self): return "dns.simpleset.Set(%s)" % repr(self.items) def add(self, item): """Add an item to the set.""" if not item in self.items: self.items.append(item) def remove(self, item): """Remove an item from the set.""" self.items.remove(item) def discard(self, item): """Remove an item from the set if present.""" try: self.items.remove(item) except ValueError: pass def _clone(self): """Make a (shallow) copy of the set. There is a 'clone protocol' that subclasses of this class should use. To make a copy, first call your super's _clone() method, and use the object returned as the new instance. Then make shallow copies of the attributes defined in the subclass. This protocol allows us to write the set algorithms that return new instances (e.g. union) once, and keep using them in subclasses. """ cls = self.__class__ obj = cls.__new__(cls) obj.items = list(self.items) return obj def __copy__(self): """Make a (shallow) copy of the set.""" return self._clone() def copy(self): """Make a (shallow) copy of the set.""" return self._clone() def union_update(self, other): """Update the set, adding any elements from other which are not already in the set. @param other: the collection of items with which to update the set @type other: Set object """ if not isinstance(other, Set): raise ValueError('other must be a Set instance') if self is other: return for item in other.items: self.add(item) def intersection_update(self, other): """Update the set, removing any elements from other which are not in both sets. @param other: the collection of items with which to update the set @type other: Set object """ if not isinstance(other, Set): raise ValueError('other must be a Set instance') if self is other: return # we make a copy of the list so that we can remove items from # the list without breaking the iterator. for item in list(self.items): if item not in other.items: self.items.remove(item) def difference_update(self, other): """Update the set, removing any elements from other which are in the set. @param other: the collection of items with which to update the set @type other: Set object """ if not isinstance(other, Set): raise ValueError('other must be a Set instance') if self is other: self.items = [] else: for item in other.items: self.discard(item) def union(self, other): """Return a new set which is the union of I{self} and I{other}. @param other: the other set @type other: Set object @rtype: the same type as I{self} """ obj = self._clone() obj.union_update(other) return obj def intersection(self, other): """Return a new set which is the intersection of I{self} and I{other}. @param other: the other set @type other: Set object @rtype: the same type as I{self} """ obj = self._clone() obj.intersection_update(other) return obj def difference(self, other): """Return a new set which I{self} - I{other}, i.e. the items in I{self} which are not also in I{other}. @param other: the other set @type other: Set object @rtype: the same type as I{self} """ obj = self._clone() obj.difference_update(other) return obj def __or__(self, other): return self.union(other) def __and__(self, other): return self.intersection(other) def __add__(self, other): return self.union(other) def __sub__(self, other): return self.difference(other) def __ior__(self, other): self.union_update(other) return self def __iand__(self, other): self.intersection_update(other) return self def __iadd__(self, other): self.union_update(other) return self def __isub__(self, other): self.difference_update(other) return self def update(self, other): """Update the set, adding any elements from other which are not already in the set. @param other: the collection of items with which to update the set @type other: any iterable type""" for item in other: self.add(item) def clear(self): """Make the set empty.""" self.items = [] def __hash__(self): return hash(self.items) def __eq__(self, other): # Yes, this is inefficient but the sets we're dealing with are # usually quite small, so it shouldn't hurt too much. for item in self.items: if not item in other.items: return False for item in other.items: if not item in self.items: return False return True def __ne__(self, other): return not self.__eq__(other) def __len__(self): return len(self.items) def __iter__(self): return iter(self.items) def __getitem__(self, i): return self.items[i] def __delitem__(self, i): del self.items[i] def __getslice__(self, i, j): return self.items[i:j] def __delslice__(self, i, j): del self.items[i:j] def issubset(self, other): """Is I{self} a subset of I{other}? @rtype: bool """ if not isinstance(other, Set): raise ValueError('other must be a Set instance') for item in self.items: if not item in other.items: return False return True def issuperset(self, other): """Is I{self} a superset of I{other}? @rtype: bool """ if not isinstance(other, Set): raise ValueError('other must be a Set instance') for item in other.items: if not item in self.items: return False return True
7,899
Python
.py
211
28.933649
78
0.602908
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,102
hash.py
wummel_linkchecker/third_party/dnspython/dns/hash.py
# Copyright (C) 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Hashing backwards compatibility wrapper""" import sys _hashes = None def _need_later_python(alg): def func(*args, **kwargs): raise NotImplementedError("TSIG algorithm " + alg + " requires Python 2.5.2 or later") return func def _setup(): global _hashes _hashes = {} try: import hashlib _hashes['MD5'] = hashlib.md5 _hashes['SHA1'] = hashlib.sha1 _hashes['SHA224'] = hashlib.sha224 _hashes['SHA256'] = hashlib.sha256 if sys.hexversion >= 0x02050200: _hashes['SHA384'] = hashlib.sha384 _hashes['SHA512'] = hashlib.sha512 else: _hashes['SHA384'] = _need_later_python('SHA384') _hashes['SHA512'] = _need_later_python('SHA512') if sys.hexversion < 0x02050000: # hashlib doesn't conform to PEP 247: API for # Cryptographic Hash Functions, which hmac before python # 2.5 requires, so add the necessary items. class HashlibWrapper: def __init__(self, basehash): self.basehash = basehash self.digest_size = self.basehash().digest_size def new(self, *args, **kwargs): return self.basehash(*args, **kwargs) for name in _hashes: _hashes[name] = HashlibWrapper(_hashes[name]) except ImportError: import md5, sha _hashes['MD5'] = md5 _hashes['SHA1'] = sha def get(algorithm): if _hashes is None: _setup() return _hashes[algorithm.upper()]
2,395
Python
.py
57
34.070175
72
0.640893
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,103
ipv4.py
wummel_linkchecker/third_party/dnspython/dns/ipv4.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """IPv4 helper functions.""" import socket import sys if sys.hexversion < 0x02030000 or sys.platform == 'win32': # # Some versions of Python 2.2 have an inet_aton which rejects # the valid IP address '255.255.255.255'. It appears this # problem is still present on the Win32 platform even in 2.3. # We'll work around the problem. # def inet_aton(text): if text == '255.255.255.255': return '\xff' * 4 else: return socket.inet_aton(text) else: inet_aton = socket.inet_aton inet_ntoa = socket.inet_ntoa
1,364
Python
.py
32
39.25
72
0.737952
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,104
flags.py
wummel_linkchecker/third_party/dnspython/dns/flags.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Message Flags.""" # Standard DNS flags QR = 0x8000 AA = 0x0400 TC = 0x0200 RD = 0x0100 RA = 0x0080 AD = 0x0020 CD = 0x0010 # EDNS flags DO = 0x8000 _by_text = { 'QR' : QR, 'AA' : AA, 'TC' : TC, 'RD' : RD, 'RA' : RA, 'AD' : AD, 'CD' : CD } _edns_by_text = { 'DO' : DO } # We construct the inverse mappings programmatically to ensure that we # cannot make any mistakes (e.g. omissions, cut-and-paste errors) that # would cause the mappings not to be true inverses. _by_value = dict([(y, x) for x, y in _by_text.iteritems()]) _edns_by_value = dict([(y, x) for x, y in _edns_by_text.iteritems()]) def _order_flags(table): order = list(table.iteritems()) order.sort() order.reverse() return order _flags_order = _order_flags(_by_value) _edns_flags_order = _order_flags(_edns_by_value) def _from_text(text, table): flags = 0 tokens = text.split() for t in tokens: flags = flags | table[t.upper()] return flags def _to_text(flags, table, order): text_flags = [] for k, v in order: if flags & k != 0: text_flags.append(v) return ' '.join(text_flags) def from_text(text): """Convert a space-separated list of flag text values into a flags value. @rtype: int""" return _from_text(text, _by_text) def to_text(flags): """Convert a flags value into a space-separated list of flag text values. @rtype: string""" return _to_text(flags, _by_value, _flags_order) def edns_from_text(text): """Convert a space-separated list of EDNS flag text values into a EDNS flags value. @rtype: int""" return _from_text(text, _edns_by_text) def edns_to_text(flags): """Convert an EDNS flags value into a space-separated list of EDNS flag text values. @rtype: string""" return _to_text(flags, _edns_by_value, _edns_flags_order)
2,682
Python
.py
81
29.728395
75
0.692935
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,105
exception.py
wummel_linkchecker/third_party/dnspython/dns/exception.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Common DNS Exceptions.""" class DNSException(Exception): """Abstract base class shared by all dnspython exceptions.""" pass class FormError(DNSException): """DNS message is malformed.""" pass class SyntaxError(DNSException): """Text input is malformed.""" pass class UnexpectedEnd(SyntaxError): """Raised if text input ends unexpectedly.""" pass class TooBig(DNSException): """The message is too big.""" pass class Timeout(DNSException): """The operation timed out.""" pass
1,318
Python
.py
33
37.272727
72
0.762911
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,106
renderer.py
wummel_linkchecker/third_party/dnspython/dns/renderer.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Help for building DNS wire format messages""" import cStringIO import struct import random import time import dns.exception import dns.tsig QUESTION = 0 ANSWER = 1 AUTHORITY = 2 ADDITIONAL = 3 class Renderer(object): """Helper class for building DNS wire-format messages. Most applications can use the higher-level L{dns.message.Message} class and its to_wire() method to generate wire-format messages. This class is for those applications which need finer control over the generation of messages. Typical use:: r = dns.renderer.Renderer(id=1, flags=0x80, max_size=512) r.add_question(qname, qtype, qclass) r.add_rrset(dns.renderer.ANSWER, rrset_1) r.add_rrset(dns.renderer.ANSWER, rrset_2) r.add_rrset(dns.renderer.AUTHORITY, ns_rrset) r.add_edns(0, 0, 4096) r.add_rrset(dns.renderer.ADDTIONAL, ad_rrset_1) r.add_rrset(dns.renderer.ADDTIONAL, ad_rrset_2) r.write_header() r.add_tsig(keyname, secret, 300, 1, 0, '', request_mac) wire = r.get_wire() @ivar output: where rendering is written @type output: cStringIO.StringIO object @ivar id: the message id @type id: int @ivar flags: the message flags @type flags: int @ivar max_size: the maximum size of the message @type max_size: int @ivar origin: the origin to use when rendering relative names @type origin: dns.name.Name object @ivar compress: the compression table @type compress: dict @ivar section: the section currently being rendered @type section: int (dns.renderer.QUESTION, dns.renderer.ANSWER, dns.renderer.AUTHORITY, or dns.renderer.ADDITIONAL) @ivar counts: list of the number of RRs in each section @type counts: int list of length 4 @ivar mac: the MAC of the rendered message (if TSIG was used) @type mac: string """ def __init__(self, id=None, flags=0, max_size=65535, origin=None): """Initialize a new renderer. @param id: the message id @type id: int @param flags: the DNS message flags @type flags: int @param max_size: the maximum message size; the default is 65535. If rendering results in a message greater than I{max_size}, then L{dns.exception.TooBig} will be raised. @type max_size: int @param origin: the origin to use when rendering relative names @type origin: dns.name.Namem or None. """ self.output = cStringIO.StringIO() if id is None: self.id = random.randint(0, 65535) else: self.id = id self.flags = flags self.max_size = max_size self.origin = origin self.compress = {} self.section = QUESTION self.counts = [0, 0, 0, 0] self.output.write('\x00' * 12) self.mac = '' def _rollback(self, where): """Truncate the output buffer at offset I{where}, and remove any compression table entries that pointed beyond the truncation point. @param where: the offset @type where: int """ self.output.seek(where) self.output.truncate() keys_to_delete = [] for k, v in self.compress.iteritems(): if v >= where: keys_to_delete.append(k) for k in keys_to_delete: del self.compress[k] def _set_section(self, section): """Set the renderer's current section. Sections must be rendered order: QUESTION, ANSWER, AUTHORITY, ADDITIONAL. Sections may be empty. @param section: the section @type section: int @raises dns.exception.FormError: an attempt was made to set a section value less than the current section. """ if self.section != section: if self.section > section: raise dns.exception.FormError self.section = section def add_question(self, qname, rdtype, rdclass=dns.rdataclass.IN): """Add a question to the message. @param qname: the question name @type qname: dns.name.Name @param rdtype: the question rdata type @type rdtype: int @param rdclass: the question rdata class @type rdclass: int """ self._set_section(QUESTION) before = self.output.tell() qname.to_wire(self.output, self.compress, self.origin) self.output.write(struct.pack("!HH", rdtype, rdclass)) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.counts[QUESTION] += 1 def add_rrset(self, section, rrset, **kw): """Add the rrset to the specified section. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param rrset: the rrset @type rrset: dns.rrset.RRset object """ self._set_section(section) before = self.output.tell() n = rrset.to_wire(self.output, self.compress, self.origin, **kw) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.counts[section] += n def add_rdataset(self, section, name, rdataset, **kw): """Add the rdataset to the specified section, using the specified name as the owner name. Any keyword arguments are passed on to the rdataset's to_wire() routine. @param section: the section @type section: int @param name: the owner name @type name: dns.name.Name object @param rdataset: the rdataset @type rdataset: dns.rdataset.Rdataset object """ self._set_section(section) before = self.output.tell() n = rdataset.to_wire(name, self.output, self.compress, self.origin, **kw) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.counts[section] += n def add_edns(self, edns, ednsflags, payload, options=None): """Add an EDNS OPT record to the message. @param edns: The EDNS level to use. @type edns: int @param ednsflags: EDNS flag values. @type ednsflags: int @param payload: The EDNS sender's payload field, which is the maximum size of UDP datagram the sender can handle. @type payload: int @param options: The EDNS options list @type options: list of dns.edns.Option instances @see: RFC 2671 """ # make sure the EDNS version in ednsflags agrees with edns ednsflags &= 0xFF00FFFFL ednsflags |= (edns << 16) self._set_section(ADDITIONAL) before = self.output.tell() self.output.write(struct.pack('!BHHIH', 0, dns.rdatatype.OPT, payload, ednsflags, 0)) if not options is None: lstart = self.output.tell() for opt in options: stuff = struct.pack("!HH", opt.otype, 0) self.output.write(stuff) start = self.output.tell() opt.to_wire(self.output) end = self.output.tell() assert end - start < 65536 self.output.seek(start - 2) stuff = struct.pack("!H", end - start) self.output.write(stuff) self.output.seek(0, 2) lend = self.output.tell() assert lend - lstart < 65536 self.output.seek(lstart - 2) stuff = struct.pack("!H", lend - lstart) self.output.write(stuff) self.output.seek(0, 2) after = self.output.tell() if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.counts[ADDITIONAL] += 1 def add_tsig(self, keyname, secret, fudge, id, tsig_error, other_data, request_mac, algorithm=dns.tsig.default_algorithm): """Add a TSIG signature to the message. @param keyname: the TSIG key name @type keyname: dns.name.Name object @param secret: the secret to use @type secret: string @param fudge: TSIG time fudge @type fudge: int @param id: the message id to encode in the tsig signature @type id: int @param tsig_error: TSIG error code; default is 0. @type tsig_error: int @param other_data: TSIG other data. @type other_data: string @param request_mac: This message is a response to the request which had the specified MAC. @type request_mac: string @param algorithm: the TSIG algorithm to use @type algorithm: dns.name.Name object """ self._set_section(ADDITIONAL) before = self.output.tell() s = self.output.getvalue() (tsig_rdata, self.mac, ctx) = dns.tsig.sign(s, keyname, secret, int(time.time()), fudge, id, tsig_error, other_data, request_mac, algorithm=algorithm) keyname.to_wire(self.output, self.compress, self.origin) self.output.write(struct.pack('!HHIH', dns.rdatatype.TSIG, dns.rdataclass.ANY, 0, 0)) rdata_start = self.output.tell() self.output.write(tsig_rdata) after = self.output.tell() assert after - rdata_start < 65536 if after >= self.max_size: self._rollback(before) raise dns.exception.TooBig self.output.seek(rdata_start - 2) self.output.write(struct.pack('!H', after - rdata_start)) self.counts[ADDITIONAL] += 1 self.output.seek(10) self.output.write(struct.pack('!H', self.counts[ADDITIONAL])) self.output.seek(0, 2) def write_header(self): """Write the DNS message header. Writing the DNS message header is done asfter all sections have been rendered, but before the optional TSIG signature is added. """ self.output.seek(0) self.output.write(struct.pack('!HHHHHH', self.id, self.flags, self.counts[0], self.counts[1], self.counts[2], self.counts[3])) self.output.seek(0, 2) def get_wire(self): """Return the wire format message. @rtype: string """ return self.output.getvalue()
11,910
Python
.py
283
31.572438
78
0.597151
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,107
namedict.py
wummel_linkchecker/third_party/dnspython/dns/namedict.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS name dictionary""" import dns.name class NameDict(dict): """A dictionary whose keys are dns.name.Name objects. @ivar max_depth: the maximum depth of the keys that have ever been added to the dictionary. @type max_depth: int """ def __init__(self, *args, **kwargs): super(NameDict, self).__init__(*args, **kwargs) self.max_depth = 0 def __setitem__(self, key, value): if not isinstance(key, dns.name.Name): raise ValueError('NameDict key must be a name') depth = len(key) if depth > self.max_depth: self.max_depth = depth super(NameDict, self).__setitem__(key, value) def get_deepest_match(self, name): """Find the deepest match to I{name} in the dictionary. The deepest match is the longest name in the dictionary which is a superdomain of I{name}. @param name: the name @type name: dns.name.Name object @rtype: (key, value) tuple """ depth = len(name) if depth > self.max_depth: depth = self.max_depth for i in xrange(-depth, 0): n = dns.name.Name(name[i:]) if n in self: return (n, self[n]) v = self[dns.name.empty] return (dns.name.empty, v)
2,100
Python
.py
49
36.510204
72
0.66732
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,108
name.py
wummel_linkchecker/third_party/dnspython/dns/name.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Names. @var root: The DNS root name. @type root: dns.name.Name object @var empty: The empty DNS name. @type empty: dns.name.Name object """ import cStringIO import struct import sys if sys.hexversion >= 0x02030000: import encodings.idna import dns.exception import dns.wiredata NAMERELN_NONE = 0 NAMERELN_SUPERDOMAIN = 1 NAMERELN_SUBDOMAIN = 2 NAMERELN_EQUAL = 3 NAMERELN_COMMONANCESTOR = 4 class EmptyLabel(dns.exception.SyntaxError): """Raised if a label is empty.""" pass class BadEscape(dns.exception.SyntaxError): """Raised if an escaped code in a text format name is invalid.""" pass class BadPointer(dns.exception.FormError): """Raised if a compression pointer points forward instead of backward.""" pass class BadLabelType(dns.exception.FormError): """Raised if the label type of a wire format name is unknown.""" pass class NeedAbsoluteNameOrOrigin(dns.exception.DNSException): """Raised if an attempt is made to convert a non-absolute name to wire when there is also a non-absolute (or missing) origin.""" pass class NameTooLong(dns.exception.FormError): """Raised if a name is > 255 octets long.""" pass class LabelTooLong(dns.exception.SyntaxError): """Raised if a label is > 63 octets long.""" pass class AbsoluteConcatenation(dns.exception.DNSException): """Raised if an attempt is made to append anything other than the empty name to an absolute name.""" pass class NoParent(dns.exception.DNSException): """Raised if an attempt is made to get the parent of the root name or the empty name.""" pass _escaped = { '"' : True, '(' : True, ')' : True, '.' : True, ';' : True, '\\' : True, '@' : True, '$' : True } def _escapify(label): """Escape the characters in label which need it. @returns: the escaped string @rtype: string""" text = '' for c in label: if c in _escaped: text += '\\' + c elif ord(c) > 0x20 and ord(c) < 0x7F: text += c else: text += '\\%03d' % ord(c) return text def _validate_labels(labels): """Check for empty labels in the middle of a label sequence, labels that are too long, and for too many labels. @raises NameTooLong: the name as a whole is too long @raises LabelTooLong: an individual label is too long @raises EmptyLabel: a label is empty (i.e. the root label) and appears in a position other than the end of the label sequence""" l = len(labels) total = 0 i = -1 j = 0 for label in labels: ll = len(label) total += ll + 1 if ll > 63: raise LabelTooLong if i < 0 and label == '': i = j j += 1 if total > 255: raise NameTooLong if i >= 0 and i != l - 1: raise EmptyLabel class Name(object): """A DNS name. The dns.name.Name class represents a DNS name as a tuple of labels. Instances of the class are immutable. @ivar labels: The tuple of labels in the name. Each label is a string of up to 63 octets.""" __slots__ = ['labels'] def __init__(self, labels): """Initialize a domain name from a list of labels. @param labels: the labels @type labels: any iterable whose values are strings """ super(Name, self).__setattr__('labels', tuple(labels)) _validate_labels(self.labels) def __setattr__(self, name, value): raise TypeError("object doesn't support attribute assignment") def is_absolute(self): """Is the most significant label of this name the root label? @rtype: bool """ return len(self.labels) > 0 and self.labels[-1] == '' def is_wild(self): """Is this name wild? (I.e. Is the least significant label '*'?) @rtype: bool """ return len(self.labels) > 0 and self.labels[0] == '*' def __hash__(self): """Return a case-insensitive hash of the name. @rtype: int """ h = 0L for label in self.labels: for c in label: h += ( h << 3 ) + ord(c.lower()) return int(h % sys.maxint) def fullcompare(self, other): """Compare two names, returning a 3-tuple (relation, order, nlabels). I{relation} describes the relation ship beween the names, and is one of: dns.name.NAMERELN_NONE, dns.name.NAMERELN_SUPERDOMAIN, dns.name.NAMERELN_SUBDOMAIN, dns.name.NAMERELN_EQUAL, or dns.name.NAMERELN_COMMONANCESTOR I{order} is < 0 if self < other, > 0 if self > other, and == 0 if self == other. A relative name is always less than an absolute name. If both names have the same relativity, then the DNSSEC order relation is used to order them. I{nlabels} is the number of significant labels that the two names have in common. """ sabs = self.is_absolute() oabs = other.is_absolute() if sabs != oabs: if sabs: return (NAMERELN_NONE, 1, 0) else: return (NAMERELN_NONE, -1, 0) l1 = len(self.labels) l2 = len(other.labels) ldiff = l1 - l2 if ldiff < 0: l = l1 else: l = l2 order = 0 nlabels = 0 namereln = NAMERELN_NONE while l > 0: l -= 1 l1 -= 1 l2 -= 1 label1 = self.labels[l1].lower() label2 = other.labels[l2].lower() if label1 < label2: order = -1 if nlabels > 0: namereln = NAMERELN_COMMONANCESTOR return (namereln, order, nlabels) elif label1 > label2: order = 1 if nlabels > 0: namereln = NAMERELN_COMMONANCESTOR return (namereln, order, nlabels) nlabels += 1 order = ldiff if ldiff < 0: namereln = NAMERELN_SUPERDOMAIN elif ldiff > 0: namereln = NAMERELN_SUBDOMAIN else: namereln = NAMERELN_EQUAL return (namereln, order, nlabels) def is_subdomain(self, other): """Is self a subdomain of other? The notion of subdomain includes equality. @rtype: bool """ (nr, o, nl) = self.fullcompare(other) if nr == NAMERELN_SUBDOMAIN or nr == NAMERELN_EQUAL: return True return False def is_superdomain(self, other): """Is self a superdomain of other? The notion of subdomain includes equality. @rtype: bool """ (nr, o, nl) = self.fullcompare(other) if nr == NAMERELN_SUPERDOMAIN or nr == NAMERELN_EQUAL: return True return False def canonicalize(self): """Return a name which is equal to the current name, but is in DNSSEC canonical form. @rtype: dns.name.Name object """ return Name([x.lower() for x in self.labels]) def __eq__(self, other): if isinstance(other, Name): return self.fullcompare(other)[1] == 0 else: return False def __ne__(self, other): if isinstance(other, Name): return self.fullcompare(other)[1] != 0 else: return True def __lt__(self, other): if isinstance(other, Name): return self.fullcompare(other)[1] < 0 else: return NotImplemented def __le__(self, other): if isinstance(other, Name): return self.fullcompare(other)[1] <= 0 else: return NotImplemented def __ge__(self, other): if isinstance(other, Name): return self.fullcompare(other)[1] >= 0 else: return NotImplemented def __gt__(self, other): if isinstance(other, Name): return self.fullcompare(other)[1] > 0 else: return NotImplemented def __repr__(self): return '<DNS name ' + self.__str__() + '>' def __str__(self): return self.to_text(False) def to_text(self, omit_final_dot = False): """Convert name to text format. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string """ if len(self.labels) == 0: return '@' if len(self.labels) == 1 and self.labels[0] == '': return '.' if omit_final_dot and self.is_absolute(): l = self.labels[:-1] else: l = self.labels s = '.'.join(map(_escapify, l)) return s def to_unicode(self, omit_final_dot = False): """Convert name to Unicode text format. IDN ACE lables are converted to Unicode. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string """ if len(self.labels) == 0: return u'@' if len(self.labels) == 1 and self.labels[0] == '': return u'.' if omit_final_dot and self.is_absolute(): l = self.labels[:-1] else: l = self.labels s = u'.'.join([encodings.idna.ToUnicode(_escapify(x)) for x in l]) return s def to_digestable(self, origin=None): """Convert name to a format suitable for digesting in hashes. The name is canonicalized and converted to uncompressed wire format. @param origin: If the name is relative and origin is not None, then origin will be appended to it. @type origin: dns.name.Name object @raises NeedAbsoluteNameOrOrigin: All names in wire format are absolute. If self is a relative name, then an origin must be supplied; if it is missing, then this exception is raised @rtype: string """ if not self.is_absolute(): if origin is None or not origin.is_absolute(): raise NeedAbsoluteNameOrOrigin labels = list(self.labels) labels.extend(list(origin.labels)) else: labels = self.labels dlabels = ["%s%s" % (chr(len(x)), x.lower()) for x in labels] return ''.join(dlabels) def to_wire(self, file = None, compress = None, origin = None): """Convert name to wire format, possibly compressing it. @param file: the file where the name is emitted (typically a cStringIO file). If None, a string containing the wire name will be returned. @type file: file or None @param compress: The compression table. If None (the default) names will not be compressed. @type compress: dict @param origin: If the name is relative and origin is not None, then origin will be appended to it. @type origin: dns.name.Name object @raises NeedAbsoluteNameOrOrigin: All names in wire format are absolute. If self is a relative name, then an origin must be supplied; if it is missing, then this exception is raised """ if file is None: file = cStringIO.StringIO() want_return = True else: want_return = False if not self.is_absolute(): if origin is None or not origin.is_absolute(): raise NeedAbsoluteNameOrOrigin labels = list(self.labels) labels.extend(list(origin.labels)) else: labels = self.labels i = 0 for label in labels: n = Name(labels[i:]) i += 1 if not compress is None: pos = compress.get(n) else: pos = None if not pos is None: value = 0xc000 + pos s = struct.pack('!H', value) file.write(s) break else: if not compress is None and len(n) > 1: pos = file.tell() if pos < 0xc000: compress[n] = pos l = len(label) file.write(chr(l)) if l > 0: file.write(label) if want_return: return file.getvalue() def __len__(self): """The length of the name (in labels). @rtype: int """ return len(self.labels) def __getitem__(self, index): return self.labels[index] def __getslice__(self, start, stop): return self.labels[start:stop] def __add__(self, other): return self.concatenate(other) def __sub__(self, other): return self.relativize(other) def split(self, depth): """Split a name into a prefix and suffix at depth. @param depth: the number of labels in the suffix @type depth: int @raises ValueError: the depth was not >= 0 and <= the length of the name. @returns: the tuple (prefix, suffix) @rtype: tuple """ l = len(self.labels) if depth == 0: return (self, dns.name.empty) elif depth == l: return (dns.name.empty, self) elif depth < 0 or depth > l: raise ValueError('depth must be >= 0 and <= the length of the name') return (Name(self[: -depth]), Name(self[-depth :])) def concatenate(self, other): """Return a new name which is the concatenation of self and other. @rtype: dns.name.Name object @raises AbsoluteConcatenation: self is absolute and other is not the empty name """ if self.is_absolute() and len(other) > 0: raise AbsoluteConcatenation labels = list(self.labels) labels.extend(list(other.labels)) return Name(labels) def relativize(self, origin): """If self is a subdomain of origin, return a new name which is self relative to origin. Otherwise return self. @rtype: dns.name.Name object """ if not origin is None and self.is_subdomain(origin): return Name(self[: -len(origin)]) else: return self def derelativize(self, origin): """If self is a relative name, return a new name which is the concatenation of self and origin. Otherwise return self. @rtype: dns.name.Name object """ if not self.is_absolute(): return self.concatenate(origin) else: return self def choose_relativity(self, origin=None, relativize=True): """Return a name with the relativity desired by the caller. If origin is None, then self is returned. Otherwise, if relativize is true the name is relativized, and if relativize is false the name is derelativized. @rtype: dns.name.Name object """ if origin: if relativize: return self.relativize(origin) else: return self.derelativize(origin) else: return self def parent(self): """Return the parent of the name. @rtype: dns.name.Name object @raises NoParent: the name is either the root name or the empty name, and thus has no parent. """ if self == root or self == empty: raise NoParent return Name(self.labels[1:]) root = Name(['']) empty = Name([]) def from_unicode(text, origin = root): """Convert unicode text into a Name object. Lables are encoded in IDN ACE form. @rtype: dns.name.Name object """ if not isinstance(text, unicode): raise ValueError("input to from_unicode() must be a unicode string") if not (origin is None or isinstance(origin, Name)): raise ValueError("origin must be a Name or None") labels = [] label = u'' escaping = False edigits = 0 total = 0 if text == u'@': text = u'' if text: if text == u'.': return Name(['']) # no Unicode "u" on this constant! for c in text: if escaping: if edigits == 0: if c.isdigit(): total = int(c) edigits += 1 else: label += c escaping = False else: if not c.isdigit(): raise BadEscape total *= 10 total += int(c) edigits += 1 if edigits == 3: escaping = False label += chr(total) elif c == u'.' or c == u'\u3002' or \ c == u'\uff0e' or c == u'\uff61': if len(label) == 0: raise EmptyLabel labels.append(encodings.idna.ToASCII(label)) label = u'' elif c == u'\\': escaping = True edigits = 0 total = 0 else: label += c if escaping: raise BadEscape if len(label) > 0: labels.append(encodings.idna.ToASCII(label)) else: labels.append('') if (len(labels) == 0 or labels[-1] != '') and not origin is None: labels.extend(list(origin.labels)) return Name(labels) def from_text(text, origin = root): """Convert text into a Name object. @rtype: dns.name.Name object """ if not isinstance(text, str): if isinstance(text, unicode) and sys.hexversion >= 0x02030000: return from_unicode(text, origin) else: raise ValueError("input to from_text() must be a string") if not (origin is None or isinstance(origin, Name)): raise ValueError("origin must be a Name or None") labels = [] label = '' escaping = False edigits = 0 total = 0 if text == '@': text = '' if text: if text == '.': return Name(['']) for c in text: if escaping: if edigits == 0: if c.isdigit(): total = int(c) edigits += 1 else: label += c escaping = False else: if not c.isdigit(): raise BadEscape total *= 10 total += int(c) edigits += 1 if edigits == 3: escaping = False label += chr(total) elif c == '.': if len(label) == 0: raise EmptyLabel labels.append(label) label = '' elif c == '\\': escaping = True edigits = 0 total = 0 else: label += c if escaping: raise BadEscape if len(label) > 0: labels.append(label) else: labels.append('') if (len(labels) == 0 or labels[-1] != '') and not origin is None: labels.extend(list(origin.labels)) return Name(labels) def from_wire(message, current): """Convert possibly compressed wire format into a Name. @param message: the entire DNS message @type message: string @param current: the offset of the beginning of the name from the start of the message @type current: int @raises dns.name.BadPointer: a compression pointer did not point backwards in the message @raises dns.name.BadLabelType: an invalid label type was encountered. @returns: a tuple consisting of the name that was read and the number of bytes of the wire format message which were consumed reading it @rtype: (dns.name.Name object, int) tuple """ if not isinstance(message, str): raise ValueError("input to from_wire() must be a byte string") message = dns.wiredata.maybe_wrap(message) labels = [] biggest_pointer = current hops = 0 count = ord(message[current]) current += 1 cused = 1 while count != 0: if count < 64: labels.append(message[current : current + count].unwrap()) current += count if hops == 0: cused += count elif count >= 192: current = (count & 0x3f) * 256 + ord(message[current]) if hops == 0: cused += 1 if current >= biggest_pointer: raise BadPointer biggest_pointer = current hops += 1 else: raise BadLabelType count = ord(message[current]) current += 1 if hops == 0: cused += 1 labels.append('') return (Name(labels), cused)
21,980
Python
.py
607
26.558484
80
0.564715
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,109
rrset.py
wummel_linkchecker/third_party/dnspython/dns/rrset.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS RRsets (an RRset is a named rdataset)""" import dns.name import dns.rdataset import dns.rdataclass import dns.renderer class RRset(dns.rdataset.Rdataset): """A DNS RRset (named rdataset). RRset inherits from Rdataset, and RRsets can be treated as Rdatasets in most cases. There are, however, a few notable exceptions. RRsets have different to_wire() and to_text() method arguments, reflecting the fact that RRsets always have an owner name. """ __slots__ = ['name', 'deleting'] def __init__(self, name, rdclass, rdtype, covers=dns.rdatatype.NONE, deleting=None): """Create a new RRset.""" super(RRset, self).__init__(rdclass, rdtype, covers) self.name = name self.deleting = deleting def _clone(self): obj = super(RRset, self)._clone() obj.name = self.name obj.deleting = self.deleting return obj def __repr__(self): if self.covers == 0: ctext = '' else: ctext = '(' + dns.rdatatype.to_text(self.covers) + ')' if not self.deleting is None: dtext = ' delete=' + dns.rdataclass.to_text(self.deleting) else: dtext = '' return '<DNS ' + str(self.name) + ' ' + \ dns.rdataclass.to_text(self.rdclass) + ' ' + \ dns.rdatatype.to_text(self.rdtype) + ctext + dtext + ' RRset>' def __str__(self): return self.to_text() def __hash__(self): return hash(self.name) + super(RRSet, self).__hash__() def __eq__(self, other): """Two RRsets are equal if they have the same name and the same rdataset @rtype: bool""" if not isinstance(other, RRset): return False if self.name != other.name: return False return super(RRset, self).__eq__(other) def match(self, name, rdclass, rdtype, covers, deleting=None): """Returns True if this rrset matches the specified class, type, covers, and deletion state.""" if not super(RRset, self).match(rdclass, rdtype, covers): return False if self.name != name or self.deleting != deleting: return False return True def to_text(self, origin=None, relativize=True, **kw): """Convert the RRset into DNS master file format. @see: L{dns.name.Name.choose_relativity} for more information on how I{origin} and I{relativize} determine the way names are emitted. Any additional keyword arguments are passed on to the rdata to_text() method. @param origin: The origin for relative names, or None. @type origin: dns.name.Name object @param relativize: True if names should names be relativized @type relativize: bool""" return super(RRset, self).to_text(self.name, origin, relativize, self.deleting, **kw) def to_wire(self, file, compress=None, origin=None, **kw): """Convert the RRset to wire format.""" return super(RRset, self).to_wire(self.name, file, compress, origin, self.deleting, **kw) def to_rdataset(self): """Convert an RRset into an Rdataset. @rtype: dns.rdataset.Rdataset object """ return dns.rdataset.from_rdata_list(self.ttl, list(self)) def from_text_list(name, ttl, rdclass, rdtype, text_rdatas): """Create an RRset with the specified name, TTL, class, and type, and with the specified list of rdatas in text format. @rtype: dns.rrset.RRset object """ if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if isinstance(rdclass, (str, unicode)): rdclass = dns.rdataclass.from_text(rdclass) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) r = RRset(name, rdclass, rdtype) r.update_ttl(ttl) for t in text_rdatas: rd = dns.rdata.from_text(r.rdclass, r.rdtype, t) r.add(rd) return r def from_text(name, ttl, rdclass, rdtype, *text_rdatas): """Create an RRset with the specified name, TTL, class, and type and with the specified rdatas in text format. @rtype: dns.rrset.RRset object """ return from_text_list(name, ttl, rdclass, rdtype, text_rdatas) def from_rdata_list(name, ttl, rdatas): """Create an RRset with the specified name and TTL, and with the specified list of rdata objects. @rtype: dns.rrset.RRset object """ if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if len(rdatas) == 0: raise ValueError("rdata list must not be empty") r = None for rd in rdatas: if r is None: r = RRset(name, rd.rdclass, rd.rdtype) r.update_ttl(ttl) first_time = False r.add(rd) return r def from_rdata(name, ttl, *rdatas): """Create an RRset with the specified name and TTL, and with the specified rdata objects. @rtype: dns.rrset.RRset object """ return from_rdata_list(name, ttl, rdatas)
5,983
Python
.py
140
35.242857
78
0.642377
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,110
ttl.py
wummel_linkchecker/third_party/dnspython/dns/ttl.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS TTL conversion.""" import dns.exception class BadTTL(dns.exception.SyntaxError): pass def from_text(text): """Convert the text form of a TTL to an integer. The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported. @param text: the textual TTL @type text: string @raises dns.ttl.BadTTL: the TTL is not well-formed @rtype: int """ if text.isdigit(): total = long(text) else: if not text[0].isdigit(): raise BadTTL total = 0L current = 0L for c in text: if c.isdigit(): current *= 10 current += long(c) else: c = c.lower() if c == 'w': total += current * 604800L elif c == 'd': total += current * 86400L elif c == 'h': total += current * 3600L elif c == 'm': total += current * 60L elif c == 's': total += current else: raise BadTTL("unknown unit '%s'" % c) current = 0 if not current == 0: raise BadTTL("trailing integer") if total < 0L or total > 2147483647L: raise BadTTL("TTL should be between 0 and 2^31 - 1 (inclusive)") return total
2,179
Python
.py
57
29.526316
72
0.598582
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,111
rdata.py
wummel_linkchecker/third_party/dnspython/dns/rdata.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS rdata. @var _rdata_modules: A dictionary mapping a (rdclass, rdtype) tuple to the module which implements that type. @type _rdata_modules: dict @var _module_prefix: The prefix to use when forming modules names. The default is 'dns.rdtypes'. Changing this value will break the library. @type _module_prefix: string @var _hex_chunk: At most this many octets that will be represented in each chunk of hexstring that _hexify() produces before whitespace occurs. @type _hex_chunk: int""" import cStringIO import dns.exception import dns.name import dns.rdataclass import dns.rdatatype import dns.tokenizer import dns.wiredata _hex_chunksize = 32 def _hexify(data, chunksize=None): """Convert a binary string into its hex encoding, broken up into chunks of I{chunksize} characters separated by a space. @param data: the binary string @type data: string @param chunksize: the chunk size. Default is L{dns.rdata._hex_chunksize} @rtype: string """ if chunksize is None: chunksize = _hex_chunksize hex = data.encode('hex_codec') l = len(hex) if l > chunksize: chunks = [] i = 0 while i < l: chunks.append(hex[i : i + chunksize]) i += chunksize hex = ' '.join(chunks) return hex _base64_chunksize = 32 def _base64ify(data, chunksize=None): """Convert a binary string into its base64 encoding, broken up into chunks of I{chunksize} characters separated by a space. @param data: the binary string @type data: string @param chunksize: the chunk size. Default is L{dns.rdata._base64_chunksize} @rtype: string """ if chunksize is None: chunksize = _base64_chunksize b64 = data.encode('base64_codec') b64 = b64.replace('\n', '') l = len(b64) if l > chunksize: chunks = [] i = 0 while i < l: chunks.append(b64[i : i + chunksize]) i += chunksize b64 = ' '.join(chunks) return b64 __escaped = { '"' : True, '\\' : True, } def _escapify(qstring): """Escape the characters in a quoted string which need it. @param qstring: the string @type qstring: string @returns: the escaped string @rtype: string """ text = '' for c in qstring: if c in __escaped: text += '\\' + c elif ord(c) >= 0x20 and ord(c) < 0x7F: text += c else: text += '\\%03d' % ord(c) return text def _truncate_bitmap(what): """Determine the index of greatest byte that isn't all zeros, and return the bitmap that contains all the bytes less than that index. @param what: a string of octets representing a bitmap. @type what: string @rtype: string """ for i in xrange(len(what) - 1, -1, -1): if what[i] != '\x00': break return ''.join(what[0 : i + 1]) class Rdata(object): """Base class for all DNS rdata types. """ __slots__ = ['rdclass', 'rdtype'] def __init__(self, rdclass, rdtype): """Initialize an rdata. @param rdclass: The rdata class @type rdclass: int @param rdtype: The rdata type @type rdtype: int """ self.rdclass = rdclass self.rdtype = rdtype def covers(self): """DNS SIG/RRSIG rdatas apply to a specific type; this type is returned by the covers() function. If the rdata type is not SIG or RRSIG, dns.rdatatype.NONE is returned. This is useful when creating rdatasets, allowing the rdataset to contain only RRSIGs of a particular type, e.g. RRSIG(NS). @rtype: int """ return dns.rdatatype.NONE def extended_rdatatype(self): """Return a 32-bit type value, the least significant 16 bits of which are the ordinary DNS type, and the upper 16 bits of which are the "covered" type, if any. @rtype: int """ return self.covers() << 16 | self.rdtype def to_text(self, origin=None, relativize=True, **kw): """Convert an rdata to text format. @rtype: string """ raise NotImplementedError def to_wire(self, file, compress = None, origin = None): """Convert an rdata to wire format. @rtype: string """ raise NotImplementedError def to_digestable(self, origin = None): """Convert rdata to a format suitable for digesting in hashes. This is also the DNSSEC canonical form.""" f = cStringIO.StringIO() self.to_wire(f, None, origin) return f.getvalue() def validate(self): """Check that the current contents of the rdata's fields are valid. If you change an rdata by assigning to its fields, it is a good idea to call validate() when you are done making changes. """ dns.rdata.from_text(self.rdclass, self.rdtype, self.to_text()) def __repr__(self): covers = self.covers() if covers == dns.rdatatype.NONE: ctext = '' else: ctext = '(' + dns.rdatatype.to_text(covers) + ')' return '<DNS ' + dns.rdataclass.to_text(self.rdclass) + ' ' + \ dns.rdatatype.to_text(self.rdtype) + ctext + ' rdata: ' + \ str(self) + '>' def __str__(self): return self.to_text() def _cmp(self, other): """Compare an rdata with another rdata of the same rdtype and rdclass. Return < 0 if self < other in the DNSSEC ordering, 0 if self == other, and > 0 if self > other. """ raise NotImplementedError def __eq__(self, other): if not isinstance(other, Rdata): return False if self.rdclass != other.rdclass or \ self.rdtype != other.rdtype: return False return self._cmp(other) == 0 def __ne__(self, other): if not isinstance(other, Rdata): return True if self.rdclass != other.rdclass or \ self.rdtype != other.rdtype: return True return self._cmp(other) != 0 def __lt__(self, other): if not isinstance(other, Rdata) or \ self.rdclass != other.rdclass or \ self.rdtype != other.rdtype: return NotImplemented return self._cmp(other) < 0 def __le__(self, other): if not isinstance(other, Rdata) or \ self.rdclass != other.rdclass or \ self.rdtype != other.rdtype: return NotImplemented return self._cmp(other) <= 0 def __ge__(self, other): if not isinstance(other, Rdata) or \ self.rdclass != other.rdclass or \ self.rdtype != other.rdtype: return NotImplemented return self._cmp(other) >= 0 def __gt__(self, other): if not isinstance(other, Rdata) or \ self.rdclass != other.rdclass or \ self.rdtype != other.rdtype: return NotImplemented return self._cmp(other) > 0 def __hash__(self): return hash(self.to_digestable(dns.name.root)) def _wire_cmp(self, other): # A number of types compare rdata in wire form, so we provide # the method here instead of duplicating it. # # We specifiy an arbitrary origin of '.' when doing the # comparison, since the rdata may have relative names and we # can't convert a relative name to wire without an origin. b1 = cStringIO.StringIO() self.to_wire(b1, None, dns.name.root) b2 = cStringIO.StringIO() other.to_wire(b2, None, dns.name.root) return cmp(b1.getvalue(), b2.getvalue()) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): """Build an rdata object from text format. @param rdclass: The rdata class @type rdclass: int @param rdtype: The rdata type @type rdtype: int @param tok: The tokenizer @type tok: dns.tokenizer.Tokenizer @param origin: The origin to use for relative names @type origin: dns.name.Name @param relativize: should names be relativized? @type relativize: bool @rtype: dns.rdata.Rdata instance """ raise NotImplementedError from_text = classmethod(from_text) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): """Build an rdata object from wire format @param rdclass: The rdata class @type rdclass: int @param rdtype: The rdata type @type rdtype: int @param wire: The wire-format message @type wire: string @param current: The offet in wire of the beginning of the rdata. @type current: int @param rdlen: The length of the wire-format rdata @type rdlen: int @param origin: The origin to use for relative names @type origin: dns.name.Name @rtype: dns.rdata.Rdata instance """ raise NotImplementedError from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): """Convert any domain names in the rdata to the specified relativization. """ pass class GenericRdata(Rdata): """Generate Rdata Class This class is used for rdata types for which we have no better implementation. It implements the DNS "unknown RRs" scheme. """ __slots__ = ['data'] def __init__(self, rdclass, rdtype, data): super(GenericRdata, self).__init__(rdclass, rdtype) self.data = data def to_text(self, origin=None, relativize=True, **kw): return r'\# %d ' % len(self.data) + _hexify(self.data) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): token = tok.get() if not token.is_identifier() or token.value != '\#': raise dns.exception.SyntaxError(r'generic rdata does not start with \#') length = tok.get_int() chunks = [] while 1: token = tok.get() if token.is_eol_or_eof(): break chunks.append(token.value) hex = ''.join(chunks) data = hex.decode('hex_codec') if len(data) != length: raise dns.exception.SyntaxError('generic rdata hex data has wrong length') return cls(rdclass, rdtype, data) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): file.write(self.data) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): return cls(rdclass, rdtype, wire[current : current + rdlen]) from_wire = classmethod(from_wire) def _cmp(self, other): return cmp(self.data, other.data) _rdata_modules = {} _module_prefix = 'dns.rdtypes' def get_rdata_class(rdclass, rdtype): def import_module(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod mod = _rdata_modules.get((rdclass, rdtype)) rdclass_text = dns.rdataclass.to_text(rdclass) rdtype_text = dns.rdatatype.to_text(rdtype) rdtype_text = rdtype_text.replace('-', '_') if not mod: mod = _rdata_modules.get((dns.rdatatype.ANY, rdtype)) if not mod: try: mod = import_module('.'.join([_module_prefix, rdclass_text, rdtype_text])) _rdata_modules[(rdclass, rdtype)] = mod except ImportError: try: mod = import_module('.'.join([_module_prefix, 'ANY', rdtype_text])) _rdata_modules[(dns.rdataclass.ANY, rdtype)] = mod except ImportError: mod = None if mod: cls = getattr(mod, rdtype_text) else: cls = GenericRdata return cls def from_text(rdclass, rdtype, tok, origin = None, relativize = True): """Build an rdata object from text format. This function attempts to dynamically load a class which implements the specified rdata class and type. If there is no class-and-type-specific implementation, the GenericRdata class is used. Once a class is chosen, its from_text() class method is called with the parameters to this function. @param rdclass: The rdata class @type rdclass: int @param rdtype: The rdata type @type rdtype: int @param tok: The tokenizer @type tok: dns.tokenizer.Tokenizer @param origin: The origin to use for relative names @type origin: dns.name.Name @param relativize: Should names be relativized? @type relativize: bool @rtype: dns.rdata.Rdata instance""" if isinstance(tok, str): tok = dns.tokenizer.Tokenizer(tok) cls = get_rdata_class(rdclass, rdtype) if cls != GenericRdata: # peek at first token token = tok.get() tok.unget(token) if token.is_identifier() and \ token.value == r'\#': # # Known type using the generic syntax. Extract the # wire form from the generic syntax, and then run # from_wire on it. # rdata = GenericRdata.from_text(rdclass, rdtype, tok, origin, relativize) return from_wire(rdclass, rdtype, rdata.data, 0, len(rdata.data), origin) return cls.from_text(rdclass, rdtype, tok, origin, relativize) def from_wire(rdclass, rdtype, wire, current, rdlen, origin = None): """Build an rdata object from wire format This function attempts to dynamically load a class which implements the specified rdata class and type. If there is no class-and-type-specific implementation, the GenericRdata class is used. Once a class is chosen, its from_wire() class method is called with the parameters to this function. @param rdclass: The rdata class @type rdclass: int @param rdtype: The rdata type @type rdtype: int @param wire: The wire-format message @type wire: string @param current: The offet in wire of the beginning of the rdata. @type current: int @param rdlen: The length of the wire-format rdata @type rdlen: int @param origin: The origin to use for relative names @type origin: dns.name.Name @rtype: dns.rdata.Rdata instance""" wire = dns.wiredata.maybe_wrap(wire) cls = get_rdata_class(rdclass, rdtype) return cls.from_wire(rdclass, rdtype, wire, current, rdlen, origin)
15,592
Python
.py
395
31.518987
86
0.622743
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,112
__init__.py
wummel_linkchecker/third_party/dnspython/dns/__init__.py
# Copyright (C) 2003-2007, 2009, 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """dnspython DNS toolkit""" __all__ = [ 'dnssec', 'e164', 'edns', 'entropy', 'exception', 'flags', 'hash', 'inet', 'ipv4', 'ipv6', 'message', 'name', 'namedict', 'node', 'opcode', 'query', 'rcode', 'rdata', 'rdataclass', 'rdataset', 'rdatatype', 'renderer', 'resolver', 'reversename', 'rrset', 'set', 'tokenizer', 'tsig', 'tsigkeyring', 'ttl', 'rdtypes', 'update', 'version', 'wiredata', 'zone', ]
1,327
Python
.py
52
21.788462
72
0.671642
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,113
e164.py
wummel_linkchecker/third_party/dnspython/dns/e164.py
# Copyright (C) 2006, 2007, 2009, 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS E.164 helpers @var public_enum_domain: The DNS public ENUM domain, e164.arpa. @type public_enum_domain: dns.name.Name object """ import dns.exception import dns.name import dns.resolver public_enum_domain = dns.name.from_text('e164.arpa.') def from_e164(text, origin=public_enum_domain): """Convert an E.164 number in textual form into a Name object whose value is the ENUM domain name for that number. @param text: an E.164 number in textual form. @type text: str @param origin: The domain in which the number should be constructed. The default is e164.arpa. @type: dns.name.Name object or None @rtype: dns.name.Name object """ parts = [d for d in text if d.isdigit()] parts.reverse() return dns.name.from_text('.'.join(parts), origin=origin) def to_e164(name, origin=public_enum_domain, want_plus_prefix=True): """Convert an ENUM domain name into an E.164 number. @param name: the ENUM domain name. @type name: dns.name.Name object. @param origin: A domain containing the ENUM domain name. The name is relativized to this domain before being converted to text. @type: dns.name.Name object or None @param want_plus_prefix: if True, add a '+' to the beginning of the returned number. @rtype: str """ if not origin is None: name = name.relativize(origin) dlabels = [d for d in name.labels if (d.isdigit() and len(d) == 1)] if len(dlabels) != len(name.labels): raise dns.exception.SyntaxError('non-digit labels in ENUM domain name') dlabels.reverse() text = ''.join(dlabels) if want_plus_prefix: text = '+' + text return text def query(number, domains, resolver=None): """Look for NAPTR RRs for the specified number in the specified domains. e.g. lookup('16505551212', ['e164.dnspython.org.', 'e164.arpa.']) """ if resolver is None: resolver = dns.resolver.get_default_resolver() for domain in domains: if isinstance(domain, (str, unicode)): domain = dns.name.from_text(domain) qname = dns.e164.from_e164(number, domain) try: return resolver.query(qname, 'NAPTR') except dns.resolver.NXDOMAIN: pass raise dns.resolver.NXDOMAIN
3,069
Python
.py
71
38.732394
79
0.711371
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,114
zone.py
wummel_linkchecker/third_party/dnspython/dns/zone.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Zones.""" from __future__ import generators import sys import dns.exception import dns.name import dns.node import dns.rdataclass import dns.rdatatype import dns.rdata import dns.rrset import dns.tokenizer import dns.ttl class BadZone(dns.exception.DNSException): """The zone is malformed.""" pass class NoSOA(BadZone): """The zone has no SOA RR at its origin.""" pass class NoNS(BadZone): """The zone has no NS RRset at its origin.""" pass class UnknownOrigin(BadZone): """The zone's origin is unknown.""" pass class Zone(object): """A DNS zone. A Zone is a mapping from names to nodes. The zone object may be treated like a Python dictionary, e.g. zone[name] will retrieve the node associated with that name. The I{name} may be a dns.name.Name object, or it may be a string. In the either case, if the name is relative it is treated as relative to the origin of the zone. @ivar rdclass: The zone's rdata class; the default is class IN. @type rdclass: int @ivar origin: The origin of the zone. @type origin: dns.name.Name object @ivar nodes: A dictionary mapping the names of nodes in the zone to the nodes themselves. @type nodes: dict @ivar relativize: should names in the zone be relativized? @type relativize: bool @cvar node_factory: the factory used to create a new node @type node_factory: class or callable """ node_factory = dns.node.Node __slots__ = ['rdclass', 'origin', 'nodes', 'relativize'] def __init__(self, origin, rdclass=dns.rdataclass.IN, relativize=True): """Initialize a zone object. @param origin: The origin of the zone. @type origin: dns.name.Name object @param rdclass: The zone's rdata class; the default is class IN. @type rdclass: int""" self.rdclass = rdclass self.origin = origin self.nodes = {} self.relativize = relativize def __eq__(self, other): """Two zones are equal if they have the same origin, class, and nodes. @rtype: bool """ if not isinstance(other, Zone): return False if self.rdclass != other.rdclass or \ self.origin != other.origin or \ self.nodes != other.nodes: return False return True def __ne__(self, other): """Are two zones not equal? @rtype: bool """ return not self.__eq__(other) def _validate_name(self, name): if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) elif not isinstance(name, dns.name.Name): raise KeyError("name parameter must be convertable to a DNS name") if name.is_absolute(): if not name.is_subdomain(self.origin): raise KeyError("name parameter must be a subdomain of the zone origin") if self.relativize: name = name.relativize(self.origin) return name def __getitem__(self, key): key = self._validate_name(key) return self.nodes[key] def __setitem__(self, key, value): key = self._validate_name(key) self.nodes[key] = value def __delitem__(self, key): key = self._validate_name(key) del self.nodes[key] def __iter__(self): return self.nodes.iterkeys() def iterkeys(self): return self.nodes.iterkeys() def keys(self): return self.nodes.keys() def itervalues(self): return self.nodes.itervalues() def values(self): return self.nodes.values() def iteritems(self): return self.nodes.iteritems() def items(self): return self.nodes.items() def get(self, key): key = self._validate_name(key) return self.nodes.get(key) def __contains__(self, other): return other in self.nodes def find_node(self, name, create=False): """Find a node in the zone, possibly creating it. @param name: the name of the node to find @type name: dns.name.Name object or string @param create: should the node be created if it doesn't exist? @type create: bool @raises KeyError: the name is not known and create was not specified. @rtype: dns.node.Node object """ name = self._validate_name(name) node = self.nodes.get(name) if node is None: if not create: raise KeyError node = self.node_factory() self.nodes[name] = node return node def get_node(self, name, create=False): """Get a node in the zone, possibly creating it. This method is like L{find_node}, except it returns None instead of raising an exception if the node does not exist and creation has not been requested. @param name: the name of the node to find @type name: dns.name.Name object or string @param create: should the node be created if it doesn't exist? @type create: bool @rtype: dns.node.Node object or None """ try: node = self.find_node(name, create) except KeyError: node = None return node def delete_node(self, name): """Delete the specified node if it exists. It is not an error if the node does not exist. """ name = self._validate_name(name) if name in self.nodes: del self.nodes[name] def find_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE, create=False): """Look for rdata with the specified name and type in the zone, and return an rdataset encapsulating it. The I{name}, I{rdtype}, and I{covers} parameters may be strings, in which case they will be converted to their proper type. The rdataset returned is not a copy; changes to it will change the zone. KeyError is raised if the name or type are not found. Use L{get_rdataset} if you want to have None returned instead. @param name: the owner name to look for @type name: DNS.name.Name object or string @param rdtype: the rdata type desired @type rdtype: int or string @param covers: the covered type (defaults to None) @type covers: int or string @param create: should the node and rdataset be created if they do not exist? @type create: bool @raises KeyError: the node or rdata could not be found @rtype: dns.rrset.RRset object """ name = self._validate_name(name) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if isinstance(covers, (str, unicode)): covers = dns.rdatatype.from_text(covers) node = self.find_node(name, create) return node.find_rdataset(self.rdclass, rdtype, covers, create) def get_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE, create=False): """Look for rdata with the specified name and type in the zone, and return an rdataset encapsulating it. The I{name}, I{rdtype}, and I{covers} parameters may be strings, in which case they will be converted to their proper type. The rdataset returned is not a copy; changes to it will change the zone. None is returned if the name or type are not found. Use L{find_rdataset} if you want to have KeyError raised instead. @param name: the owner name to look for @type name: DNS.name.Name object or string @param rdtype: the rdata type desired @type rdtype: int or string @param covers: the covered type (defaults to None) @type covers: int or string @param create: should the node and rdataset be created if they do not exist? @type create: bool @rtype: dns.rrset.RRset object """ try: rdataset = self.find_rdataset(name, rdtype, covers, create) except KeyError: rdataset = None return rdataset def delete_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE): """Delete the rdataset matching I{rdtype} and I{covers}, if it exists at the node specified by I{name}. The I{name}, I{rdtype}, and I{covers} parameters may be strings, in which case they will be converted to their proper type. It is not an error if the node does not exist, or if there is no matching rdataset at the node. If the node has no rdatasets after the deletion, it will itself be deleted. @param name: the owner name to look for @type name: DNS.name.Name object or string @param rdtype: the rdata type desired @type rdtype: int or string @param covers: the covered type (defaults to None) @type covers: int or string """ name = self._validate_name(name) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if isinstance(covers, (str, unicode)): covers = dns.rdatatype.from_text(covers) node = self.get_node(name) if not node is None: node.delete_rdataset(self.rdclass, rdtype, covers) if len(node) == 0: self.delete_node(name) def replace_rdataset(self, name, replacement): """Replace an rdataset at name. It is not an error if there is no rdataset matching I{replacement}. Ownership of the I{replacement} object is transferred to the zone; in other words, this method does not store a copy of I{replacement} at the node, it stores I{replacement} itself. If the I{name} node does not exist, it is created. @param name: the owner name @type name: DNS.name.Name object or string @param replacement: the replacement rdataset @type replacement: dns.rdataset.Rdataset """ if replacement.rdclass != self.rdclass: raise ValueError('replacement.rdclass != zone.rdclass') node = self.find_node(name, True) node.replace_rdataset(replacement) def find_rrset(self, name, rdtype, covers=dns.rdatatype.NONE): """Look for rdata with the specified name and type in the zone, and return an RRset encapsulating it. The I{name}, I{rdtype}, and I{covers} parameters may be strings, in which case they will be converted to their proper type. This method is less efficient than the similar L{find_rdataset} because it creates an RRset instead of returning the matching rdataset. It may be more convenient for some uses since it returns an object which binds the owner name to the rdata. This method may not be used to create new nodes or rdatasets; use L{find_rdataset} instead. KeyError is raised if the name or type are not found. Use L{get_rrset} if you want to have None returned instead. @param name: the owner name to look for @type name: DNS.name.Name object or string @param rdtype: the rdata type desired @type rdtype: int or string @param covers: the covered type (defaults to None) @type covers: int or string @raises KeyError: the node or rdata could not be found @rtype: dns.rrset.RRset object """ name = self._validate_name(name) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if isinstance(covers, (str, unicode)): covers = dns.rdatatype.from_text(covers) rdataset = self.nodes[name].find_rdataset(self.rdclass, rdtype, covers) rrset = dns.rrset.RRset(name, self.rdclass, rdtype, covers) rrset.update(rdataset) return rrset def get_rrset(self, name, rdtype, covers=dns.rdatatype.NONE): """Look for rdata with the specified name and type in the zone, and return an RRset encapsulating it. The I{name}, I{rdtype}, and I{covers} parameters may be strings, in which case they will be converted to their proper type. This method is less efficient than the similar L{get_rdataset} because it creates an RRset instead of returning the matching rdataset. It may be more convenient for some uses since it returns an object which binds the owner name to the rdata. This method may not be used to create new nodes or rdatasets; use L{find_rdataset} instead. None is returned if the name or type are not found. Use L{find_rrset} if you want to have KeyError raised instead. @param name: the owner name to look for @type name: DNS.name.Name object or string @param rdtype: the rdata type desired @type rdtype: int or string @param covers: the covered type (defaults to None) @type covers: int or string @rtype: dns.rrset.RRset object """ try: rrset = self.find_rrset(name, rdtype, covers) except KeyError: rrset = None return rrset def iterate_rdatasets(self, rdtype=dns.rdatatype.ANY, covers=dns.rdatatype.NONE): """Return a generator which yields (name, rdataset) tuples for all rdatasets in the zone which have the specified I{rdtype} and I{covers}. If I{rdtype} is dns.rdatatype.ANY, the default, then all rdatasets will be matched. @param rdtype: int or string @type rdtype: int or string @param covers: the covered type (defaults to None) @type covers: int or string """ if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if isinstance(covers, (str, unicode)): covers = dns.rdatatype.from_text(covers) for (name, node) in self.iteritems(): for rds in node: if rdtype == dns.rdatatype.ANY or \ (rds.rdtype == rdtype and rds.covers == covers): yield (name, rds) def iterate_rdatas(self, rdtype=dns.rdatatype.ANY, covers=dns.rdatatype.NONE): """Return a generator which yields (name, ttl, rdata) tuples for all rdatas in the zone which have the specified I{rdtype} and I{covers}. If I{rdtype} is dns.rdatatype.ANY, the default, then all rdatas will be matched. @param rdtype: int or string @type rdtype: int or string @param covers: the covered type (defaults to None) @type covers: int or string """ if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if isinstance(covers, (str, unicode)): covers = dns.rdatatype.from_text(covers) for (name, node) in self.iteritems(): for rds in node: if rdtype == dns.rdatatype.ANY or \ (rds.rdtype == rdtype and rds.covers == covers): for rdata in rds: yield (name, rds.ttl, rdata) def to_file(self, f, sorted=True, relativize=True, nl=None): """Write a zone to a file. @param f: file or string. If I{f} is a string, it is treated as the name of a file to open. @param sorted: if True, the file will be written with the names sorted in DNSSEC order from least to greatest. Otherwise the names will be written in whatever order they happen to have in the zone's dictionary. @param relativize: if True, domain names in the output will be relativized to the zone's origin (if possible). @type relativize: bool @param nl: The end of line string. If not specified, the output will use the platform's native end-of-line marker (i.e. LF on POSIX, CRLF on Windows, CR on Macintosh). @type nl: string or None """ if sys.hexversion >= 0x02030000: # allow Unicode filenames str_type = basestring else: str_type = str if nl is None: opts = 'w' else: opts = 'wb' if isinstance(f, str_type): f = file(f, opts) want_close = True else: want_close = False try: if sorted: names = self.keys() names.sort() else: names = self.iterkeys() for n in names: l = self[n].to_text(n, origin=self.origin, relativize=relativize) if nl is None: print >> f, l else: f.write(l) f.write(nl) finally: if want_close: f.close() def check_origin(self): """Do some simple checking of the zone's origin. @raises dns.zone.NoSOA: there is no SOA RR @raises dns.zone.NoNS: there is no NS RRset @raises KeyError: there is no origin node """ if self.relativize: name = dns.name.empty else: name = self.origin if self.get_rdataset(name, dns.rdatatype.SOA) is None: raise NoSOA if self.get_rdataset(name, dns.rdatatype.NS) is None: raise NoNS class _MasterReader(object): """Read a DNS master file @ivar tok: The tokenizer @type tok: dns.tokenizer.Tokenizer object @ivar ttl: The default TTL @type ttl: int @ivar last_name: The last name read @type last_name: dns.name.Name object @ivar current_origin: The current origin @type current_origin: dns.name.Name object @ivar relativize: should names in the zone be relativized? @type relativize: bool @ivar zone: the zone @type zone: dns.zone.Zone object @ivar saved_state: saved reader state (used when processing $INCLUDE) @type saved_state: list of (tokenizer, current_origin, last_name, file) tuples. @ivar current_file: the file object of the $INCLUDed file being parsed (None if no $INCLUDE is active). @ivar allow_include: is $INCLUDE allowed? @type allow_include: bool @ivar check_origin: should sanity checks of the origin node be done? The default is True. @type check_origin: bool """ def __init__(self, tok, origin, rdclass, relativize, zone_factory=Zone, allow_include=False, check_origin=True): if isinstance(origin, (str, unicode)): origin = dns.name.from_text(origin) self.tok = tok self.current_origin = origin self.relativize = relativize self.ttl = 0 self.last_name = None self.zone = zone_factory(origin, rdclass, relativize=relativize) self.saved_state = [] self.current_file = None self.allow_include = allow_include self.check_origin = check_origin def _eat_line(self): while 1: token = self.tok.get() if token.is_eol_or_eof(): break def _rr_line(self): """Process one line from a DNS master file.""" # Name if self.current_origin is None: raise UnknownOrigin token = self.tok.get(want_leading = True) if not token.is_whitespace(): self.last_name = dns.name.from_text(token.value, self.current_origin) else: token = self.tok.get() if token.is_eol_or_eof(): # treat leading WS followed by EOL/EOF as if they were EOL/EOF. return self.tok.unget(token) name = self.last_name if not name.is_subdomain(self.zone.origin): self._eat_line() return if self.relativize: name = name.relativize(self.zone.origin) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError # TTL try: ttl = dns.ttl.from_text(token.value) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError except dns.ttl.BadTTL: ttl = self.ttl # Class try: rdclass = dns.rdataclass.from_text(token.value) token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError except dns.exception.SyntaxError: raise except Exception: rdclass = self.zone.rdclass if rdclass != self.zone.rdclass: raise dns.exception.SyntaxError("RR class is not zone's class") # Type try: rdtype = dns.rdatatype.from_text(token.value) except Exception: raise dns.exception.SyntaxError("unknown rdatatype '%s'" % token.value) n = self.zone.nodes.get(name) if n is None: n = self.zone.node_factory() self.zone.nodes[name] = n try: rd = dns.rdata.from_text(rdclass, rdtype, self.tok, self.current_origin, False) except dns.exception.SyntaxError: # Catch and reraise. (ty, va) = sys.exc_info()[:2] raise va except Exception: # All exceptions that occur in the processing of rdata # are treated as syntax errors. This is not strictly # correct, but it is correct almost all of the time. # We convert them to syntax errors so that we can emit # helpful filename:line info. (ty, va) = sys.exc_info()[:2] raise dns.exception.SyntaxError("caught exception %s: %s" % (str(ty), str(va))) rd.choose_relativity(self.zone.origin, self.relativize) covers = rd.covers() rds = n.find_rdataset(rdclass, rdtype, covers, True) rds.add(rd, ttl) def read(self): """Read a DNS master file and build a zone object. @raises dns.zone.NoSOA: No SOA RR was found at the zone origin @raises dns.zone.NoNS: No NS RRset was found at the zone origin """ try: while 1: token = self.tok.get(True, True).unescape() if token.is_eof(): if not self.current_file is None: self.current_file.close() if len(self.saved_state) > 0: (self.tok, self.current_origin, self.last_name, self.current_file, self.ttl) = self.saved_state.pop(-1) continue break elif token.is_eol(): continue elif token.is_comment(): self.tok.get_eol() continue elif token.value[0] == '$': u = token.value.upper() if u == '$TTL': token = self.tok.get() if not token.is_identifier(): raise dns.exception.SyntaxError("bad $TTL") self.ttl = dns.ttl.from_text(token.value) self.tok.get_eol() elif u == '$ORIGIN': self.current_origin = self.tok.get_name() self.tok.get_eol() if self.zone.origin is None: self.zone.origin = self.current_origin elif u == '$INCLUDE' and self.allow_include: token = self.tok.get() if not token.is_quoted_string(): raise dns.exception.SyntaxError("bad filename in $INCLUDE") filename = token.value token = self.tok.get() if token.is_identifier(): new_origin = dns.name.from_text(token.value, \ self.current_origin) self.tok.get_eol() elif not token.is_eol_or_eof(): raise dns.exception.SyntaxError("bad origin in $INCLUDE") else: new_origin = self.current_origin self.saved_state.append((self.tok, self.current_origin, self.last_name, self.current_file, self.ttl)) self.current_file = file(filename, 'r') self.tok = dns.tokenizer.Tokenizer(self.current_file, filename) self.current_origin = new_origin else: raise dns.exception.SyntaxError("Unknown master file directive '" + u + "'") continue self.tok.unget(token) self._rr_line() except dns.exception.SyntaxError, detail: (filename, line_number) = self.tok.where() if detail is None: detail = "syntax error" raise dns.exception.SyntaxError("%s:%d: %s" % (filename, line_number, detail)) # Now that we're done reading, do some basic checking of the zone. if self.check_origin: self.zone.check_origin() def from_text(text, origin = None, rdclass = dns.rdataclass.IN, relativize = True, zone_factory=Zone, filename=None, allow_include=False, check_origin=True): """Build a zone object from a master file format string. @param text: the master file format input @type text: string. @param origin: The origin of the zone; if not specified, the first $ORIGIN statement in the master file will determine the origin of the zone. @type origin: dns.name.Name object or string @param rdclass: The zone's rdata class; the default is class IN. @type rdclass: int @param relativize: should names be relativized? The default is True @type relativize: bool @param zone_factory: The zone factory to use @type zone_factory: function returning a Zone @param filename: The filename to emit when describing where an error occurred; the default is '<string>'. @type filename: string @param allow_include: is $INCLUDE allowed? @type allow_include: bool @param check_origin: should sanity checks of the origin node be done? The default is True. @type check_origin: bool @raises dns.zone.NoSOA: No SOA RR was found at the zone origin @raises dns.zone.NoNS: No NS RRset was found at the zone origin @rtype: dns.zone.Zone object """ # 'text' can also be a file, but we don't publish that fact # since it's an implementation detail. The official file # interface is from_file(). if filename is None: filename = '<string>' tok = dns.tokenizer.Tokenizer(text, filename) reader = _MasterReader(tok, origin, rdclass, relativize, zone_factory, allow_include=allow_include, check_origin=check_origin) reader.read() return reader.zone def from_file(f, origin = None, rdclass = dns.rdataclass.IN, relativize = True, zone_factory=Zone, filename=None, allow_include=True, check_origin=True): """Read a master file and build a zone object. @param f: file or string. If I{f} is a string, it is treated as the name of a file to open. @param origin: The origin of the zone; if not specified, the first $ORIGIN statement in the master file will determine the origin of the zone. @type origin: dns.name.Name object or string @param rdclass: The zone's rdata class; the default is class IN. @type rdclass: int @param relativize: should names be relativized? The default is True @type relativize: bool @param zone_factory: The zone factory to use @type zone_factory: function returning a Zone @param filename: The filename to emit when describing where an error occurred; the default is '<file>', or the value of I{f} if I{f} is a string. @type filename: string @param allow_include: is $INCLUDE allowed? @type allow_include: bool @param check_origin: should sanity checks of the origin node be done? The default is True. @type check_origin: bool @raises dns.zone.NoSOA: No SOA RR was found at the zone origin @raises dns.zone.NoNS: No NS RRset was found at the zone origin @rtype: dns.zone.Zone object """ if sys.hexversion >= 0x02030000: # allow Unicode filenames; turn on universal newline support str_type = basestring opts = 'rU' else: str_type = str opts = 'r' if isinstance(f, str_type): if filename is None: filename = f f = file(f, opts) want_close = True else: if filename is None: filename = '<file>' want_close = False try: z = from_text(f, origin, rdclass, relativize, zone_factory, filename, allow_include, check_origin) finally: if want_close: f.close() return z def from_xfr(xfr, zone_factory=Zone, relativize=True): """Convert the output of a zone transfer generator into a zone object. @param xfr: The xfr generator @type xfr: generator of dns.message.Message objects @param relativize: should names be relativized? The default is True. It is essential that the relativize setting matches the one specified to dns.query.xfr(). @type relativize: bool @raises dns.zone.NoSOA: No SOA RR was found at the zone origin @raises dns.zone.NoNS: No NS RRset was found at the zone origin @rtype: dns.zone.Zone object """ z = None for r in xfr: if z is None: if relativize: origin = r.origin else: origin = r.answer[0].name rdclass = r.answer[0].rdclass z = zone_factory(origin, rdclass, relativize=relativize) for rrset in r.answer: znode = z.nodes.get(rrset.name) if not znode: znode = z.node_factory() z.nodes[rrset.name] = znode zrds = znode.find_rdataset(rrset.rdclass, rrset.rdtype, rrset.covers, True) zrds.update_ttl(rrset.ttl) for rd in rrset: rd.choose_relativity(z.origin, relativize) zrds.add(rd) z.check_origin() return z
32,037
Python
.py
741
32.704453
100
0.601469
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,115
tsigkeyring.py
wummel_linkchecker/third_party/dnspython/dns/tsigkeyring.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """A place to store TSIG keys.""" import base64 import dns.name def from_text(textring): """Convert a dictionary containing (textual DNS name, base64 secret) pairs into a binary keyring which has (dns.name.Name, binary secret) pairs. @rtype: dict""" keyring = {} for keytext in textring: keyname = dns.name.from_text(keytext) secret = base64.decodestring(textring[keytext]) keyring[keyname] = secret return keyring def to_text(keyring): """Convert a dictionary containing (dns.name.Name, binary secret) pairs into a text keyring which has (textual DNS name, base64 secret) pairs. @rtype: dict""" textring = {} for keyname in keyring: keytext = dns.name.to_text(keyname) secret = base64.encodestring(keyring[keyname]) textring[keytext] = secret return textring
1,649
Python
.py
37
40.783784
78
0.744548
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,116
rdatatype.py
wummel_linkchecker/third_party/dnspython/dns/rdatatype.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Rdata Types. @var _by_text: The rdata type textual name to value mapping @type _by_text: dict @var _by_value: The rdata type value to textual name mapping @type _by_value: dict @var _metatypes: If an rdatatype is a metatype, there will be a mapping whose key is the rdatatype value and whose value is True in this dictionary. @type _metatypes: dict @var _singletons: If an rdatatype is a singleton, there will be a mapping whose key is the rdatatype value and whose value is True in this dictionary. @type _singletons: dict""" import re import dns.exception NONE = 0 A = 1 NS = 2 MD = 3 MF = 4 CNAME = 5 SOA = 6 MB = 7 MG = 8 MR = 9 NULL = 10 WKS = 11 PTR = 12 HINFO = 13 MINFO = 14 MX = 15 TXT = 16 RP = 17 AFSDB = 18 X25 = 19 ISDN = 20 RT = 21 NSAP = 22 NSAP_PTR = 23 SIG = 24 KEY = 25 PX = 26 GPOS = 27 AAAA = 28 LOC = 29 NXT = 30 SRV = 33 NAPTR = 35 KX = 36 CERT = 37 A6 = 38 DNAME = 39 OPT = 41 APL = 42 DS = 43 SSHFP = 44 IPSECKEY = 45 RRSIG = 46 NSEC = 47 DNSKEY = 48 DHCID = 49 NSEC3 = 50 NSEC3PARAM = 51 HIP = 55 SPF = 99 UNSPEC = 103 TKEY = 249 TSIG = 250 IXFR = 251 AXFR = 252 MAILB = 253 MAILA = 254 ANY = 255 TA = 32768 DLV = 32769 _by_text = { 'NONE' : NONE, '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, 'X25' : X25, 'ISDN' : ISDN, 'RT' : RT, 'NSAP' : NSAP, 'NSAP-PTR' : NSAP_PTR, 'SIG' : SIG, 'KEY' : KEY, 'PX' : PX, 'GPOS' : GPOS, 'AAAA' : AAAA, 'LOC' : LOC, 'NXT' : NXT, 'SRV' : SRV, 'NAPTR' : NAPTR, 'KX' : KX, 'CERT' : CERT, 'A6' : A6, 'DNAME' : DNAME, 'OPT' : OPT, 'APL' : APL, 'DS' : DS, 'SSHFP' : SSHFP, 'IPSECKEY' : IPSECKEY, 'RRSIG' : RRSIG, 'NSEC' : NSEC, 'DNSKEY' : DNSKEY, 'DHCID' : DHCID, 'NSEC3' : NSEC3, 'NSEC3PARAM' : NSEC3PARAM, 'HIP' : HIP, 'SPF' : SPF, 'UNSPEC' : UNSPEC, 'TKEY' : TKEY, 'TSIG' : TSIG, 'IXFR' : IXFR, 'AXFR' : AXFR, 'MAILB' : MAILB, 'MAILA' : MAILA, 'ANY' : ANY, 'TA' : TA, 'DLV' : DLV, } # We construct the inverse mapping programmatically to ensure that we # cannot make any mistakes (e.g. omissions, cut-and-paste errors) that # would cause the mapping not to be true inverse. _by_value = dict([(y, x) for x, y in _by_text.iteritems()]) _metatypes = { OPT : True } _singletons = { SOA : True, NXT : True, DNAME : True, NSEC : True, # CNAME is technically a singleton, but we allow multiple CNAMEs. } _unknown_type_pattern = re.compile('TYPE([0-9]+)$', re.I); class UnknownRdatatype(dns.exception.DNSException): """Raised if a type is unknown.""" pass def from_text(text): """Convert text into a DNS rdata type value. @param text: the text @type text: string @raises dns.rdatatype.UnknownRdatatype: the type is unknown @raises ValueError: the rdata type value is not >= 0 and <= 65535 @rtype: int""" value = _by_text.get(text.upper()) if value is None: match = _unknown_type_pattern.match(text) if match == None: raise UnknownRdatatype value = int(match.group(1)) if value < 0 or value > 65535: raise ValueError("type must be between >= 0 and <= 65535") return value def to_text(value): """Convert a DNS rdata type to text. @param value: the rdata type value @type value: int @raises ValueError: the rdata type value is not >= 0 and <= 65535 @rtype: string""" if value < 0 or value > 65535: raise ValueError("type must be between >= 0 and <= 65535") text = _by_value.get(value) if text is None: text = 'TYPE' + repr(value) return text def is_metatype(rdtype): """True if the type is a metatype. @param rdtype: the type @type rdtype: int @rtype: bool""" if rdtype >= TKEY and rdtype <= ANY or rdtype in _metatypes: return True return False def is_singleton(rdtype): """True if the type is a singleton. @param rdtype: the type @type rdtype: int @rtype: bool""" if rdtype in _singletons: return True return False
5,155
Python
.py
211
21
76
0.639447
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,117
query.py
wummel_linkchecker/third_party/dnspython/dns/query.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Talk to a DNS server.""" from __future__ import generators import errno import select import socket import struct import sys import time import dns.exception import dns.inet import dns.name import dns.message import dns.rdataclass import dns.rdatatype class UnexpectedSource(dns.exception.DNSException): """Raised if a query response comes from an unexpected address or port.""" pass class BadResponse(dns.exception.FormError): """Raised if a query response does not respond to the question asked.""" pass def _compute_expiration(timeout): if timeout is None: return None else: return time.time() + timeout def _poll_for(fd, readable, writable, error, timeout): """ @param fd: File descriptor (int). @param readable: Whether to wait for readability (bool). @param writable: Whether to wait for writability (bool). @param expiration: Deadline timeout (expiration time, in seconds (float)). @return True on success, False on timeout """ event_mask = 0 if readable: event_mask |= select.POLLIN if writable: event_mask |= select.POLLOUT if error: event_mask |= select.POLLERR pollable = select.poll() pollable.register(fd, event_mask) if timeout: event_list = pollable.poll(long(timeout * 1000)) else: event_list = pollable.poll() return bool(event_list) def _select_for(fd, readable, writable, error, timeout): """ @param fd: File descriptor (int). @param readable: Whether to wait for readability (bool). @param writable: Whether to wait for writability (bool). @param expiration: Deadline timeout (expiration time, in seconds (float)). @return True on success, False on timeout """ rset, wset, xset = [], [], [] if readable: rset = [fd] if writable: wset = [fd] if error: xset = [fd] if timeout is None: (rcount, wcount, xcount) = select.select(rset, wset, xset) else: (rcount, wcount, xcount) = select.select(rset, wset, xset, timeout) return bool((rcount or wcount or xcount)) def _wait_for(fd, readable, writable, error, expiration): done = False while not done: if expiration is None: timeout = None else: timeout = expiration - time.time() if timeout <= 0.0: raise dns.exception.Timeout try: if not _polling_backend(fd, readable, writable, error, timeout): raise dns.exception.Timeout except select.error, e: if e.args[0] != errno.EINTR: raise e done = True def _set_polling_backend(fn): """ Internal API. Do not use. """ global _polling_backend _polling_backend = fn if hasattr(select, 'poll'): # Prefer poll() on platforms that support it because it has no # limits on the maximum value of a file descriptor (plus it will # be more efficient for high values). _polling_backend = _poll_for else: _polling_backend = _select_for def _wait_for_readable(s, expiration): _wait_for(s, True, False, True, expiration) def _wait_for_writable(s, expiration): _wait_for(s, False, True, True, expiration) def _addresses_equal(af, a1, a2): # Convert the first value of the tuple, which is a textual format # address into binary form, so that we are not confused by different # textual representations of the same address n1 = dns.inet.inet_pton(af, a1[0]) n2 = dns.inet.inet_pton(af, a2[0]) return n1 == n2 and a1[1:] == a2[1:] def udp(q, where, timeout=None, port=53, af=None, source=None, source_port=0, ignore_unexpected=False, one_rr_per_rrset=False): """Return the response obtained after sending a query via UDP. @param q: the query @type q: dns.message.Message @param where: where to send the message @type where: string containing an IPv4 or IPv6 address @param timeout: The number of seconds to wait before the query times out. If None, the default, wait forever. @type timeout: float @param port: The port to which to send the message. The default is 53. @type port: int @param af: the address family to use. The default is None, which causes the address family to use to be inferred from the form of of where. If the inference attempt fails, AF_INET is used. @type af: int @rtype: dns.message.Message object @param source: source address. The default is the IPv4 wildcard address. @type source: string @param source_port: The port from which to send the message. The default is 0. @type source_port: int @param ignore_unexpected: If True, ignore responses from unexpected sources. The default is False. @type ignore_unexpected: bool @param one_rr_per_rrset: Put each RR into its own RRset @type one_rr_per_rrset: bool """ wire = q.to_wire() if af is None: try: af = dns.inet.af_for_address(where) except Exception: af = dns.inet.AF_INET if af == dns.inet.AF_INET: destination = (where, port) if source is not None: source = (source, source_port) elif af == dns.inet.AF_INET6: destination = (where, port, 0, 0) if source is not None: source = (source, source_port, 0, 0) s = socket.socket(af, socket.SOCK_DGRAM, 0) try: expiration = _compute_expiration(timeout) s.setblocking(0) if source is not None: s.bind(source) _wait_for_writable(s, expiration) s.sendto(wire, destination) while 1: _wait_for_readable(s, expiration) (wire, from_address) = s.recvfrom(65535) if _addresses_equal(af, from_address, destination) or \ (dns.inet.is_multicast(where) and \ from_address[1:] == destination[1:]): break if not ignore_unexpected: raise UnexpectedSource('got a response from ' '%s instead of %s' % (from_address, destination)) finally: s.close() r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac, one_rr_per_rrset=one_rr_per_rrset) if not q.is_response(r): raise BadResponse return r def _net_read(sock, count, expiration): """Read the specified number of bytes from sock. Keep trying until we either get the desired amount, or we hit EOF. A Timeout exception will be raised if the operation is not completed by the expiration time. """ s = '' while count > 0: _wait_for_readable(sock, expiration) n = sock.recv(count) if n == '': raise EOFError count = count - len(n) s = s + n return s def _net_write(sock, data, expiration): """Write the specified data to the socket. A Timeout exception will be raised if the operation is not completed by the expiration time. """ current = 0 l = len(data) while current < l: _wait_for_writable(sock, expiration) current += sock.send(data[current:]) def _connect(s, address): try: s.connect(address) except socket.error: (ty, v) = sys.exc_info()[:2] if v[0] != errno.EINPROGRESS and \ v[0] != errno.EWOULDBLOCK and \ v[0] != errno.EALREADY: raise v def tcp(q, where, timeout=None, port=53, af=None, source=None, source_port=0, one_rr_per_rrset=False): """Return the response obtained after sending a query via TCP. @param q: the query @type q: dns.message.Message object @param where: where to send the message @type where: string containing an IPv4 or IPv6 address @param timeout: The number of seconds to wait before the query times out. If None, the default, wait forever. @type timeout: float @param port: The port to which to send the message. The default is 53. @type port: int @param af: the address family to use. The default is None, which causes the address family to use to be inferred from the form of of where. If the inference attempt fails, AF_INET is used. @type af: int @rtype: dns.message.Message object @param source: source address. The default is the IPv4 wildcard address. @type source: string @param source_port: The port from which to send the message. The default is 0. @type source_port: int @param one_rr_per_rrset: Put each RR into its own RRset @type one_rr_per_rrset: bool """ wire = q.to_wire() if af is None: try: af = dns.inet.af_for_address(where) except Exception: af = dns.inet.AF_INET if af == dns.inet.AF_INET: destination = (where, port) if source is not None: source = (source, source_port) elif af == dns.inet.AF_INET6: destination = (where, port, 0, 0) if source is not None: source = (source, source_port, 0, 0) s = socket.socket(af, socket.SOCK_STREAM, 0) try: expiration = _compute_expiration(timeout) s.setblocking(0) if source is not None: s.bind(source) _connect(s, destination) l = len(wire) # copying the wire into tcpmsg is inefficient, but lets us # avoid writev() or doing a short write that would get pushed # onto the net tcpmsg = struct.pack("!H", l) + wire _net_write(s, tcpmsg, expiration) ldata = _net_read(s, 2, expiration) (l,) = struct.unpack("!H", ldata) wire = _net_read(s, l, expiration) finally: s.close() r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac, one_rr_per_rrset=one_rr_per_rrset) if not q.is_response(r): raise BadResponse return r def xfr(where, zone, rdtype=dns.rdatatype.AXFR, rdclass=dns.rdataclass.IN, timeout=None, port=53, keyring=None, keyname=None, relativize=True, af=None, lifetime=None, source=None, source_port=0, serial=0, use_udp=False, keyalgorithm=dns.tsig.default_algorithm): """Return a generator for the responses to a zone transfer. @param where: where to send the message @type where: string containing an IPv4 or IPv6 address @param zone: The name of the zone to transfer @type zone: dns.name.Name object or string @param rdtype: The type of zone transfer. The default is dns.rdatatype.AXFR. @type rdtype: int or string @param rdclass: The class of the zone transfer. The default is dns.rdatatype.IN. @type rdclass: int or string @param timeout: The number of seconds to wait for each response message. If None, the default, wait forever. @type timeout: float @param port: The port to which to send the message. The default is 53. @type port: int @param keyring: The TSIG keyring to use @type keyring: dict @param keyname: The name of the TSIG key to use @type keyname: dns.name.Name object or string @param relativize: If True, all names in the zone will be relativized to the zone origin. It is essential that the relativize setting matches the one specified to dns.zone.from_xfr(). @type relativize: bool @param af: the address family to use. The default is None, which causes the address family to use to be inferred from the form of of where. If the inference attempt fails, AF_INET is used. @type af: int @param lifetime: The total number of seconds to spend doing the transfer. If None, the default, then there is no limit on the time the transfer may take. @type lifetime: float @rtype: generator of dns.message.Message objects. @param source: source address. The default is the IPv4 wildcard address. @type source: string @param source_port: The port from which to send the message. The default is 0. @type source_port: int @param serial: The SOA serial number to use as the base for an IXFR diff sequence (only meaningful if rdtype == dns.rdatatype.IXFR). @type serial: int @param use_udp: Use UDP (only meaningful for IXFR) @type use_udp: bool @param keyalgorithm: The TSIG algorithm to use; defaults to dns.tsig.default_algorithm @type keyalgorithm: string """ if isinstance(zone, (str, unicode)): zone = dns.name.from_text(zone) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) q = dns.message.make_query(zone, rdtype, rdclass) if rdtype == dns.rdatatype.IXFR: rrset = dns.rrset.from_text(zone, 0, 'IN', 'SOA', '. . %u 0 0 0 0' % serial) q.authority.append(rrset) if not keyring is None: q.use_tsig(keyring, keyname, algorithm=keyalgorithm) wire = q.to_wire() if af is None: try: af = dns.inet.af_for_address(where) except Exception: af = dns.inet.AF_INET if af == dns.inet.AF_INET: destination = (where, port) if source is not None: source = (source, source_port) elif af == dns.inet.AF_INET6: destination = (where, port, 0, 0) if source is not None: source = (source, source_port, 0, 0) if use_udp: if rdtype != dns.rdatatype.IXFR: raise ValueError('cannot do a UDP AXFR') s = socket.socket(af, socket.SOCK_DGRAM, 0) else: s = socket.socket(af, socket.SOCK_STREAM, 0) s.setblocking(0) if source is not None: s.bind(source) expiration = _compute_expiration(lifetime) _connect(s, destination) l = len(wire) if use_udp: _wait_for_writable(s, expiration) s.send(wire) else: tcpmsg = struct.pack("!H", l) + wire _net_write(s, tcpmsg, expiration) done = False soa_rrset = None soa_count = 0 if relativize: origin = zone oname = dns.name.empty else: origin = None oname = zone tsig_ctx = None first = True while not done: mexpiration = _compute_expiration(timeout) if mexpiration is None or mexpiration > expiration: mexpiration = expiration if use_udp: _wait_for_readable(s, expiration) (wire, from_address) = s.recvfrom(65535) else: ldata = _net_read(s, 2, mexpiration) (l,) = struct.unpack("!H", ldata) wire = _net_read(s, l, mexpiration) r = dns.message.from_wire(wire, keyring=q.keyring, request_mac=q.mac, xfr=True, origin=origin, tsig_ctx=tsig_ctx, multi=True, first=first, one_rr_per_rrset=(rdtype==dns.rdatatype.IXFR)) tsig_ctx = r.tsig_ctx first = False answer_index = 0 delete_mode = False expecting_SOA = False if soa_rrset is None: if not r.answer or r.answer[0].name != oname: raise dns.exception.FormError rrset = r.answer[0] if rrset.rdtype != dns.rdatatype.SOA: raise dns.exception.FormError("first RRset is not an SOA") answer_index = 1 soa_rrset = rrset.copy() if rdtype == dns.rdatatype.IXFR: if soa_rrset[0].serial == serial: # # We're already up-to-date. # done = True else: expecting_SOA = True # # Process SOAs in the answer section (other than the initial # SOA in the first message). # for rrset in r.answer[answer_index:]: if done: raise dns.exception.FormError("answers after final SOA") if rrset.rdtype == dns.rdatatype.SOA and rrset.name == oname: if expecting_SOA: if rrset[0].serial != serial: raise dns.exception.FormError("IXFR base serial mismatch") expecting_SOA = False elif rdtype == dns.rdatatype.IXFR: delete_mode = not delete_mode if rrset == soa_rrset and not delete_mode: done = True elif expecting_SOA: # # We made an IXFR request and are expecting another # SOA RR, but saw something else, so this must be an # AXFR response. # rdtype = dns.rdatatype.AXFR expecting_SOA = False if done and q.keyring and not r.had_tsig: raise dns.exception.FormError("missing TSIG") yield r s.close()
17,810
Python
.py
454
31.253304
82
0.626516
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,118
rdataset.py
wummel_linkchecker/third_party/dnspython/dns/rdataset.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS rdatasets (an rdataset is a set of rdatas of a given type and class)""" import random import StringIO import struct import dns.exception import dns.rdatatype import dns.rdataclass import dns.rdata import dns.set # define SimpleSet here for backwards compatibility SimpleSet = dns.set.Set class DifferingCovers(dns.exception.DNSException): """Raised if an attempt is made to add a SIG/RRSIG whose covered type is not the same as that of the other rdatas in the rdataset.""" pass class IncompatibleTypes(dns.exception.DNSException): """Raised if an attempt is made to add rdata of an incompatible type.""" pass class Rdataset(dns.set.Set): """A DNS rdataset. @ivar rdclass: The class of the rdataset @type rdclass: int @ivar rdtype: The type of the rdataset @type rdtype: int @ivar covers: The covered type. Usually this value is dns.rdatatype.NONE, but if the rdtype is dns.rdatatype.SIG or dns.rdatatype.RRSIG, then the covers value will be the rdata type the SIG/RRSIG covers. The library treats the SIG and RRSIG types as if they were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This makes RRSIGs much easier to work with than if RRSIGs covering different rdata types were aggregated into a single RRSIG rdataset. @type covers: int @ivar ttl: The DNS TTL (Time To Live) value @type ttl: int """ __slots__ = ['rdclass', 'rdtype', 'covers', 'ttl'] def __init__(self, rdclass, rdtype, covers=dns.rdatatype.NONE): """Create a new rdataset of the specified class and type. @see: the description of the class instance variables for the meaning of I{rdclass} and I{rdtype}""" super(Rdataset, self).__init__() self.rdclass = rdclass self.rdtype = rdtype self.covers = covers self.ttl = 0 def _clone(self): obj = super(Rdataset, self)._clone() obj.rdclass = self.rdclass obj.rdtype = self.rdtype obj.covers = self.covers obj.ttl = self.ttl return obj def update_ttl(self, ttl): """Set the TTL of the rdataset to be the lesser of the set's current TTL or the specified TTL. If the set contains no rdatas, set the TTL to the specified TTL. @param ttl: The TTL @type ttl: int""" if len(self) == 0: self.ttl = ttl elif ttl < self.ttl: self.ttl = ttl def add(self, rd, ttl=None): """Add the specified rdata to the rdataset. If the optional I{ttl} parameter is supplied, then self.update_ttl(ttl) will be called prior to adding the rdata. @param rd: The rdata @type rd: dns.rdata.Rdata object @param ttl: The TTL @type ttl: int""" # # If we're adding a signature, do some special handling to # check that the signature covers the same type as the # other rdatas in this rdataset. If this is the first rdata # in the set, initialize the covers field. # if self.rdclass != rd.rdclass or self.rdtype != rd.rdtype: raise IncompatibleTypes if not ttl is None: self.update_ttl(ttl) if self.rdtype == dns.rdatatype.RRSIG or \ self.rdtype == dns.rdatatype.SIG: covers = rd.covers() if len(self) == 0 and self.covers == dns.rdatatype.NONE: self.covers = covers elif self.covers != covers: raise DifferingCovers if dns.rdatatype.is_singleton(rd.rdtype) and len(self) > 0: self.clear() super(Rdataset, self).add(rd) def union_update(self, other): self.update_ttl(other.ttl) super(Rdataset, self).union_update(other) def intersection_update(self, other): self.update_ttl(other.ttl) super(Rdataset, self).intersection_update(other) def update(self, other): """Add all rdatas in other to self. @param other: The rdataset from which to update @type other: dns.rdataset.Rdataset object""" self.update_ttl(other.ttl) super(Rdataset, self).update(other) def __repr__(self): if self.covers == 0: ctext = '' else: ctext = '(' + dns.rdatatype.to_text(self.covers) + ')' return '<DNS ' + dns.rdataclass.to_text(self.rdclass) + ' ' + \ dns.rdatatype.to_text(self.rdtype) + ctext + ' rdataset>' def __str__(self): return self.to_text() def __hash__(self): return hash((self.rdclass, self.rdtype, self.covers)) + \ super(Rdataset, self).__hash__() def __eq__(self, other): """Two rdatasets are equal if they have the same class, type, and covers, and contain the same rdata. @rtype: bool""" if not isinstance(other, Rdataset): return False if self.rdclass != other.rdclass or \ self.rdtype != other.rdtype or \ self.covers != other.covers: return False return super(Rdataset, self).__eq__(other) def __ne__(self, other): return not self.__eq__(other) def to_text(self, name=None, origin=None, relativize=True, override_rdclass=None, **kw): """Convert the rdataset into DNS master file format. @see: L{dns.name.Name.choose_relativity} for more information on how I{origin} and I{relativize} determine the way names are emitted. Any additional keyword arguments are passed on to the rdata to_text() method. @param name: If name is not None, emit a RRs with I{name} as the owner name. @type name: dns.name.Name object @param origin: The origin for relative names, or None. @type origin: dns.name.Name object @param relativize: True if names should names be relativized @type relativize: bool""" if not name is None: name = name.choose_relativity(origin, relativize) ntext = str(name) pad = ' ' else: ntext = '' pad = '' s = StringIO.StringIO() if not override_rdclass is None: rdclass = override_rdclass else: rdclass = self.rdclass if len(self) == 0: # # Empty rdatasets are used for the question section, and in # some dynamic updates, so we don't need to print out the TTL # (which is meaningless anyway). # print >> s, '%s%s%s %s' % (ntext, pad, dns.rdataclass.to_text(rdclass), dns.rdatatype.to_text(self.rdtype)) else: for rd in self: print >> s, '%s%s%d %s %s %s' % \ (ntext, pad, self.ttl, dns.rdataclass.to_text(rdclass), dns.rdatatype.to_text(self.rdtype), rd.to_text(origin=origin, relativize=relativize, **kw)) # # We strip off the final \n for the caller's convenience in printing # return s.getvalue()[:-1] def to_wire(self, name, file, compress=None, origin=None, override_rdclass=None, want_shuffle=True): """Convert the rdataset to wire format. @param name: The owner name of the RRset that will be emitted @type name: dns.name.Name object @param file: The file to which the wire format data will be appended @type file: file @param compress: The compression table to use; the default is None. @type compress: dict @param origin: The origin to be appended to any relative names when they are emitted. The default is None. @returns: the number of records emitted @rtype: int """ if not override_rdclass is None: rdclass = override_rdclass want_shuffle = False else: rdclass = self.rdclass file.seek(0, 2) if len(self) == 0: name.to_wire(file, compress, origin) stuff = struct.pack("!HHIH", self.rdtype, rdclass, 0, 0) file.write(stuff) return 1 else: if want_shuffle: l = list(self) random.shuffle(l) else: l = self for rd in l: name.to_wire(file, compress, origin) stuff = struct.pack("!HHIH", self.rdtype, rdclass, self.ttl, 0) file.write(stuff) start = file.tell() rd.to_wire(file, compress, origin) end = file.tell() assert end - start < 65536 file.seek(start - 2) stuff = struct.pack("!H", end - start) file.write(stuff) file.seek(0, 2) return len(self) def match(self, rdclass, rdtype, covers): """Returns True if this rdataset matches the specified class, type, and covers""" if self.rdclass == rdclass and \ self.rdtype == rdtype and \ self.covers == covers: return True return False def from_text_list(rdclass, rdtype, ttl, text_rdatas): """Create an rdataset with the specified class, type, and TTL, and with the specified list of rdatas in text format. @rtype: dns.rdataset.Rdataset object """ if isinstance(rdclass, (str, unicode)): rdclass = dns.rdataclass.from_text(rdclass) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) r = Rdataset(rdclass, rdtype) r.update_ttl(ttl) for t in text_rdatas: rd = dns.rdata.from_text(r.rdclass, r.rdtype, t) r.add(rd) return r def from_text(rdclass, rdtype, ttl, *text_rdatas): """Create an rdataset with the specified class, type, and TTL, and with the specified rdatas in text format. @rtype: dns.rdataset.Rdataset object """ return from_text_list(rdclass, rdtype, ttl, text_rdatas) def from_rdata_list(ttl, rdatas): """Create an rdataset with the specified TTL, and with the specified list of rdata objects. @rtype: dns.rdataset.Rdataset object """ if len(rdatas) == 0: raise ValueError("rdata list must not be empty") r = None for rd in rdatas: if r is None: r = Rdataset(rd.rdclass, rd.rdtype) r.update_ttl(ttl) first_time = False r.add(rd) return r def from_rdata(ttl, *rdatas): """Create an rdataset with the specified TTL, and with the specified rdata objects. @rtype: dns.rdataset.Rdataset object """ return from_rdata_list(ttl, rdatas)
11,684
Python
.py
283
32.265018
78
0.612721
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,119
edns.py
wummel_linkchecker/third_party/dnspython/dns/edns.py
# Copyright (C) 2009, 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """EDNS Options""" NSID = 3 class Option(object): """Base class for all EDNS option types. """ def __init__(self, otype): """Initialize an option. @param rdtype: The rdata type @type rdtype: int """ self.otype = otype def to_wire(self, file): """Convert an option to wire format. """ raise NotImplementedError def from_wire(cls, otype, wire, current, olen): """Build an EDNS option object from wire format @param otype: The option type @type otype: int @param wire: The wire-format message @type wire: string @param current: The offet in wire of the beginning of the rdata. @type current: int @param olen: The length of the wire-format option data @type olen: int @rtype: dns.ends.Option instance""" raise NotImplementedError from_wire = classmethod(from_wire) def _cmp(self, other): """Compare an ENDS option with another option of the same type. Return < 0 if self < other, 0 if self == other, and > 0 if self > other. """ raise NotImplementedError def __hash__(self): return hash(self.otype) def __eq__(self, other): if not isinstance(other, Option): return False if self.otype != other.otype: return False return self._cmp(other) == 0 def __ne__(self, other): if not isinstance(other, Option): return False if self.otype != other.otype: return False return self._cmp(other) != 0 def __lt__(self, other): if not isinstance(other, Option) or \ self.otype != other.otype: return NotImplemented return self._cmp(other) < 0 def __le__(self, other): if not isinstance(other, Option) or \ self.otype != other.otype: return NotImplemented return self._cmp(other) <= 0 def __ge__(self, other): if not isinstance(other, Option) or \ self.otype != other.otype: return NotImplemented return self._cmp(other) >= 0 def __gt__(self, other): if not isinstance(other, Option) or \ self.otype != other.otype: return NotImplemented return self._cmp(other) > 0 class GenericOption(Option): """Generate Rdata Class This class is used for EDNS option types for which we have no better implementation. """ def __init__(self, otype, data): super(GenericOption, self).__init__(otype) self.data = data def to_wire(self, file): file.write(self.data) def from_wire(cls, otype, wire, current, olen): return cls(otype, wire[current : current + olen]) from_wire = classmethod(from_wire) def _cmp(self, other): return cmp(self.data, other.data) _type_to_class = { } def get_option_class(otype): cls = _type_to_class.get(otype) if cls is None: cls = GenericOption return cls def option_from_wire(otype, wire, current, olen): """Build an EDNS option object from wire format @param otype: The option type @type otype: int @param wire: The wire-format message @type wire: string @param current: The offet in wire of the beginning of the rdata. @type current: int @param olen: The length of the wire-format option data @type olen: int @rtype: dns.ends.Option instance""" cls = get_option_class(otype) return cls.from_wire(otype, wire, current, olen)
4,382
Python
.py
116
30.836207
80
0.643616
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,120
reversename.py
wummel_linkchecker/third_party/dnspython/dns/reversename.py
# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Reverse Map Names. @var ipv4_reverse_domain: The DNS IPv4 reverse-map domain, in-addr.arpa. @type ipv4_reverse_domain: dns.name.Name object @var ipv6_reverse_domain: The DNS IPv6 reverse-map domain, ip6.arpa. @type ipv6_reverse_domain: dns.name.Name object """ import dns.name import dns.ipv6 import dns.ipv4 ipv4_reverse_domain = dns.name.from_text('in-addr.arpa.') ipv6_reverse_domain = dns.name.from_text('ip6.arpa.') def from_address(text): """Convert an IPv4 or IPv6 address in textual form into a Name object whose value is the reverse-map domain name of the address. @param text: an IPv4 or IPv6 address in textual form (e.g. '127.0.0.1', '::1') @type text: str @rtype: dns.name.Name object """ try: parts = list(dns.ipv6.inet_aton(text).encode('hex_codec')) origin = ipv6_reverse_domain except Exception: parts = ['%d' % ord(byte) for byte in dns.ipv4.inet_aton(text)] origin = ipv4_reverse_domain parts.reverse() return dns.name.from_text('.'.join(parts), origin=origin) def to_address(name): """Convert a reverse map domain name into textual address form. @param name: an IPv4 or IPv6 address in reverse-map form. @type name: dns.name.Name object @rtype: str """ if name.is_subdomain(ipv4_reverse_domain): name = name.relativize(ipv4_reverse_domain) labels = list(name.labels) labels.reverse() text = '.'.join(labels) # run through inet_aton() to check syntax and make pretty. return dns.ipv4.inet_ntoa(dns.ipv4.inet_aton(text)) elif name.is_subdomain(ipv6_reverse_domain): name = name.relativize(ipv6_reverse_domain) labels = list(name.labels) labels.reverse() parts = [] i = 0 l = len(labels) while i < l: parts.append(''.join(labels[i:i+4])) i += 4 text = ':'.join(parts) # run through inet_aton() to check syntax and make pretty. return dns.ipv6.inet_ntoa(dns.ipv6.inet_aton(text)) else: raise dns.exception.SyntaxError('unknown reverse-map address family')
2,940
Python
.py
69
37.637681
79
0.697731
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,121
node.py
wummel_linkchecker/third_party/dnspython/dns/node.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS nodes. A node is a set of rdatasets.""" import StringIO import dns.rdataset import dns.rdatatype import dns.renderer class Node(object): """A DNS node. A node is a set of rdatasets @ivar rdatasets: the node's rdatasets @type rdatasets: list of dns.rdataset.Rdataset objects""" __slots__ = ['rdatasets'] def __init__(self): """Initialize a DNS node. """ self.rdatasets = []; def to_text(self, name, **kw): """Convert a node to text format. Each rdataset at the node is printed. Any keyword arguments to this method are passed on to the rdataset's to_text() method. @param name: the owner name of the rdatasets @type name: dns.name.Name object @rtype: string """ s = StringIO.StringIO() for rds in self.rdatasets: print >> s, rds.to_text(name, **kw) return s.getvalue()[:-1] def __repr__(self): return '<DNS node ' + str(id(self)) + '>' def __eq__(self, other): """Two nodes are equal if they have the same rdatasets. @rtype: bool """ # # This is inefficient. Good thing we don't need to do it much. # for rd in self.rdatasets: if rd not in other.rdatasets: return False for rd in other.rdatasets: if rd not in self.rdatasets: return False return True def __ne__(self, other): return not self.__eq__(other) def __len__(self): return len(self.rdatasets) def __iter__(self): return iter(self.rdatasets) def find_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE, create=False): """Find an rdataset matching the specified properties in the current node. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the rdataset @type rdtype: int @param covers: The covered type. Usually this value is dns.rdatatype.NONE, but if the rdtype is dns.rdatatype.SIG or dns.rdatatype.RRSIG, then the covers value will be the rdata type the SIG/RRSIG covers. The library treats the SIG and RRSIG types as if they were a family of types, e.g. RRSIG(A), RRSIG(NS), RRSIG(SOA). This makes RRSIGs much easier to work with than if RRSIGs covering different rdata types were aggregated into a single RRSIG rdataset. @type covers: int @param create: If True, create the rdataset if it is not found. @type create: bool @raises KeyError: An rdataset of the desired type and class does not exist and I{create} is not True. @rtype: dns.rdataset.Rdataset object """ for rds in self.rdatasets: if rds.match(rdclass, rdtype, covers): return rds if not create: raise KeyError rds = dns.rdataset.Rdataset(rdclass, rdtype) self.rdatasets.append(rds) return rds def get_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE, create=False): """Get an rdataset matching the specified properties in the current node. None is returned if an rdataset of the specified type and class does not exist and I{create} is not True. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the rdataset @type rdtype: int @param covers: The covered type. @type covers: int @param create: If True, create the rdataset if it is not found. @type create: bool @rtype: dns.rdataset.Rdataset object or None """ try: rds = self.find_rdataset(rdclass, rdtype, covers, create) except KeyError: rds = None return rds def delete_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE): """Delete the rdataset matching the specified properties in the current node. If a matching rdataset does not exist, it is not an error. @param rdclass: The class of the rdataset @type rdclass: int @param rdtype: The type of the rdataset @type rdtype: int @param covers: The covered type. @type covers: int """ rds = self.get_rdataset(rdclass, rdtype, covers) if not rds is None: self.rdatasets.remove(rds) def replace_rdataset(self, replacement): """Replace an rdataset. It is not an error if there is no rdataset matching I{replacement}. Ownership of the I{replacement} object is transferred to the node; in other words, this method does not store a copy of I{replacement} at the node, it stores I{replacement} itself. """ self.delete_rdataset(replacement.rdclass, replacement.rdtype, replacement.covers) self.rdatasets.append(replacement)
5,869
Python
.py
139
33.848921
76
0.643497
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,122
dnssec.py
wummel_linkchecker/third_party/dnspython/dns/dnssec.py
# Copyright (C) 2003-2007, 2009, 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Common DNSSEC-related functions and constants.""" import cStringIO import struct import time import dns.exception import dns.hash import dns.name import dns.node import dns.rdataset import dns.rdata import dns.rdatatype import dns.rdataclass class UnsupportedAlgorithm(dns.exception.DNSException): """Raised if an algorithm is not supported.""" pass class ValidationFailure(dns.exception.DNSException): """The DNSSEC signature is invalid.""" pass RSAMD5 = 1 DH = 2 DSA = 3 ECC = 4 RSASHA1 = 5 DSANSEC3SHA1 = 6 RSASHA1NSEC3SHA1 = 7 RSASHA256 = 8 RSASHA512 = 10 INDIRECT = 252 PRIVATEDNS = 253 PRIVATEOID = 254 _algorithm_by_text = { 'RSAMD5' : RSAMD5, 'DH' : DH, 'DSA' : DSA, 'ECC' : ECC, 'RSASHA1' : RSASHA1, 'DSANSEC3SHA1' : DSANSEC3SHA1, 'RSASHA1NSEC3SHA1' : RSASHA1NSEC3SHA1, 'RSASHA256' : RSASHA256, 'RSASHA512' : RSASHA512, 'INDIRECT' : INDIRECT, 'PRIVATEDNS' : PRIVATEDNS, 'PRIVATEOID' : PRIVATEOID, } # We construct the inverse mapping programmatically to ensure that we # cannot make any mistakes (e.g. omissions, cut-and-paste errors) that # would cause the mapping not to be true inverse. _algorithm_by_value = dict([(y, x) for x, y in _algorithm_by_text.iteritems()]) def algorithm_from_text(text): """Convert text into a DNSSEC algorithm value @rtype: int""" value = _algorithm_by_text.get(text.upper()) if value is None: value = int(text) return value def algorithm_to_text(value): """Convert a DNSSEC algorithm value to text @rtype: string""" text = _algorithm_by_value.get(value) if text is None: text = str(value) return text def _to_rdata(record, origin): s = cStringIO.StringIO() record.to_wire(s, origin=origin) return s.getvalue() def key_id(key, origin=None): rdata = _to_rdata(key, origin) if key.algorithm == RSAMD5: return (ord(rdata[-3]) << 8) + ord(rdata[-2]) else: total = 0 for i in range(len(rdata) // 2): total += (ord(rdata[2 * i]) << 8) + ord(rdata[2 * i + 1]) if len(rdata) % 2 != 0: total += ord(rdata[len(rdata) - 1]) << 8 total += ((total >> 16) & 0xffff); return total & 0xffff def make_ds(name, key, algorithm, origin=None): if algorithm.upper() == 'SHA1': dsalg = 1 hash = dns.hash.get('SHA1')() elif algorithm.upper() == 'SHA256': dsalg = 2 hash = dns.hash.get('SHA256')() else: raise UnsupportedAlgorithm, 'unsupported algorithm "%s"' % algorithm if isinstance(name, (str, unicode)): name = dns.name.from_text(name, origin) hash.update(name.canonicalize().to_wire()) hash.update(_to_rdata(key, origin)) digest = hash.digest() dsrdata = struct.pack("!HBB", key_id(key), key.algorithm, dsalg) + digest return dns.rdata.from_wire(dns.rdataclass.IN, dns.rdatatype.DS, dsrdata, 0, len(dsrdata)) def _find_key(keys, rrsig): value = keys.get(rrsig.signer) if value is None: return None if isinstance(value, dns.node.Node): try: rdataset = node.find_rdataset(dns.rdataclass.IN, dns.rdatatype.DNSKEY) except KeyError: return None else: rdataset = value for rdata in rdataset: if rdata.algorithm == rrsig.algorithm and \ key_id(rdata) == rrsig.key_tag: return rdata return None def _is_rsa(algorithm): return algorithm in (RSAMD5, RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512) def _is_dsa(algorithm): return algorithm in (DSA, DSANSEC3SHA1) def _is_md5(algorithm): return algorithm == RSAMD5 def _is_sha1(algorithm): return algorithm in (DSA, RSASHA1, DSANSEC3SHA1, RSASHA1NSEC3SHA1) def _is_sha256(algorithm): return algorithm == RSASHA256 def _is_sha512(algorithm): return algorithm == RSASHA512 def _make_hash(algorithm): if _is_md5(algorithm): return dns.hash.get('MD5')() if _is_sha1(algorithm): return dns.hash.get('SHA1')() if _is_sha256(algorithm): return dns.hash.get('SHA256')() if _is_sha512(algorithm): return dns.hash.get('SHA512')() raise ValidationFailure, 'unknown hash for algorithm %u' % algorithm def _make_algorithm_id(algorithm): if _is_md5(algorithm): oid = [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05] elif _is_sha1(algorithm): oid = [0x2b, 0x0e, 0x03, 0x02, 0x1a] elif _is_sha256(algorithm): oid = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01] elif _is_sha512(algorithm): oid = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03] else: raise ValidationFailure, 'unknown algorithm %u' % algorithm olen = len(oid) dlen = _make_hash(algorithm).digest_size idbytes = [0x30] + [8 + olen + dlen] + \ [0x30, olen + 4] + [0x06, olen] + oid + \ [0x05, 0x00] + [0x04, dlen] return ''.join(map(chr, idbytes)) def _validate_rrsig(rrset, rrsig, keys, origin=None, now=None): """Validate an RRset against a single signature rdata The owner name of the rrsig is assumed to be the same as the owner name of the rrset. @param rrset: The RRset to validate @type rrset: dns.rrset.RRset or (dns.name.Name, dns.rdataset.Rdataset) tuple @param rrsig: The signature rdata @type rrsig: dns.rrset.Rdata @param keys: The key dictionary. @type keys: a dictionary keyed by dns.name.Name with node or rdataset values @param origin: The origin to use for relative names @type origin: dns.name.Name or None @param now: The time to use when validating the signatures. The default is the current time. @type now: int """ if isinstance(origin, (str, unicode)): origin = dns.name.from_text(origin, dns.name.root) key = _find_key(keys, rrsig) if not key: raise ValidationFailure, 'unknown key' # For convenience, allow the rrset to be specified as a (name, rdataset) # tuple as well as a proper rrset if isinstance(rrset, tuple): rrname = rrset[0] rdataset = rrset[1] else: rrname = rrset.name rdataset = rrset if now is None: now = time.time() if rrsig.expiration < now: raise ValidationFailure, 'expired' if rrsig.inception > now: raise ValidationFailure, 'not yet valid' hash = _make_hash(rrsig.algorithm) if _is_rsa(rrsig.algorithm): keyptr = key.key (bytes,) = struct.unpack('!B', keyptr[0:1]) keyptr = keyptr[1:] if bytes == 0: (bytes,) = struct.unpack('!H', keyptr[0:2]) keyptr = keyptr[2:] rsa_e = keyptr[0:bytes] rsa_n = keyptr[bytes:] keylen = len(rsa_n) * 8 pubkey = Crypto.PublicKey.RSA.construct( (Crypto.Util.number.bytes_to_long(rsa_n), Crypto.Util.number.bytes_to_long(rsa_e))) sig = (Crypto.Util.number.bytes_to_long(rrsig.signature),) elif _is_dsa(rrsig.algorithm): keyptr = key.key (t,) = struct.unpack('!B', keyptr[0:1]) keyptr = keyptr[1:] octets = 64 + t * 8 dsa_q = keyptr[0:20] keyptr = keyptr[20:] dsa_p = keyptr[0:octets] keyptr = keyptr[octets:] dsa_g = keyptr[0:octets] keyptr = keyptr[octets:] dsa_y = keyptr[0:octets] pubkey = Crypto.PublicKey.DSA.construct( (Crypto.Util.number.bytes_to_long(dsa_y), Crypto.Util.number.bytes_to_long(dsa_g), Crypto.Util.number.bytes_to_long(dsa_p), Crypto.Util.number.bytes_to_long(dsa_q))) (dsa_r, dsa_s) = struct.unpack('!20s20s', rrsig.signature[1:]) sig = (Crypto.Util.number.bytes_to_long(dsa_r), Crypto.Util.number.bytes_to_long(dsa_s)) else: raise ValidationFailure, 'unknown algorithm %u' % rrsig.algorithm hash.update(_to_rdata(rrsig, origin)[:18]) hash.update(rrsig.signer.to_digestable(origin)) if rrsig.labels < len(rrname) - 1: suffix = rrname.split(rrsig.labels + 1)[1] rrname = dns.name.from_text('*', suffix) rrnamebuf = rrname.to_digestable(origin) rrfixed = struct.pack('!HHI', rdataset.rdtype, rdataset.rdclass, rrsig.original_ttl) rrlist = sorted(rdataset); for rr in rrlist: hash.update(rrnamebuf) hash.update(rrfixed) rrdata = rr.to_digestable(origin) rrlen = struct.pack('!H', len(rrdata)) hash.update(rrlen) hash.update(rrdata) digest = hash.digest() if _is_rsa(rrsig.algorithm): # PKCS1 algorithm identifier goop digest = _make_algorithm_id(rrsig.algorithm) + digest padlen = keylen // 8 - len(digest) - 3 digest = chr(0) + chr(1) + chr(0xFF) * padlen + chr(0) + digest elif _is_dsa(rrsig.algorithm): pass else: # Raise here for code clarity; this won't actually ever happen # since if the algorithm is really unknown we'd already have # raised an exception above raise ValidationFailure, 'unknown algorithm %u' % rrsig.algorithm if not pubkey.verify(digest, sig): raise ValidationFailure, 'verify failure' def _validate(rrset, rrsigset, keys, origin=None, now=None): """Validate an RRset @param rrset: The RRset to validate @type rrset: dns.rrset.RRset or (dns.name.Name, dns.rdataset.Rdataset) tuple @param rrsigset: The signature RRset @type rrsigset: dns.rrset.RRset or (dns.name.Name, dns.rdataset.Rdataset) tuple @param keys: The key dictionary. @type keys: a dictionary keyed by dns.name.Name with node or rdataset values @param origin: The origin to use for relative names @type origin: dns.name.Name or None @param now: The time to use when validating the signatures. The default is the current time. @type now: int """ if isinstance(origin, (str, unicode)): origin = dns.name.from_text(origin, dns.name.root) if isinstance(rrset, tuple): rrname = rrset[0] else: rrname = rrset.name if isinstance(rrsigset, tuple): rrsigname = rrsigset[0] rrsigrdataset = rrsigset[1] else: rrsigname = rrsigset.name rrsigrdataset = rrsigset rrname = rrname.choose_relativity(origin) rrsigname = rrname.choose_relativity(origin) if rrname != rrsigname: raise ValidationFailure, "owner names do not match" for rrsig in rrsigrdataset: try: _validate_rrsig(rrset, rrsig, keys, origin, now) return except ValidationFailure, e: pass raise ValidationFailure, "no RRSIGs validated" def _need_pycrypto(*args, **kwargs): raise NotImplementedError, "DNSSEC validation requires pycrypto" try: import Crypto.PublicKey.RSA import Crypto.PublicKey.DSA import Crypto.Util.number validate = _validate validate_rrsig = _validate_rrsig except ImportError: validate = _need_pycrypto validate_rrsig = _need_pycrypto
12,068
Python
.py
322
31.006211
80
0.649282
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,123
resolver.py
wummel_linkchecker/third_party/dnspython/dns/resolver.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS stub resolver. @var default_resolver: The default resolver object @type default_resolver: dns.resolver.Resolver object""" import socket import sys import os import time import dns.exception import dns.message import dns.name import dns.query import dns.rcode import dns.rdataclass import dns.rdatatype if sys.platform == 'win32': import _winreg class NXDOMAIN(dns.exception.DNSException): """The query name does not exist.""" pass # The definition of the Timeout exception has moved from here to the # dns.exception module. We keep dns.resolver.Timeout defined for # backwards compatibility. Timeout = dns.exception.Timeout class NoAnswer(dns.exception.DNSException): """The response did not contain an answer to the question.""" pass class NoNameservers(dns.exception.DNSException): """No non-broken nameservers are available to answer the query.""" pass class NotAbsolute(dns.exception.DNSException): """Raised if an absolute domain name is required but a relative name was provided.""" pass class NoRootSOA(dns.exception.DNSException): """Raised if for some reason there is no SOA at the root name. This should never happen!""" pass class NoMetaqueries(dns.exception.DNSException): """Metaqueries are not allowed.""" pass class Answer(object): """DNS stub resolver answer Instances of this class bundle up the result of a successful DNS resolution. For convenience, the answer object implements much of the sequence protocol, forwarding to its rrset. E.g. "for a in answer" is equivalent to "for a in answer.rrset", "answer[i]" is equivalent to "answer.rrset[i]", and "answer[i:j]" is equivalent to "answer.rrset[i:j]". Note that CNAMEs or DNAMEs in the response may mean that answer node's name might not be the query name. @ivar qname: The query name @type qname: dns.name.Name object @ivar rdtype: The query type @type rdtype: int @ivar rdclass: The query class @type rdclass: int @ivar response: The response message @type response: dns.message.Message object @ivar rrset: The answer @type rrset: dns.rrset.RRset object @ivar expiration: The time when the answer expires @type expiration: float (seconds since the epoch) @ivar canonical_name: The canonical name of the query name @type canonical_name: dns.name.Name object """ def __init__(self, qname, rdtype, rdclass, response, raise_on_no_answer=True): self.qname = qname self.rdtype = rdtype self.rdclass = rdclass self.response = response min_ttl = -1 rrset = None for count in xrange(0, 15): try: rrset = response.find_rrset(response.answer, qname, rdclass, rdtype) if min_ttl == -1 or rrset.ttl < min_ttl: min_ttl = rrset.ttl break except KeyError: if rdtype != dns.rdatatype.CNAME: try: crrset = response.find_rrset(response.answer, qname, rdclass, dns.rdatatype.CNAME) if min_ttl == -1 or crrset.ttl < min_ttl: min_ttl = crrset.ttl for rd in crrset: qname = rd.target break continue except KeyError: if raise_on_no_answer: raise NoAnswer("DNS response had no answer") if raise_on_no_answer: raise NoAnswer("DNS response had no answer") if rrset is None and raise_on_no_answer: raise NoAnswer("DNS response had no answer") self.canonical_name = qname self.rrset = rrset if rrset is None: while 1: # Look for a SOA RR whose owner name is a superdomain # of qname. try: srrset = response.find_rrset(response.authority, qname, rdclass, dns.rdatatype.SOA) if min_ttl == -1 or srrset.ttl < min_ttl: min_ttl = srrset.ttl if srrset[0].minimum < min_ttl: min_ttl = srrset[0].minimum break except KeyError: try: qname = qname.parent() except dns.name.NoParent: break self.expiration = time.time() + min_ttl def __str__ (self): return str(self.rrset) def __getattr__(self, attr): if attr == 'name': return self.rrset.name elif attr == 'ttl': return self.rrset.ttl elif attr == 'covers': return self.rrset.covers elif attr == 'rdclass': return self.rrset.rdclass elif attr == 'rdtype': return self.rrset.rdtype else: raise AttributeError(attr) def __len__(self): return len(self.rrset) def __iter__(self): return iter(self.rrset) def __getitem__(self, i): return self.rrset[i] def __delitem__(self, i): del self.rrset[i] def __getslice__(self, i, j): return self.rrset[i:j] def __delslice__(self, i, j): del self.rrset[i:j] class Cache(object): """Simple DNS answer cache. @ivar data: A dictionary of cached data @type data: dict @ivar cleaning_interval: The number of seconds between cleanings. The default is 300 (5 minutes). @type cleaning_interval: float @ivar next_cleaning: The time the cache should next be cleaned (in seconds since the epoch.) @type next_cleaning: float """ def __init__(self, cleaning_interval=300.0): """Initialize a DNS cache. @param cleaning_interval: the number of seconds between periodic cleanings. The default is 300.0 @type cleaning_interval: float. """ self.data = {} self.cleaning_interval = cleaning_interval self.next_cleaning = time.time() + self.cleaning_interval def maybe_clean(self): """Clean the cache if it's time to do so.""" now = time.time() if self.next_cleaning <= now: keys_to_delete = [] for (k, v) in self.data.iteritems(): if v.expiration <= now: keys_to_delete.append(k) for k in keys_to_delete: del self.data[k] now = time.time() self.next_cleaning = now + self.cleaning_interval def get(self, key): """Get the answer associated with I{key}. Returns None if no answer is cached for the key. @param key: the key @type key: (dns.name.Name, int, int) tuple whose values are the query name, rdtype, and rdclass. @rtype: dns.resolver.Answer object or None """ self.maybe_clean() v = self.data.get(key) if v is None or v.expiration <= time.time(): return None return v def put(self, key, value): """Associate key and value in the cache. @param key: the key @type key: (dns.name.Name, int, int) tuple whose values are the query name, rdtype, and rdclass. @param value: The answer being cached @type value: dns.resolver.Answer object """ self.maybe_clean() self.data[key] = value def flush(self, key=None): """Flush the cache. If I{key} is specified, only that item is flushed. Otherwise the entire cache is flushed. @param key: the key to flush @type key: (dns.name.Name, int, int) tuple or None """ if not key is None: if key in self.data: del self.data[key] else: self.data = {} self.next_cleaning = time.time() + self.cleaning_interval class Resolver(object): """DNS stub resolver @ivar domain: The domain of this host @type domain: dns.name.Name object @ivar nameservers: A list of nameservers to query. Each nameserver is a string which contains the IP address of a nameserver. @type nameservers: list of strings @ivar search: The search list. If the query name is a relative name, the resolver will construct an absolute query name by appending the search names one by one to the query name. @type search: list of dns.name.Name objects @ivar port: The port to which to send queries. The default is 53. @type port: int @ivar timeout: The number of seconds to wait for a response from a server, before timing out. @type timeout: float @ivar lifetime: The total number of seconds to spend trying to get an answer to the question. If the lifetime expires, a Timeout exception will occur. @type lifetime: float @ivar keyring: The TSIG keyring to use. The default is None. @type keyring: dict @ivar keyname: The TSIG keyname to use. The default is None. @type keyname: dns.name.Name object @ivar keyalgorithm: The TSIG key algorithm to use. The default is dns.tsig.default_algorithm. @type keyalgorithm: string @ivar edns: The EDNS level to use. The default is -1, no Edns. @type edns: int @ivar ednsflags: The EDNS flags @type ednsflags: int @ivar payload: The EDNS payload size. The default is 0. @type payload: int @ivar cache: The cache to use. The default is None. @type cache: dns.resolver.Cache object """ def __init__(self, filename='/etc/resolv.conf', configure=True): """Initialize a resolver instance. @param filename: The filename of a configuration file in standard /etc/resolv.conf format. This parameter is meaningful only when I{configure} is true and the platform is POSIX. @type filename: string or file object @param configure: If True (the default), the resolver instance is configured in the normal fashion for the operating system the resolver is running on. (I.e. a /etc/resolv.conf file on POSIX systems and from the registry on Windows systems.) @type configure: bool""" self.reset() if configure: if sys.platform == 'win32': self.read_registry() elif filename: self.read_resolv_conf(filename) self.read_local_hosts() if len(self.search) == 0: self.search.add(self.domain) def reset(self): """Reset all resolver configuration to the defaults.""" self.domain = \ dns.name.Name(dns.name.from_text(socket.gethostname())[1:]) if len(self.domain) == 0: self.domain = dns.name.root self.nameservers = [] self.localhosts = set([ 'localhost', 'loopback', '127.0.0.1', '0.0.0.0', '::1', 'ip6-localhost', 'ip6-loopback', ]) # connected and active network interfaces self.interfaces = set() self.search = set() self.search_patterns = ['www.%s.com', 'www.%s.org', 'www.%s.net', ] self.port = 53 self.timeout = 2.0 self.lifetime = 30.0 self.keyring = None self.keyname = None self.keyalgorithm = dns.tsig.default_algorithm self.edns = -1 self.ednsflags = 0 self.payload = 0 self.cache = None def read_resolv_conf(self, f): """Process f as a file in the /etc/resolv.conf format. If f is a string, it is used as the name of the file to open; otherwise it is treated as the file itself.""" if isinstance(f, basestring): try: f = open(f, 'r') except IOError: # /etc/resolv.conf doesn't exist, can't be read, etc. # We'll just use the default resolver configuration. self.nameservers = ['127.0.0.1'] return want_close = True else: want_close = False try: for l in f: l = l.strip() if len(l) == 0 or l[0] == '#' or l[0] == ';': continue tokens = l.split() if len(tokens) < 2: continue if tokens[0] == 'nameserver': self.nameservers.append(tokens[1]) elif tokens[0] == 'domain': self.domain = dns.name.from_text(tokens[1]) elif tokens[0] == 'search': for suffix in tokens[1:]: self.search.add(dns.name.from_text(suffix)) finally: if want_close: f.close() if len(self.nameservers) == 0: self.nameservers.append('127.0.0.1') def read_local_hosts (self): self.add_addrinfo(socket.gethostname()) # add system specific hosts for all enabled interfaces self.add_addrinfo('localhost', interface=True) for addr in self.read_local_ifaddrs(): self.add_addrinfo(addr, interface=True) def read_local_ifaddrs (self): """ IP addresses for all active interfaces. @return: list of IP addresses @rtype: list of strings """ if os.name != 'posix': # only POSIX is supported right now return [] try: from linkcheck.network import IfConfig except ImportError: return [] ifaddrs = [] ifc = IfConfig() for iface in ifc.getInterfaceList(flags=IfConfig.IFF_UP): addr = ifc.getAddr(iface) if addr: ifaddrs.append(addr) return ifaddrs def add_addrinfo (self, host, interface=False): try: addrinfo = socket.gethostbyaddr(host) except socket.error: self.localhosts.add(host.lower()) if interface: self.interfaces.add(host.lower()) return self.localhosts.add(addrinfo[0].lower()) if interface: self.interfaces.add(addrinfo[0].lower()) for h in addrinfo[1]: self.localhosts.add(h.lower()) for h in addrinfo[2]: self.localhosts.add(h.lower()) def _determine_split_char(self, entry): # The windows registry irritatingly changes the list element # delimiter in between ' ' and ',' (and vice-versa) in various # versions of windows. if entry.find(' ') >= 0: split_char = ' ' elif entry.find(',') >= 0: split_char = ',' else: # probably a singleton; treat as a space-separated list. split_char = ' ' return split_char def _config_win32_nameservers(self, nameservers): """Configure a NameServer registry entry.""" # we call str() on nameservers to convert it from unicode to ascii nameservers = str(nameservers) split_char = self._determine_split_char(nameservers) ns_list = nameservers.split(split_char) for ns in ns_list: if not ns in self.nameservers: self.nameservers.append(ns) def _config_win32_domain(self, domain): """Configure a Domain registry entry.""" # we call str() on domain to convert it from unicode to ascii self.domain = dns.name.from_text(str(domain)) def _config_win32_search(self, search): """Configure a Search registry entry.""" # we call str() on search to convert it from unicode to ascii search = str(search) split_char = self._determine_split_char(search) search_list = search.split(split_char) for s in search_list: if not s in self.search: self.search.add(dns.name.from_text(s)) def _config_win32_add_ifaddr (self, key, name): """Add interface ip address to self.localhosts.""" try: ip, rtype = _winreg.QueryValueEx(key, name) if isinstance(ip, basestring) and ip: ip = str(ip).lower() self.localhosts.add(ip) self.interfaces.add(ip) except WindowsError: pass def _config_win32_fromkey(self, key): """Extract DNS info from a registry key.""" try: enable_dhcp, rtype = _winreg.QueryValueEx(key, 'EnableDHCP') except WindowsError: enable_dhcp = False if enable_dhcp: try: servers, rtype = _winreg.QueryValueEx(key, 'DhcpNameServer') except WindowsError: servers = None if servers: self._config_win32_nameservers(servers) try: dom, rtype = _winreg.QueryValueEx(key, 'DhcpDomain') if dom: self._config_win32_domain(servers) except WindowsError: pass self._config_win32_add_ifaddr(key, 'DhcpIPAddress') else: try: servers, rtype = _winreg.QueryValueEx(key, 'NameServer') except WindowsError: servers = None if servers: self._config_win32_nameservers(servers) try: dom, rtype = _winreg.QueryValueEx(key, 'Domain') if dom: self._config_win32_domain(servers) except WindowsError: pass self._config_win32_add_ifaddr(key, 'IPAddress') try: search, rtype = _winreg.QueryValueEx(key, 'SearchList') except WindowsError: search = None if search: self._config_win32_search(search) def read_registry(self): """Extract resolver configuration from the Windows registry.""" lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) want_scan = False try: try: # XP, 2000 tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters') want_scan = True except EnvironmentError: # ME tcp_params = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\VxD\MSTCP') try: self._config_win32_fromkey(tcp_params) finally: tcp_params.Close() if want_scan: interfaces = _winreg.OpenKey(lm, r'SYSTEM\CurrentControlSet' r'\Services\Tcpip\Parameters' r'\Interfaces') try: i = 0 while True: try: guid = _winreg.EnumKey(interfaces, i) i += 1 key = _winreg.OpenKey(interfaces, guid) if not self._win32_is_nic_enabled(lm, guid, key): continue try: self._config_win32_fromkey(key) finally: key.Close() except EnvironmentError: break finally: interfaces.Close() finally: lm.Close() def _win32_is_nic_enabled(self, lm, guid, interface_key): # Look in the Windows Registry to determine whether the network # interface corresponding to the given guid is enabled. # (Code contributed by Paul Marks, thanks!) try: # This hard-coded location seems to be consistent, at least # from Windows 2000 through Vista. connection_key = _winreg.OpenKey( lm, r'SYSTEM\CurrentControlSet\Control\Network' r'\{4D36E972-E325-11CE-BFC1-08002BE10318}' r'\%s\Connection' % guid) try: # The PnpInstanceID points to a key inside Enum (pnp_id, ttype) = _winreg.QueryValueEx( connection_key, 'PnpInstanceID') if ttype != _winreg.REG_SZ: raise ValueError device_key = _winreg.OpenKey( lm, r'SYSTEM\CurrentControlSet\Enum\%s' % pnp_id) try: # Get ConfigFlags for this device (flags, ttype) = _winreg.QueryValueEx( device_key, 'ConfigFlags') if ttype != _winreg.REG_DWORD: raise ValueError # Based on experimentation, bit 0x1 indicates that the # device is disabled. return not (flags & 0x1) finally: device_key.Close() finally: connection_key.Close() except (EnvironmentError, ValueError): # Pre-vista, enabled interfaces seem to have a non-empty # NTEContextList; this was how dnspython detected enabled # nics before the code above was contributed. We've retained # the old method since we don't know if the code above works # on Windows 95/98/ME. try: (nte, ttype) = _winreg.QueryValueEx(interface_key, 'NTEContextList') return nte is not None except WindowsError: return False def _compute_timeout(self, start): now = time.time() if now < start: if start - now > 1: # Time going backwards is bad. Just give up. raise Timeout else: # Time went backwards, but only a little. This can # happen, e.g. under vmware with older linux kernels. # Pretend it didn't happen. now = start duration = now - start if duration >= self.lifetime: raise Timeout return min(self.lifetime - duration, self.timeout) def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN, tcp=False, source=None, raise_on_no_answer=True): """Query nameservers to find the answer to the question. The I{qname}, I{rdtype}, and I{rdclass} parameters may be objects of the appropriate type, or strings that can be converted into objects of the appropriate type. E.g. For I{rdtype} the integer 2 and the the string 'NS' both mean to query for records with DNS rdata type NS. @param qname: the query name @type qname: dns.name.Name object or string @param rdtype: the query type @type rdtype: int or string @param rdclass: the query class @type rdclass: int or string @param tcp: use TCP to make the query (default is False). @type tcp: bool @param source: bind to this IP address (defaults to machine default IP). @type source: IP address in dotted quad notation @param raise_on_no_answer: raise NoAnswer if there's no answer (defaults is True). @type raise_on_no_answer: bool @rtype: dns.resolver.Answer instance @raises Timeout: no answers could be found in the specified lifetime @raises NXDOMAIN: the query name does not exist @raises NoAnswer: the response did not contain an answer and raise_on_no_answer is True. @raises NoNameservers: no non-broken nameservers are available to answer the question.""" if isinstance(qname, basestring): qname = dns.name.from_text(qname, None) if isinstance(rdtype, basestring): rdtype = dns.rdatatype.from_text(rdtype) if dns.rdatatype.is_metatype(rdtype): raise NoMetaqueries if isinstance(rdclass, basestring): rdclass = dns.rdataclass.from_text(rdclass) if dns.rdataclass.is_metaclass(rdclass): raise NoMetaqueries qnames_to_try = [] if qname.is_absolute(): qnames_to_try.append(qname) else: if len(qname) > 1: qnames_to_try.append(qname.concatenate(dns.name.root)) if self.search: for suffix in self.search: qnames_to_try.append(qname.concatenate(suffix)) else: qnames_to_try.append(qname.concatenate(self.domain)) all_nxdomain = True start = time.time() for qname in qnames_to_try: if self.cache: answer = self.cache.get((qname, rdtype, rdclass)) if answer: return answer request = dns.message.make_query(qname, rdtype, rdclass) if not self.keyname is None: request.use_tsig(self.keyring, self.keyname, algorithm=self.keyalgorithm) request.use_edns(self.edns, self.ednsflags, self.payload) response = None # make a copy of the servers list so we can alter it later. nameservers = self.nameservers[:] backoff = 0.10 while response is None: if len(nameservers) == 0: raise NoNameservers("No DNS servers %s could answer the query %s" % \ (str(self.nameservers), str(qname))) for nameserver in nameservers[:]: timeout = self._compute_timeout(start) try: if tcp: response = dns.query.tcp(request, nameserver, timeout, self.port, source=source) else: response = dns.query.udp(request, nameserver, timeout, self.port, source=source) except (socket.error, dns.exception.Timeout): # Communication failure or timeout. Go to the # next server response = None continue except dns.query.UnexpectedSource: # Who knows? Keep going. response = None continue except dns.exception.FormError: # We don't understand what this server is # saying. Take it out of the mix and # continue. nameservers.remove(nameserver) response = None continue rcode = response.rcode() if rcode == dns.rcode.NOERROR or \ rcode == dns.rcode.NXDOMAIN: break # We got a response, but we're not happy with the # rcode in it. Remove the server from the mix if # the rcode isn't SERVFAIL. if rcode != dns.rcode.SERVFAIL: nameservers.remove(nameserver) response = None if response is not None: break # All nameservers failed! if len(nameservers) > 0: # But we still have servers to try. Sleep a bit # so we don't pound them! timeout = self._compute_timeout(start) sleep_time = min(timeout, backoff) backoff *= 2 time.sleep(sleep_time) if response.rcode() == dns.rcode.NXDOMAIN: continue all_nxdomain = False break if all_nxdomain: raise NXDOMAIN("Domain does not exist") answer = Answer(qname, rdtype, rdclass, response, raise_on_no_answer) if self.cache: self.cache.put((qname, rdtype, rdclass), answer) return answer def use_tsig(self, keyring, keyname=None, algorithm=dns.tsig.default_algorithm): """Add a TSIG signature to the query. @param keyring: The TSIG keyring to use; defaults to None. @type keyring: dict @param keyname: The name of the TSIG key to use; defaults to None. The key must be defined in the keyring. If a keyring is specified but a keyname is not, then the key used will be the first key in the keyring. Note that the order of keys in a dictionary is not defined, so applications should supply a keyname when a keyring is used, unless they know the keyring contains only one key. @param algorithm: The TSIG key algorithm to use. The default is dns.tsig.default_algorithm. @type algorithm: string""" self.keyring = keyring if keyname is None: self.keyname = self.keyring.keys()[0] else: self.keyname = keyname self.keyalgorithm = algorithm def use_edns(self, edns, ednsflags, payload): """Configure Edns. @param edns: The EDNS level to use. The default is -1, no Edns. @type edns: int @param ednsflags: The EDNS flags @type ednsflags: int @param payload: The EDNS payload size. The default is 0. @type payload: int""" if edns is None: edns = -1 self.edns = edns self.ednsflags = ednsflags self.payload = payload default_resolver = None def get_default_resolver(): """Get the default resolver, initializing it if necessary.""" global default_resolver if default_resolver is None: default_resolver = Resolver() return default_resolver def query(qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN, tcp=False, source=None, raise_on_no_answer=True, resolver=None): """Query nameservers to find the answer to the question. This is a convenience function that uses the default resolver object to make the query. @see: L{dns.resolver.Resolver.query} for more information on the parameters.""" if resolver is None: resolver = get_default_resolver() return resolver.query(qname, rdtype, rdclass, tcp, source, raise_on_no_answer) def zone_for_name(name, rdclass=dns.rdataclass.IN, tcp=False, resolver=None): """Find the name of the zone which contains the specified name. @param name: the query name @type name: absolute dns.name.Name object or string @param rdclass: The query class @type rdclass: int @param tcp: use TCP to make the query (default is False). @type tcp: bool @param resolver: the resolver to use @type resolver: dns.resolver.Resolver object or None @rtype: dns.name.Name""" if isinstance(name, basestring): name = dns.name.from_text(name, dns.name.root) if resolver is None: resolver = get_default_resolver() if not name.is_absolute(): raise NotAbsolute(name) while 1: try: answer = resolver.query(name, dns.rdatatype.SOA, rdclass, tcp) if answer.rrset.name == name: return name # otherwise we were CNAMEd or DNAMEd and need to look higher except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer): pass try: name = name.parent() except dns.name.NoParent: raise NoRootSOA
33,406
Python
.py
785
30.056051
89
0.562888
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,124
version.py
wummel_linkchecker/third_party/dnspython/dns/version.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """dnspython release version information.""" MAJOR = 1 MINOR = 9 MICRO = 5 RELEASELEVEL = 0x0f SERIAL = 0 if RELEASELEVEL == 0x0f: version = '%d.%d.%d' % (MAJOR, MINOR, MICRO) elif RELEASELEVEL == 0x00: version = '%d.%d.%dx%d' % \ (MAJOR, MINOR, MICRO, SERIAL) else: version = '%d.%d.%d%x%d' % \ (MAJOR, MINOR, MICRO, RELEASELEVEL, SERIAL) hexversion = MAJOR << 24 | MINOR << 16 | MICRO << 8 | RELEASELEVEL << 4 | \ SERIAL
1,266
Python
.py
30
39.3
75
0.719156
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,125
opcode.py
wummel_linkchecker/third_party/dnspython/dns/opcode.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Opcodes.""" import dns.exception QUERY = 0 IQUERY = 1 STATUS = 2 NOTIFY = 4 UPDATE = 5 _by_text = { 'QUERY' : QUERY, 'IQUERY' : IQUERY, 'STATUS' : STATUS, 'NOTIFY' : NOTIFY, 'UPDATE' : UPDATE } # We construct the inverse mapping programmatically to ensure that we # cannot make any mistakes (e.g. omissions, cut-and-paste errors) that # would cause the mapping not to be true inverse. _by_value = dict([(y, x) for x, y in _by_text.iteritems()]) class UnknownOpcode(dns.exception.DNSException): """Raised if an opcode is unknown.""" pass def from_text(text): """Convert text into an opcode. @param text: the textual opcode @type text: string @raises UnknownOpcode: the opcode is unknown @rtype: int """ if text.isdigit(): value = int(text) if value >= 0 and value <= 15: return value value = _by_text.get(text.upper()) if value is None: raise UnknownOpcode return value def from_flags(flags): """Extract an opcode from DNS message flags. @param flags: int @rtype: int """ return (flags & 0x7800) >> 11 def to_flags(value): """Convert an opcode to a value suitable for ORing into DNS message flags. @rtype: int """ return (value << 11) & 0x7800 def to_text(value): """Convert an opcode to text. @param value: the opcdoe @type value: int @raises UnknownOpcode: the opcode is unknown @rtype: string """ text = _by_value.get(value) if text is None: text = str(value) return text def is_update(flags): """True if the opcode in flags is UPDATE. @param flags: DNS flags @type flags: int @rtype: bool """ if (from_flags(flags) == UPDATE): return True return False
2,594
Python
.py
82
27.634146
72
0.692771
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,126
tokenizer.py
wummel_linkchecker/third_party/dnspython/dns/tokenizer.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Tokenize DNS master file format""" import cStringIO import sys import dns.exception import dns.name import dns.ttl _DELIMITERS = { ' ' : True, '\t' : True, '\n' : True, ';' : True, '(' : True, ')' : True, '"' : True } _QUOTING_DELIMITERS = { '"' : True } EOF = 0 EOL = 1 WHITESPACE = 2 IDENTIFIER = 3 QUOTED_STRING = 4 COMMENT = 5 DELIMITER = 6 class UngetBufferFull(dns.exception.DNSException): """Raised when an attempt is made to unget a token when the unget buffer is full.""" pass class Token(object): """A DNS master file format token. @ivar ttype: The token type @type ttype: int @ivar value: The token value @type value: string @ivar has_escape: Does the token value contain escapes? @type has_escape: bool """ def __init__(self, ttype, value='', has_escape=False): """Initialize a token instance. @param ttype: The token type @type ttype: int @ivar value: The token value @type value: string @ivar has_escape: Does the token value contain escapes? @type has_escape: bool """ self.ttype = ttype self.value = value self.has_escape = has_escape def is_eof(self): return self.ttype == EOF def is_eol(self): return self.ttype == EOL def is_whitespace(self): return self.ttype == WHITESPACE def is_identifier(self): return self.ttype == IDENTIFIER def is_quoted_string(self): return self.ttype == QUOTED_STRING def is_comment(self): return self.ttype == COMMENT def is_delimiter(self): return self.ttype == DELIMITER def is_eol_or_eof(self): return (self.ttype == EOL or self.ttype == EOF) def __hash__(self): return hash((self.ttype, self.value)) def __eq__(self, other): if not isinstance(other, Token): return False return (self.ttype == other.ttype and self.value == other.value) def __ne__(self, other): if not isinstance(other, Token): return True return (self.ttype != other.ttype or self.value != other.value) def __str__(self): return '%d "%s"' % (self.ttype, self.value) def unescape(self): if not self.has_escape: return self unescaped = '' l = len(self.value) i = 0 while i < l: c = self.value[i] i += 1 if c == '\\': if i >= l: raise dns.exception.UnexpectedEnd c = self.value[i] i += 1 if c.isdigit(): if i >= l: raise dns.exception.UnexpectedEnd c2 = self.value[i] i += 1 if i >= l: raise dns.exception.UnexpectedEnd c3 = self.value[i] i += 1 if not (c2.isdigit() and c3.isdigit()): raise dns.exception.SyntaxError c = chr(int(c) * 100 + int(c2) * 10 + int(c3)) unescaped += c return Token(self.ttype, unescaped) # compatibility for old-style tuple tokens def __len__(self): return 2 def __iter__(self): return iter((self.ttype, self.value)) def __getitem__(self, i): if i == 0: return self.ttype elif i == 1: return self.value else: raise IndexError class Tokenizer(object): """A DNS master file format tokenizer. A token is a (type, value) tuple, where I{type} is an int, and I{value} is a string. The valid types are EOF, EOL, WHITESPACE, IDENTIFIER, QUOTED_STRING, COMMENT, and DELIMITER. @ivar file: The file to tokenize @type file: file @ivar ungotten_char: The most recently ungotten character, or None. @type ungotten_char: string @ivar ungotten_token: The most recently ungotten token, or None. @type ungotten_token: (int, string) token tuple @ivar multiline: The current multiline level. This value is increased by one every time a '(' delimiter is read, and decreased by one every time a ')' delimiter is read. @type multiline: int @ivar quoting: This variable is true if the tokenizer is currently reading a quoted string. @type quoting: bool @ivar eof: This variable is true if the tokenizer has encountered EOF. @type eof: bool @ivar delimiters: The current delimiter dictionary. @type delimiters: dict @ivar line_number: The current line number @type line_number: int @ivar filename: A filename that will be returned by the L{where} method. @type filename: string """ def __init__(self, f=sys.stdin, filename=None): """Initialize a tokenizer instance. @param f: The file to tokenize. The default is sys.stdin. This parameter may also be a string, in which case the tokenizer will take its input from the contents of the string. @type f: file or string @param filename: the name of the filename that the L{where} method will return. @type filename: string """ if isinstance(f, str): f = cStringIO.StringIO(f) if filename is None: filename = '<string>' else: if filename is None: if f is sys.stdin: filename = '<stdin>' else: filename = '<file>' self.file = f self.ungotten_char = None self.ungotten_token = None self.multiline = 0 self.quoting = False self.eof = False self.delimiters = _DELIMITERS self.line_number = 1 self.filename = filename def _get_char(self): """Read a character from input. @rtype: string """ if self.ungotten_char is None: if self.eof: c = '' else: c = self.file.read(1) if c == '': self.eof = True elif c == '\n': self.line_number += 1 else: c = self.ungotten_char self.ungotten_char = None return c def where(self): """Return the current location in the input. @rtype: (string, int) tuple. The first item is the filename of the input, the second is the current line number. """ return (self.filename, self.line_number) def _unget_char(self, c): """Unget a character. The unget buffer for characters is only one character large; it is an error to try to unget a character when the unget buffer is not empty. @param c: the character to unget @type c: string @raises UngetBufferFull: there is already an ungotten char """ if not self.ungotten_char is None: raise UngetBufferFull self.ungotten_char = c def skip_whitespace(self): """Consume input until a non-whitespace character is encountered. The non-whitespace character is then ungotten, and the number of whitespace characters consumed is returned. If the tokenizer is in multiline mode, then newlines are whitespace. @rtype: int """ skipped = 0 while True: c = self._get_char() if c != ' ' and c != '\t': if (c != '\n') or not self.multiline: self._unget_char(c) return skipped skipped += 1 def get(self, want_leading = False, want_comment = False): """Get the next token. @param want_leading: If True, return a WHITESPACE token if the first character read is whitespace. The default is False. @type want_leading: bool @param want_comment: If True, return a COMMENT token if the first token read is a comment. The default is False. @type want_comment: bool @rtype: Token object @raises dns.exception.UnexpectedEnd: input ended prematurely @raises dns.exception.SyntaxError: input was badly formed """ if not self.ungotten_token is None: token = self.ungotten_token self.ungotten_token = None if token.is_whitespace(): if want_leading: return token elif token.is_comment(): if want_comment: return token else: return token skipped = self.skip_whitespace() if want_leading and skipped > 0: return Token(WHITESPACE, ' ') token = '' ttype = IDENTIFIER has_escape = False while True: c = self._get_char() if c == '' or c in self.delimiters: if c == '' and self.quoting: raise dns.exception.UnexpectedEnd if token == '' and ttype != QUOTED_STRING: if c == '(': self.multiline += 1 self.skip_whitespace() continue elif c == ')': if not self.multiline > 0: raise dns.exception.SyntaxError self.multiline -= 1 self.skip_whitespace() continue elif c == '"': if not self.quoting: self.quoting = True self.delimiters = _QUOTING_DELIMITERS ttype = QUOTED_STRING continue else: self.quoting = False self.delimiters = _DELIMITERS self.skip_whitespace() continue elif c == '\n': return Token(EOL, '\n') elif c == ';': while 1: c = self._get_char() if c == '\n' or c == '': break token += c if want_comment: self._unget_char(c) return Token(COMMENT, token) elif c == '': if self.multiline: raise dns.exception.SyntaxError('unbalanced parentheses') return Token(EOF) elif self.multiline: self.skip_whitespace() token = '' continue else: return Token(EOL, '\n') else: # This code exists in case we ever want a # delimiter to be returned. It never produces # a token currently. token = c ttype = DELIMITER else: self._unget_char(c) break elif self.quoting: if c == '\\': c = self._get_char() if c == '': raise dns.exception.UnexpectedEnd if c.isdigit(): c2 = self._get_char() if c2 == '': raise dns.exception.UnexpectedEnd c3 = self._get_char() if c == '': raise dns.exception.UnexpectedEnd if not (c2.isdigit() and c3.isdigit()): raise dns.exception.SyntaxError c = chr(int(c) * 100 + int(c2) * 10 + int(c3)) elif c == '\n': raise dns.exception.SyntaxError('newline in quoted string') elif c == '\\': # # It's an escape. Put it and the next character into # the token; it will be checked later for goodness. # token += c has_escape = True c = self._get_char() if c == '' or c == '\n': raise dns.exception.UnexpectedEnd token += c if token == '' and ttype != QUOTED_STRING: if self.multiline: raise dns.exception.SyntaxError('unbalanced parentheses') ttype = EOF return Token(ttype, token, has_escape) def unget(self, token): """Unget a token. The unget buffer for tokens is only one token large; it is an error to try to unget a token when the unget buffer is not empty. @param token: the token to unget @type token: Token object @raises UngetBufferFull: there is already an ungotten token """ if not self.ungotten_token is None: raise UngetBufferFull self.ungotten_token = token def next(self): """Return the next item in an iteration. @rtype: (int, string) """ token = self.get() if token.is_eof(): raise StopIteration return token def __iter__(self): return self # Helpers def get_int(self): """Read the next token and interpret it as an integer. @raises dns.exception.SyntaxError: @rtype: int """ token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') if not token.value.isdigit(): raise dns.exception.SyntaxError('expecting an integer') return int(token.value) def get_uint8(self): """Read the next token and interpret it as an 8-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int """ value = self.get_int() if value < 0 or value > 255: raise dns.exception.SyntaxError('%d is not an unsigned 8-bit integer' % value) return value def get_uint16(self): """Read the next token and interpret it as a 16-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int """ value = self.get_int() if value < 0 or value > 65535: raise dns.exception.SyntaxError('%d is not an unsigned 16-bit integer' % value) return value def get_uint32(self): """Read the next token and interpret it as a 32-bit unsigned integer. @raises dns.exception.SyntaxError: @rtype: int """ token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') if not token.value.isdigit(): raise dns.exception.SyntaxError('expecting an integer') value = long(token.value) if value < 0 or value > 4294967296L: raise dns.exception.SyntaxError('%d is not an unsigned 32-bit integer' % value) return value def get_string(self, origin=None): """Read the next token and interpret it as a string. @raises dns.exception.SyntaxError: @rtype: string """ token = self.get().unescape() if not (token.is_identifier() or token.is_quoted_string()): raise dns.exception.SyntaxError('expecting a string') return token.value def get_identifier(self, origin=None): """Read the next token and raise an exception if it is not an identifier. @raises dns.exception.SyntaxError: @rtype: string """ token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') return token.value def get_name(self, origin=None): """Read the next token and interpret it as a DNS name. @raises dns.exception.SyntaxError: @rtype: dns.name.Name object""" token = self.get() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') return dns.name.from_text(token.value, origin) def get_eol(self): """Read the next token and raise an exception if it isn't EOL or EOF. @raises dns.exception.SyntaxError: @rtype: string """ token = self.get() if not token.is_eol_or_eof(): raise dns.exception.SyntaxError('expected EOL or EOF, got %d "%s"' % (token.ttype, token.value)) return token.value def get_ttl(self): token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') return dns.ttl.from_text(token.value)
18,032
Python
.py
466
26.905579
108
0.542386
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,127
update.py
wummel_linkchecker/third_party/dnspython/dns/update.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS Dynamic Update Support""" import dns.message import dns.name import dns.opcode import dns.rdata import dns.rdataclass import dns.rdataset import dns.tsig class Update(dns.message.Message): def __init__(self, zone, rdclass=dns.rdataclass.IN, keyring=None, keyname=None, keyalgorithm=dns.tsig.default_algorithm): """Initialize a new DNS Update object. @param zone: The zone which is being updated. @type zone: A dns.name.Name or string @param rdclass: The class of the zone; defaults to dns.rdataclass.IN. @type rdclass: An int designating the class, or a string whose value is the name of a class. @param keyring: The TSIG keyring to use; defaults to None. @type keyring: dict @param keyname: The name of the TSIG key to use; defaults to None. The key must be defined in the keyring. If a keyring is specified but a keyname is not, then the key used will be the first key in the keyring. Note that the order of keys in a dictionary is not defined, so applications should supply a keyname when a keyring is used, unless they know the keyring contains only one key. @type keyname: dns.name.Name or string @param keyalgorithm: The TSIG algorithm to use; defaults to dns.tsig.default_algorithm. Constants for TSIG algorithms are defined in dns.tsig, and the currently implemented algorithms are HMAC_MD5, HMAC_SHA1, HMAC_SHA224, HMAC_SHA256, HMAC_SHA384, and HMAC_SHA512. @type keyalgorithm: string """ super(Update, self).__init__() self.flags |= dns.opcode.to_flags(dns.opcode.UPDATE) if isinstance(zone, (str, unicode)): zone = dns.name.from_text(zone) self.origin = zone if isinstance(rdclass, str): rdclass = dns.rdataclass.from_text(rdclass) self.zone_rdclass = rdclass self.find_rrset(self.question, self.origin, rdclass, dns.rdatatype.SOA, create=True, force_unique=True) if not keyring is None: self.use_tsig(keyring, keyname, algorithm=keyalgorithm) def _add_rr(self, name, ttl, rd, deleting=None, section=None): """Add a single RR to the update section.""" if section is None: section = self.authority covers = rd.covers() rrset = self.find_rrset(section, name, self.zone_rdclass, rd.rdtype, covers, deleting, True, True) rrset.add(rd, ttl) def _add(self, replace, section, name, *args): """Add records. The first argument is the replace mode. If false, RRs are added to an existing RRset; if true, the RRset is replaced with the specified contents. The second argument is the section to add to. The third argument is always a name. The other arguments can be: - rdataset... - ttl, rdata... - ttl, rdtype, string...""" if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if isinstance(args[0], dns.rdataset.Rdataset): for rds in args: if replace: self.delete(name, rds.rdtype) for rd in rds: self._add_rr(name, rds.ttl, rd, section=section) else: args = list(args) ttl = int(args.pop(0)) if isinstance(args[0], dns.rdata.Rdata): if replace: self.delete(name, args[0].rdtype) for rd in args: self._add_rr(name, ttl, rd, section=section) else: rdtype = args.pop(0) if isinstance(rdtype, str): rdtype = dns.rdatatype.from_text(rdtype) if replace: self.delete(name, rdtype) for s in args: rd = dns.rdata.from_text(self.zone_rdclass, rdtype, s, self.origin) self._add_rr(name, ttl, rd, section=section) def add(self, name, *args): """Add records. The first argument is always a name. The other arguments can be: - rdataset... - ttl, rdata... - ttl, rdtype, string...""" self._add(False, self.authority, name, *args) def delete(self, name, *args): """Delete records. The first argument is always a name. The other arguments can be: - I{nothing} - rdataset... - rdata... - rdtype, [string...]""" if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if len(args) == 0: rrset = self.find_rrset(self.authority, name, dns.rdataclass.ANY, dns.rdatatype.ANY, dns.rdatatype.NONE, dns.rdatatype.ANY, True, True) elif isinstance(args[0], dns.rdataset.Rdataset): for rds in args: for rd in rds: self._add_rr(name, 0, rd, dns.rdataclass.NONE) else: args = list(args) if isinstance(args[0], dns.rdata.Rdata): for rd in args: self._add_rr(name, 0, rd, dns.rdataclass.NONE) else: rdtype = args.pop(0) if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) if len(args) == 0: rrset = self.find_rrset(self.authority, name, self.zone_rdclass, rdtype, dns.rdatatype.NONE, dns.rdataclass.ANY, True, True) else: for s in args: rd = dns.rdata.from_text(self.zone_rdclass, rdtype, s, self.origin) self._add_rr(name, 0, rd, dns.rdataclass.NONE) def replace(self, name, *args): """Replace records. The first argument is always a name. The other arguments can be: - rdataset... - ttl, rdata... - ttl, rdtype, string... Note that if you want to replace the entire node, you should do a delete of the name followed by one or more calls to add.""" self._add(True, self.authority, name, *args) def present(self, name, *args): """Require that an owner name (and optionally an rdata type, or specific rdataset) exists as a prerequisite to the execution of the update. The first argument is always a name. The other arguments can be: - rdataset... - rdata... - rdtype, string...""" if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if len(args) == 0: rrset = self.find_rrset(self.answer, name, dns.rdataclass.ANY, dns.rdatatype.ANY, dns.rdatatype.NONE, None, True, True) elif isinstance(args[0], dns.rdataset.Rdataset) or \ isinstance(args[0], dns.rdata.Rdata) or \ len(args) > 1: if not isinstance(args[0], dns.rdataset.Rdataset): # Add a 0 TTL args = list(args) args.insert(0, 0) self._add(False, self.answer, name, *args) else: rdtype = args[0] if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) rrset = self.find_rrset(self.answer, name, dns.rdataclass.ANY, rdtype, dns.rdatatype.NONE, None, True, True) def absent(self, name, rdtype=None): """Require that an owner name (and optionally an rdata type) does not exist as a prerequisite to the execution of the update.""" if isinstance(name, (str, unicode)): name = dns.name.from_text(name, None) if rdtype is None: rrset = self.find_rrset(self.answer, name, dns.rdataclass.NONE, dns.rdatatype.ANY, dns.rdatatype.NONE, None, True, True) else: if isinstance(rdtype, (str, unicode)): rdtype = dns.rdatatype.from_text(rdtype) rrset = self.find_rrset(self.answer, name, dns.rdataclass.NONE, rdtype, dns.rdatatype.NONE, None, True, True) def to_wire(self, origin=None, max_size=65535): """Return a string containing the update in DNS compressed wire format. @rtype: string""" if origin is None: origin = self.origin return super(Update, self).to_wire(origin, max_size)
10,163
Python
.py
210
34.309524
79
0.553741
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,128
tsig.py
wummel_linkchecker/third_party/dnspython/dns/tsig.py
# Copyright (C) 2001-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS TSIG support.""" import hmac import struct import sys import dns.exception import dns.hash import dns.rdataclass import dns.name class BadTime(dns.exception.DNSException): """Raised if the current time is not within the TSIG's validity time.""" pass class BadSignature(dns.exception.DNSException): """Raised if the TSIG signature fails to verify.""" pass class PeerError(dns.exception.DNSException): """Base class for all TSIG errors generated by the remote peer""" pass class PeerBadKey(PeerError): """Raised if the peer didn't know the key we used""" pass class PeerBadSignature(PeerError): """Raised if the peer didn't like the signature we sent""" pass class PeerBadTime(PeerError): """Raised if the peer didn't like the time we sent""" pass class PeerBadTruncation(PeerError): """Raised if the peer didn't like amount of truncation in the TSIG we sent""" pass # TSIG Algorithms HMAC_MD5 = dns.name.from_text("HMAC-MD5.SIG-ALG.REG.INT") HMAC_SHA1 = dns.name.from_text("hmac-sha1") HMAC_SHA224 = dns.name.from_text("hmac-sha224") HMAC_SHA256 = dns.name.from_text("hmac-sha256") HMAC_SHA384 = dns.name.from_text("hmac-sha384") HMAC_SHA512 = dns.name.from_text("hmac-sha512") default_algorithm = HMAC_MD5 BADSIG = 16 BADKEY = 17 BADTIME = 18 BADTRUNC = 22 def sign(wire, keyname, secret, time, fudge, original_id, error, other_data, request_mac, ctx=None, multi=False, first=True, algorithm=default_algorithm): """Return a (tsig_rdata, mac, ctx) tuple containing the HMAC TSIG rdata for the input parameters, the HMAC MAC calculated by applying the TSIG signature algorithm, and the TSIG digest context. @rtype: (string, string, hmac.HMAC object) @raises ValueError: I{other_data} is too long @raises NotImplementedError: I{algorithm} is not supported """ (algorithm_name, digestmod) = get_algorithm(algorithm) if first: ctx = hmac.new(secret, digestmod=digestmod) ml = len(request_mac) if ml > 0: ctx.update(struct.pack('!H', ml)) ctx.update(request_mac) id = struct.pack('!H', original_id) ctx.update(id) ctx.update(wire[2:]) if first: ctx.update(keyname.to_digestable()) ctx.update(struct.pack('!H', dns.rdataclass.ANY)) ctx.update(struct.pack('!I', 0)) long_time = time + 0L upper_time = (long_time >> 32) & 0xffffL lower_time = long_time & 0xffffffffL time_mac = struct.pack('!HIH', upper_time, lower_time, fudge) pre_mac = algorithm_name + time_mac ol = len(other_data) if ol > 65535: raise ValueError('TSIG Other Data is > 65535 bytes') post_mac = struct.pack('!HH', error, ol) + other_data if first: ctx.update(pre_mac) ctx.update(post_mac) else: ctx.update(time_mac) mac = ctx.digest() mpack = struct.pack('!H', len(mac)) tsig_rdata = pre_mac + mpack + mac + id + post_mac if multi: ctx = hmac.new(secret) ml = len(mac) ctx.update(struct.pack('!H', ml)) ctx.update(mac) else: ctx = None return (tsig_rdata, mac, ctx) def hmac_md5(wire, keyname, secret, time, fudge, original_id, error, other_data, request_mac, ctx=None, multi=False, first=True, algorithm=default_algorithm): return sign(wire, keyname, secret, time, fudge, original_id, error, other_data, request_mac, ctx, multi, first, algorithm) def validate(wire, keyname, secret, now, request_mac, tsig_start, tsig_rdata, tsig_rdlen, ctx=None, multi=False, first=True): """Validate the specified TSIG rdata against the other input parameters. @raises FormError: The TSIG is badly formed. @raises BadTime: There is too much time skew between the client and the server. @raises BadSignature: The TSIG signature did not validate @rtype: hmac.HMAC object""" (adcount,) = struct.unpack("!H", wire[10:12]) if adcount == 0: raise dns.exception.FormError adcount -= 1 new_wire = wire[0:10] + struct.pack("!H", adcount) + wire[12:tsig_start] current = tsig_rdata (aname, used) = dns.name.from_wire(wire, current) current = current + used (upper_time, lower_time, fudge, mac_size) = \ struct.unpack("!HIHH", wire[current:current + 10]) time = ((upper_time + 0L) << 32) + (lower_time + 0L) current += 10 mac = wire[current:current + mac_size] current += mac_size (original_id, error, other_size) = \ struct.unpack("!HHH", wire[current:current + 6]) current += 6 other_data = wire[current:current + other_size] current += other_size if current != tsig_rdata + tsig_rdlen: raise dns.exception.FormError if error != 0: if error == BADSIG: raise PeerBadSignature elif error == BADKEY: raise PeerBadKey elif error == BADTIME: raise PeerBadTime elif error == BADTRUNC: raise PeerBadTruncation else: raise PeerError('unknown TSIG error code %d' % error) time_low = time - fudge time_high = time + fudge if now < time_low or now > time_high: raise BadTime (junk, our_mac, ctx) = sign(new_wire, keyname, secret, time, fudge, original_id, error, other_data, request_mac, ctx, multi, first, aname) if (our_mac != mac): raise BadSignature return ctx _hashes = None def _maybe_add_hash(tsig_alg, hash_alg): try: _hashes[tsig_alg] = dns.hash.get(hash_alg) except KeyError: pass def _setup_hashes(): global _hashes _hashes = {} _maybe_add_hash(HMAC_SHA224, 'SHA224') _maybe_add_hash(HMAC_SHA256, 'SHA256') _maybe_add_hash(HMAC_SHA384, 'SHA384') _maybe_add_hash(HMAC_SHA512, 'SHA512') _maybe_add_hash(HMAC_SHA1, 'SHA1') _maybe_add_hash(HMAC_MD5, 'MD5') def get_algorithm(algorithm): """Returns the wire format string and the hash module to use for the specified TSIG algorithm @rtype: (string, hash constructor) @raises NotImplementedError: I{algorithm} is not supported """ global _hashes if _hashes is None: _setup_hashes() if isinstance(algorithm, (str, unicode)): algorithm = dns.name.from_text(algorithm) if sys.hexversion < 0x02050200 and \ (algorithm == HMAC_SHA384 or algorithm == HMAC_SHA512): raise NotImplementedError("TSIG algorithm " + str(algorithm) + " requires Python 2.5.2 or later") try: return (algorithm.to_digestable(), _hashes[algorithm]) except KeyError: raise NotImplementedError("TSIG algorithm " + str(algorithm) + " is not supported")
7,681
Python
.py
194
33.5
81
0.662912
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,129
entropy.py
wummel_linkchecker/third_party/dnspython/dns/entropy.py
# Copyright (C) 2009, 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import os import time try: import threading as _threading except ImportError: import dummy_threading as _threading class EntropyPool(object): def __init__(self, seed=None): self.pool_index = 0 self.digest = None self.next_byte = 0 self.lock = _threading.Lock() try: import hashlib self.hash = hashlib.sha1() self.hash_len = 20 except Exception: try: import sha self.hash = sha.new() self.hash_len = 20 except Exception: import md5 self.hash = md5.new() self.hash_len = 16 self.pool = '\0' * self.hash_len if not seed is None: self.stir(seed) self.seeded = True else: self.seeded = False def stir(self, entropy, already_locked=False): if not already_locked: self.lock.acquire() try: bytes = [ord(c) for c in self.pool] for c in entropy: if self.pool_index == self.hash_len: self.pool_index = 0 b = ord(c) & 0xff bytes[self.pool_index] ^= b self.pool_index += 1 self.pool = ''.join([chr(c) for c in bytes]) finally: if not already_locked: self.lock.release() def _maybe_seed(self): if not self.seeded: try: seed = os.urandom(16) except Exception: try: r = file('/dev/urandom', 'r', 0) try: seed = r.read(16) finally: r.close() except Exception: seed = str(time.time()) self.seeded = True self.stir(seed, True) def random_8(self): self.lock.acquire() self._maybe_seed() try: if self.digest is None or self.next_byte == self.hash_len: self.hash.update(self.pool) self.digest = self.hash.digest() self.stir(self.digest, True) self.next_byte = 0 value = ord(self.digest[self.next_byte]) self.next_byte += 1 finally: self.lock.release() return value def random_16(self): return self.random_8() * 256 + self.random_8() def random_32(self): return self.random_16() * 65536 + self.random_16() def random_between(self, first, last): size = last - first + 1 if size > 4294967296L: raise ValueError('too big') if size > 65536: rand = self.random_32 max = 4294967295L elif size > 256: rand = self.random_16 max = 65535 else: rand = self.random_8 max = 255 return (first + size * rand() // (max + 1)) pool = EntropyPool() def random_16(): return pool.random_16() def between(first, last): return pool.random_between(first, last)
3,925
Python
.py
112
24.803571
72
0.554708
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,130
ipv6.py
wummel_linkchecker/third_party/dnspython/dns/ipv6.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """IPv6 helper functions.""" import re import dns.exception import dns.ipv4 _leading_zero = re.compile(r'0+([0-9a-f]+)') def inet_ntoa(address): """Convert a network format IPv6 address into text. @param address: the binary address @type address: string @rtype: string @raises ValueError: the address isn't 16 bytes long """ if len(address) != 16: raise ValueError("IPv6 addresses are 16 bytes long") hex = address.encode('hex_codec') chunks = [] i = 0 l = len(hex) while i < l: chunk = hex[i : i + 4] # strip leading zeros. we do this with an re instead of # with lstrip() because lstrip() didn't support chars until # python 2.2.2 m = _leading_zero.match(chunk) if not m is None: chunk = m.group(1) chunks.append(chunk) i += 4 # # Compress the longest subsequence of 0-value chunks to :: # best_start = 0 best_len = 0 start = -1 last_was_zero = False for i in xrange(8): if chunks[i] != '0': if last_was_zero: end = i current_len = end - start if current_len > best_len: best_start = start best_len = current_len last_was_zero = False elif not last_was_zero: start = i last_was_zero = True if last_was_zero: end = 8 current_len = end - start if current_len > best_len: best_start = start best_len = current_len if best_len > 0: if best_start == 0 and \ (best_len == 6 or best_len == 5 and chunks[5] == 'ffff'): # We have an embedded IPv4 address if best_len == 6: prefix = '::' else: prefix = '::ffff:' hex = prefix + dns.ipv4.inet_ntoa(address[12:]) else: hex = ':'.join(chunks[:best_start]) + '::' + \ ':'.join(chunks[best_start + best_len:]) else: hex = ':'.join(chunks) return hex _v4_ending = re.compile(r'(.*):(\d+)\.(\d+)\.(\d+)\.(\d+)$') _colon_colon_start = re.compile(r'::.*') _colon_colon_end = re.compile(r'.*::$') def inet_aton(text): """Convert a text format IPv6 address into network format. @param text: the textual address @type text: string @rtype: string @raises dns.exception.SyntaxError: the text was not properly formatted """ # # Our aim here is not something fast; we just want something that works. # if text == '::': text = '0::' # # Get rid of the icky dot-quad syntax if we have it. # m = _v4_ending.match(text) if not m is None: text = "%s:%04x:%04x" % (m.group(1), int(m.group(2)) * 256 + int(m.group(3)), int(m.group(4)) * 256 + int(m.group(5))) # # Try to turn '::<whatever>' into ':<whatever>'; if no match try to # turn '<whatever>::' into '<whatever>:' # m = _colon_colon_start.match(text) if not m is None: text = text[1:] else: m = _colon_colon_end.match(text) if not m is None: text = text[:-1] # # Now canonicalize into 8 chunks of 4 hex digits each # chunks = text.split(':') l = len(chunks) if l > 8: raise dns.exception.SyntaxError seen_empty = False canonical = [] for c in chunks: if c == '': if seen_empty: raise dns.exception.SyntaxError seen_empty = True for i in xrange(0, 8 - l + 1): canonical.append('0000') else: lc = len(c) if lc > 4: raise dns.exception.SyntaxError if lc != 4: c = ('0' * (4 - lc)) + c canonical.append(c) if l < 8 and not seen_empty: raise dns.exception.SyntaxError text = ''.join(canonical) # # Finally we can go to binary. # try: return text.decode('hex_codec') except TypeError: raise dns.exception.SyntaxError
4,994
Python
.py
150
25.493333
76
0.566963
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,131
txtbase.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/txtbase.py
# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """TXT-like base class.""" import dns.exception import dns.rdata import dns.tokenizer class TXTBase(dns.rdata.Rdata): """Base class for rdata that is like a TXT record @ivar strings: the text strings @type strings: list of string @see: RFC 1035""" __slots__ = ['strings'] def __init__(self, rdclass, rdtype, strings): super(TXTBase, self).__init__(rdclass, rdtype) if isinstance(strings, str): strings = [ strings ] self.strings = strings[:] def to_text(self, origin=None, relativize=True, **kw): txt = '' prefix = '' for s in self.strings: txt += '%s"%s"' % (prefix, dns.rdata._escapify(s)) prefix = ' ' return txt def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): strings = [] while 1: token = tok.get().unescape() if token.is_eol_or_eof(): break if not (token.is_quoted_string() or token.is_identifier()): raise dns.exception.SyntaxError("expected a string") if len(token.value) > 255: raise dns.exception.SyntaxError("string too long") strings.append(token.value) if len(strings) == 0: raise dns.exception.UnexpectedEnd return cls(rdclass, rdtype, strings) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): for s in self.strings: l = len(s) assert l < 256 byte = chr(l) file.write(byte) file.write(s) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): strings = [] while rdlen > 0: l = ord(wire[current]) current += 1 rdlen -= 1 if l > rdlen: raise dns.exception.FormError s = wire[current : current + l].unwrap() current += l rdlen -= l strings.append(s) return cls(rdclass, rdtype, strings) from_wire = classmethod(from_wire) def _cmp(self, other): return cmp(self.strings, other.strings)
2,994
Python
.py
74
32.418919
79
0.622291
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,132
dsbase.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/dsbase.py
# Copyright (C) 2010, 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import struct import dns.rdata import dns.rdatatype class DSBase(dns.rdata.Rdata): """Base class for rdata that is like a DS record @ivar key_tag: the key tag @type key_tag: int @ivar algorithm: the algorithm @type algorithm: int @ivar digest_type: the digest type @type digest_type: int @ivar digest: the digest @type digest: int @see: draft-ietf-dnsext-delegation-signer-14.txt""" __slots__ = ['key_tag', 'algorithm', 'digest_type', 'digest'] def __init__(self, rdclass, rdtype, key_tag, algorithm, digest_type, digest): super(DSBase, self).__init__(rdclass, rdtype) self.key_tag = key_tag self.algorithm = algorithm self.digest_type = digest_type self.digest = digest def to_text(self, origin=None, relativize=True, **kw): return '%d %d %d %s' % (self.key_tag, self.algorithm, self.digest_type, dns.rdata._hexify(self.digest, chunksize=128)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): key_tag = tok.get_uint16() algorithm = tok.get_uint8() digest_type = tok.get_uint8() chunks = [] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) digest = ''.join(chunks) digest = digest.decode('hex_codec') return cls(rdclass, rdtype, key_tag, algorithm, digest_type, digest) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): header = struct.pack("!HBB", self.key_tag, self.algorithm, self.digest_type) file.write(header) file.write(self.digest) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): header = struct.unpack("!HBB", wire[current : current + 4]) current += 4 rdlen -= 4 digest = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], header[1], header[2], digest) from_wire = classmethod(from_wire) def _cmp(self, other): hs = struct.pack("!HBB", self.key_tag, self.algorithm, self.digest_type) ho = struct.pack("!HBB", other.key_tag, other.algorithm, other.digest_type) v = cmp(hs, ho) if v == 0: v = cmp(self.digest, other.digest) return v
3,460
Python
.py
79
34.873418
79
0.617874
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,133
nsbase.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/nsbase.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """NS-like base classes.""" import cStringIO import dns.exception import dns.rdata import dns.name class NSBase(dns.rdata.Rdata): """Base class for rdata that is like an NS record. @ivar target: the target name of the rdata @type target: dns.name.Name object""" __slots__ = ['target'] def __init__(self, rdclass, rdtype, target): super(NSBase, self).__init__(rdclass, rdtype) self.target = target def to_text(self, origin=None, relativize=True, **kw): target = self.target.choose_relativity(origin, relativize) return str(target) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): target = tok.get_name() target = target.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, target) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): self.target.to_wire(file, compress, origin) def to_digestable(self, origin = None): return self.target.to_digestable(origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (target, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: target = target.relativize(origin) return cls(rdclass, rdtype, target) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.target = self.target.choose_relativity(origin, relativize) def _cmp(self, other): return cmp(self.target, other.target) class UncompressedNS(NSBase): """Base class for rdata that is like an NS record, but whose name is not compressed when convert to DNS wire format, and whose digestable form is not downcased.""" def to_wire(self, file, compress = None, origin = None): super(UncompressedNS, self).to_wire(file, None, origin) def to_digestable(self, origin = None): f = cStringIO.StringIO() self.to_wire(f, None, origin) return f.getvalue()
2,994
Python
.py
63
41.380952
79
0.693681
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,134
__init__.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/__init__.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """DNS rdata type classes""" __all__ = [ 'ANY', 'IN', 'mxbase', 'nsbase', ]
880
Python
.py
21
40.047619
72
0.765461
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,135
mxbase.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/mxbase.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """MX-like base classes.""" import cStringIO import struct import dns.exception import dns.rdata import dns.name class MXBase(dns.rdata.Rdata): """Base class for rdata that is like an MX record. @ivar preference: the preference value @type preference: int @ivar exchange: the exchange name @type exchange: dns.name.Name object""" __slots__ = ['preference', 'exchange'] def __init__(self, rdclass, rdtype, preference, exchange): super(MXBase, self).__init__(rdclass, rdtype) self.preference = preference self.exchange = exchange def to_text(self, origin=None, relativize=True, **kw): exchange = self.exchange.choose_relativity(origin, relativize) return '%d %s' % (self.preference, exchange) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): preference = tok.get_uint16() exchange = tok.get_name() exchange = exchange.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, preference, exchange) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): pref = struct.pack("!H", self.preference) file.write(pref) self.exchange.to_wire(file, compress, origin) def to_digestable(self, origin = None): return struct.pack("!H", self.preference) + \ self.exchange.to_digestable(origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (preference, ) = struct.unpack('!H', wire[current : current + 2]) current += 2 rdlen -= 2 (exchange, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: exchange = exchange.relativize(origin) return cls(rdclass, rdtype, preference, exchange) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.exchange = self.exchange.choose_relativity(origin, relativize) def _cmp(self, other): sp = struct.pack("!H", self.preference) op = struct.pack("!H", other.preference) v = cmp(sp, op) if v == 0: v = cmp(self.exchange, other.exchange) return v class UncompressedMX(MXBase): """Base class for rdata that is like an MX record, but whose name is not compressed when converted to DNS wire format, and whose digestable form is not downcased.""" def to_wire(self, file, compress = None, origin = None): super(UncompressedMX, self).to_wire(file, None, origin) def to_digestable(self, origin = None): f = cStringIO.StringIO() self.to_wire(f, None, origin) return f.getvalue() class UncompressedDowncasingMX(MXBase): """Base class for rdata that is like an MX record, but whose name is not compressed when convert to DNS wire format.""" def to_wire(self, file, compress = None, origin = None): super(UncompressedDowncasingMX, self).to_wire(file, None, origin)
3,968
Python
.py
84
40.666667
79
0.680559
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,136
SSHFP.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/SSHFP.py
# Copyright (C) 2005-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import struct import dns.rdata import dns.rdatatype class SSHFP(dns.rdata.Rdata): """SSHFP record @ivar algorithm: the algorithm @type algorithm: int @ivar fp_type: the digest type @type fp_type: int @ivar fingerprint: the fingerprint @type fingerprint: string @see: draft-ietf-secsh-dns-05.txt""" __slots__ = ['algorithm', 'fp_type', 'fingerprint'] def __init__(self, rdclass, rdtype, algorithm, fp_type, fingerprint): super(SSHFP, self).__init__(rdclass, rdtype) self.algorithm = algorithm self.fp_type = fp_type self.fingerprint = fingerprint def to_text(self, origin=None, relativize=True, **kw): return '%d %d %s' % (self.algorithm, self.fp_type, dns.rdata._hexify(self.fingerprint, chunksize=128)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): algorithm = tok.get_uint8() fp_type = tok.get_uint8() fingerprint = tok.get_string() fingerprint = fingerprint.decode('hex_codec') tok.get_eol() return cls(rdclass, rdtype, algorithm, fp_type, fingerprint) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): header = struct.pack("!BB", self.algorithm, self.fp_type) file.write(header) file.write(self.fingerprint) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): header = struct.unpack("!BB", wire[current : current + 2]) current += 2 rdlen -= 2 fingerprint = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], header[1], fingerprint) from_wire = classmethod(from_wire) def _cmp(self, other): hs = struct.pack("!BB", self.algorithm, self.fp_type) ho = struct.pack("!BB", other.algorithm, other.fp_type) v = cmp(hs, ho) if v == 0: v = cmp(self.fingerprint, other.fingerprint) return v
2,901
Python
.py
64
37.96875
79
0.656161
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,137
SOA.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/SOA.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import struct import dns.exception import dns.rdata import dns.name class SOA(dns.rdata.Rdata): """SOA record @ivar mname: the SOA MNAME (master name) field @type mname: dns.name.Name object @ivar rname: the SOA RNAME (responsible name) field @type rname: dns.name.Name object @ivar serial: The zone's serial number @type serial: int @ivar refresh: The zone's refresh value (in seconds) @type refresh: int @ivar retry: The zone's retry value (in seconds) @type retry: int @ivar expire: The zone's expiration value (in seconds) @type expire: int @ivar minimum: The zone's negative caching time (in seconds, called "minimum" for historical reasons) @type minimum: int @see: RFC 1035""" __slots__ = ['mname', 'rname', 'serial', 'refresh', 'retry', 'expire', 'minimum'] def __init__(self, rdclass, rdtype, mname, rname, serial, refresh, retry, expire, minimum): super(SOA, self).__init__(rdclass, rdtype) self.mname = mname self.rname = rname self.serial = serial self.refresh = refresh self.retry = retry self.expire = expire self.minimum = minimum def to_text(self, origin=None, relativize=True, **kw): mname = self.mname.choose_relativity(origin, relativize) rname = self.rname.choose_relativity(origin, relativize) return '%s %s %d %d %d %d %d' % ( mname, rname, self.serial, self.refresh, self.retry, self.expire, self.minimum ) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): mname = tok.get_name() rname = tok.get_name() mname = mname.choose_relativity(origin, relativize) rname = rname.choose_relativity(origin, relativize) serial = tok.get_uint32() refresh = tok.get_ttl() retry = tok.get_ttl() expire = tok.get_ttl() minimum = tok.get_ttl() tok.get_eol() return cls(rdclass, rdtype, mname, rname, serial, refresh, retry, expire, minimum ) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): self.mname.to_wire(file, compress, origin) self.rname.to_wire(file, compress, origin) five_ints = struct.pack('!IIIII', self.serial, self.refresh, self.retry, self.expire, self.minimum) file.write(five_ints) def to_digestable(self, origin = None): return self.mname.to_digestable(origin) + \ self.rname.to_digestable(origin) + \ struct.pack('!IIIII', self.serial, self.refresh, self.retry, self.expire, self.minimum) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (mname, cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -= cused (rname, cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -= cused if rdlen != 20: raise dns.exception.FormError five_ints = struct.unpack('!IIIII', wire[current : current + rdlen]) if not origin is None: mname = mname.relativize(origin) rname = rname.relativize(origin) return cls(rdclass, rdtype, mname, rname, five_ints[0], five_ints[1], five_ints[2], five_ints[3], five_ints[4]) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.mname = self.mname.choose_relativity(origin, relativize) self.rname = self.rname.choose_relativity(origin, relativize) def _cmp(self, other): v = cmp(self.mname, other.mname) if v == 0: v = cmp(self.rname, other.rname) if v == 0: self_ints = struct.pack('!IIIII', self.serial, self.refresh, self.retry, self.expire, self.minimum) other_ints = struct.pack('!IIIII', other.serial, other.refresh, other.retry, other.expire, other.minimum) v = cmp(self_ints, other_ints) return v
5,163
Python
.py
112
36.866071
79
0.622319
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,138
RRSIG.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/RRSIG.py
# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import calendar import struct import time import dns.dnssec import dns.exception import dns.rdata import dns.rdatatype class BadSigTime(dns.exception.DNSException): """Raised when a SIG or RRSIG RR's time cannot be parsed.""" pass def sigtime_to_posixtime(what): if len(what) != 14: raise BadSigTime year = int(what[0:4]) month = int(what[4:6]) day = int(what[6:8]) hour = int(what[8:10]) minute = int(what[10:12]) second = int(what[12:14]) return calendar.timegm((year, month, day, hour, minute, second, 0, 0, 0)) def posixtime_to_sigtime(what): return time.strftime('%Y%m%d%H%M%S', time.gmtime(what)) class RRSIG(dns.rdata.Rdata): """RRSIG record @ivar type_covered: the rdata type this signature covers @type type_covered: int @ivar algorithm: the algorithm used for the sig @type algorithm: int @ivar labels: number of labels @type labels: int @ivar original_ttl: the original TTL @type original_ttl: long @ivar expiration: signature expiration time @type expiration: long @ivar inception: signature inception time @type inception: long @ivar key_tag: the key tag @type key_tag: int @ivar signer: the signer @type signer: dns.name.Name object @ivar signature: the signature @type signature: string""" __slots__ = ['type_covered', 'algorithm', 'labels', 'original_ttl', 'expiration', 'inception', 'key_tag', 'signer', 'signature'] def __init__(self, rdclass, rdtype, type_covered, algorithm, labels, original_ttl, expiration, inception, key_tag, signer, signature): super(RRSIG, self).__init__(rdclass, rdtype) self.type_covered = type_covered self.algorithm = algorithm self.labels = labels self.original_ttl = original_ttl self.expiration = expiration self.inception = inception self.key_tag = key_tag self.signer = signer self.signature = signature def covers(self): return self.type_covered def to_text(self, origin=None, relativize=True, **kw): return '%s %d %d %d %s %s %d %s %s' % ( dns.rdatatype.to_text(self.type_covered), self.algorithm, self.labels, self.original_ttl, posixtime_to_sigtime(self.expiration), posixtime_to_sigtime(self.inception), self.key_tag, self.signer, dns.rdata._base64ify(self.signature) ) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): type_covered = dns.rdatatype.from_text(tok.get_string()) algorithm = dns.dnssec.algorithm_from_text(tok.get_string()) labels = tok.get_int() original_ttl = tok.get_ttl() expiration = sigtime_to_posixtime(tok.get_string()) inception = sigtime_to_posixtime(tok.get_string()) key_tag = tok.get_int() signer = tok.get_name() signer = signer.choose_relativity(origin, relativize) chunks = [] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) signature = b64.decode('base64_codec') return cls(rdclass, rdtype, type_covered, algorithm, labels, original_ttl, expiration, inception, key_tag, signer, signature) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): header = struct.pack('!HBBIIIH', self.type_covered, self.algorithm, self.labels, self.original_ttl, self.expiration, self.inception, self.key_tag) file.write(header) self.signer.to_wire(file, None, origin) file.write(self.signature) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): header = struct.unpack('!HBBIIIH', wire[current : current + 18]) current += 18 rdlen -= 18 (signer, cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -= cused if not origin is None: signer = signer.relativize(origin) signature = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], header[1], header[2], header[3], header[4], header[5], header[6], signer, signature) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.signer = self.signer.choose_relativity(origin, relativize) def _cmp(self, other): return self._wire_cmp(other)
5,737
Python
.py
137
33.649635
79
0.634832
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,139
NS.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/NS.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.nsbase class NS(dns.rdtypes.nsbase.NSBase): """NS record""" pass
880
Python
.py
18
47.333333
72
0.790698
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,140
LOC.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/LOC.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import dns.exception import dns.rdata _pows = (1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L) def _exponent_of(what, desc): exp = None for i in xrange(len(_pows)): if what // _pows[i] == 0L: exp = i - 1 break if exp is None or exp < 0: raise dns.exception.SyntaxError("%s value out of bounds" % desc) return exp def _float_to_tuple(what): if what < 0: sign = -1 what *= -1 else: sign = 1 what = long(round(what * 3600000)) degrees = int(what // 3600000) what -= degrees * 3600000 minutes = int(what // 60000) what -= minutes * 60000 seconds = int(what // 1000) what -= int(seconds * 1000) what = int(what) return (degrees * sign, minutes, seconds, what) def _tuple_to_float(what): if what[0] < 0: sign = -1 value = float(what[0]) * -1 else: sign = 1 value = float(what[0]) value += float(what[1]) / 60.0 value += float(what[2]) / 3600.0 value += float(what[3]) / 3600000.0 return sign * value def _encode_size(what, desc): what = long(what); exponent = _exponent_of(what, desc) & 0xF base = what // pow(10, exponent) & 0xF return base * 16 + exponent def _decode_size(what, desc): exponent = what & 0x0F if exponent > 9: raise dns.exception.SyntaxError("bad %s exponent" % desc) base = (what & 0xF0) >> 4 if base > 9: raise dns.exception.SyntaxError("bad %s base" % desc) return long(base) * pow(10, exponent) class LOC(dns.rdata.Rdata): """LOC record @ivar latitude: latitude @type latitude: (int, int, int, int) tuple specifying the degrees, minutes, seconds, and milliseconds of the coordinate. @ivar longitude: longitude @type longitude: (int, int, int, int) tuple specifying the degrees, minutes, seconds, and milliseconds of the coordinate. @ivar altitude: altitude @type altitude: float @ivar size: size of the sphere @type size: float @ivar horizontal_precision: horizontal precision @type horizontal_precision: float @ivar vertical_precision: vertical precision @type vertical_precision: float @see: RFC 1876""" __slots__ = ['latitude', 'longitude', 'altitude', 'size', 'horizontal_precision', 'vertical_precision'] def __init__(self, rdclass, rdtype, latitude, longitude, altitude, size=1.0, hprec=10000.0, vprec=10.0): """Initialize a LOC record instance. The parameters I{latitude} and I{longitude} may be either a 4-tuple of integers specifying (degrees, minutes, seconds, milliseconds), or they may be floating point values specifying the number of degrees. The other parameters are floats.""" super(LOC, self).__init__(rdclass, rdtype) if isinstance(latitude, int) or isinstance(latitude, long): latitude = float(latitude) if isinstance(latitude, float): latitude = _float_to_tuple(latitude) self.latitude = latitude if isinstance(longitude, int) or isinstance(longitude, long): longitude = float(longitude) if isinstance(longitude, float): longitude = _float_to_tuple(longitude) self.longitude = longitude self.altitude = float(altitude) self.size = float(size) self.horizontal_precision = float(hprec) self.vertical_precision = float(vprec) def to_text(self, origin=None, relativize=True, **kw): if self.latitude[0] > 0: lat_hemisphere = 'N' lat_degrees = self.latitude[0] else: lat_hemisphere = 'S' lat_degrees = -1 * self.latitude[0] if self.longitude[0] > 0: long_hemisphere = 'E' long_degrees = self.longitude[0] else: long_hemisphere = 'W' long_degrees = -1 * self.longitude[0] text = "%d %d %d.%03d %s %d %d %d.%03d %s %0.2fm" % ( lat_degrees, self.latitude[1], self.latitude[2], self.latitude[3], lat_hemisphere, long_degrees, self.longitude[1], self.longitude[2], self.longitude[3], long_hemisphere, self.altitude / 100.0 ) if self.size != 1.0 or self.horizontal_precision != 10000.0 or \ self.vertical_precision != 10.0: text += " %0.2fm %0.2fm %0.2fm" % ( self.size / 100.0, self.horizontal_precision / 100.0, self.vertical_precision / 100.0 ) return text def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): latitude = [0, 0, 0, 0] longitude = [0, 0, 0, 0] size = 1.0 hprec = 10000.0 vprec = 10.0 latitude[0] = tok.get_int() t = tok.get_string() if t.isdigit(): latitude[1] = int(t) t = tok.get_string() if '.' in t: (seconds, milliseconds) = t.split('.') if not seconds.isdigit(): raise dns.exception.SyntaxError('bad latitude seconds value') latitude[2] = int(seconds) if latitude[2] >= 60: raise dns.exception.SyntaxError('latitude seconds >= 60') l = len(milliseconds) if l == 0 or l > 3 or not milliseconds.isdigit(): raise dns.exception.SyntaxError('bad latitude milliseconds value') if l == 1: m = 100 elif l == 2: m = 10 else: m = 1 latitude[3] = m * int(milliseconds) t = tok.get_string() elif t.isdigit(): latitude[2] = int(t) t = tok.get_string() if t == 'S': latitude[0] *= -1 elif t != 'N': raise dns.exception.SyntaxError('bad latitude hemisphere value') longitude[0] = tok.get_int() t = tok.get_string() if t.isdigit(): longitude[1] = int(t) t = tok.get_string() if '.' in t: (seconds, milliseconds) = t.split('.') if not seconds.isdigit(): raise dns.exception.SyntaxError('bad longitude seconds value') longitude[2] = int(seconds) if longitude[2] >= 60: raise dns.exception.SyntaxError('longitude seconds >= 60') l = len(milliseconds) if l == 0 or l > 3 or not milliseconds.isdigit(): raise dns.exception.SyntaxError('bad longitude milliseconds value') if l == 1: m = 100 elif l == 2: m = 10 else: m = 1 longitude[3] = m * int(milliseconds) t = tok.get_string() elif t.isdigit(): longitude[2] = int(t) t = tok.get_string() if t == 'W': longitude[0] *= -1 elif t != 'E': raise dns.exception.SyntaxError('bad longitude hemisphere value') t = tok.get_string() if t[-1] == 'm': t = t[0 : -1] altitude = float(t) * 100.0 # m -> cm token = tok.get().unescape() if not token.is_eol_or_eof(): value = token.value if value[-1] == 'm': value = value[0 : -1] size = float(value) * 100.0 # m -> cm token = tok.get().unescape() if not token.is_eol_or_eof(): value = token.value if value[-1] == 'm': value = value[0 : -1] hprec = float(value) * 100.0 # m -> cm token = tok.get().unescape() if not token.is_eol_or_eof(): value = token.value if value[-1] == 'm': value = value[0 : -1] vprec = float(value) * 100.0 # m -> cm tok.get_eol() return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): if self.latitude[0] < 0: sign = -1 degrees = long(-1 * self.latitude[0]) else: sign = 1 degrees = long(self.latitude[0]) milliseconds = (degrees * 3600000 + self.latitude[1] * 60000 + self.latitude[2] * 1000 + self.latitude[3]) * sign latitude = 0x80000000L + milliseconds if self.longitude[0] < 0: sign = -1 degrees = long(-1 * self.longitude[0]) else: sign = 1 degrees = long(self.longitude[0]) milliseconds = (degrees * 3600000 + self.longitude[1] * 60000 + self.longitude[2] * 1000 + self.longitude[3]) * sign longitude = 0x80000000L + milliseconds altitude = long(self.altitude) + 10000000L size = _encode_size(self.size, "size") hprec = _encode_size(self.horizontal_precision, "horizontal precision") vprec = _encode_size(self.vertical_precision, "vertical precision") wire = struct.pack("!BBBBIII", 0, size, hprec, vprec, latitude, longitude, altitude) file.write(wire) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (version, size, hprec, vprec, latitude, longitude, altitude) = \ struct.unpack("!BBBBIII", wire[current : current + rdlen]) if latitude > 0x80000000L: latitude = float(latitude - 0x80000000L) / 3600000 else: latitude = -1 * float(0x80000000L - latitude) / 3600000 if latitude < -90.0 or latitude > 90.0: raise dns.exception.FormError("bad latitude") if longitude > 0x80000000L: longitude = float(longitude - 0x80000000L) / 3600000 else: longitude = -1 * float(0x80000000L - longitude) / 3600000 if longitude < -180.0 or longitude > 180.0: raise dns.exception.FormError("bad longitude") altitude = float(altitude) - 10000000.0 size = _decode_size(size, "size") hprec = _decode_size(hprec, "horizontal precision") vprec = _decode_size(vprec, "vertical precision") return cls(rdclass, rdtype, latitude, longitude, altitude, size, hprec, vprec) from_wire = classmethod(from_wire) def _cmp(self, other): f = cStringIO.StringIO() self.to_wire(f) wire1 = f.getvalue() f.seek(0) f.truncate() other.to_wire(f) wire2 = f.getvalue() f.close() return cmp(wire1, wire2) def _get_float_latitude(self): return _tuple_to_float(self.latitude) def _set_float_latitude(self, value): self.latitude = _float_to_tuple(value) float_latitude = property(_get_float_latitude, _set_float_latitude, doc="latitude as a floating point value") def _get_float_longitude(self): return _tuple_to_float(self.longitude) def _set_float_longitude(self, value): self.longitude = _float_to_tuple(value) float_longitude = property(_get_float_longitude, _set_float_longitude, doc="longitude as a floating point value")
12,598
Python
.py
300
31.286667
87
0.559524
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,141
NSEC3.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/NSEC3.py
# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import base64 import cStringIO import string import struct import dns.exception import dns.rdata import dns.rdatatype b32_hex_to_normal = string.maketrans('0123456789ABCDEFGHIJKLMNOPQRSTUV', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567') b32_normal_to_hex = string.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', '0123456789ABCDEFGHIJKLMNOPQRSTUV') # hash algorithm constants SHA1 = 1 # flag constants OPTOUT = 1 class NSEC3(dns.rdata.Rdata): """NSEC3 record @ivar algorithm: the hash algorithm number @type algorithm: int @ivar flags: the flags @type flags: int @ivar iterations: the number of iterations @type iterations: int @ivar salt: the salt @type salt: string @ivar next: the next name hash @type next: string @ivar windows: the windowed bitmap list @type windows: list of (window number, string) tuples""" __slots__ = ['algorithm', 'flags', 'iterations', 'salt', 'next', 'windows'] def __init__(self, rdclass, rdtype, algorithm, flags, iterations, salt, next, windows): super(NSEC3, self).__init__(rdclass, rdtype) self.algorithm = algorithm self.flags = flags self.iterations = iterations self.salt = salt self.next = next self.windows = windows def to_text(self, origin=None, relativize=True, **kw): next = base64.b32encode(self.next).translate(b32_normal_to_hex).lower() if self.salt == '': salt = '-' else: salt = self.salt.encode('hex-codec') text = '' for (window, bitmap) in self.windows: bits = [] for i in xrange(0, len(bitmap)): byte = ord(bitmap[i]) for j in xrange(0, 8): if byte & (0x80 >> j): bits.append(dns.rdatatype.to_text(window * 256 + \ i * 8 + j)) text += (' ' + ' '.join(bits)) return '%u %u %u %s %s%s' % (self.algorithm, self.flags, self.iterations, salt, next, text) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): algorithm = tok.get_uint8() flags = tok.get_uint8() iterations = tok.get_uint16() salt = tok.get_string() if salt == '-': salt = '' else: salt = salt.decode('hex-codec') next = tok.get_string().upper().translate(b32_hex_to_normal) next = base64.b32decode(next) rdtypes = [] while 1: token = tok.get().unescape() if token.is_eol_or_eof(): break nrdtype = dns.rdatatype.from_text(token.value) if nrdtype == 0: raise dns.exception.SyntaxError("NSEC3 with bit 0") if nrdtype > 65535: raise dns.exception.SyntaxError("NSEC3 with bit > 65535") rdtypes.append(nrdtype) rdtypes.sort() window = 0 octets = 0 prior_rdtype = 0 bitmap = ['\0'] * 32 windows = [] for nrdtype in rdtypes: if nrdtype == prior_rdtype: continue prior_rdtype = nrdtype new_window = nrdtype // 256 if new_window != window: windows.append((window, ''.join(bitmap[0:octets]))) bitmap = ['\0'] * 32 window = new_window offset = nrdtype % 256 byte = offset // 8 bit = offset % 8 octets = byte + 1 bitmap[byte] = chr(ord(bitmap[byte]) | (0x80 >> bit)) windows.append((window, ''.join(bitmap[0:octets]))) return cls(rdclass, rdtype, algorithm, flags, iterations, salt, next, windows) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): l = len(self.salt) file.write(struct.pack("!BBHB", self.algorithm, self.flags, self.iterations, l)) file.write(self.salt) l = len(self.next) file.write(struct.pack("!B", l)) file.write(self.next) for (window, bitmap) in self.windows: file.write(chr(window)) file.write(chr(len(bitmap))) file.write(bitmap) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (algorithm, flags, iterations, slen) = struct.unpack('!BBHB', wire[current : current + 5]) current += 5 rdlen -= 5 salt = wire[current : current + slen].unwrap() current += slen rdlen -= slen (nlen, ) = struct.unpack('!B', wire[current]) current += 1 rdlen -= 1 next = wire[current : current + nlen].unwrap() current += nlen rdlen -= nlen windows = [] while rdlen > 0: if rdlen < 3: raise dns.exception.FormError("NSEC3 too short") window = ord(wire[current]) octets = ord(wire[current + 1]) if octets == 0 or octets > 32: raise dns.exception.FormError("bad NSEC3 octets") current += 2 rdlen -= 2 if rdlen < octets: raise dns.exception.FormError("bad NSEC3 bitmap length") bitmap = wire[current : current + octets].unwrap() current += octets rdlen -= octets windows.append((window, bitmap)) return cls(rdclass, rdtype, algorithm, flags, iterations, salt, next, windows) from_wire = classmethod(from_wire) def _cmp(self, other): b1 = cStringIO.StringIO() self.to_wire(b1) b2 = cStringIO.StringIO() other.to_wire(b2) return cmp(b1.getvalue(), b2.getvalue())
6,743
Python
.py
166
30.451807
89
0.574303
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,142
MX.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/MX.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.mxbase class MX(dns.rdtypes.mxbase.MXBase): """MX record""" pass
880
Python
.py
18
47.333333
72
0.790698
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,143
CERT.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/CERT.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import dns.exception import dns.dnssec import dns.rdata import dns.tokenizer _ctype_by_value = { 1 : 'PKIX', 2 : 'SPKI', 3 : 'PGP', 253 : 'URI', 254 : 'OID', } _ctype_by_name = { 'PKIX' : 1, 'SPKI' : 2, 'PGP' : 3, 'URI' : 253, 'OID' : 254, } def _ctype_from_text(what): v = _ctype_by_name.get(what) if not v is None: return v return int(what) def _ctype_to_text(what): v = _ctype_by_value.get(what) if not v is None: return v return str(what) class CERT(dns.rdata.Rdata): """CERT record @ivar certificate_type: certificate type @type certificate_type: int @ivar key_tag: key tag @type key_tag: int @ivar algorithm: algorithm @type algorithm: int @ivar certificate: the certificate or CRL @type certificate: string @see: RFC 2538""" __slots__ = ['certificate_type', 'key_tag', 'algorithm', 'certificate'] def __init__(self, rdclass, rdtype, certificate_type, key_tag, algorithm, certificate): super(CERT, self).__init__(rdclass, rdtype) self.certificate_type = certificate_type self.key_tag = key_tag self.algorithm = algorithm self.certificate = certificate def to_text(self, origin=None, relativize=True, **kw): certificate_type = _ctype_to_text(self.certificate_type) return "%s %d %s %s" % (certificate_type, self.key_tag, dns.dnssec.algorithm_to_text(self.algorithm), dns.rdata._base64ify(self.certificate)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): certificate_type = _ctype_from_text(tok.get_string()) key_tag = tok.get_uint16() algorithm = dns.dnssec.algorithm_from_text(tok.get_string()) if algorithm < 0 or algorithm > 255: raise dns.exception.SyntaxError("bad algorithm type") chunks = [] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) certificate = b64.decode('base64_codec') return cls(rdclass, rdtype, certificate_type, key_tag, algorithm, certificate) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): prefix = struct.pack("!HHB", self.certificate_type, self.key_tag, self.algorithm) file.write(prefix) file.write(self.certificate) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): prefix = wire[current : current + 5].unwrap() current += 5 rdlen -= 5 if rdlen < 0: raise dns.exception.FormError (certificate_type, key_tag, algorithm) = struct.unpack("!HHB", prefix) certificate = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, certificate_type, key_tag, algorithm, certificate) from_wire = classmethod(from_wire) def _cmp(self, other): f = cStringIO.StringIO() self.to_wire(f) wire1 = f.getvalue() f.seek(0) f.truncate() other.to_wire(f) wire2 = f.getvalue() f.close() return cmp(wire1, wire2)
4,280
Python
.py
113
30.557522
79
0.631477
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,144
RP.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/RP.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.rdata import dns.name class RP(dns.rdata.Rdata): """RP record @ivar mbox: The responsible person's mailbox @type mbox: dns.name.Name object @ivar txt: The owner name of a node with TXT records, or the root name if no TXT records are associated with this RP. @type txt: dns.name.Name object @see: RFC 1183""" __slots__ = ['mbox', 'txt'] def __init__(self, rdclass, rdtype, mbox, txt): super(RP, self).__init__(rdclass, rdtype) self.mbox = mbox self.txt = txt def to_text(self, origin=None, relativize=True, **kw): mbox = self.mbox.choose_relativity(origin, relativize) txt = self.txt.choose_relativity(origin, relativize) return "%s %s" % (str(mbox), str(txt)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): mbox = tok.get_name() txt = tok.get_name() mbox = mbox.choose_relativity(origin, relativize) txt = txt.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, mbox, txt) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): self.mbox.to_wire(file, None, origin) self.txt.to_wire(file, None, origin) def to_digestable(self, origin = None): return self.mbox.to_digestable(origin) + \ self.txt.to_digestable(origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (mbox, cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -= cused if rdlen <= 0: raise dns.exception.FormError (txt, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: mbox = mbox.relativize(origin) txt = txt.relativize(origin) return cls(rdclass, rdtype, mbox, txt) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.mbox = self.mbox.choose_relativity(origin, relativize) self.txt = self.txt.choose_relativity(origin, relativize) def _cmp(self, other): v = cmp(self.mbox, other.mbox) if v == 0: v = cmp(self.txt, other.txt) return v
3,274
Python
.py
72
37.986111
79
0.653701
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,145
HIP.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/HIP.py
# Copyright (C) 2010, 2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import string import struct import dns.exception import dns.rdata import dns.rdatatype class HIP(dns.rdata.Rdata): """HIP record @ivar hit: the host identity tag @type hit: string @ivar algorithm: the public key cryptographic algorithm @type algorithm: int @ivar key: the public key @type key: string @ivar servers: the rendezvous servers @type servers: list of dns.name.Name objects @see: RFC 5205""" __slots__ = ['hit', 'algorithm', 'key', 'servers'] def __init__(self, rdclass, rdtype, hit, algorithm, key, servers): super(HIP, self).__init__(rdclass, rdtype) self.hit = hit self.algorithm = algorithm self.key = key self.servers = servers def to_text(self, origin=None, relativize=True, **kw): hit = self.hit.encode('hex-codec') key = self.key.encode('base64-codec').replace('\n', '') text = '' servers = [] for server in self.servers: servers.append(str(server.choose_relativity(origin, relativize))) if len(servers) > 0: text += (' ' + ' '.join(servers)) return '%u %s %s%s' % (self.algorithm, hit, key, text) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): algorithm = tok.get_uint8() hit = tok.get_string().decode('hex-codec') if len(hit) > 255: raise dns.exception.SyntaxError("HIT too long") key = tok.get_string().decode('base64-codec') servers = [] while 1: token = tok.get() if token.is_eol_or_eof(): break server = dns.name.from_text(token.value, origin) server.choose_relativity(origin, relativize) servers.append(server) return cls(rdclass, rdtype, hit, algorithm, key, servers) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): lh = len(self.hit) lk = len(self.key) file.write(struct.pack("!BBH", lh, self.algorithm, lk)) file.write(self.hit) file.write(self.key) for server in self.servers: server.to_wire(file, None, origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (lh, algorithm, lk) = struct.unpack('!BBH', wire[current : current + 4]) current += 4 rdlen -= 4 hit = wire[current : current + lh].unwrap() current += lh rdlen -= lh key = wire[current : current + lk].unwrap() current += lk rdlen -= lk servers = [] while rdlen > 0: (server, cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -= cused if not origin is None: server = server.relativize(origin) servers.append(server) return cls(rdclass, rdtype, hit, algorithm, key, servers) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): servers = [] for server in self.servers: server = server.choose_relativity(origin, relativize) servers.append(server) self.servers = servers def _cmp(self, other): b1 = cStringIO.StringIO() lh = len(self.hit) lk = len(self.key) b1.write(struct.pack("!BBH", lh, self.algorithm, lk)) b1.write(self.hit) b1.write(self.key) b2 = cStringIO.StringIO() lh = len(other.hit) lk = len(other.key) b2.write(struct.pack("!BBH", lh, other.algorithm, lk)) b2.write(other.hit) b2.write(other.key) v = cmp(b1.getvalue(), b2.getvalue()) if v != 0: return v ls = len(self.servers) lo = len(other.servers) count = min(ls, lo) i = 0 while i < count: v = cmp(self.servers[i], other.servers[i]) if v != 0: return v i += 1 return ls - lo
4,957
Python
.py
126
30.761905
79
0.599543
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,146
X25.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/X25.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.rdata import dns.tokenizer class X25(dns.rdata.Rdata): """X25 record @ivar address: the PSDN address @type address: string @see: RFC 1183""" __slots__ = ['address'] def __init__(self, rdclass, rdtype, address): super(X25, self).__init__(rdclass, rdtype) self.address = address def to_text(self, origin=None, relativize=True, **kw): return '"%s"' % dns.rdata._escapify(self.address) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): address = tok.get_string() tok.get_eol() return cls(rdclass, rdtype, address) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): l = len(self.address) assert l < 256 byte = chr(l) file.write(byte) file.write(self.address) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): l = ord(wire[current]) current += 1 rdlen -= 1 if l != rdlen: raise dns.exception.FormError address = wire[current : current + l].unwrap() return cls(rdclass, rdtype, address) from_wire = classmethod(from_wire) def _cmp(self, other): return cmp(self.address, other.address)
2,107
Python
.py
50
36.74
79
0.687531
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,147
DNSKEY.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/DNSKEY.py
# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import struct import dns.exception import dns.dnssec import dns.rdata # flag constants SEP = 0x0001 REVOKE = 0x0080 ZONE = 0x0100 class DNSKEY(dns.rdata.Rdata): """DNSKEY record @ivar flags: the key flags @type flags: int @ivar protocol: the protocol for which this key may be used @type protocol: int @ivar algorithm: the algorithm used for the key @type algorithm: int @ivar key: the public key @type key: string""" __slots__ = ['flags', 'protocol', 'algorithm', 'key'] def __init__(self, rdclass, rdtype, flags, protocol, algorithm, key): super(DNSKEY, self).__init__(rdclass, rdtype) self.flags = flags self.protocol = protocol self.algorithm = algorithm self.key = key def to_text(self, origin=None, relativize=True, **kw): return '%d %d %d %s' % (self.flags, self.protocol, self.algorithm, dns.rdata._base64ify(self.key)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): flags = tok.get_uint16() protocol = tok.get_uint8() algorithm = dns.dnssec.algorithm_from_text(tok.get_string()) chunks = [] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) key = b64.decode('base64_codec') return cls(rdclass, rdtype, flags, protocol, algorithm, key) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): header = struct.pack("!HBB", self.flags, self.protocol, self.algorithm) file.write(header) file.write(self.key) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): if rdlen < 4: raise dns.exception.FormError header = struct.unpack('!HBB', wire[current : current + 4]) current += 4 rdlen -= 4 key = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], header[1], header[2], key) from_wire = classmethod(from_wire) def _cmp(self, other): hs = struct.pack("!HBB", self.flags, self.protocol, self.algorithm) ho = struct.pack("!HBB", other.flags, other.protocol, other.algorithm) v = cmp(hs, ho) if v == 0: v = cmp(self.key, other.key) return v
3,320
Python
.py
79
35.139241
79
0.650449
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,148
DLV.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/DLV.py
# Copyright (C) 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.dsbase class DLV(dns.rdtypes.dsbase.DSBase): """DLV record""" pass
871
Python
.py
18
46.833333
72
0.792009
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,149
AFSDB.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/AFSDB.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.mxbase class AFSDB(dns.rdtypes.mxbase.UncompressedDowncasingMX): """AFSDB record @ivar subtype: the subtype value @type subtype: int @ivar hostname: the hostname name @type hostname: dns.name.Name object""" # Use the property mechanism to make "subtype" an alias for the # "preference" attribute, and "hostname" an alias for the "exchange" # attribute. # # This lets us inherit the UncompressedMX implementation but lets # the caller use appropriate attribute names for the rdata type. # # We probably lose some performance vs. a cut-and-paste # implementation, but this way we don't copy code, and that's # good. def get_subtype(self): return self.preference def set_subtype(self, subtype): self.preference = subtype subtype = property(get_subtype, set_subtype) def get_hostname(self): return self.exchange def set_hostname(self, hostname): self.exchange = hostname hostname = property(get_hostname, set_hostname)
1,846
Python
.py
41
40.95122
72
0.747632
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,150
__init__.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/__init__.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Class ANY (generic) rdata type classes.""" __all__ = [ 'AFSDB', 'CERT', 'CNAME', 'DLV', 'DNAME', 'DNSKEY', 'DS', 'GPOS', 'HINFO', 'HIP', 'ISDN', 'LOC', 'MX', 'NS', 'NSEC', 'NSEC3', 'NSEC3PARAM', 'PTR', 'RP', 'RRSIG', 'RT', 'SOA', 'SPF', 'SSHFP', 'TXT', 'X25', ]
1,157
Python
.py
43
23.44186
72
0.676259
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,151
NSEC3PARAM.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/NSEC3PARAM.py
# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import dns.exception import dns.rdata class NSEC3PARAM(dns.rdata.Rdata): """NSEC3PARAM record @ivar algorithm: the hash algorithm number @type algorithm: int @ivar flags: the flags @type flags: int @ivar iterations: the number of iterations @type iterations: int @ivar salt: the salt @type salt: string""" __slots__ = ['algorithm', 'flags', 'iterations', 'salt'] def __init__(self, rdclass, rdtype, algorithm, flags, iterations, salt): super(NSEC3PARAM, self).__init__(rdclass, rdtype) self.algorithm = algorithm self.flags = flags self.iterations = iterations self.salt = salt def to_text(self, origin=None, relativize=True, **kw): if self.salt == '': salt = '-' else: salt = self.salt.encode('hex-codec') return '%u %u %u %s' % (self.algorithm, self.flags, self.iterations, salt) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): algorithm = tok.get_uint8() flags = tok.get_uint8() iterations = tok.get_uint16() salt = tok.get_string() if salt == '-': salt = '' else: salt = salt.decode('hex-codec') return cls(rdclass, rdtype, algorithm, flags, iterations, salt) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): l = len(self.salt) file.write(struct.pack("!BBHB", self.algorithm, self.flags, self.iterations, l)) file.write(self.salt) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (algorithm, flags, iterations, slen) = struct.unpack('!BBHB', wire[current : current + 5]) current += 5 rdlen -= 5 salt = wire[current : current + slen].unwrap() current += slen rdlen -= slen if rdlen != 0: raise dns.exception.FormError return cls(rdclass, rdtype, algorithm, flags, iterations, salt) from_wire = classmethod(from_wire) def _cmp(self, other): b1 = cStringIO.StringIO() self.to_wire(b1) b2 = cStringIO.StringIO() other.to_wire(b2) return cmp(b1.getvalue(), b2.getvalue())
3,169
Python
.py
75
34.786667
89
0.64135
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,152
DNAME.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/DNAME.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.nsbase class DNAME(dns.rdtypes.nsbase.UncompressedNS): """DNAME record""" def to_digestable(self, origin = None): return self.target.to_digestable(origin)
979
Python
.py
19
49.526316
72
0.786834
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,153
TXT.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/TXT.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.txtbase class TXT(dns.rdtypes.txtbase.TXTBase): """TXT record""" pass
885
Python
.py
18
47.611111
72
0.791908
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,154
ISDN.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/ISDN.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.rdata import dns.tokenizer class ISDN(dns.rdata.Rdata): """ISDN record @ivar address: the ISDN address @type address: string @ivar subaddress: the ISDN subaddress (or '' if not present) @type subaddress: string @see: RFC 1183""" __slots__ = ['address', 'subaddress'] def __init__(self, rdclass, rdtype, address, subaddress): super(ISDN, self).__init__(rdclass, rdtype) self.address = address self.subaddress = subaddress def to_text(self, origin=None, relativize=True, **kw): if self.subaddress: return '"%s" "%s"' % (dns.rdata._escapify(self.address), dns.rdata._escapify(self.subaddress)) else: return '"%s"' % dns.rdata._escapify(self.address) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): address = tok.get_string() t = tok.get() if not t.is_eol_or_eof(): tok.unget(t) subaddress = tok.get_string() else: tok.unget(t) subaddress = '' tok.get_eol() return cls(rdclass, rdtype, address, subaddress) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): l = len(self.address) assert l < 256 byte = chr(l) file.write(byte) file.write(self.address) l = len(self.subaddress) if l > 0: assert l < 256 byte = chr(l) file.write(byte) file.write(self.subaddress) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): l = ord(wire[current]) current += 1 rdlen -= 1 if l > rdlen: raise dns.exception.FormError address = wire[current : current + l].unwrap() current += l rdlen -= l if rdlen > 0: l = ord(wire[current]) current += 1 rdlen -= 1 if l != rdlen: raise dns.exception.FormError subaddress = wire[current : current + l].unwrap() else: subaddress = '' return cls(rdclass, rdtype, address, subaddress) from_wire = classmethod(from_wire) def _cmp(self, other): v = cmp(self.address, other.address) if v == 0: v = cmp(self.subaddress, other.subaddress) return v
3,250
Python
.py
84
30.714286
79
0.617945
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,155
HINFO.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/HINFO.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.rdata import dns.tokenizer class HINFO(dns.rdata.Rdata): """HINFO record @ivar cpu: the CPU type @type cpu: string @ivar os: the OS type @type os: string @see: RFC 1035""" __slots__ = ['cpu', 'os'] def __init__(self, rdclass, rdtype, cpu, os): super(HINFO, self).__init__(rdclass, rdtype) self.cpu = cpu self.os = os def to_text(self, origin=None, relativize=True, **kw): return '"%s" "%s"' % (dns.rdata._escapify(self.cpu), dns.rdata._escapify(self.os)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): cpu = tok.get_string() os = tok.get_string() tok.get_eol() return cls(rdclass, rdtype, cpu, os) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): l = len(self.cpu) assert l < 256 byte = chr(l) file.write(byte) file.write(self.cpu) l = len(self.os) assert l < 256 byte = chr(l) file.write(byte) file.write(self.os) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): l = ord(wire[current]) current += 1 rdlen -= 1 if l > rdlen: raise dns.exception.FormError cpu = wire[current : current + l].unwrap() current += l rdlen -= l l = ord(wire[current]) current += 1 rdlen -= 1 if l != rdlen: raise dns.exception.FormError os = wire[current : current + l].unwrap() return cls(rdclass, rdtype, cpu, os) from_wire = classmethod(from_wire) def _cmp(self, other): v = cmp(self.cpu, other.cpu) if v == 0: v = cmp(self.os, other.os) return v
2,652
Python
.py
71
30.577465
79
0.627092
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,156
DS.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/DS.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.dsbase class DS(dns.rdtypes.dsbase.DSBase): """DS record""" pass
880
Python
.py
18
47.333333
72
0.790698
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,157
GPOS.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/GPOS.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.rdata import dns.tokenizer def _validate_float_string(what): if what[0] == '-' or what[0] == '+': what = what[1:] if what.isdigit(): return (left, right) = what.split('.') if left == '' and right == '': raise dns.exception.FormError if not left == '' and not left.isdigit(): raise dns.exception.FormError if not right == '' and not right.isdigit(): raise dns.exception.FormError class GPOS(dns.rdata.Rdata): """GPOS record @ivar latitude: latitude @type latitude: string @ivar longitude: longitude @type longitude: string @ivar altitude: altitude @type altitude: string @see: RFC 1712""" __slots__ = ['latitude', 'longitude', 'altitude'] def __init__(self, rdclass, rdtype, latitude, longitude, altitude): super(GPOS, self).__init__(rdclass, rdtype) if isinstance(latitude, float) or \ isinstance(latitude, int) or \ isinstance(latitude, long): latitude = str(latitude) if isinstance(longitude, float) or \ isinstance(longitude, int) or \ isinstance(longitude, long): longitude = str(longitude) if isinstance(altitude, float) or \ isinstance(altitude, int) or \ isinstance(altitude, long): altitude = str(altitude) _validate_float_string(latitude) _validate_float_string(longitude) _validate_float_string(altitude) self.latitude = latitude self.longitude = longitude self.altitude = altitude def to_text(self, origin=None, relativize=True, **kw): return '%s %s %s' % (self.latitude, self.longitude, self.altitude) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): latitude = tok.get_string() longitude = tok.get_string() altitude = tok.get_string() tok.get_eol() return cls(rdclass, rdtype, latitude, longitude, altitude) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): l = len(self.latitude) assert l < 256 byte = chr(l) file.write(byte) file.write(self.latitude) l = len(self.longitude) assert l < 256 byte = chr(l) file.write(byte) file.write(self.longitude) l = len(self.altitude) assert l < 256 byte = chr(l) file.write(byte) file.write(self.altitude) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): l = ord(wire[current]) current += 1 rdlen -= 1 if l > rdlen: raise dns.exception.FormError latitude = wire[current : current + l].unwrap() current += l rdlen -= l l = ord(wire[current]) current += 1 rdlen -= 1 if l > rdlen: raise dns.exception.FormError longitude = wire[current : current + l].unwrap() current += l rdlen -= l l = ord(wire[current]) current += 1 rdlen -= 1 if l != rdlen: raise dns.exception.FormError altitude = wire[current : current + l].unwrap() return cls(rdclass, rdtype, latitude, longitude, altitude) from_wire = classmethod(from_wire) def _cmp(self, other): v = cmp(self.latitude, other.latitude) if v == 0: v = cmp(self.longitude, other.longitude) if v == 0: v = cmp(self.altitude, other.altitude) return v def _get_float_latitude(self): return float(self.latitude) def _set_float_latitude(self, value): self.latitude = str(value) float_latitude = property(_get_float_latitude, _set_float_latitude, doc="latitude as a floating point value") def _get_float_longitude(self): return float(self.longitude) def _set_float_longitude(self, value): self.longitude = str(value) float_longitude = property(_get_float_longitude, _set_float_longitude, doc="longitude as a floating point value") def _get_float_altitude(self): return float(self.altitude) def _set_float_altitude(self, value): self.altitude = str(value) float_altitude = property(_get_float_altitude, _set_float_altitude, doc="altitude as a floating point value")
5,302
Python
.py
134
31.559701
79
0.6267
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,158
SPF.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/SPF.py
# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.txtbase class SPF(dns.rdtypes.txtbase.TXTBase): """SPF record @see: RFC 4408""" pass
906
Python
.py
19
45.894737
72
0.786199
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,159
NSEC.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/NSEC.py
# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import dns.exception import dns.rdata import dns.rdatatype import dns.name class NSEC(dns.rdata.Rdata): """NSEC record @ivar next: the next name @type next: dns.name.Name object @ivar windows: the windowed bitmap list @type windows: list of (window number, string) tuples""" __slots__ = ['next', 'windows'] def __init__(self, rdclass, rdtype, next, windows): super(NSEC, self).__init__(rdclass, rdtype) self.next = next self.windows = windows def to_text(self, origin=None, relativize=True, **kw): next = self.next.choose_relativity(origin, relativize) text = '' for (window, bitmap) in self.windows: bits = [] for i in xrange(0, len(bitmap)): byte = ord(bitmap[i]) for j in xrange(0, 8): if byte & (0x80 >> j): bits.append(dns.rdatatype.to_text(window * 256 + \ i * 8 + j)) text += (' ' + ' '.join(bits)) return '%s%s' % (next, text) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): next = tok.get_name() next = next.choose_relativity(origin, relativize) rdtypes = [] while 1: token = tok.get().unescape() if token.is_eol_or_eof(): break nrdtype = dns.rdatatype.from_text(token.value) if nrdtype == 0: raise dns.exception.SyntaxError("NSEC with bit 0") if nrdtype > 65535: raise dns.exception.SyntaxError("NSEC with bit > 65535") rdtypes.append(nrdtype) rdtypes.sort() window = 0 octets = 0 prior_rdtype = 0 bitmap = ['\0'] * 32 windows = [] for nrdtype in rdtypes: if nrdtype == prior_rdtype: continue prior_rdtype = nrdtype new_window = nrdtype // 256 if new_window != window: windows.append((window, ''.join(bitmap[0:octets]))) bitmap = ['\0'] * 32 window = new_window offset = nrdtype % 256 byte = offset // 8 bit = offset % 8 octets = byte + 1 bitmap[byte] = chr(ord(bitmap[byte]) | (0x80 >> bit)) windows.append((window, ''.join(bitmap[0:octets]))) return cls(rdclass, rdtype, next, windows) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): self.next.to_wire(file, None, origin) for (window, bitmap) in self.windows: file.write(chr(window)) file.write(chr(len(bitmap))) file.write(bitmap) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (next, cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -= cused windows = [] while rdlen > 0: if rdlen < 3: raise dns.exception.FormError("NSEC too short") window = ord(wire[current]) octets = ord(wire[current + 1]) if octets == 0 or octets > 32: raise dns.exception.FormError("bad NSEC octets") current += 2 rdlen -= 2 if rdlen < octets: raise dns.exception.FormError("bad NSEC bitmap length") bitmap = wire[current : current + octets].unwrap() current += octets rdlen -= octets windows.append((window, bitmap)) if not origin is None: next = next.relativize(origin) return cls(rdclass, rdtype, next, windows) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.next = self.next.choose_relativity(origin, relativize) def _cmp(self, other): return self._wire_cmp(other)
4,812
Python
.py
114
32.333333
79
0.586038
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,160
CNAME.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/CNAME.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.nsbase class CNAME(dns.rdtypes.nsbase.NSBase): """CNAME record Note: although CNAME is officially a singleton type, dnspython allows non-singleton CNAME rdatasets because such sets have been commonly used by BIND and other nameservers for load balancing.""" pass
1,091
Python
.py
21
49.857143
73
0.792877
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,161
PTR.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/PTR.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.nsbase class PTR(dns.rdtypes.nsbase.NSBase): """PTR record""" pass
882
Python
.py
18
47.444444
72
0.791183
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,162
RT.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/ANY/RT.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.mxbase class RT(dns.rdtypes.mxbase.UncompressedDowncasingMX): """RT record""" pass
898
Python
.py
18
48.333333
72
0.794989
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,163
NSAP.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/NSAP.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.rdata import dns.tokenizer class NSAP(dns.rdata.Rdata): """NSAP record. @ivar address: a NASP @type address: string @see: RFC 1706""" __slots__ = ['address'] def __init__(self, rdclass, rdtype, address): super(NSAP, self).__init__(rdclass, rdtype) self.address = address def to_text(self, origin=None, relativize=True, **kw): return "0x%s" % self.address.encode('hex_codec') def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): address = tok.get_string() t = tok.get_eol() if address[0:2] != '0x': raise dns.exception.SyntaxError('string does not start with 0x') address = address[2:].replace('.', '') if len(address) % 2 != 0: raise dns.exception.SyntaxError('hexstring has odd length') address = address.decode('hex_codec') return cls(rdclass, rdtype, address) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): file.write(self.address) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): address = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, address) from_wire = classmethod(from_wire) def _cmp(self, other): return cmp(self.address, other.address)
2,181
Python
.py
47
41.148936
79
0.694628
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,164
WKS.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/WKS.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import socket import struct import dns.ipv4 import dns.rdata _proto_tcp = socket.getprotobyname('tcp') _proto_udp = socket.getprotobyname('udp') class WKS(dns.rdata.Rdata): """WKS record @ivar address: the address @type address: string @ivar protocol: the protocol @type protocol: int @ivar bitmap: the bitmap @type bitmap: string @see: RFC 1035""" __slots__ = ['address', 'protocol', 'bitmap'] def __init__(self, rdclass, rdtype, address, protocol, bitmap): super(WKS, self).__init__(rdclass, rdtype) self.address = address self.protocol = protocol self.bitmap = bitmap def to_text(self, origin=None, relativize=True, **kw): bits = [] for i in xrange(0, len(self.bitmap)): byte = ord(self.bitmap[i]) for j in xrange(0, 8): if byte & (0x80 >> j): bits.append(str(i * 8 + j)) text = ' '.join(bits) return '%s %d %s' % (self.address, self.protocol, text) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): address = tok.get_string() protocol = tok.get_string() if protocol.isdigit(): protocol = int(protocol) else: protocol = socket.getprotobyname(protocol) bitmap = [] while 1: token = tok.get().unescape() if token.is_eol_or_eof(): break if token.value.isdigit(): serv = int(token.value) else: if protocol != _proto_udp and protocol != _proto_tcp: raise NotImplementedError("protocol must be TCP or UDP") if protocol == _proto_udp: protocol_text = "udp" else: protocol_text = "tcp" serv = socket.getservbyname(token.value, protocol_text) i = serv // 8 l = len(bitmap) if l < i + 1: for j in xrange(l, i + 1): bitmap.append('\x00') bitmap[i] = chr(ord(bitmap[i]) | (0x80 >> (serv % 8))) bitmap = dns.rdata._truncate_bitmap(bitmap) return cls(rdclass, rdtype, address, protocol, bitmap) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): file.write(dns.ipv4.inet_aton(self.address)) protocol = struct.pack('!B', self.protocol) file.write(protocol) file.write(self.bitmap) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): address = dns.ipv4.inet_ntoa(wire[current : current + 4]) protocol, = struct.unpack('!B', wire[current + 4 : current + 5]) current += 5 rdlen -= 5 bitmap = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, address, protocol, bitmap) from_wire = classmethod(from_wire) def _cmp(self, other): sa = dns.ipv4.inet_aton(self.address) oa = dns.ipv4.inet_aton(other.address) v = cmp(sa, oa) if v == 0: sp = struct.pack('!B', self.protocol) op = struct.pack('!B', other.protocol) v = cmp(sp, op) if v == 0: v = cmp(self.bitmap, other.bitmap) return v
4,124
Python
.py
99
32.919192
79
0.601097
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,165
IPSECKEY.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/IPSECKEY.py
# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import dns.exception import dns.inet import dns.name class IPSECKEY(dns.rdata.Rdata): """IPSECKEY record @ivar precedence: the precedence for this key data @type precedence: int @ivar gateway_type: the gateway type @type gateway_type: int @ivar algorithm: the algorithm to use @type algorithm: int @ivar gateway: the public key @type gateway: None, IPv4 address, IPV6 address, or domain name @ivar key: the public key @type key: string @see: RFC 4025""" __slots__ = ['precedence', 'gateway_type', 'algorithm', 'gateway', 'key'] def __init__(self, rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key): super(IPSECKEY, self).__init__(rdclass, rdtype) if gateway_type == 0: if gateway != '.' and not gateway is None: raise SyntaxError('invalid gateway for gateway type 0') gateway = None elif gateway_type == 1: # check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET, gateway) elif gateway_type == 2: # check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, gateway) elif gateway_type == 3: pass else: raise SyntaxError('invalid IPSECKEY gateway type: %d' % gateway_type) self.precedence = precedence self.gateway_type = gateway_type self.algorithm = algorithm self.gateway = gateway self.key = key def to_text(self, origin=None, relativize=True, **kw): if self.gateway_type == 0: gateway = '.' elif self.gateway_type == 1: gateway = self.gateway elif self.gateway_type == 2: gateway = self.gateway elif self.gateway_type == 3: gateway = str(self.gateway.choose_relativity(origin, relativize)) else: raise ValueError('invalid gateway type') return '%d %d %d %s %s' % (self.precedence, self.gateway_type, self.algorithm, gateway, dns.rdata._base64ify(self.key)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): precedence = tok.get_uint8() gateway_type = tok.get_uint8() algorithm = tok.get_uint8() if gateway_type == 3: gateway = tok.get_name().choose_relativity(origin, relativize) else: gateway = tok.get_string() chunks = [] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) key = b64.decode('base64_codec') return cls(rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): header = struct.pack("!BBB", self.precedence, self.gateway_type, self.algorithm) file.write(header) if self.gateway_type == 0: pass elif self.gateway_type == 1: file.write(dns.inet.inet_pton(dns.inet.AF_INET, self.gateway)) elif self.gateway_type == 2: file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.gateway)) elif self.gateway_type == 3: self.gateway.to_wire(file, None, origin) else: raise ValueError('invalid gateway type') file.write(self.key) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): if rdlen < 3: raise dns.exception.FormError header = struct.unpack('!BBB', wire[current : current + 3]) gateway_type = header[1] current += 3 rdlen -= 3 if gateway_type == 0: gateway = None elif gateway_type == 1: gateway = dns.inet.inet_ntop(dns.inet.AF_INET, wire[current : current + 4]) current += 4 rdlen -= 4 elif gateway_type == 2: gateway = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current + 16]) current += 16 rdlen -= 16 elif gateway_type == 3: (gateway, cused) = dns.name.from_wire(wire[: current + rdlen], current) current += cused rdlen -= cused else: raise dns.exception.FormError('invalid IPSECKEY gateway type') key = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], gateway_type, header[2], gateway, key) from_wire = classmethod(from_wire) def _cmp(self, other): f = cStringIO.StringIO() self.to_wire(f) wire1 = f.getvalue() f.seek(0) f.truncate() other.to_wire(f) wire2 = f.getvalue() f.close() return cmp(wire1, wire2)
5,993
Python
.py
145
31.282759
81
0.589647
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,166
A.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/A.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.ipv4 import dns.rdata import dns.tokenizer class A(dns.rdata.Rdata): """A record. @ivar address: an IPv4 address @type address: string (in the standard "dotted quad" format)""" __slots__ = ['address'] def __init__(self, rdclass, rdtype, address): super(A, self).__init__(rdclass, rdtype) # check that it's OK junk = dns.ipv4.inet_aton(address) self.address = address def to_text(self, origin=None, relativize=True, **kw): return self.address def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): address = tok.get_identifier() tok.get_eol() return cls(rdclass, rdtype, address) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): file.write(dns.ipv4.inet_aton(self.address)) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): address = dns.ipv4.inet_ntoa(wire[current : current + rdlen]) return cls(rdclass, rdtype, address) from_wire = classmethod(from_wire) def _cmp(self, other): sa = dns.ipv4.inet_aton(self.address) oa = dns.ipv4.inet_aton(other.address) return cmp(sa, oa)
2,054
Python
.py
45
40.822222
79
0.708563
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,167
__init__.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/__init__.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Class IN rdata type classes.""" __all__ = [ 'A', 'AAAA', 'APL', 'DHCID', 'KX', 'NAPTR', 'NSAP', 'NSAP_PTR', 'PX', 'SRV', 'WKS', ]
965
Python
.py
28
31.821429
72
0.729412
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,168
SRV.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/SRV.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import struct import dns.exception import dns.rdata import dns.name class SRV(dns.rdata.Rdata): """SRV record @ivar priority: the priority @type priority: int @ivar weight: the weight @type weight: int @ivar port: the port of the service @type port: int @ivar target: the target host @type target: dns.name.Name object @see: RFC 2782""" __slots__ = ['priority', 'weight', 'port', 'target'] def __init__(self, rdclass, rdtype, priority, weight, port, target): super(SRV, self).__init__(rdclass, rdtype) self.priority = priority self.weight = weight self.port = port self.target = target def to_text(self, origin=None, relativize=True, **kw): target = self.target.choose_relativity(origin, relativize) return '%d %d %d %s' % (self.priority, self.weight, self.port, target) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): priority = tok.get_uint16() weight = tok.get_uint16() port = tok.get_uint16() target = tok.get_name(None) target = target.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, priority, weight, port, target) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): three_ints = struct.pack("!HHH", self.priority, self.weight, self.port) file.write(three_ints) self.target.to_wire(file, compress, origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (priority, weight, port) = struct.unpack('!HHH', wire[current : current + 6]) current += 6 rdlen -= 6 (target, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: target = target.relativize(origin) return cls(rdclass, rdtype, priority, weight, port, target) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.target = self.target.choose_relativity(origin, relativize) def _cmp(self, other): sp = struct.pack("!HHH", self.priority, self.weight, self.port) op = struct.pack("!HHH", other.priority, other.weight, other.port) v = cmp(sp, op) if v == 0: v = cmp(self.target, other.target) return v
3,395
Python
.py
75
37.653333
79
0.649425
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,169
APL.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/APL.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import cStringIO import struct import dns.exception import dns.inet import dns.rdata import dns.tokenizer class APLItem(object): """An APL list item. @ivar family: the address family (IANA address family registry) @type family: int @ivar negation: is this item negated? @type negation: bool @ivar address: the address @type address: string @ivar prefix: the prefix length @type prefix: int """ __slots__ = ['family', 'negation', 'address', 'prefix'] def __init__(self, family, negation, address, prefix): self.family = family self.negation = negation self.address = address self.prefix = prefix def __str__(self): if self.negation: return "!%d:%s/%s" % (self.family, self.address, self.prefix) else: return "%d:%s/%s" % (self.family, self.address, self.prefix) def to_wire(self, file): if self.family == 1: address = dns.inet.inet_pton(dns.inet.AF_INET, self.address) elif self.family == 2: address = dns.inet.inet_pton(dns.inet.AF_INET6, self.address) else: address = self.address.decode('hex_codec') # # Truncate least significant zero bytes. # last = 0 for i in xrange(len(address) - 1, -1, -1): if address[i] != chr(0): last = i + 1 break address = address[0 : last] l = len(address) assert l < 128 if self.negation: l |= 0x80 header = struct.pack('!HBB', self.family, self.prefix, l) file.write(header) file.write(address) class APL(dns.rdata.Rdata): """APL record. @ivar items: a list of APL items @type items: list of APL_Item @see: RFC 3123""" __slots__ = ['items'] def __init__(self, rdclass, rdtype, items): super(APL, self).__init__(rdclass, rdtype) self.items = items def to_text(self, origin=None, relativize=True, **kw): return ' '.join(map(lambda x: str(x), self.items)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): items = [] while 1: token = tok.get().unescape() if token.is_eol_or_eof(): break item = token.value if item[0] == '!': negation = True item = item[1:] else: negation = False (family, rest) = item.split(':', 1) family = int(family) (address, prefix) = rest.split('/', 1) prefix = int(prefix) item = APLItem(family, negation, address, prefix) items.append(item) return cls(rdclass, rdtype, items) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): for item in self.items: item.to_wire(file) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): items = [] while 1: if rdlen < 4: raise dns.exception.FormError header = struct.unpack('!HBB', wire[current : current + 4]) afdlen = header[2] if afdlen > 127: negation = True afdlen -= 128 else: negation = False current += 4 rdlen -= 4 if rdlen < afdlen: raise dns.exception.FormError address = wire[current : current + afdlen].unwrap() l = len(address) if header[0] == 1: if l < 4: address += '\x00' * (4 - l) address = dns.inet.inet_ntop(dns.inet.AF_INET, address) elif header[0] == 2: if l < 16: address += '\x00' * (16 - l) address = dns.inet.inet_ntop(dns.inet.AF_INET6, address) else: # # This isn't really right according to the RFC, but it # seems better than throwing an exception # address = address.encode('hex_codec') current += afdlen rdlen -= afdlen item = APLItem(header[0], negation, address, header[1]) items.append(item) if rdlen == 0: break return cls(rdclass, rdtype, items) from_wire = classmethod(from_wire) def _cmp(self, other): f = cStringIO.StringIO() self.to_wire(f) wire1 = f.getvalue() f.seek(0) f.truncate() other.to_wire(f) wire2 = f.getvalue() f.close() return cmp(wire1, wire2)
5,533
Python
.py
149
27.61745
79
0.566474
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,170
NSAP_PTR.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/NSAP_PTR.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.nsbase class NSAP_PTR(dns.rdtypes.nsbase.UncompressedNS): """NSAP-PTR record""" pass
900
Python
.py
18
48.444444
72
0.793182
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,171
PX.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/PX.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import struct import dns.exception import dns.rdata import dns.name class PX(dns.rdata.Rdata): """PX record. @ivar preference: the preference value @type preference: int @ivar map822: the map822 name @type map822: dns.name.Name object @ivar mapx400: the mapx400 name @type mapx400: dns.name.Name object @see: RFC 2163""" __slots__ = ['preference', 'map822', 'mapx400'] def __init__(self, rdclass, rdtype, preference, map822, mapx400): super(PX, self).__init__(rdclass, rdtype) self.preference = preference self.map822 = map822 self.mapx400 = mapx400 def to_text(self, origin=None, relativize=True, **kw): map822 = self.map822.choose_relativity(origin, relativize) mapx400 = self.mapx400.choose_relativity(origin, relativize) return '%d %s %s' % (self.preference, map822, mapx400) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): preference = tok.get_uint16() map822 = tok.get_name() map822 = map822.choose_relativity(origin, relativize) mapx400 = tok.get_name(None) mapx400 = mapx400.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, preference, map822, mapx400) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): pref = struct.pack("!H", self.preference) file.write(pref) self.map822.to_wire(file, None, origin) self.mapx400.to_wire(file, None, origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (preference, ) = struct.unpack('!H', wire[current : current + 2]) current += 2 rdlen -= 2 (map822, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused > rdlen: raise dns.exception.FormError current += cused rdlen -= cused if not origin is None: map822 = map822.relativize(origin) (mapx400, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: mapx400 = mapx400.relativize(origin) return cls(rdclass, rdtype, preference, map822, mapx400) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.map822 = self.map822.choose_relativity(origin, relativize) self.mapx400 = self.mapx400.choose_relativity(origin, relativize) def _cmp(self, other): sp = struct.pack("!H", self.preference) op = struct.pack("!H", other.preference) v = cmp(sp, op) if v == 0: v = cmp(self.map822, other.map822) if v == 0: v = cmp(self.mapx400, other.mapx400) return v
3,763
Python
.py
83
37.554217
79
0.652482
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,172
DHCID.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/DHCID.py
# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception class DHCID(dns.rdata.Rdata): """DHCID record @ivar data: the data (the content of the RR is opaque as far as the DNS is concerned) @type data: string @see: RFC 4701""" __slots__ = ['data'] def __init__(self, rdclass, rdtype, data): super(DHCID, self).__init__(rdclass, rdtype) self.data = data def to_text(self, origin=None, relativize=True, **kw): return dns.rdata._base64ify(self.data) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): chunks = [] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) b64 = ''.join(chunks) data = b64.decode('base64_codec') return cls(rdclass, rdtype, data) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): file.write(self.data) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): data = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, data) from_wire = classmethod(from_wire) def _cmp(self, other): return cmp(self.data, other.data)
2,124
Python
.py
48
38.166667
79
0.676357
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,173
NAPTR.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/NAPTR.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import struct import dns.exception import dns.name import dns.rdata def _write_string(file, s): l = len(s) assert l < 256 byte = chr(l) file.write(byte) file.write(s) class NAPTR(dns.rdata.Rdata): """NAPTR record @ivar order: order @type order: int @ivar preference: preference @type preference: int @ivar flags: flags @type flags: string @ivar service: service @type service: string @ivar regexp: regular expression @type regexp: string @ivar replacement: replacement name @type replacement: dns.name.Name object @see: RFC 3403""" __slots__ = ['order', 'preference', 'flags', 'service', 'regexp', 'replacement'] def __init__(self, rdclass, rdtype, order, preference, flags, service, regexp, replacement): super(NAPTR, self).__init__(rdclass, rdtype) self.order = order self.preference = preference self.flags = flags self.service = service self.regexp = regexp self.replacement = replacement def to_text(self, origin=None, relativize=True, **kw): replacement = self.replacement.choose_relativity(origin, relativize) return '%d %d "%s" "%s" "%s" %s' % \ (self.order, self.preference, dns.rdata._escapify(self.flags), dns.rdata._escapify(self.service), dns.rdata._escapify(self.regexp), self.replacement) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): order = tok.get_uint16() preference = tok.get_uint16() flags = tok.get_string() service = tok.get_string() regexp = tok.get_string() replacement = tok.get_name() replacement = replacement.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, order, preference, flags, service, regexp, replacement) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): two_ints = struct.pack("!HH", self.order, self.preference) file.write(two_ints) _write_string(file, self.flags) _write_string(file, self.service) _write_string(file, self.regexp) self.replacement.to_wire(file, compress, origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (order, preference) = struct.unpack('!HH', wire[current : current + 4]) current += 4 rdlen -= 4 strings = [] for i in xrange(3): l = ord(wire[current]) current += 1 rdlen -= 1 if l > rdlen or rdlen < 0: raise dns.exception.FormError s = wire[current : current + l].unwrap() current += l rdlen -= l strings.append(s) (replacement, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: replacement = replacement.relativize(origin) return cls(rdclass, rdtype, order, preference, strings[0], strings[1], strings[2], replacement) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.replacement = self.replacement.choose_relativity(origin, relativize) def _cmp(self, other): sp = struct.pack("!HH", self.order, self.preference) op = struct.pack("!HH", other.order, other.preference) v = cmp(sp, op) if v == 0: v = cmp(self.flags, other.flags) if v == 0: v = cmp(self.service, other.service) if v == 0: v = cmp(self.regexp, other.regexp) if v == 0: v = cmp(self.replacement, other.replacement) return v
4,873
Python
.py
117
32.42735
79
0.608732
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,174
AAAA.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/AAAA.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.exception import dns.inet import dns.rdata import dns.tokenizer class AAAA(dns.rdata.Rdata): """AAAA record. @ivar address: an IPv6 address @type address: string (in the standard IPv6 format)""" __slots__ = ['address'] def __init__(self, rdclass, rdtype, address): super(AAAA, self).__init__(rdclass, rdtype) # check that it's OK junk = dns.inet.inet_pton(dns.inet.AF_INET6, address) self.address = address def to_text(self, origin=None, relativize=True, **kw): return self.address def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): address = tok.get_identifier() tok.get_eol() return cls(rdclass, rdtype, address) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): file.write(dns.inet.inet_pton(dns.inet.AF_INET6, self.address)) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): address = dns.inet.inet_ntop(dns.inet.AF_INET6, wire[current : current + rdlen]) return cls(rdclass, rdtype, address) from_wire = classmethod(from_wire) def _cmp(self, other): sa = dns.inet.inet_pton(dns.inet.AF_INET6, self.address) oa = dns.inet.inet_pton(dns.inet.AF_INET6, other.address) return cmp(sa, oa)
2,186
Python
.py
46
41.978261
79
0.699248
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,175
KX.py
wummel_linkchecker/third_party/dnspython/dns/rdtypes/IN/KX.py
# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.mxbase class KX(dns.rdtypes.mxbase.UncompressedMX): """KX record""" pass
888
Python
.py
18
47.777778
72
0.792627
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,176
test_updater.py
wummel_linkchecker/tests/test_updater.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2011-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test update check functionality. """ import unittest from tests import need_network import linkcheck.updater class TestUpdater (unittest.TestCase): """Test update check.""" @need_network def test_updater (self): res, value = linkcheck.updater.check_update() self.assertTrue(type(res) == bool) if res: self.assertTrue(value is None or isinstance(value, tuple), repr(value)) if isinstance(value, tuple): self.assertEqual(len(value), 2) version, url = value self.assertTrue(isinstance(version, basestring), repr(version)) self.assertTrue(url is None or isinstance(url, basestring), repr(url)) else: self.assertTrue(isinstance(value, unicode), repr(value))
1,585
Python
.py
37
37.837838
86
0.709845
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,177
test_clamav.py
wummel_linkchecker/tests/test_clamav.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2006-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test virus filter. """ import unittest from tests import need_clamav from linkcheck.plugins import viruscheck as clamav class TestClamav (unittest.TestCase): def setUp(self): self.clamav_conf = clamav.get_clamav_conf("/etc/clamav/clamd.conf") @need_clamav def testClean (self): data = "" infected, errors = clamav.scan(data, self.clamav_conf) self.assertFalse(infected) self.assertFalse(errors) @need_clamav def testInfected (self): # from the clamav test direcotry: the clamav test file as html data data = '<a href="data:application/octet-stream;base64,' \ 'TVpQAAIAAAAEAA8A//8AALgAAAAhAAAAQAAaAAAAAAAAAAAAAAAAAAAAAAAAAA' \ 'AAAAAAAAAAAAAAAAAAAAEAALtxEEAAM8BQUIvzU1NQsClAMARmrHn5ujEAeA2t' \ 'UP9mcA4fvjEA6eX/tAnNIbRMzSFiDAoBAnB2FwIeTgwEL9rMEAAAAAAAAAAAAA' \ 'AAAAAAwBAAAIAQAAAAAAAAAAAAAAAAAADaEAAA9BAAAAAAAAAAAAAAAAAAAAAA' \ 'AAAAAAAAS0VSTkVMMzIuRExMAABFeGl0UHJvY2VzcwBVU0VSMzIuRExMAENMQU' \ '1lc3NhZ2VCb3hBAOYQAAAAAAAAPz8/P1BFAABMAQEAYUNhQgAAAAAAAAAA4ACO' \ 'gQsBAhkABAAAAAYAAAAAAABAEAAAABAAAEAAAAAAAEAAABAAAAACAAABAAAAAA' \ 'AAAAMACgAAAAAAACAAAAAEAAAAAAAAAgAAAAAAEAAAIAAAAAAQAAAQAAAAAAAA' \ 'EAAAAAAAAAAAAAAAhBAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' \ 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' \ 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAW0NMQU1BVl' \ '0AEAAAABAAAAACAAABAAAAAAAAAAAAAAAAAAAAAAAAwA==">t</a>' infected, errors = clamav.scan(data, self.clamav_conf) msg = 'stream: ClamAV-Test-File(2d1206194bd704385e37000be6113f73:781) FOUND\n' self.assertTrue(msg in infected) self.assertFalse(errors)
2,573
Python
.py
51
44.647059
86
0.755264
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,178
test_po.py
wummel_linkchecker/tests/test_po.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005 Joe Wreschnig # Copyright (C) 2005-2010 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test gettext .po files. """ import unittest import os import glob from tests import need_msgfmt, need_posix pofiles = None def get_pofiles (): """Find all .po files in this source.""" global pofiles if pofiles is None: pofiles = [] pofiles.extend(glob.glob("po/*.po")) pofiles.extend(glob.glob("doc/*.po")) return pofiles class TestPo (unittest.TestCase): """Test .po file syntax.""" @need_posix @need_msgfmt def test_pos (self): """Test .po files syntax.""" for f in get_pofiles(): ret = os.system("msgfmt -c -o - %s > /dev/null" % f) self.assertEqual(ret, 0, msg="PO-file syntax error in %r" % f) class TestGTranslator (unittest.TestCase): """GTranslator displays a middot · for a space. Unfortunately, it gets copied with copy-and-paste, what a shame.""" def test_gtranslator (self): """Test all pofiles for GTranslator brokenness.""" for f in get_pofiles(): fd = file(f) try: self.check_file(fd, f) finally: fd.close() def check_file (self, fd, f): """Test for GTranslator broken syntax.""" for line in fd: if line.strip().startswith("#"): continue self.assertFalse("\xc2\xb7" in line, "Broken GTranslator copy/paste in %r:\n%r" % (f, line))
2,245
Python
.py
60
31.75
74
0.653634
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,179
test_ftpparse.py
wummel_linkchecker/tests/test_ftpparse.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2009-2010 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test ftpparse routine. """ import unittest from linkcheck.ftpparse import ftpparse patterns = ( # EPLF format # http://pobox.com/~djb/proto/eplf.html ("+i8388621.29609,m824255902,/,\tdev", dict(name='dev', tryretr=False, trycwd=True)), ("+i8388621.44468,m839956783,r,s10376,\tRFCEPLF", dict(name='RFCEPLF', tryretr=True, trycwd=False)), # UNIX-style listing, without inum and without blocks ("-rw-r--r-- 1 root other 531 Jan 29 03:26 README", dict(name='README', tryretr=True, trycwd=False)), ("dr-xr-xr-x 2 root other 512 Apr 8 1994 etc", dict(name='etc', tryretr=False, trycwd=True)), ("dr-xr-xr-x 2 root 512 Apr 8 1994 etc", dict(name='etc', tryretr=False, trycwd=True)), ("lrwxrwxrwx 1 root other 7 Jan 25 00:17 bin -> usr/bin", dict(name='usr/bin', tryretr=True, trycwd=True)), # Also produced by Microsoft's FTP servers for Windows: ("---------- 1 owner group 1803128 Jul 10 10:18 ls-lR.Z", dict(name='ls-lR.Z', tryretr=True, trycwd=False)), ("d--------- 1 owner group 0 May 9 19:45 Softlib", dict(name='Softlib', tryretr=False, trycwd=True)), # Also WFTPD for MSDOS: ("-rwxrwxrwx 1 noone nogroup 322 Aug 19 1996 message.ftp", dict(name='message.ftp', tryretr=True, trycwd=False)), # Also NetWare: ("d [R----F--] supervisor 512 Jan 16 18:53 login", dict(name='login', tryretr=False, trycwd=True)), ("- [R----F--] rhesus 214059 Oct 20 15:27 cx.exe", dict(name='cx.exe', tryretr=True, trycwd=False)), # Also NetPresenz for the Mac: ("-------r-- 326 1391972 1392298 Nov 22 1995 MegaPhone.sit", dict(name='MegaPhone.sit', tryretr=True, trycwd=False)), ("drwxrwxr-x folder 2 May 10 1996 network", dict(name='network', tryretr=False, trycwd=True)), # MultiNet (some spaces removed from examples) ("00README.TXT;1 2 30-DEC-1996 17:44 [SYSTEM] (RWED,RWED,RE,RE)", dict(name='00README.TXT', tryretr=True, trycwd=False)), ("CORE.DIR;1 1 8-SEP-1996 16:09 [SYSTEM] (RWE,RWE,RE,RE)", dict(name='CORE', tryretr=False, trycwd=True)), # and non-MutliNet VMS: ("CII-MANUAL.TEX;1 213/216 29-JAN-1996 03:33:12 [ANONYMOU,ANONYMOUS] (RWED,RWED,,)", dict(name='CII-MANUAL.TEX', tryretr=True, trycwd=False)), # MSDOS format ("04-27-00 09:09PM <DIR> licensed", dict(name='licensed', tryretr=False, trycwd=True)), ("07-18-00 10:16AM <DIR> pub", dict(name='pub', tryretr=False, trycwd=True)), ("04-14-00 03:47PM 589 readme.htm", dict(name='readme.htm', tryretr=True, trycwd=False)), # Some useless lines, safely ignored: ("Total of 11 Files, 10966 Blocks.", None), # (VMS) ("total 14786", None), # (UNIX) ("DISK$ANONFTP:[ANONYMOUS]", None), # (VMS) ("Directory DISK$PCSA:[ANONYM]", None), # (VMS) ("", None), ) class TestFtpparse (unittest.TestCase): """ Test FTP LIST line parsing. """ def test_ftpparse (self): for line, expected in patterns: res = ftpparse(line) self.assertEqual(expected, res, "got %r\nexpected %r\n%r" % (res, expected, line))
4,156
Python
.py
86
43.790698
93
0.626322
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,180
test_filenames.py
wummel_linkchecker/tests/test_filenames.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test filename routines. """ import unittest import os from linkcheck.checker.fileurl import get_nt_filename from . import need_windows class TestFilenames (unittest.TestCase): """ Test filename routines. """ @need_windows def test_nt_filename (self): path = os.getcwd() realpath = get_nt_filename(path) self.assertEqual(path, realpath) path = 'c:\\' realpath = get_nt_filename(path) self.assertEqual(path, realpath) # XXX Only works on my computer. # Is there a Windows UNC share that is always available for tests? #path = '\\Vboxsrv\share\msg.txt' #realpath = get_nt_filename(path) #self.assertEqual(path, realpath)
1,514
Python
.py
40
34.05
74
0.719728
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,181
test_containers.py
wummel_linkchecker/tests/test_containers.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2011 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test container routines. """ import unittest import random import linkcheck.containers class TestAttrDict (unittest.TestCase): def setUp (self): self.d = linkcheck.containers.AttrDict() def test_access (self): self.d["test"] = 1 self.assertEqual(self.d.test, self.d["test"]) self.assertEqual(self.d.test, 1) def test_method (self): self.d["get"] = 1 self.assertTrue(isinstance(self.d.get, type({}.get))) class TestListDict (unittest.TestCase): """Test list dictionary routines.""" def setUp (self): """Set up self.d as empty listdict.""" self.d = linkcheck.containers.ListDict() def test_insertion_order (self): self.assertTrue(not self.d) self.d[2] = 1 self.d[1] = 2 self.assertTrue(2 in self.d) self.assertTrue(1 in self.d) def test_deletion_order (self): self.assertTrue(not self.d) self.d[2] = 1 self.d[1] = 2 del self.d[1] self.assertTrue(2 in self.d) self.assertTrue(1 not in self.d) def test_update_order (self): self.assertTrue(not self.d) self.d[2] = 1 self.d[1] = 2 self.d[1] = 1 self.assertEqual(self.d[1], 1) def test_sorting (self): self.assertTrue(not self.d) toinsert = random.sample(xrange(10000000), 60) for x in toinsert: self.d[x] = x for i, k in enumerate(self.d.keys()): self.assertEqual(self.d[k], toinsert[i]) for i, k in enumerate(self.d.iterkeys()): self.assertEqual(self.d[k], toinsert[i]) for x in self.d.values(): self.assertTrue(x in toinsert) for x in self.d.itervalues(): self.assertTrue(x in toinsert) for x, y in self.d.items(): self.assertTrue(x in toinsert) self.assertTrue(y in toinsert) for x, y in self.d.iteritems(): self.assertTrue(x in toinsert) self.assertTrue(y in toinsert) def test_clear (self): self.assertTrue(not self.d) self.d[2] = 1 self.d[1] = 3 self.d.clear() self.assertTrue(not self.d) def test_get_true (self): self.assertTrue(not self.d) self.d["a"] = 0 self.d["b"] = 1 self.assertEqual(self.d.get_true("a", 2), 2) self.assertEqual(self.d.get_true("b", 2), 1) class TestCaselessDict (unittest.TestCase): """Test caseless dictionary routines.""" def setUp (self): """Set up self.d as empty caseless dict.""" self.d = linkcheck.containers.CaselessDict() def test_insert (self): self.assertTrue(not self.d) self.d["a"] = 1 self.assertTrue("a" in self.d) self.assertTrue("A" in self.d) self.d["aBcD"] = 2 self.assertTrue("abcd" in self.d) self.assertTrue("Abcd" in self.d) self.assertTrue("ABCD" in self.d) def test_delete (self): self.assertTrue(not self.d) self.d["a"] = 1 del self.d["A"] self.assertTrue("a" not in self.d) self.assertTrue("A" not in self.d) def test_update (self): self.assertTrue(not self.d) self.d["a"] = 1 self.d["A"] = 2 self.assertEqual(self.d["a"], 2) def test_clear (self): self.assertTrue(not self.d) self.d["a"] = 5 self.d["b"] = 6 self.d.clear() self.assertTrue(not self.d) def test_containment (self): self.assertTrue(not self.d) self.assertTrue("A" not in self.d) self.assertTrue("a" not in self.d) self.d["a"] = 5 self.assertTrue("A" in self.d) self.assertTrue("a" in self.d) def test_setdefault (self): self.assertTrue(not self.d) self.d["a"] = 5 self.assertEqual(self.d.setdefault("A", 6), 5) self.assertEqual(self.d.setdefault("b", 7), 7) def test_get (self): self.assertTrue(not self.d) self.d["a"] = 42 self.assertEqual(self.d.get("A"), 42) self.assertTrue(self.d.get("B") is None) def test_update2 (self): self.assertTrue(not self.d) self.d["a"] = 42 self.d.update({"A": 43}) self.assertEqual(self.d["a"], 43) def test_fromkeys (self): self.assertTrue(not self.d) keys = ["a", "A", "b", "C"] d1 = self.d.fromkeys(keys, 42) for key in keys: self.assertEqual(d1[key], 42) def test_pop (self): self.assertTrue(not self.d) self.d["a"] = 42 self.assertEqual(self.d.pop("A"), 42) self.assertTrue(not self.d) self.assertRaises(KeyError, self.d.pop, "A") def test_popitem (self): self.assertTrue(not self.d) self.d["a"] = 42 self.assertEqual(self.d.popitem(), ("a", 42)) self.assertTrue(not self.d) self.assertRaises(KeyError, self.d.popitem) class TestCaselessSortedDict (unittest.TestCase): """Test caseless sorted dictionary routines.""" def setUp (self): """Set up self.d as empty caseless sorted dict.""" self.d = linkcheck.containers.CaselessSortedDict() def test_sorted (self): self.assertTrue(not self.d) self.d["b"] = 6 self.d["a"] = 7 self.d["C"] = 8 prev = None for key in self.d.keys(): if prev is not None: self.assertTrue(key > prev) prev = key prev = None for key, value in self.d.items(): self.assertEqual(value, self.d[key]) if prev is not None: self.assertTrue(key > prev) prev = key class TestLFUCache (unittest.TestCase): """Test LFU cache implementation.""" def setUp (self): """Set up self.d as empty LFU cache with default size of 1000.""" self.size = 1000 self.d = linkcheck.containers.LFUCache(self.size) def test_num_uses (self): self.assertTrue(not self.d) self.d["a"] = 1 self.assertTrue("a" in self.d) self.assertEqual(self.d.uses("a"), 0) dummy = self.d["a"] self.assertEqual(self.d.uses("a"), 1) def test_values (self): self.assertTrue(not self.d) self.d["a"] = 1 self.d["b"] = 2 self.assertEqual(set([1, 2]), set(self.d.values())) self.assertEqual(set([1, 2]), set(self.d.itervalues())) def test_popitem (self): self.assertTrue(not self.d) self.d["a"] = 42 self.assertEqual(self.d.popitem(), ("a", 42)) self.assertTrue(not self.d) self.assertRaises(KeyError, self.d.popitem) def test_shrink (self): self.assertTrue(not self.d) for i in range(self.size): self.d[i] = i self.d[1001] = 1001 self.assertTrue(950 <= len(self.d) <= self.size) class TestEnum (unittest.TestCase): def test_enum (self): e = linkcheck.containers.enum("a", "b", "c") self.assertEqual(e.a, 0) self.assertEqual(e.b, 1) self.assertEqual(e.c, 2) self.assertEqual(e, (0, 1, 2))
7,944
Python
.py
217
28.700461
73
0.594742
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,182
test_network.py
wummel_linkchecker/tests/test_network.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2008-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test network functions. """ import unittest from tests import need_posix, need_network, need_linux import linkcheck.network from linkcheck.network import iputil class TestNetwork (unittest.TestCase): """Test network functions.""" @need_posix def test_ifreq_size (self): self.assertTrue(linkcheck.network.ifreq_size() > 0) @need_posix def test_interfaces (self): ifc = linkcheck.network.IfConfig() ifc.getInterfaceList() @need_network @need_linux def test_iputils (self): # note: need a hostname whose reverse lookup of the IP is the same host host = "dinsdale.python.org" ips = iputil.resolve_host(host) self.assertTrue(len(ips) > 0) for ip in ips: if iputil.is_valid_ipv4(ip): obfuscated = iputil.obfuscate_ip(ip) self.assertTrue(iputil.is_obfuscated_ip(obfuscated)) hosts = iputil.lookup_ips([obfuscated]) self.assertTrue(host in hosts)
1,801
Python
.py
45
35.066667
79
0.708
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,183
test_cgi.py
wummel_linkchecker/tests/test_cgi.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2012 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test cgi form routines. """ import unittest import wsgiref import urllib from StringIO import StringIO from wsgiref.util import setup_testing_defaults from linkcheck.lc_cgi import checkform, checklink, LCFormError, application from linkcheck.strformat import limit class TestWsgi (unittest.TestCase): """Test wsgi application.""" def test_form_valid_url (self): # Check url validity. env = dict() form = dict(url="http://www.example.com/", level="1") checkform(form, env) def test_form_empty_url (self): # Check with empty url. env = dict() form = dict(url="", level="0") self.assertRaises(LCFormError, checkform, form, env) def test_form_default_url (self): # Check with default url. env = dict() form = dict(url="http://", level="0") self.assertRaises(LCFormError, checkform, form, env) def test_form_invalid_url (self): # Check url (in)validity. env = dict() form = dict(url="http://www.foo bar/", level="0") self.assertRaises(LCFormError, checkform, form, env) def test_checklink (self): form = dict(url="http://www.example.com/", level="0") checklink(form) def test_application (self): form = dict(url="http://www.example.com/", level="0") formdata = urllib.urlencode(form) environ = {'wsgi.input': StringIO(formdata)} setup_testing_defaults(environ) test_response = "" test_headers = [None] test_status = [None] def start_response(status, headers): test_status[0] = status test_headers[0] = headers for str_data in application(environ, start_response): if not isinstance(str_data, str): err = "answer is not a byte string: %r" % limit(str_data, 30) self.assertTrue(False, err) test_response += str_data self.assertEqual(test_status[0], '200 OK') self.assertTrue("Generated by LinkChecker" in test_response)
2,844
Python
.py
69
35.188406
77
0.66763
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,184
test_linkname.py
wummel_linkchecker/tests/test_linkname.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2009 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test linkname routines. """ import unittest from linkcheck.htmlutil import linkname class TestLinkname (unittest.TestCase): """ Test href and image name parsing. """ def image_name_test (self, txt, expected): """ Helper function calling linkname.image_name(). """ self.assertEqual(linkname.image_name(txt), expected) def href_name_test (self, txt, expected): """ Helper function calling linkname.href_name(). """ self.assertEqual(linkname.href_name(txt), expected) def test_image_name (self): """ Test image name parsing. """ self.image_name_test("<img src='' alt=''></a>", '') self.image_name_test("<img src alt=abc></a>", 'abc') def test_href_name (self): """ Test href name parsing. """ self.href_name_test("<b>guru guru</a>", 'guru guru') self.href_name_test("a\njo</a>", "a\njo") self.href_name_test("test<</a>", "test<") self.href_name_test("test</</a>", "test</") self.href_name_test("test</a</a>", "test</a") self.href_name_test("test", "") self.href_name_test("\n", "") self.href_name_test("", "") self.href_name_test('"</a>"foo', '"') self.href_name_test("<img src='' alt=''></a>", '') self.href_name_test("<img src alt=abc></a>", 'abc')
2,183
Python
.py
56
33.5
73
0.635377
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,185
test_urlbuild.py
wummel_linkchecker/tests/test_urlbuild.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test url build method from url data objects. """ import unittest import linkcheck.configuration import linkcheck.director import linkcheck.checker.urlbase from linkcheck.checker import get_url_from def get_test_aggregate (): """ Initialize a test configuration object. """ config = linkcheck.configuration.Configuration() config['logger'] = config.logger_new('none') return linkcheck.director.get_aggregate(config) class TestUrlBuild (unittest.TestCase): """ Test url building. """ def test_http_build (self): parent_url = "http://localhost:8001/tests/checker/data/http.html" base_url = "http://foo" recursion_level = 0 aggregate = get_test_aggregate() o = get_url_from(base_url, recursion_level, aggregate, parent_url=parent_url) o.build_url() self.assertEqual(o.url, u'http://foo') def test_urljoin (self): parent_url = "http://localhost:8001/test" base_url = ";param=value" res = linkcheck.checker.urlbase.urljoin(parent_url, base_url) self.assertEqual(res, 'http://localhost:8001/;param=value') def test_urljoin_file (self): parent_url = "file:///a/b.html" base_url = "?c=d" recursion_level = 0 aggregate = get_test_aggregate() o = get_url_from(base_url, recursion_level, aggregate, parent_url=parent_url) o.build_url() self.assertEqual(o.url, parent_url) def test_http_build2 (self): parent_url = u'http://example.org/test?a=b&c=d' base_url = u'#usemap' recursion_level = 0 aggregate = get_test_aggregate() o = get_url_from(base_url, recursion_level, aggregate, parent_url=parent_url) o.build_url() self.assertEqual(o.url, parent_url+base_url)
2,609
Python
.py
65
34.892308
85
0.688757
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,186
test_parser.py
wummel_linkchecker/tests/test_parser.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2012 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test html parsing. """ import linkcheck.HtmlParser.htmlsax import linkcheck.HtmlParser.htmllib from cStringIO import StringIO import unittest # list of tuples # (<test pattern>, <expected parse output>) parsetests = [ # start tags ("""<a b="c" >""", """<a b="c">"""), ("""<a b='c' >""", """<a b="c">"""), ("""<a b=c" >""", """<a b="c">"""), ("""<a b=c' >""", """<a b="c'">"""), ("""<a b="c >""", """<a b="c >"""), ("""<a b="" >""", """<a b="">"""), ("""<a b='' >""", """<a b="">"""), ("""<a b=>""", """<a b="">"""), ("""<a b= >""", """<a b="">"""), ("""<a =c>""", """<a c>"""), ("""<a =c >""", """<a c>"""), ("""<a =>""", """<a>"""), ("""<a = >""", """<a>"""), ("""<a b= "c" >""", """<a b="c">"""), ("""<a b ="c" >""", """<a b="c">"""), ("""<a b = "c" >""", """<a b="c">"""), ("""<a >""", """<a>"""), ("""< a>""", """<a>"""), ("""< a >""", """<a>"""), ("""<>""", """<>"""), ("""< >""", """< >"""), ("""<aä>""", """<a>"""), ("""<a aä="b">""", """<a a="b">"""), ("""<a a="bä">""", """<a a="b&#228;">"""), # multiple attribute names should be ignored... ("""<a b="c" b="c" >""", """<a b="c">"""), # ... but which one wins - in our implementation the last one ("""<a b="c" b="d" >""", """<a b="d">"""), # reduce test ("""<a b="c"><""", """<a b="c"><"""), ("""d>""", """d>"""), # numbers in tag ("""<h1>bla</h1>""", """<h1>bla</h1>"""), # more start tags ("""<a b=c"><a b="c">""", """<a b="c"><a b="c">"""), ("""<a b=/c/></a><br>""", """<a b="/c/"></a><br>"""), ("""<br/>""", """<br>"""), ("""<a b="50%"><br>""", """<a b="50%"><br>"""), # comments ("""<!---->< 1>""", """<!----><1>"""), ("""<!-- a - b -->< 2>""", """<!-- a - b --><2>"""), ("""<!----->< 3>""", """<!-----><3>"""), ("""<!------>< 4>""", """<!------><4>"""), ("""<!------->< 5>""", """<!-------><5>"""), ("""<!-- -->< 7>""", """<!-- --><7>"""), ("""<!---- />-->""", """<!---- />-->"""), ("""<!-- a-2 -->< 9>""", """<!-- a-2 --><9>"""), ("""<!-- --- -->< 10>""", """<!-- --- --><10>"""), ("""<!>""", """<!---->"""), # empty comment # invalid comments ("""<!-- -- >< 8>""", """<!-- --><8>"""), ("""<!---- >< 6>""", """<!----><6>"""), ("""<!- blubb ->""", """<!-- blubb -->"""), ("""<! -- blubb -->""", """<!-- blubb -->"""), ("""<!-- blubb -- >""", """<!-- blubb -->"""), ("""<! blubb !>< a>""", """<!--blubb !--><a>"""), ("""<! blubb >< a>""", """<!--blubb --><a>"""), # end tags ("""</a>""", """</a>"""), ("""</ a>""", """</a>"""), ("""</ a >""", """</a>"""), ("""</a >""", """</a>"""), ("""< / a>""", """</a>"""), ("""< /a>""", """</a>"""), ("""</aä>""", """</a>"""), # start and end tag (HTML doctype assumed) ("""<a/>""", """<a/>"""), ("""<meta/>""", """<meta>"""), ("""<MetA/>""", """<meta>"""), # declaration tags ("""<!DOCtype adrbook SYSTEM "adrbook.dtd">""", """<!DOCTYPE adrbook SYSTEM "adrbook.dtd">"""), # misc ("""<?xmL version="1.0" encoding="latin1"?>""", """<?xmL version="1.0" encoding="latin1"?>"""), # javascript ("""<script >\n</script>""", """<script>\n</script>"""), ("""<sCrIpt lang="a">bla </a> fasel</scripT>""", """<script lang="a">bla </a> fasel</script>"""), ("""<script ><!--bla//-->// </script >""", """<script><!--bla//-->// </script>"""), # line continuation (Dr. Fun webpage) ("""<img bo\\\nrder=0 >""", """<img border="0">"""), ("""<img align="mid\\\ndle">""", """<img align="middle">"""), ("""<img align='mid\\\ndle'>""", """<img align="middle">"""), # href with $ ("""<a href="123$456">""", """<a href="123$456">"""), # quoting ("""<a href=/ >""", """<a href="/">"""), ("""<a href= />""", """<a href="/">"""), ("""<a href= >""", """<a href="">"""), ("""<a href="'" >""", """<a href="'">"""), ("""<a href='"' >""", """<a href="&quot;">"""), ("""<a href="bla" %]" >""", """<a href="bla">"""), ("""<a href=bla" >""", """<a href="bla">"""), ("""<a onmouseover=blubb('nav1','',"""\ """'/images/nav.gif',1);move(this); b="c">""", """<a onmouseover="blubb('nav1','',"""\ """'/images/nav.gif',1);move(this);" b="c">"""), ("""<a onClick=location.href('/index.htm') b="c">""", """<a onclick="location.href('/index.htm')" b="c">"""), # entity resolving ("""<a href="&#6D;ailto:" >""", """<a href="ailto:">"""), ("""<a href="&amp;ailto:" >""", """<a href="&amp;ailto:">"""), ("""<a href="&amp;amp;ailto:" >""", """<a href="&amp;amp;ailto:">"""), ("""<a href="&hulla;ailto:" >""", """<a href="ailto:">"""), ("""<a href="&#109;ailto:" >""", """<a href="mailto:">"""), ("""<a href="&#x6D;ailto:" >""", """<a href="mailto:">"""), # note that \u8156 is not valid encoding and therefore gets removed ("""<a href="&#8156;ailto:" >""", """<a href="ailto:">"""), # non-ascii characters ("""<Üzgür> fahr </langsamer> ¹²³¼½¬{""", """<Üzgür> fahr </langsamer> ¹²³¼½¬{"""), # mailto link ("""<a href=mailto:calvin@LocalHost?subject=Hallo&to=michi>1</a>""", """<a href="mailto:calvin@LocalHost?subject=Hallo&amp;to=michi">1</a>"""), # doctype XHTML ("""<!DOCTYPe html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><MeTa a="b"/>""", """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><meta a="b"/>"""), # meta tag with charset encoding ("""<meta http-equiv="content-type" content>""", """<meta http-equiv="content-type" content>"""), ("""<meta http-equiv="content-type" content=>""", """<meta http-equiv="content-type" content="">"""), ("""<meta http-equiv="content-type" content="hulla">""", """<meta http-equiv="content-type" content="hulla">"""), ("""<meta http-equiv="content-type" content="text/html; charset=iso8859-1">""", """<meta http-equiv="content-type" content="text/html; charset=iso8859-1">"""), ("""<meta http-equiv="content-type" content="text/html; charset=hulla">""", """<meta http-equiv="content-type" content="text/html; charset=hulla">"""), # CDATA ("""<![CDATA[<a>hallo</a>]]>""", """<![CDATA[<a>hallo</a>]]>"""), # missing > in end tag ("""</td <td a="b" >""", """</td><td a="b">"""), ("""</td<td a="b" >""", """</td><td a="b">"""), # missing beginning quote ("""<td a=b">""", """<td a="b">"""), # stray < before start tag ("""<0.<td a="b" >""", """<0.<td a="b">"""), # stray < before end tag ("""<0.</td >""", """<0.</td>"""), # missing end quote (XXX TODO) #("""<td a="b>\n""", """<td a="b">\n"""), #("""<td a="b></td>\na""", """<td a="b"></td>\na"""), #("""<a b="c><a b="c>\n""", """<a b="c"><a b="c">\n"""), #("""<td a="b c="d"></td>\n""", """<td a="b" c="d"></td>\n"""), # HTML5 tags ("""<audio src=bla>""", """<audio src="bla">"""), ("""<button formaction=bla>""", """<button formaction="bla">"""), ("""<html manifest=bla>""", """<html manifest="bla">"""), ("""<source src=bla>""", """<source src="bla">"""), ("""<track src=bla>""", """<track src="bla">"""), ("""<video src=bla>""", """<video src="bla">"""), ] flushtests = [ ("<", "<"), ("<a", "<a"), ("<!a", "<!a"), ("<?a", "<?a"), ] class TestParser (unittest.TestCase): """ Test html parser. """ def setUp (self): """ Initialize two internal html parsers to be used for testing. """ self.htmlparser = linkcheck.HtmlParser.htmlsax.parser() self.htmlparser2 = linkcheck.HtmlParser.htmlsax.parser() def test_parse (self): # Parse all test patterns in one go. for _in, _out in parsetests: out = StringIO() handler = linkcheck.HtmlParser.htmllib.HtmlPrettyPrinter(out) self.htmlparser.handler = handler self.htmlparser.feed(_in) self.check_results(self.htmlparser, _in, _out, out) def check_results (self, htmlparser, _in, _out, out): """ Check parse results. """ htmlparser.flush() res = out.getvalue() msg = "Test error; in: %r, out: %r, expect: %r" % \ (_in, res, _out) self.assertEqual(res, _out, msg=msg) htmlparser.reset() def test_feed (self): # Parse all test patterns sequentially. for _in, _out in parsetests: out = StringIO() handler = linkcheck.HtmlParser.htmllib.HtmlPrettyPrinter(out) self.htmlparser.handler = handler for c in _in: self.htmlparser.feed(c) self.check_results(self.htmlparser, _in, _out, out) def test_interwoven (self): # Parse all test patterns on two parsers interwoven. for _in, _out in parsetests: out = StringIO() out2 = StringIO() handler = linkcheck.HtmlParser.htmllib.HtmlPrettyPrinter(out) self.htmlparser.handler = handler handler2 = linkcheck.HtmlParser.htmllib.HtmlPrettyPrinter(out2) self.htmlparser2.handler = handler2 for c in _in: self.htmlparser.feed(c) self.htmlparser2.feed(c) self.check_results(self.htmlparser, _in, _out, out) self.check_results(self.htmlparser2, _in, _out, out2) def test_handler (self): for _in, _out in parsetests: out = StringIO() out2 = StringIO() handler = linkcheck.HtmlParser.htmllib.HtmlPrinter(out) self.htmlparser.handler = handler handler2 = linkcheck.HtmlParser.htmllib.HtmlPrinter(out2) self.htmlparser2.handler = handler2 for c in _in: self.htmlparser.feed(c) self.htmlparser2.feed(c) self.assertEqual(out.getvalue(), out2.getvalue()) def test_flush (self): # Test parser flushing. for _in, _out in flushtests: out = StringIO() handler = linkcheck.HtmlParser.htmllib.HtmlPrettyPrinter(out) self.htmlparser.handler = handler self.htmlparser.feed(_in) self.check_results(self.htmlparser, _in, _out, out) def test_entities (self): # Test entity resolving. resolve = linkcheck.HtmlParser.resolve_entities for c in "abcdefghijklmnopqrstuvwxyz": self.assertEqual(resolve("&#%d;" % ord(c)), c) self.assertEqual(resolve("&#1114112;"), u"") def test_peek (self): # Test peek() parser function data = '<a href="test.html">name</a>' class NamePeeker (object): def start_element (self_handler, tag, attrs): # use self reference of TestParser instance self.assertRaises(TypeError, self.htmlparser.peek, -1) self.assertEqual(self.htmlparser.peek(0), "") self.assertEqual(self.htmlparser.peek(4), "name") self.htmlparser.handler = NamePeeker() self.htmlparser.feed(data) def test_encoding_detection (self): html = '<meta http-equiv="content-type" content="text/html; charset=UTF-8">' self.encoding_test(html, "utf-8") html = '<meta charset="UTF-8">' self.encoding_test(html, "utf-8") html = '<meta charset="hulla">' self.encoding_test(html, "iso8859-1") html = '<meta http-equiv="content-type" content="text/html; charset=blabla">' self.encoding_test(html, "iso8859-1") def encoding_test (self, html, expected): parser = linkcheck.HtmlParser.htmlsax.parser() self.assertEqual(parser.encoding, "iso8859-1") parser.feed(html) self.assertEqual(parser.encoding, expected)
12,777
Python
.py
289
37.567474
147
0.478906
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,187
test_url.py
wummel_linkchecker/tests/test_url.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test url routines. """ from . import need_network, need_posix, need_windows import unittest import os import re import linkcheck.url # 'ftp://user:pass@ftp.foo.net/foo/bar': # 'ftp://user:pass@ftp.foo.net/foo/bar', # 'http://USER:pass@www.Example.COM/foo/bar': # 'http://USER:pass@www.example.com/foo/bar', # '-': '-', # All portions of the URI must be utf-8 encoded NFC form Unicode strings #valid: http://example.com/?q=%C3%87 (C-cedilla U+00C7) #valid: http://example.com/?q=%E2%85%A0 (Roman numeral one U+2160) #invalid: http://example.com/?q=%C7 (C-cedilla ISO-8859-1) #invalid: http://example.com/?q=C%CC%A7 # (Latin capital letter C + Combining cedilla U+0327) def url_norm (url, encoding=None): return linkcheck.url.url_norm(url, encoding=encoding)[0] class TestUrl (unittest.TestCase): """Test url norming and quoting.""" def urlnormtest (self, url, nurl, encoding=None): self.assertFalse(linkcheck.url.url_needs_quoting(nurl), "Result URL %r must not need quoting" % nurl) nurl1 = url_norm(url, encoding=encoding) self.assertFalse(linkcheck.url.url_needs_quoting(nurl1), "Normed URL %r needs quoting" % nurl) self.assertEqual(nurl1, nurl) def test_pathattack (self): # Windows winamp path attack prevention. url = "http://server/..%5c..%5c..%5c..%5c..%5c..%5c..%5c.."\ "%5ccskin.zip" nurl = "http://server/cskin.zip" self.assertEqual(linkcheck.url.url_quote(url_norm(url)), nurl) def test_safe_patterns (self): is_safe_host = linkcheck.url.is_safe_host safe_host_pattern = linkcheck.url.safe_host_pattern self.assertTrue(is_safe_host("example.org")) self.assertTrue(is_safe_host("example.org:80")) self.assertTrue(not is_safe_host("example.org:21")) pat = safe_host_pattern("example.org") ro = re.compile(pat) self.assertTrue(ro.match("http://example.org:80/")) def test_url_quote (self): url_quote = linkcheck.url.url_quote url = "http://a:80/bcd" self.assertEqual(url_quote(url), url) url = "http://a:80/bcd?" url2 = "http://a:80/bcd" self.assertEqual(url_quote(url), url2) url = "http://a:80/bcd?a=b" url2 = "http://a:80/bcd?a=b" self.assertEqual(url_quote(url), url2) url = "a/b" self.assertEqual(url_quote(url), url) url = "bcd?" url2 = "bcd" self.assertEqual(url_quote(url), url2) url = "bcd?a=b" url2 = "bcd?a=b" self.assertEqual(url_quote(url), url2) def test_norm_quote (self): # Test url norm quoting. url = "http://groups.google.com/groups?hl=en&lr&ie=UTF-8&"\ "threadm=3845B54D.E546F9BD%40monmouth.com&rnum=2&"\ "prev=/groups%3Fq%3Dlogitech%2Bwingman%2Bextreme%2Bdigital"\ "%2B3d%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3D3845B54D.E5"\ "46F9BD%2540monmouth.com%26rnum%3D2" self.urlnormtest(url, url) url = "http://redirect.alexa.com/redirect?"\ "http://www.offeroptimizer.com" self.urlnormtest(url, url) url = "http://www.lesgensducinema.com/photo/Philippe%20Nahon.jpg" self.urlnormtest(url, url) # Only perform percent-encoding where it is essential. url = "http://example.com/%7Ejane" nurl = "http://example.com/~jane" self.urlnormtest(url, nurl) url = "http://example.com/%7ejane" self.urlnormtest(url, nurl) # Always use uppercase A-through-F characters when percent-encoding. url = "http://example.com/?q=1%2a2" nurl = "http://example.com/?q=1%2A2" self.urlnormtest(url, nurl) # the no-quote chars url = "http://example.com/a*+-();b" self.urlnormtest(url, url) url = "http://linkchecker.git.sourceforge.net/git/gitweb.cgi?p=linkchecker/linkchecker;a=blob;f=doc/changelog.txt;hb=HEAD" self.urlnormtest(url, url) url = "http://www.company.com/path/doc.html?url=/path2/doc2.html?foo=bar" self.urlnormtest(url, url) url = "http://example.com/#a b" nurl = "http://example.com/#a%20b" self.urlnormtest(url, nurl) url = "http://example.com/?u=http://example2.com?b=c " nurl = "http://example.com/?u=http://example2.com?b=c%20" self.urlnormtest(url, nurl) url = "http://example.com/?u=http://example2.com?b=" nurl = "http://example.com/?u=http://example2.com?b=" self.urlnormtest(url, nurl) url = "http://localhost:8001/?quoted=�" nurl = "http://localhost:8001/?quoted=%FC" self.urlnormtest(url, nurl, encoding="iso-8859-1") url = "http://host/?a=b/c+d=" nurl = "http://host/?a=b/c%20d%3D" self.urlnormtest(url, nurl) def test_norm_case_sensitivity (self): # Test url norm case sensitivity. # Always provide the URI scheme in lowercase characters. url = "HTTP://example.com/" nurl = "http://example.com/" self.urlnormtest(url, nurl) # Always provide the host, if any, in lowercase characters. url = "http://EXAMPLE.COM/" nurl = "http://example.com/" self.urlnormtest(url, nurl) url = "http://EXAMPLE.COM:55/" nurl = "http://example.com:55/" self.urlnormtest(url, nurl) def test_norm_defaultport (self): # Test url norm default port recognition. # For schemes that define a port, use an empty port if the default # is desired url = "http://example.com:80/" nurl = "http://example.com/" self.urlnormtest(url, nurl) url = "http://example.com:8080/" nurl = "http://example.com:8080/" self.urlnormtest(url, nurl) def test_norm_host_dot (self): # Test url norm host dot removal. url = "http://example.com./" nurl = "http://example.com/" self.urlnormtest(url, nurl) url = "http://example.com.:81/" nurl = "http://example.com:81/" self.urlnormtest(url, nurl) def test_norm_fragment (self): # Test url norm fragment preserving. # Empty fragment identifiers must be preserved: url = "http://www.w3.org/2000/01/rdf-schema#" nurl = url self.urlnormtest(url, nurl) url = "http://example.org/foo/ #a=1,2,3" nurl = "http://example.org/foo/%20#a%3D1%2C2%2C3" self.urlnormtest(url, nurl) def test_norm_empty_path (self): # Test url norm empty path handling. # For schemes that define an empty path to be equivalent to a # path of "/", use "/". url = "http://example.com" nurl = "http://example.com" self.urlnormtest(url, nurl) url = "http://example.com?a=b" nurl = "http://example.com/?a=b" self.urlnormtest(url, nurl) url = "http://example.com#foo" nurl = "http://example.com/#foo" self.urlnormtest(url, nurl) def test_norm_path_backslashes (self): # Test url norm backslash path handling. # note: this is not RFC conform (see url.py for more info) url = r"http://example.com\test.html" nurl = "http://example.com/test.html" self.urlnormtest(url, nurl) url = r"http://example.com/a\test.html" nurl = "http://example.com/a/test.html" self.urlnormtest(url, nurl) url = r"http://example.com\a\test.html" nurl = "http://example.com/a/test.html" self.urlnormtest(url, nurl) url = r"http://example.com\a/test.html" nurl = "http://example.com/a/test.html" self.urlnormtest(url, nurl) def test_norm_path_slashes (self): # Test url norm slashes in path handling. # reduce duplicate slashes url = "http://example.com//a/test.html" nurl = "http://example.com/a/test.html" self.urlnormtest(url, nurl) url = "http://example.com//a/b/" nurl = "http://example.com/a/b/" self.urlnormtest(url, nurl) def test_norm_path_dots (self): # Test url norm dots in path handling. # Prevent dot-segments appearing in non-relative URI paths. url = "http://example.com/a/./b" nurl = "http://example.com/a/b" self.urlnormtest(url, nurl) url = "http://example.com/a/../a/b" self.urlnormtest(url, nurl) url = "http://example.com/../a/b" self.urlnormtest(url, nurl) def test_norm_path_relative_dots (self): # Test url norm relative path handling with dots. # normalize redundant path segments url = '/foo/bar/.' nurl = '/foo/bar/' self.urlnormtest(url, nurl) url = '/foo/bar/./' nurl = '/foo/bar/' self.urlnormtest(url, nurl) url = '/foo/bar/..' nurl = '/foo/' self.urlnormtest(url, nurl) url = '/foo/bar/../' nurl = '/foo/' self.urlnormtest(url, nurl) url = '/foo/bar/../baz' nurl = '/foo/baz' self.urlnormtest(url, nurl) url = '/foo/bar/../..' nurl = '/' self.urlnormtest(url, nurl) url = '/foo/bar/../../' nurl = '/' self.urlnormtest(url, nurl) url = '/foo/bar/../../baz' nurl = '/baz' self.urlnormtest(url, nurl) url = '/foo/bar/../../../baz' nurl = '/baz' self.urlnormtest(url, nurl) url = '/foo/bar/../../../../baz' nurl = '/baz' self.urlnormtest(url, nurl) url = '/./foo' nurl = '/foo' self.urlnormtest(url, nurl) url = '/../foo' nurl = '/foo' self.urlnormtest(url, nurl) url = '/foo.' nurl = url self.urlnormtest(url, nurl) url = '/.foo' nurl = url self.urlnormtest(url, nurl) url = '/foo..' nurl = url self.urlnormtest(url, nurl) url = '/..foo' nurl = url self.urlnormtest(url, nurl) url = '/./../foo' nurl = '/foo' self.urlnormtest(url, nurl) url = '/./foo/.' nurl = '/foo/' self.urlnormtest(url, nurl) url = '/foo/./bar' nurl = '/foo/bar' self.urlnormtest(url, nurl) url = '/foo/../bar' nurl = '/bar' self.urlnormtest(url, nurl) url = '../../../images/miniXmlButton.gif' nurl = url self.urlnormtest(url, nurl) url = '/a..b/../images/miniXmlButton.gif' nurl = '/images/miniXmlButton.gif' self.urlnormtest(url, nurl) url = '/.a.b/../foo/' nurl = '/foo/' self.urlnormtest(url, nurl) url = '/..a.b/../foo/' nurl = '/foo/' self.urlnormtest(url, nurl) url = 'b/../../foo/' nurl = '../foo/' self.urlnormtest(url, nurl) url = './foo' nurl = 'foo' self.urlnormtest(url, nurl) def test_norm_path_relative_slashes (self): # Test url norm relative path handling with slashes. url = '/foo//' nurl = '/foo/' self.urlnormtest(url, nurl) url = '/foo///bar//' nurl = '/foo/bar/' self.urlnormtest(url, nurl) def test_mail_url (self): # Test mailto URLs. # no netloc and no path url = 'mailto:' nurl = url self.urlnormtest(url, nurl) # standard email url = 'mailto:user@www.example.org' nurl = url self.urlnormtest(url, nurl) # emails with subject url = 'mailto:user@www.example.org?subject=a_b' nurl = url self.urlnormtest(url, nurl) url = 'mailto:business.inquiries@designingpatterns.com?subject=Business%20Inquiry' nurl = url self.urlnormtest(url, nurl) def test_norm_other (self): # Test norming of other schemes. url = 'news:' nurl = 'news:' self.urlnormtest(url, nurl) url = 'snews:' nurl = 'snews://' self.urlnormtest(url, nurl) url = 'nntp:' nurl = 'nntp://' self.urlnormtest(url, nurl) url = "news:!$%&/()=" nurl = 'news:!%24%25%26/()=' self.urlnormtest(url, nurl) url = "news:comp.infosystems.www.servers.unix" nurl = url self.urlnormtest(url, nurl) # javascript url url = "javascript:loadthis()" nurl = url self.urlnormtest(url, nurl) # ldap url # XXX failing on Travis build #url = "ldap://[2001:db8::7]/c=GB?objectClass?one" #nurl = "ldap://%5B2001:db8::7%5D/c=GB?objectClass?one" #self.urlnormtest(url, nurl) url = "tel:+1-816-555-1212" nurl = url self.urlnormtest(url, nurl) url = "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" nurl = "urn:oasis%3Anames%3Aspecification%3Adocbook%3Adtd%3Axml%3A4.1.2" self.urlnormtest(url, nurl) def test_norm_with_auth (self): # Test norming of URLs with authentication tokens. url = "telnet://User@www.example.org" nurl = url self.urlnormtest(url, nurl) url = "telnet://User:Pass@www.example.org" nurl = url self.urlnormtest(url, nurl) url = "http://User:Pass@www.example.org/" nurl = url self.urlnormtest(url, nurl) @need_posix def test_norm_file1 (self): url = "file:///a/b.txt" nurl = url self.urlnormtest(url, nurl) @need_windows def test_norm_file2 (self): url = "file:///C|/a/b.txt" nurl = url self.urlnormtest(url, nurl) @need_posix def test_norm_file_unicode (self): url = u"file:///a/b.txt" nurl = url self.urlnormtest(url, nurl) url = u"file:///a/ה.txt" nurl = u"file:///a/%E4.txt" self.urlnormtest(url, nurl, encoding="iso-8859-1") #url = u"file:///\u041c\u043e\u0448\u043a\u043e\u0432\u0430.bin" #nurl = u"file:///a.bin" # XXX #self.urlnormtest(url, nurl) def test_norm_invalid (self): url = u"הצ�?:" nurl = u"%E4%F6%FC?:" self.urlnormtest(url, nurl, encoding="iso-8859-1") def test_fixing (self): # Test url fix method. url = "http//www.example.org" nurl = "http://www.example.org" self.assertEqual(linkcheck.url.url_fix_common_typos(url), nurl) url = u"http//www.example.org" nurl = u"http://www.example.org" self.assertEqual(linkcheck.url.url_fix_common_typos(url), nurl) url = u"https//www.example.org" nurl = u"https://www.example.org" self.assertEqual(linkcheck.url.url_fix_common_typos(url), nurl) def test_valid (self): # Test url validity functions. u = "http://www.example.com" self.assertTrue(linkcheck.url.is_safe_url(u), u) u = "http://www.example.com/" self.assertTrue(linkcheck.url.is_safe_url(u), u) u = "http://www.example.com/~calvin" self.assertTrue(linkcheck.url.is_safe_url(u), u) u = "http://www.example.com/a,b" self.assertTrue(linkcheck.url.is_safe_url(u), u) u = "http://www.example.com#anchor55" self.assertTrue(linkcheck.url.is_safe_url(u), u) def test_needs_quoting (self): # Test url quoting necessity. url = "mailto:<calvin@example.org>?subject=Halli Hallo" self.assertTrue(linkcheck.url.url_needs_quoting(url), repr(url)) url = " http://www.example.com/" self.assertTrue(linkcheck.url.url_needs_quoting(url), repr(url)) url = "http://www.example.com/ " self.assertTrue(linkcheck.url.url_needs_quoting(url), repr(url)) url = "http://www.example.com/\n" self.assertTrue(linkcheck.url.url_needs_quoting(url), repr(url)) url = "\nhttp://www.example.com/" self.assertTrue(linkcheck.url.url_needs_quoting(url), repr(url)) url = "http://www.example.com/#a!" self.assertTrue(not linkcheck.url.url_needs_quoting(url), repr(url)) url = "http://www.example.com/#a b" self.assertTrue(linkcheck.url.url_needs_quoting(url), repr(url)) def test_absolute_url (self): url = "hutzli:" self.assertTrue(linkcheck.url.url_is_absolute(url), repr(url)) url = "file:/" self.assertTrue(linkcheck.url.url_is_absolute(url), repr(url)) url = ":" self.assertTrue(not linkcheck.url.url_is_absolute(url), repr(url)) url = "/a/b?http://" self.assertTrue(not linkcheck.url.url_is_absolute(url), repr(url)) def test_nopathquote_chars (self): if os.name == 'nt': url = "file:///c|/msys/" nurl = url self.assertEqual(url_norm(url), nurl) self.assertTrue(not linkcheck.url.url_needs_quoting(url)) url = "http://hulla/a/b/!?c=d" nurl = url self.assertEqual(url_norm(url), nurl) def test_idn_encoding (self): # Test idna encoding. url = u'www.צko.de' idna_encode = linkcheck.url.idna_encode encurl, is_idn = idna_encode(url) self.assertTrue(is_idn) self.assertTrue(encurl) url = u'' encurl, is_idn = idna_encode(url) self.assertFalse(is_idn) self.assertFalse(encurl) url = u"ה.." self.assertRaises(UnicodeError, idna_encode, url) def test_match_host (self): # Test host matching. match_host = linkcheck.url.match_host match_url = linkcheck.url.match_url self.assertTrue(not match_host("", [])) self.assertTrue(not match_host("", [".localhost"])) self.assertTrue(not match_host("localhost", [])) self.assertTrue(not match_host("localhost", [".localhost"])) self.assertTrue(match_host("a.localhost", [".localhost"])) self.assertTrue(match_host("localhost", ["localhost"])) self.assertTrue(not match_url("", [])) self.assertTrue(not match_url("a", [])) self.assertTrue(match_url("http://example.org/hulla", ["example.org"])) def test_splitparam (self): # Path parameter split test. p = [ ("", ("", "")), ("/", ("/", "")), ("a", ("a", "")), ("a;", ("a", "")), ("a/b;c/d;e", ("a/b;c/d", "e")), ] for x in p: self._splitparam(x) def _splitparam (self, x): self.assertEqual(linkcheck.url.splitparams(x[0]), (x[1][0], x[1][1])) def test_cgi_split (self): # Test cgi parameter splitting. u = "scid=kb;en-us;Q248840" self.assertEqual(linkcheck.url.url_parse_query(u), u) u = "scid=kb;en-us;Q248840&b=c;hulla=bulla" self.assertEqual(linkcheck.url.url_parse_query(u), u) def test_long_cgi (self): u = "/test%s;" % ("?a="*1000) self.assertEqual(linkcheck.url.url_parse_query(u), u) def test_port (self): is_numeric_port = linkcheck.url.is_numeric_port self.assertTrue(is_numeric_port("80")) self.assertTrue(is_numeric_port("1")) self.assertFalse(is_numeric_port("0")) self.assertFalse(is_numeric_port("66000")) self.assertFalse(is_numeric_port("-1")) self.assertFalse(is_numeric_port("a")) def test_split (self): url_split = linkcheck.url.url_split url_unsplit = linkcheck.url.url_unsplit url = "http://example.org/whoops" self.assertEqual(url_unsplit(url_split(url)), url) url = "http://example.org:123/whoops" self.assertEqual(url_unsplit(url_split(url)), url) def test_safe_domain (self): is_safe_domain = linkcheck.url.is_safe_domain self.assertFalse(is_safe_domain(u"a..example.com")) self.assertFalse(is_safe_domain(u"a_b.example.com")) self.assertTrue(is_safe_domain(u"a-b.example.com")) self.assertTrue(is_safe_domain(u"x1.example.com")) @need_network def test_get_content (self): linkcheck.url.get_content('http://www.debian.org/') def test_duplicate_urls(self): is_dup = linkcheck.url.is_duplicate_content_url self.assertTrue(is_dup("http://example.org", "http://example.org")) self.assertTrue(is_dup("http://example.org/", "http://example.org")) self.assertTrue(is_dup("http://example.org", "http://example.org/")) self.assertTrue(is_dup("http://example.org/index.html", "http://example.org")) self.assertTrue(is_dup("http://example.org", "http://example.org/index.html")) self.assertTrue(is_dup("http://example.org/index.htm", "http://example.org")) self.assertTrue(is_dup("http://example.org", "http://example.org/index.htm")) def test_splitport(self): splitport = linkcheck.url.splitport netloc = "hostname" host, port = splitport(netloc, 99) self.assertEqual(host, netloc) self.assertEqual(port, 99) netloc = "hostname:" host, port = splitport(netloc, 99) self.assertEqual(host, "hostname") self.assertEqual(port, 99) netloc = "hostname:42" host, port = splitport(netloc, 99) self.assertEqual(host, "hostname") self.assertEqual(port, 42) netloc = "hostname:foo" host, port = splitport(netloc, 99) self.assertEqual(host, netloc) self.assertEqual(port, 99)
22,287
Python
.py
540
32.914815
130
0.591604
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,188
test_fileutil.py
wummel_linkchecker/tests/test_fileutil.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2010-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test file utility functions. """ import unittest import linkcheck.fileutil file_existing = __file__ file_non_existing = "ZZZ.i_dont_exist" class TestFileutil (unittest.TestCase): """Test file utility functions.""" def test_size (self): self.assertTrue(linkcheck.fileutil.get_size(file_existing) > 0) self.assertEqual(linkcheck.fileutil.get_size(file_non_existing), -1) def test_mtime (self): self.assertTrue(linkcheck.fileutil.get_mtime(file_existing) > 0) self.assertEqual(linkcheck.fileutil.get_mtime(file_non_existing), 0)
1,360
Python
.py
31
41.258065
76
0.755102
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,189
test_cookies.py
wummel_linkchecker/tests/test_cookies.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test cookie routines. """ import unittest import linkcheck.cookies class TestCookies (unittest.TestCase): """Test cookie routines.""" def test_cookie_parse_multiple_headers (self): lines = [ 'Host: example.org', 'Path: /hello', 'Set-cookie: ID="smee"', 'Set-cookie: spam="egg"', ] from_headers = linkcheck.cookies.from_headers cookies = from_headers("\r\n".join(lines)) self.assertEqual(len(cookies), 2) for cookie in cookies: self.assertEqual(cookie.domain, "example.org") self.assertEqual(cookie.path, "/hello") self.assertEqual(cookies[0].name, 'ID') self.assertEqual(cookies[0].value, 'smee') self.assertEqual(cookies[1].name, 'spam') self.assertEqual(cookies[1].value, 'egg') def test_cookie_parse_multiple_values (self): lines = [ 'Host: example.org', 'Set-cookie: baggage="elitist"; comment="hologram"', ] from_headers = linkcheck.cookies.from_headers cookies = from_headers("\r\n".join(lines)) self.assertEqual(len(cookies), 2) for cookie in cookies: self.assertEqual(cookie.domain, "example.org") self.assertEqual(cookie.path, "/") self.assertEqual(cookies[0].name, 'baggage') self.assertEqual(cookies[0].value, 'elitist') self.assertEqual(cookies[1].name, 'comment') self.assertEqual(cookies[1].value, 'hologram') def test_cookie_parse_error (self): lines = [ ' Host: imaweevil.org', 'Set-cookie: baggage="elitist"; comment="hologram"', ] from_headers = linkcheck.cookies.from_headers self.assertRaises(ValueError, from_headers, "\r\n".join(lines))
2,601
Python
.py
62
35.177419
73
0.659297
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,190
test_linkchecker.py
wummel_linkchecker/tests/test_linkchecker.py
# -*- coding: utf-8 -*- # Copyright (C) 2014 Bastian Kleineidam # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import unittest import sys from . import linkchecker_cmd, run_checked def run_with_options(options, cmd=linkchecker_cmd): """Run a command with given options.""" run_checked([sys.executable, cmd] + options) class TestLinkchecker (unittest.TestCase): """Test the linkchecker commandline client.""" def test_linkchecker(self): # test some single options for option in ("-V", "--version", "-h", "--help", "--list-plugins", "-Dall"): run_with_options([option]) # unknown option self.assertRaises(OSError, run_with_options, ['--imadoofus'])
1,301
Python
.py
29
41.62069
85
0.723757
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,191
__init__.py
wummel_linkchecker/tests/__init__.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import signal import subprocess import os import sys import socket import pytest from contextlib import contextmanager from linkcheck import LinkCheckerInterrupt basedir = os.path.dirname(__file__) linkchecker_cmd = os.path.join(os.path.dirname(basedir), "linkchecker") class memoized (object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated.""" def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): try: return self.cache[args] except KeyError: self.cache[args] = value = self.func(*args) return value except TypeError: # uncachable -- for instance, passing a list as an argument. # Better to not cache than to blow up entirely. return self.func(*args) def __repr__(self): """Return the function's docstring.""" return self.func.__doc__ def run (cmd, verbosity=0, **kwargs): """Run command without error checking. @return: command return code""" if kwargs.get("shell"): # for shell calls the command must be a string cmd = " ".join(cmd) return subprocess.call(cmd, **kwargs) def run_checked (cmd, ret_ok=(0,), **kwargs): """Run command and raise OSError on error.""" retcode = run(cmd, **kwargs) if retcode not in ret_ok: msg = "Command `%s' returned non-zero exit status %d" % (cmd, retcode) raise OSError(msg) return retcode def run_silent (cmd): """Run given command without output.""" null = open(os.name == 'nt' and ':NUL' or "/dev/null", 'w') try: return run(cmd, stdout=null, stderr=subprocess.STDOUT) finally: null.close() def _need_func (testfunc, name): """Decorator skipping test if given testfunc fails.""" def check_func (func): def newfunc (*args, **kwargs): if not testfunc(): pytest.skip("%s is not available" % name) return func(*args, **kwargs) newfunc.func_name = func.func_name return newfunc return check_func @memoized def has_network (): """Test if network is up.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("www.python.org", 80)) s.close() return True except StandardError: pass return False need_network = _need_func(has_network, "network") @memoized def has_msgfmt (): """Test if msgfmt is available.""" return run_silent(["msgfmt", "-V"]) == 0 need_msgfmt = _need_func(has_msgfmt, "msgfmt") @memoized def has_posix (): """Test if this is a POSIX system.""" return os.name == "posix" need_posix = _need_func(has_posix, "POSIX system") @memoized def has_windows (): """Test if this is a Windows system.""" return os.name == "nt" need_windows = _need_func(has_windows, "Windows system") @memoized def has_linux (): """Test if this is a Linux system.""" return sys.platform.startswith("linux") need_linux = _need_func(has_linux, "Linux system") @memoized def has_clamav (): """Test if ClamAV daemon is installed and running.""" try: cmd = ["grep", "LocalSocket", "/etc/clamav/clamd.conf"] sock = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0].split()[1] if sock: s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect(sock) s.close() return True except StandardError: pass return False need_clamav = _need_func(has_clamav, "ClamAV") @memoized def has_proxy (): """Test if proxy is running on port 8081.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", 8081)) s.close() return True except StandardError: return False need_proxy = _need_func(has_proxy, "proxy") @memoized def has_pyftpdlib (): """Test if pyftpdlib is available.""" try: import pyftpdlib return True except ImportError: return False need_pyftpdlib = _need_func(has_pyftpdlib, "pyftpdlib") @memoized def has_biplist (): """Test if biplist is available.""" try: import biplist return True except ImportError: return False need_biplist = _need_func(has_biplist, "biplist") @memoized def has_newsserver (server): import nntplib try: nntp = nntplib.NNTP(server, usenetrc=False) nntp.quit() return True except nntplib.NNTPError: return False def need_newsserver (server): """Decorator skipping test if newsserver is not available.""" def check_func (func): def newfunc (*args, **kwargs): if not has_newsserver(server): pytest.skip("Newsserver `%s' is not available" % server) return func(*args, **kwargs) newfunc.func_name = func.func_name return newfunc return check_func @memoized def has_x11 (): """Test if DISPLAY variable is set.""" return os.getenv('DISPLAY') is not None need_x11 = _need_func(has_x11, 'X11') @memoized def has_word(): """Test if Word is available.""" from linkcheck.plugins import parseword return parseword.has_word() need_word = _need_func(has_word, 'Word') @memoized def has_pdflib(): from linkcheck.plugins import parsepdf return parsepdf.has_pdflib need_pdflib = _need_func(has_pdflib, 'pdflib') @contextmanager def _limit_time (seconds): """Raises LinkCheckerInterrupt if given number of seconds have passed.""" if os.name == 'posix': def signal_handler(signum, frame): raise LinkCheckerInterrupt("timed out") old_handler = signal.getsignal(signal.SIGALRM) signal.signal(signal.SIGALRM, signal_handler) signal.alarm(seconds) yield if os.name == 'posix': signal.alarm(0) if old_handler is not None: signal.signal(signal.SIGALRM, old_handler) def limit_time (seconds, skip=False): """Limit test time to the given number of seconds, else fail or skip.""" def run_limited (func): def new_func (*args, **kwargs): try: with _limit_time(seconds): return func(*args, **kwargs) except LinkCheckerInterrupt as msg: if skip: pytest.skip("time limit of %d seconds exceeded" % seconds) assert False, msg new_func.func_name = func.func_name return new_func return run_limited def get_file (filename=None): """ Get file name located within 'data' directory. """ directory = os.path.join("tests", "checker", "data") if filename: return unicode(os.path.join(directory, filename)) return unicode(directory) if __name__ == '__main__': print "has clamav", has_clamav() print "has network", has_network() print "has msgfmt", has_msgfmt() print "has POSIX", has_posix() print "has proxy", has_proxy() print "has X11", has_x11()
7,978
Python
.py
231
28.614719
88
0.650482
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,192
test_strformat.py
wummel_linkchecker/tests/test_strformat.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test string formatting operations. """ import unittest import os import time import linkcheck.strformat class TestStrFormat (unittest.TestCase): """ Test string formatting routines. """ def test_unquote (self): # Test quote stripping. u = linkcheck.strformat.unquote self.assertEqual(u(""), "") self.assertEqual(u(None), None) self.assertEqual(u("'"), "'") self.assertEqual(u("\""), "\"") self.assertEqual(u("\"\""), "") self.assertEqual(u("''"), "") self.assertEqual(u("'a'"), "a") self.assertEqual(u("'a\"'"), "a\"") self.assertEqual(u("'\"a'"), "\"a") self.assertEqual(u('"a\'"'), 'a\'') self.assertEqual(u('"\'a"'), '\'a') self.assertEqual(u("'a'", matching=True), "a") self.assertEqual(u('"a"', matching=True), "a") # even mis-matching quotes should be removed... self.assertEqual(u("'a\""), "a") self.assertEqual(u("\"a'"), "a") # ...but not when matching is True self.assertEqual(u("'a\"", matching=True), "'a\"") self.assertEqual(u("\"a'", matching=True), "\"a'") def test_wrap (self): # Test line wrapping. wrap = linkcheck.strformat.wrap s = "11%(sep)s22%(sep)s33%(sep)s44%(sep)s55" % {'sep': os.linesep} # testing width <= 0 self.assertEqual(wrap(s, -1), s) self.assertEqual(wrap(s, 0), s) l = len(os.linesep) gap = " " s2 = "11%(gap)s22%(sep)s33%(gap)s44%(sep)s55" % \ {'sep': os.linesep, 'gap': gap} # splitting lines self.assertEqual(wrap(s2, 2), s) # combining lines self.assertEqual(wrap(s, 4+l), s2) # misc self.assertEqual(wrap(s, -1), s) self.assertEqual(wrap(s, 0), s) self.assertEqual(wrap(None, 10), None) self.assertFalse(linkcheck.strformat.get_paragraphs(None)) def test_remove_markup (self): # Test markup removing. self.assertEqual(linkcheck.strformat.remove_markup("<a>"), "") self.assertEqual(linkcheck.strformat.remove_markup("<>"), "") self.assertEqual(linkcheck.strformat.remove_markup("<<>"), "") self.assertEqual(linkcheck.strformat.remove_markup("a < b"), "a < b") def test_strsize (self): # Test byte size strings. self.assertRaises(ValueError, linkcheck.strformat.strsize, -1) self.assertEqual(linkcheck.strformat.strsize(0), "0B") self.assertEqual(linkcheck.strformat.strsize(1), "1B") self.assertEqual(linkcheck.strformat.strsize(2), "2B") self.assertEqual(linkcheck.strformat.strsize(1023, grouping=False), "1023B") self.assertEqual(linkcheck.strformat.strsize(1024), "1KB") self.assertEqual(linkcheck.strformat.strsize(1024*25), "25.00KB") self.assertEqual(linkcheck.strformat.strsize(1024*1024), "1.00MB") self.assertEqual(linkcheck.strformat.strsize(1024*1024*11), "11.0MB") self.assertEqual(linkcheck.strformat.strsize(1024*1024*1024), "1.00GB") self.assertEqual(linkcheck.strformat.strsize(1024*1024*1024*14), "14.0GB") def test_is_ascii (self): self.assertTrue(linkcheck.strformat.is_ascii("abcd./")) self.assertTrue(not linkcheck.strformat.is_ascii("ä")) self.assertTrue(not linkcheck.strformat.is_ascii(u"ä")) def test_indent (self): s = "bla" self.assertEqual(linkcheck.strformat.indent(s, ""), s) self.assertEqual(linkcheck.strformat.indent(s, " "), " "+s) def test_stripurl (self): self.assertEqual(linkcheck.strformat.stripurl(u"a\tb"), u"a\tb") self.assertEqual(linkcheck.strformat.stripurl(u" a\t b"), u"a\t b") self.assertEqual(linkcheck.strformat.stripurl(u" ab\t\ra\nb"), u"ab") self.assertEqual(linkcheck.strformat.stripurl(None), None) self.assertEqual(linkcheck.strformat.stripurl(u""), u"") def test_limit (self): self.assertEqual(linkcheck.strformat.limit("", 0), "") self.assertEqual(linkcheck.strformat.limit("a", 0), "") self.assertEqual(linkcheck.strformat.limit("1", 1), "1") self.assertEqual(linkcheck.strformat.limit("11", 1), "1...") def test_strtime (self): zone = linkcheck.strformat.strtimezone() t = linkcheck.strformat.strtime(0, func=time.gmtime) self.assertEqual(t, "1970-01-01 00:00:00"+zone) def test_duration (self): duration = linkcheck.strformat.strduration self.assertEqual(duration(-0.5), "-00:01") self.assertEqual(duration(0), "00:00") self.assertEqual(duration(0.9), "00:01") self.assertEqual(duration(1), "00:01") self.assertEqual(duration(2), "00:02") self.assertEqual(duration(60), "01:00") self.assertEqual(duration(120), "02:00") self.assertEqual(duration(60*60), "01:00:00") self.assertEqual(duration(60*60*24), "24:00:00") def test_duration_long (self): duration = lambda s: linkcheck.strformat.strduration_long(s, do_translate=False) self.assertEqual(duration(-0.5), "-0.50 seconds") self.assertEqual(duration(0), "0.00 seconds") self.assertEqual(duration(0.9), "0.90 seconds") self.assertEqual(duration(1), "1 second") self.assertEqual(duration(2), "2 seconds") self.assertEqual(duration(60), "1 minute") self.assertEqual(duration(120), "2 minutes") self.assertEqual(duration(60*60), "1 hour") self.assertEqual(duration(60*60*24), "1 day") self.assertEqual(duration(60*60*24*365), "1 year") self.assertEqual(duration(60*60*24*365 + 60*60*24 + 2), "1 year, 1 day") def test_linenumber (self): get_line_number = linkcheck.strformat.get_line_number self.assertEqual(get_line_number("a", -5), 0) self.assertEqual(get_line_number("a", 0), 1) self.assertEqual(get_line_number("a\nb", 2), 2) def test_encoding (self): is_encoding = linkcheck.strformat.is_encoding self.assertTrue(is_encoding('ascii')) self.assertFalse(is_encoding('hulla')) def test_unicode_safe (self): unicode_safe = linkcheck.strformat.unicode_safe self.assertEqual(unicode_safe("a"), u"a") self.assertEqual(unicode_safe(u"a"), u"a") def test_ascii_safe (self): ascii_safe = linkcheck.strformat.ascii_safe self.assertEqual(ascii_safe("a"), "a") self.assertEqual(ascii_safe(u"a"), "a") self.assertEqual(ascii_safe(u"ä"), "") def test_strip_control_chars(self): strip = linkcheck.strformat.strip_control_chars self.assertEqual(strip(""), "") self.assertEqual(strip(u""), u"") self.assertEqual(strip("a"), "a") self.assertEqual(strip(u"a"), u"a") self.assertEqual(strip("ä"), "ä") self.assertEqual(strip(u"ä"), u"ä") self.assertEqual(strip("\x01"), "") self.assertEqual(strip(u"\x01"), u"")
7,840
Python
.py
166
39.548193
88
0.633834
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,193
test_robotstxt.py
wummel_linkchecker/tests/test_robotstxt.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2006-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test robots.txt parsing. """ import unittest import linkcheck.robotparser2 class TestRobotsTxt (unittest.TestCase): """ Test string formatting routines. """ def setUp (self): """ Initialize self.rp as a robots.txt parser. """ self.rp = linkcheck.robotparser2.RobotFileParser() def test_robotstxt (self): lines = [ "User-agent: *", ] self.rp.parse(lines) self.assertTrue(self.rp.mtime() > 0) self.assertEqual(str(self.rp), "\n".join(lines)) def test_robotstxt2 (self): lines = [ "User-agent: *", "Disallow: /search", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines)) def test_robotstxt3 (self): lines = [ "Disallow: /search", "", "Allow: /search", "", "Crawl-Delay: 5", "", "Blabla", "", "Bla: bla", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "") def test_robotstxt4 (self): lines = [ "User-agent: Bla", "Disallow: /cgi-bin", "User-agent: *", "Disallow: /search", ] self.rp.parse(lines) lines.insert(2, "") self.assertEqual(str(self.rp), "\n".join(lines)) def test_robotstxt5 (self): lines = [ "#one line comment", "User-agent: Bla", "Disallow: /cgi-bin # comment", "Allow: /search", ] lines2 = [ "User-agent: Bla", "Disallow: /cgi-bin", "Allow: /search", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines2)) def test_robotstxt6 (self): lines = [ "User-agent: Bla", "", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "") def test_robotstxt7 (self): lines = [ "User-agent: Bla", "Allow: /", "", "User-agent: *", "Disallow: /", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines)) self.assertTrue(self.rp.can_fetch("Bla", "/")) def test_crawldelay (self): lines = [ "User-agent: Blubb", "Crawl-delay: 10", "", "User-agent: Hulla", "Crawl-delay: 5", "", "User-agent: *", "Crawl-delay: 1", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines)) self.assertEqual(self.rp.get_crawldelay("Blubb"), 10) self.assertEqual(self.rp.get_crawldelay("Hulla"), 5) self.assertEqual(self.rp.get_crawldelay("Bulla"), 1) def test_crawldelay2 (self): lines = [ "User-agent: Blubb", "Crawl-delay: X", ] self.rp.parse(lines) del lines[1] self.assertEqual(str(self.rp), "\n".join(lines)) def check_urls (self, good, bad, agent="test_robotparser"): for url in good: self.check_url(agent, url, True) for url in bad: self.check_url(agent, url, False) def check_url (self, agent, url, can_fetch): if isinstance(url, tuple): agent, url = url res = self.rp.can_fetch(agent, url) if can_fetch: self.assertTrue(res, "%s disallowed" % url) else: self.assertFalse(res, "%s allowed" % url) def test_access1 (self): lines = [ "User-agent: *", "Disallow: /cyberworld/map/ # This is an infinite virtual URL space", "Disallow: /tmp/ # these will soon disappear", "Disallow: /foo.html", ] lines2 = [ "User-agent: *", "Disallow: /cyberworld/map/", "Disallow: /tmp/", "Disallow: /foo.html", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines2)) good = ['/', '/test.html'] bad = ['/cyberworld/map/index.html', '/tmp/xxx', '/foo.html'] self.check_urls(good, bad) def test_access2 (self): lines = [ "# robots.txt for http://www.example.com/", "", "User-agent: *", "Disallow: /cyberworld/map/ # This is an infinite virtual URL space", "", "# Cybermapper knows where to go.", "User-agent: cybermapper", "Disallow:", "", ] lines2 = [ "User-agent: cybermapper", "Allow: /", "", "User-agent: *", "Disallow: /cyberworld/map/", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines2)) good = ['/', '/test.html', ('cybermapper', '/cyberworld/map/index.html')] bad = ['/cyberworld/map/index.html'] self.check_urls(good, bad) def test_access3 (self): lines = [ "# go away", "User-agent: *", "Disallow: /", ] lines2 = [ "User-agent: *", "Disallow: /", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines2)) good = [] bad = ['/cyberworld/map/index.html', '/', '/tmp/'] self.check_urls(good, bad) def test_access4 (self): lines = [ "User-agent: figtree", "Disallow: /tmp", "Disallow: /a%3cd.html", "Disallow: /a%2fb.html", "Disallow: /%7ejoe/index.html", ] lines2 = [ "User-agent: figtree", "Disallow: /tmp", "Disallow: /a%3Cd.html", "Disallow: /a/b.html", "Disallow: /%7Ejoe/index.html", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines2)) good = [] bad = ['/tmp', '/tmp.html', '/tmp/a.html', '/a%3cd.html', '/a%3Cd.html', '/a%2fb.html', '/~joe/index.html', '/a/b.html', ] self.check_urls(good, bad, 'figtree') self.check_urls(good, bad, 'FigTree/1.0 Robot libwww-perl/5.04') def test_access5 (self): lines = [ "User-agent: *", "Disallow: /tmp/", "Disallow: /a%3Cd.html", "Disallow: /a/b.html", "Disallow: /%7ejoe/index.html", ] lines2 = [ "User-agent: *", "Disallow: /tmp/", "Disallow: /a%3Cd.html", "Disallow: /a/b.html", "Disallow: /%7Ejoe/index.html", ] self.rp.parse(lines) self.assertEqual(str(self.rp), "\n".join(lines2)) good = ['/tmp'] # XFAIL: '/a%2fb.html' bad = ['/tmp/', '/tmp/a.html', '/a%3cd.html', '/a%3Cd.html', "/a/b.html", '/%7Ejoe/index.html'] self.check_urls(good, bad) def test_access6 (self): lines = [ "User-Agent: *", "Disallow: /.", ] self.rp.parse(lines) good = ['/foo.html'] bad = [] # Bug report says "/" should be denied, but that is not in the RFC self.check_urls(good, bad) def test_access7 (self): lines = [ "User-agent: Example", "Disallow: /example", "", "User-agent: *", "Disallow: /cgi-bin", ] self.rp.parse(lines) # test re.escape self.check_url("*", "/", True) # should match first agent self.check_url("", "/example", False) # test agent matching self.check_url("Example", "/example", False) self.check_url("Example/1.0", "/example", False) self.check_url("example", "/example", False) self.check_url("spam", "/cgi-bin", False) self.check_url("spam", "/cgi-bin/foo/bar", False) self.check_url("spam", "/cgi-bin?a=1", False) self.check_url("spam", "/", True) def test_sitemap(self): lines = [ "Sitemap: bla", ] self.rp.parse(lines) self.assertTrue(len(self.rp.sitemap_urls) > 0) self.assertTrue(self.rp.sitemap_urls[0] == ("bla", 1))
9,168
Python
.py
277
23.436823
83
0.508457
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,194
test_console.py
wummel_linkchecker/tests/test_console.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2011 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test console operations. """ import unittest import linkcheck.director.console class TestConsole (unittest.TestCase): """Test console operations.""" def test_internal_error (self): linkcheck.director.console.internal_error()
1,024
Python
.py
25
39.16
73
0.770854
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,195
test_linkparser.py
wummel_linkchecker/tests/test_linkparser.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test linkparser routines. """ import unittest from linkcheck.htmlutil import linkparse import linkcheck.HtmlParser.htmlsax class TestLinkparser (unittest.TestCase): """ Test link parsing. """ def _test_one_link (self, content, url): self.count_url = 0 h = linkparse.LinkFinder(self._test_one_url(url), linkparse.LinkTags) p = linkcheck.HtmlParser.htmlsax.parser(h) h.parser = p try: p.feed(content) p.flush() except linkparse.StopParse: pass h.parser = None p.handler = None self.assertEqual(self.count_url, 1) def _test_one_url (self, origurl): """Return parser callback function.""" def callback (url, line, column, name, base): self.count_url += 1 self.assertEqual(origurl, url) return callback def _test_no_link (self, content): def callback (url, line, column, name, base): self.assertTrue(False, 'URL %r found' % url) h = linkparse.LinkFinder(callback, linkparse.LinkTags) p = linkcheck.HtmlParser.htmlsax.parser(h) h.parser = p try: p.feed(content) p.flush() except linkparse.StopParse: pass h.parser = None p.handler = None def test_href_parsing (self): # Test <a href> parsing. content = u'<a href="%s">' url = u"alink" self._test_one_link(content % url, url) url = u" alink" self._test_one_link(content % url, url) url = u"alink " self._test_one_link(content % url, url) url = u" alink " self._test_one_link(content % url, url) def test_img_srcset_parsing(self): content = u'<img srcset="%s 1x">' url = u"imagesmall.jpg" self._test_one_link(content % url, url) def test_itemtype_parsing(self): content = u'<div itemtype="%s">' url = u"http://example.org/Movie" self._test_one_link(content % url, url) def test_form_parsing(self): # Test <form action> parsing content = u'<form action="%s">' url = u"alink" self._test_one_link(content % url, url) content = u'<form action="%s" method="POST">' url = u"alink" self._test_no_link(content % url) def test_css_parsing (self): # Test css style attribute parsing. content = u'<table style="background: url(%s) no-repeat" >' url = u"alink" self._test_one_link(content % url, url) content = u'<table style="background: url(%s) no-repeat" >' self._test_one_link(content % url, url) content = u'<table style="background: url(%s ) no-repeat" >' self._test_one_link(content % url, url) content = u'<table style="background: url( %s ) no-repeat" >' self._test_one_link(content % url, url) content = u'<table style="background: url(\'%s\') no-repeat" >' self._test_one_link(content % url, url) content = u"<table style='background: url(\"%s\") no-repeat' >" self._test_one_link(content % url, url) content = u'<table style="background: url(\'%s\' ) no-repeat" >' self._test_one_link(content % url, url) content = u"<table style='background: url( \"%s\") no-repeat' >" self._test_one_link(content % url, url) def test_comment_stripping (self): strip = linkparse.strip_c_comments content = "/* url('http://example.org')*/" self.assertEqual(strip(content), "") content = "/* * * **/" self.assertEqual(strip(content), "") content = "/* * /* * **//* */" self.assertEqual(strip(content), "") content = "a/* */b/* */c" self.assertEqual(strip(content), "abc") def test_url_quoting(self): url = u'http://example.com/bla/a=b' content = u'<a href="%s&quot;">' self._test_one_link(content % url, url + u'"')
4,781
Python
.py
118
33.101695
77
0.606882
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,196
test_decorators.py
wummel_linkchecker/tests/test_decorators.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005-2010 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test decorators. """ import unittest import time from cStringIO import StringIO import linkcheck.decorators class TestDecorators (unittest.TestCase): """ Test decorators. """ def test_timeit (self): @linkcheck.decorators.timed() def f (): return 42 self.assertEqual(f(), 42) def test_timeit2 (self): log = StringIO() @linkcheck.decorators.timed(log=log, limit=0) def f (): time.sleep(1) return 42 self.assertEqual(f(), 42) self.assertTrue(log.getvalue())
1,364
Python
.py
40
29.975
73
0.706596
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,197
test_mimeutil.py
wummel_linkchecker/tests/test_mimeutil.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2010-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test mime utility functions. """ import unittest import os from . import get_file import linkcheck.mimeutil class TestMiMeutil (unittest.TestCase): """Test file utility functions.""" def mime_test (self, filename, mime_expected): absfilename = get_file(filename) with open(absfilename) as fd: mime = linkcheck.mimeutil.guess_mimetype(absfilename, read=fd.read) self.assertEqual(mime, mime_expected) def test_mime (self): filename = os.path.join("plist_binary", "Bookmarks.plist") self.mime_test(filename, "application/x-plist+safari") filename = os.path.join("plist_xml", "Bookmarks.plist") self.mime_test(filename, "application/x-plist+safari") self.mime_test("file.wml", "text/vnd.wap.wml") self.mime_test("sitemap.xml", "application/xml+sitemap") self.mime_test("sitemapindex.xml", "application/xml+sitemapindex")
1,709
Python
.py
38
41.131579
79
0.730054
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,198
test_dummy.py
wummel_linkchecker/tests/test_dummy.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005-2011 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test dummy object. """ import unittest import linkcheck.dummy class TestDummy (unittest.TestCase): """ Test dummy object. """ def test_creation (self): dummy = linkcheck.dummy.Dummy() dummy = linkcheck.dummy.Dummy("1") dummy = linkcheck.dummy.Dummy("1", "2") dummy = linkcheck.dummy.Dummy(a=1, b=2) dummy = linkcheck.dummy.Dummy("1", a=None, b=2) def test_attributes (self): dummy = linkcheck.dummy.Dummy() dummy.hulla dummy.hulla.bulla dummy.hulla = 1 del dummy.wulla del dummy.wulla.mulla def test_methods (self): dummy = linkcheck.dummy.Dummy() dummy.hulla() dummy.hulla().bulla() if "a" in dummy: pass def test_indexes (self): dummy = linkcheck.dummy.Dummy() len(dummy) dummy[1] = dummy[2] dummy[1][-1] dummy[1:3] = None del dummy[1] del dummy[2] del dummy[2:3] str(dummy) repr(dummy) unicode(dummy)
1,843
Python
.py
56
27.357143
73
0.657303
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)
22,199
test_robotparser.py
wummel_linkchecker/tests/test_robotparser.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2004-2014 Bastian Kleineidam # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Test robots.txt parsing. """ import unittest from tests import need_network from linkcheck import configuration, robotparser2 class TestRobotParser (unittest.TestCase): """ Test robots.txt parser (needs internet access). """ def setUp (self): """Initialize self.rp as a robots.txt parser.""" self.rp = robotparser2.RobotFileParser() def check (self, a, b): """Helper function comparing two results a and b.""" if not b: ac = "access denied" else: ac = "access allowed" if a != b: self.fail("%s != %s (%s)" % (a, b, ac)) @need_network def test_nonexisting_robots (self): # robots.txt that does not exist self.rp.set_url('http://www.lycos.com/robots.txt') self.rp.read() self.check(self.rp.can_fetch(configuration.UserAgent, 'http://www.lycos.com/search'), True) @need_network def test_disallowed_robots (self): self.rp.set_url('http://google.com/robots.txt') self.rp.read() self.check(self.rp.can_fetch(configuration.UserAgent, "http://google.com/search"), False)
2,004
Python
.py
50
33.94
74
0.662558
wummel/linkchecker
1,417
234
200
GPL-2.0
9/5/2024, 5:13:10 PM (Europe/Amsterdam)