SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.
Python attacksurfacecticybersecurityfootprintinghackinginformation-gatheringinformation-securityinfosecintelligence-gatheringosintosint-frameworkosint-reconnaissanceosint-toolpentestingpythonreconsecurity-toolsthreat-intelligencethreatintel
Removed packaged dependencies and now fully rely on requirements.txt.
smicallef83439bc2925a
diff --git a/ext/PyPDF2/__init__.py b/ext/PyPDF2/__init__.pydeleted file mode 100755index f458c0ea..00000000--- a/ext/PyPDF2/__init__.py+++ /dev/null@@ -1,5 +0,0 @@-from .pdf import PdfFileReader, PdfFileWriter-from .merger import PdfFileMerger-from .pagerange import PageRange, parse_filename_page_ranges-from ._version import __version__-__all__ = ["pdf", "PdfFileMerger"]diff --git a/ext/PyPDF2/_version.py b/ext/PyPDF2/_version.pydeleted file mode 100755index 5fc7041e..00000000--- a/ext/PyPDF2/_version.py+++ /dev/null@@ -1 +0,0 @@-__version__ = '1.26.0'diff --git a/ext/PyPDF2/filters.py b/ext/PyPDF2/filters.pydeleted file mode 100755index 3717fd4c..00000000--- a/ext/PyPDF2/filters.py+++ /dev/null@@ -1,362 +0,0 @@-# vim: sw=4:expandtab:foldmethod=marker-#-# Copyright (c) 2006, Mathieu Fenniak-# All rights reserved.-#-# Redistribution and use in source and binary forms, with or without-# modification, are permitted provided that the following conditions are-# met:-#-# * Redistributions of source code must retain the above copyright notice,-# this list of conditions and the following disclaimer.-# * Redistributions in binary form must reproduce the above copyright notice,-# this list of conditions and the following disclaimer in the documentation-# and/or other materials provided with the distribution.-# * The name of the author may not be used to endorse or promote products-# derived from this software without specific prior written permission.-#-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE-# POSSIBILITY OF SUCH DAMAGE.---"""-Implementation of stream filters for PDF.-"""-__author__ = "Mathieu Fenniak"-__author_email__ = "[email protected]"--from .utils import PdfReadError, ord_, chr_-from sys import version_info-if version_info < ( 3, 0 ):- from cStringIO import StringIO-else:- from io import StringIO- import struct--try:- import zlib-- def decompress(data):- return zlib.decompress(data)-- def compress(data):- return zlib.compress(data)--except ImportError:- # Unable to import zlib. Attempt to use the System.IO.Compression- # library from the .NET framework. (IronPython only)- import System- from System import IO, Collections, Array-- def _string_to_bytearr(buf):- retval = Array.CreateInstance(System.Byte, len(buf))- for i in range(len(buf)):- retval[i] = ord(buf[i])- return retval-- def _bytearr_to_string(bytes):- retval = ""- for i in range(bytes.Length):- retval += chr(bytes[i])- return retval-- def _read_bytes(stream):- ms = IO.MemoryStream()- buf = Array.CreateInstance(System.Byte, 2048)- while True:- bytes = stream.Read(buf, 0, buf.Length)- if bytes == 0:- break- else:- ms.Write(buf, 0, bytes)- retval = ms.ToArray()- ms.Close()- return retval-- def decompress(data):- bytes = _string_to_bytearr(data)- ms = IO.MemoryStream()- ms.Write(bytes, 0, bytes.Length)- ms.Position = 0 # fseek 0- gz = IO.Compression.DeflateStream(ms, IO.Compression.CompressionMode.Decompress)- bytes = _read_bytes(gz)- retval = _bytearr_to_string(bytes)- gz.Close()- return retval-- def compress(data):- bytes = _string_to_bytearr(data)- ms = IO.MemoryStream()- gz = IO.Compression.DeflateStream(ms, IO.Compression.CompressionMode.Compress, True)- gz.Write(bytes, 0, bytes.Length)- gz.Close()- ms.Position = 0 # fseek 0- bytes = ms.ToArray()- retval = _bytearr_to_string(bytes)- ms.Close()- return retval---class FlateDecode(object):- def decode(data, decodeParms):- data = decompress(data)- predictor = 1- if decodeParms:- try:- predictor = decodeParms.get("/Predictor", 1)- except AttributeError:- pass # usually an array with a null object was read-- # predictor 1 == no predictor- if predictor != 1:- columns = decodeParms["/Columns"]- # PNG prediction:- if predictor >= 10 and predictor <= 15:- output = StringIO()- # PNG prediction can vary from row to row- rowlength = columns + 1- assert len(data) % rowlength == 0- prev_rowdata = (0,) * rowlength- for row in range(len(data) // rowlength):- rowdata = [ord_(x) for x in data[(row*rowlength):((row+1)*rowlength)]]- filterByte = rowdata[0]- if filterByte == 0:- pass- elif filterByte == 1:- for i in range(2, rowlength):- rowdata[i] = (rowdata[i] + rowdata[i-1]) % 256- elif filterByte == 2:- for i in range(1, rowlength):- rowdata[i] = (rowdata[i] + prev_rowdata[i]) % 256- else:- # unsupported PNG filter- raise PdfReadError("Unsupported PNG filter %r" % filterByte)- prev_rowdata = rowdata- output.write(''.join([chr(x) for x in rowdata[1:]]))- data = output.getvalue()- else:- # unsupported predictor- raise PdfReadError("Unsupported flatedecode predictor %r" % predictor)- return data- decode = staticmethod(decode)-- def encode(data):- return compress(data)- encode = staticmethod(encode)---class ASCIIHexDecode(object):- def decode(data, decodeParms=None):- retval = ""- char = ""- x = 0- while True:- c = data[x]- if c == ">":- break- elif c.isspace():- x += 1- continue- char += c- if len(char) == 2:- retval += chr(int(char, base=16))- char = ""- x += 1- assert char == ""- return retval- decode = staticmethod(decode)---class LZWDecode(object):- """Taken from:- http://www.java2s.com/Open-Source/Java-Document/PDF/PDF-Renderer/com/sun/pdfview/decode/LZWDecode.java.htm- """- class decoder(object):- def __init__(self, data):- self.STOP=257- self.CLEARDICT=256- self.data=data- self.bytepos=0- self.bitpos=0- self.dict=[""]*4096- for i in range(256):- self.dict[i]=chr(i)- self.resetDict()-- def resetDict(self):- self.dictlen=258- self.bitspercode=9-- def nextCode(self):- fillbits=self.bitspercode- value=0- while fillbits>0 :- if self.bytepos >= len(self.data):- return -1- nextbits=ord(self.data[self.bytepos])- bitsfromhere=8-self.bitpos- if bitsfromhere>fillbits:- bitsfromhere=fillbits- value |= (((nextbits >> (8-self.bitpos-bitsfromhere)) &- (0xff >> (8-bitsfromhere))) <<- (fillbits-bitsfromhere))- fillbits -= bitsfromhere- self.bitpos += bitsfromhere- if self.bitpos >=8:- self.bitpos=0- self.bytepos = self.bytepos+1- return value-- def decode(self):- """ algorithm derived from:- http://www.rasip.fer.hr/research/compress/algorithms/fund/lz/lzw.html- and the PDFReference- """- cW = self.CLEARDICT;- baos=""- while True:- pW = cW;- cW = self.nextCode();- if cW == -1:- raise PdfReadError("Missed the stop code in LZWDecode!")- if cW == self.STOP:- break;- elif cW == self.CLEARDICT:- self.resetDict();- elif pW == self.CLEARDICT:- baos+=self.dict[cW]- else:- if cW < self.dictlen:- baos += self.dict[cW]- p=self.dict[pW]+self.dict[cW][0]- self.dict[self.dictlen]=p- self.dictlen+=1- else:- p=self.dict[pW]+self.dict[pW][0]- baos+=p- self.dict[self.dictlen] = p;- self.dictlen+=1- if (self.dictlen >= (1 << self.bitspercode) - 1 and- self.bitspercode < 12):- self.bitspercode+=1- return baos-- @staticmethod- def decode(data,decodeParams=None):- return LZWDecode.decoder(data).decode()---class ASCII85Decode(object):- def decode(data, decodeParms=None):- if version_info < ( 3, 0 ):- retval = ""- group = []- x = 0- hitEod = False- # remove all whitespace from data- data = [y for y in data if not (y in ' \n\r\t')]- while not hitEod:- c = data[x]- if len(retval) == 0 and c == "<" and data[x+1] == "~":- x += 2- continue- #elif c.isspace():- # x += 1- # continue- elif c == 'z':- assert len(group) == 0- retval += '\x00\x00\x00\x00'- x += 1- continue- elif c == "~" and data[x+1] == ">":- if len(group) != 0:- # cannot have a final group of just 1 char- assert len(group) > 1- cnt = len(group) - 1- group += [ 85, 85, 85 ]- hitEod = cnt- else:- break- else:- c = ord(c) - 33- assert c >= 0 and c < 85- group += [ c ]- if len(group) >= 5:- b = group[0] * (85**4) + \- group[1] * (85**3) + \- group[2] * (85**2) + \- group[3] * 85 + \- group[4]- assert b < (2**32 - 1)- c4 = chr((b >> 0) % 256)- c3 = chr((b >> 8) % 256)- c2 = chr((b >> 16) % 256)- c1 = chr(b >> 24)- retval += (c1 + c2 + c3 + c4)- if hitEod:- retval = retval[:-4+hitEod]- group = []- x += 1- return retval- else:- if isinstance(data, str):- data = data.encode('ascii')- n = b = 0- out = bytearray()- for c in data:- if ord('!') <= c and c <= ord('u'):- n += 1- b = b*85+(c-33)- if n == 5:- out += struct.pack(b'>L',b)- n = b = 0- elif c == ord('z'):- assert n == 0- out += b'\0\0\0\0'- elif c == ord('~'):- if n:- for _ in range(5-n):- b = b*85+84- out += struct.pack(b'>L',b)[:n-1]- break- return bytes(out)- decode = staticmethod(decode)---def decodeStreamData(stream):- from .generic import NameObject- filters = stream.get("/Filter", ())- if len(filters) and not isinstance(filters[0], NameObject):- # we have a single filter instance- filters = (filters,)- data = stream._data- # If there is not data to decode we should not try to decode the data.- if data:- for filterType in filters:- if filterType == "/FlateDecode" or filterType == "/Fl":- data = FlateDecode.decode(data, stream.get("/DecodeParms"))- elif filterType == "/ASCIIHexDecode" or filterType == "/AHx":- data = ASCIIHexDecode.decode(data)- elif filterType == "/LZWDecode" or filterType == "/LZW":- data = LZWDecode.decode(data, stream.get("/DecodeParms"))- elif filterType == "/ASCII85Decode" or filterType == "/A85":- data = ASCII85Decode.decode(data)- elif filterType == "/Crypt":- decodeParams = stream.get("/DecodeParams", {})- if "/Name" not in decodeParams and "/Type" not in decodeParams:- pass- else:- raise NotImplementedError("/Crypt filter with /Name or /Type not supported yet")- else:- # unsupported filter- raise NotImplementedError("unsupported filter %s" % filterType)- return datadiff --git a/ext/PyPDF2/generic.py b/ext/PyPDF2/generic.pydeleted file mode 100755index c4332297..00000000--- a/ext/PyPDF2/generic.py+++ /dev/null@@ -1,1226 +0,0 @@-# vim: sw=4:expandtab:foldmethod=marker-#-# Copyright (c) 2006, Mathieu Fenniak-# All rights reserved.-#-# Redistribution and use in source and binary forms, with or without-# modification, are permitted provided that the following conditions are-# met:-#-# * Redistributions of source code must retain the above copyright notice,-# this list of conditions and the following disclaimer.-# * Redistributions in binary form must reproduce the above copyright notice,-# this list of conditions and the following disclaimer in the documentation-# and/or other materials provided with the distribution.-# * The name of the author may not be used to endorse or promote products-# derived from this software without specific prior written permission.-#-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE-# POSSIBILITY OF SUCH DAMAGE.---"""-Implementation of generic PDF objects (dictionary, number, string, and so on)-"""-__author__ = "Mathieu Fenniak"-__author_email__ = "[email protected]"--import re-from .utils import readNonWhitespace, RC4_encrypt, skipOverComment-from .utils import b_, u_, chr_, ord_-from .utils import PdfStreamError-import warnings-from . import filters-from . import utils-import decimal-import codecs-import sys-#import debugging--ObjectPrefix = b_('/<[tf(n%')-NumberSigns = b_('+-')-IndirectPattern = re.compile(b_(r"(\d+)\s+(\d+)\s+R[^a-zA-Z]"))---def readObject(stream, pdf):- tok = stream.read(1)- stream.seek(-1, 1) # reset to start- idx = ObjectPrefix.find(tok)- if idx == 0:- # name object- return NameObject.readFromStream(stream, pdf)- elif idx == 1:- # hexadecimal string OR dictionary- peek = stream.read(2)- stream.seek(-2, 1) # reset to start- if peek == b_('<<'):- return DictionaryObject.readFromStream(stream, pdf)- else:- return readHexStringFromStream(stream)- elif idx == 2:- # array object- return ArrayObject.readFromStream(stream, pdf)- elif idx == 3 or idx == 4:- # boolean object- return BooleanObject.readFromStream(stream)- elif idx == 5:- # string object- return readStringFromStream(stream)- elif idx == 6:- # null object- return NullObject.readFromStream(stream)- elif idx == 7:- # comment- while tok not in (b_('\r'), b_('\n')):- tok = stream.read(1)- tok = readNonWhitespace(stream)- stream.seek(-1, 1)- return readObject(stream, pdf)- else:- # number object OR indirect reference- if tok in NumberSigns:- # number- return NumberObject.readFromStream(stream)- peek = stream.read(20)- stream.seek(-len(peek), 1) # reset to start- if IndirectPattern.match(peek) != None:- return IndirectObject.readFromStream(stream, pdf)- else:- return NumberObject.readFromStream(stream)---class PdfObject(object):- def getObject(self):- """Resolves indirect references."""- return self---class NullObject(PdfObject):- def writeToStream(self, stream, encryption_key):- stream.write(b_("null"))-- def readFromStream(stream):- nulltxt = stream.read(4)- if nulltxt != b_("null"):- raise utils.PdfReadError("Could not read Null object")- return NullObject()- readFromStream = staticmethod(readFromStream)---class BooleanObject(PdfObject):- def __init__(self, value):- self.value = value-- def writeToStream(self, stream, encryption_key):- if self.value:- stream.write(b_("true"))- else:- stream.write(b_("false"))-- def readFromStream(stream):- word = stream.read(4)- if word == b_("true"):- return BooleanObject(True)- elif word == b_("fals"):- stream.read(1)- return BooleanObject(False)- else:- raise utils.PdfReadError('Could not read Boolean object')- readFromStream = staticmethod(readFromStream)---class ArrayObject(list, PdfObject):- def writeToStream(self, stream, encryption_key):- stream.write(b_("["))- for data in self:- stream.write(b_(" "))- data.writeToStream(stream, encryption_key)- stream.write(b_(" ]"))-- def readFromStream(stream, pdf):- arr = ArrayObject()- tmp = stream.read(1)- if tmp != b_("["):- raise utils.PdfReadError("Could not read array")- while True:- # skip leading whitespace- tok = stream.read(1)- while tok.isspace():- tok = stream.read(1)- stream.seek(-1, 1)- # check for array ending- peekahead = stream.read(1)- if peekahead == b_("]"):- break- stream.seek(-1, 1)- # read and append obj- arr.append(readObject(stream, pdf))- return arr- readFromStream = staticmethod(readFromStream)---class IndirectObject(PdfObject):- def __init__(self, idnum, generation, pdf):- self.idnum = idnum- self.generation = generation- self.pdf = pdf-- def getObject(self):- return self.pdf.getObject(self).getObject()-- def __repr__(self):- return "IndirectObject(%r, %r)" % (self.idnum, self.generation)-- def __eq__(self, other):- return (- other != None and- isinstance(other, IndirectObject) and- self.idnum == other.idnum and- self.generation == other.generation and- self.pdf is other.pdf- )-- def __ne__(self, other):- return not self.__eq__(other)-- def writeToStream(self, stream, encryption_key):- stream.write(b_("%s %s R" % (self.idnum, self.generation)))-- def readFromStream(stream, pdf):- idnum = b_("")- while True:- tok = stream.read(1)- if not tok:- # stream has truncated prematurely- raise PdfStreamError("Stream has ended unexpectedly")- if tok.isspace():- break- idnum += tok- generation = b_("")- while True:- tok = stream.read(1)- if not tok:- # stream has truncated prematurely- raise PdfStreamError("Stream has ended unexpectedly")- if tok.isspace():- if not generation:- continue- break- generation += tok- r = readNonWhitespace(stream)- if r != b_("R"):- raise utils.PdfReadError("Error reading indirect object reference at byte %s" % utils.hexStr(stream.tell()))- return IndirectObject(int(idnum), int(generation), pdf)- readFromStream = staticmethod(readFromStream)---class FloatObject(decimal.Decimal, PdfObject):- def __new__(cls, value="0", context=None):- try:- return decimal.Decimal.__new__(cls, utils.str_(value), context)- except:- return decimal.Decimal.__new__(cls, str(value))-- def __repr__(self):- if self == self.to_integral():- return str(self.quantize(decimal.Decimal(1)))- else:- # Standard formatting adds useless extraneous zeros.- o = "%.5f" % self- # Remove the zeros.- while o and o[-1] == '0':- o = o[:-1]- return o-- def as_numeric(self):- return float(b_(repr(self)))-- def writeToStream(self, stream, encryption_key):- stream.write(b_(repr(self)))---class NumberObject(int, PdfObject):- NumberPattern = re.compile(b_('[^+-.0-9]'))- ByteDot = b_(".")-- def __new__(cls, value):- val = int(value)- try:- return int.__new__(cls, val)- except OverflowError:- return int.__new__(cls, 0)-- def as_numeric(self):- return int(b_(repr(self)))-- def writeToStream(self, stream, encryption_key):- stream.write(b_(repr(self)))-- def readFromStream(stream):- num = utils.readUntilRegex(stream, NumberObject.NumberPattern)- if num.find(NumberObject.ByteDot) != -1:- return FloatObject(num)- else:- return NumberObject(num)- readFromStream = staticmethod(readFromStream)---##-# Given a string (either a "str" or "unicode"), create a ByteStringObject or a-# TextStringObject to represent the string.-def createStringObject(string):- if isinstance(string, utils.string_type):- return TextStringObject(string)- elif isinstance(string, utils.bytes_type):- try:- if string.startswith(codecs.BOM_UTF16_BE):- retval = TextStringObject(string.decode("utf-16"))- retval.autodetect_utf16 = True- return retval- else:- # This is probably a big performance hit here, but we need to- # convert string objects into the text/unicode-aware version if- # possible... and the only way to check if that's possible is- # to try. Some strings are strings, some are just byte arrays.- retval = TextStringObject(decode_pdfdocencoding(string))- retval.autodetect_pdfdocencoding = True- return retval- except UnicodeDecodeError:- return ByteStringObject(string)- else:- raise TypeError("createStringObject should have str or unicode arg")---def readHexStringFromStream(stream):- stream.read(1)- txt = ""- x = b_("")- while True:- tok = readNonWhitespace(stream)- if not tok:- # stream has truncated prematurely- raise PdfStreamError("Stream has ended unexpectedly")- if tok == b_(">"):- break- x += tok- if len(x) == 2:- txt += chr(int(x, base=16))- x = b_("")- if len(x) == 1:- x += b_("0")- if len(x) == 2:- txt += chr(int(x, base=16))- return createStringObject(b_(txt))---def readStringFromStream(stream):- tok = stream.read(1)- parens = 1- txt = b_("")- while True:- tok = stream.read(1)- if not tok:- # stream has truncated prematurely- raise PdfStreamError("Stream has ended unexpectedly")- if tok == b_("("):- parens += 1- elif tok == b_(")"):- parens -= 1- if parens == 0:- break- elif tok == b_("\\"):- tok = stream.read(1)- if tok == b_("n"):- tok = b_("\n")- elif tok == b_("r"):- tok = b_("\r")- elif tok == b_("t"):- tok = b_("\t")- elif tok == b_("b"):- tok = b_("\b")- elif tok == b_("f"):- tok = b_("\f")- elif tok == b_("c"):- tok = b_("\c")- elif tok == b_("("):- tok = b_("(")- elif tok == b_(")"):- tok = b_(")")- elif tok == b_("/"):- tok = b_("/")- elif tok == b_("\\"):- tok = b_("\\")- elif tok in (b_(" "), b_("/"), b_("%"), b_("<"), b_(">"), b_("["),- b_("]"), b_("#"), b_("_"), b_("&"), b_('$')):- # odd/unnessecary escape sequences we have encountered- tok = b_(tok)- elif tok.isdigit():- # "The number ddd may consist of one, two, or three- # octal digits; high-order overflow shall be ignored.- # Three octal digits shall be used, with leading zeros- # as needed, if the next character of the string is also- # a digit." (PDF reference 7.3.4.2, p 16)- for i in range(2):- ntok = stream.read(1)- if ntok.isdigit():- tok += ntok- else:- break- tok = b_(chr(int(tok, base=8)))- elif tok in b_("\n\r"):- # This case is hit when a backslash followed by a line- # break occurs. If it's a multi-char EOL, consume the- # second character:- tok = stream.read(1)- if not tok in b_("\n\r"):- stream.seek(-1, 1)- # Then don't add anything to the actual string, since this- # line break was escaped:- tok = b_('')- else:- raise utils.PdfReadError(r"Unexpected escaped string: %s" % tok)- txt += tok- return createStringObject(txt)---##-# Represents a string object where the text encoding could not be determined.-# This occurs quite often, as the PDF spec doesn't provide an alternate way to-# represent strings -- for example, the encryption data stored in files (like-# /O) is clearly not text, but is still stored in a "String" object.-class ByteStringObject(utils.bytes_type, PdfObject):-- ##- # For compatibility with TextStringObject.original_bytes. This method- # returns self.- original_bytes = property(lambda self: self)-- def writeToStream(self, stream, encryption_key):- bytearr = self- if encryption_key:- bytearr = RC4_encrypt(encryption_key, bytearr)- stream.write(b_("<"))- stream.write(utils.hexencode(bytearr))- stream.write(b_(">"))---##-# Represents a string object that has been decoded into a real unicode string.-# If read from a PDF document, this string appeared to match the-# PDFDocEncoding, or contained a UTF-16BE BOM mark to cause UTF-16 decoding to-# occur.-class TextStringObject(utils.string_type, PdfObject):- autodetect_pdfdocencoding = False- autodetect_utf16 = False-- ##- # It is occasionally possible that a text string object gets created where- # a byte string object was expected due to the autodetection mechanism --- # if that occurs, this "original_bytes" property can be used to- # back-calculate what the original encoded bytes were.- original_bytes = property(lambda self: self.get_original_bytes())-- def get_original_bytes(self):- # We're a text string object, but the library is trying to get our raw- # bytes. This can happen if we auto-detected this string as text, but- # we were wrong. It's pretty common. Return the original bytes that- # would have been used to create this object, based upon the autodetect- # method.- if self.autodetect_utf16:- return codecs.BOM_UTF16_BE + self.encode("utf-16be")- elif self.autodetect_pdfdocencoding:- return encode_pdfdocencoding(self)- else:- raise Exception("no information about original bytes")-- def writeToStream(self, stream, encryption_key):- # Try to write the string out as a PDFDocEncoding encoded string. It's- # nicer to look at in the PDF file. Sadly, we take a performance hit- # here for trying...- try:- bytearr = encode_pdfdocencoding(self)- except UnicodeEncodeError:- bytearr = codecs.BOM_UTF16_BE + self.encode("utf-16be")- if encryption_key:- bytearr = RC4_encrypt(encryption_key, bytearr)- obj = ByteStringObject(bytearr)- obj.writeToStream(stream, None)- else:- stream.write(b_("("))- for c in bytearr:- if not chr_(c).isalnum() and c != b_(' '):- stream.write(b_("\\%03o" % ord_(c)))- else:- stream.write(b_(chr_(c)))- stream.write(b_(")"))---class NameObject(str, PdfObject):- delimiterPattern = re.compile(b_(r"\s+|[\(\)<>\[\]{}/%]"))- surfix = b_("/")-- def writeToStream(self, stream, encryption_key):- stream.write(b_(self))-- def readFromStream(stream, pdf):- debug = False- if debug: print((stream.tell()))- name = stream.read(1)- if name != NameObject.surfix:- raise utils.PdfReadError("name read error")- name += utils.readUntilRegex(stream, NameObject.delimiterPattern,- ignore_eof=True)- if debug: print(name)- try:- return NameObject(name.decode('utf-8'))- except (UnicodeEncodeError, UnicodeDecodeError) as e:- # Name objects should represent irregular characters- # with a '#' followed by the symbol's hex number- if not pdf.strict:- warnings.warn("Illegal character in Name Object", utils.PdfReadWarning)- return NameObject(name)- else:- raise utils.PdfReadError("Illegal character in Name Object")-- readFromStream = staticmethod(readFromStream)---class DictionaryObject(dict, PdfObject):- def raw_get(self, key):- return dict.__getitem__(self, key)-- def __setitem__(self, key, value):- if not isinstance(key, PdfObject):- raise ValueError("key must be PdfObject")- if not isinstance(value, PdfObject):- raise ValueError("value must be PdfObject")- return dict.__setitem__(self, key, value)-- def setdefault(self, key, value=None):- if not isinstance(key, PdfObject):- raise ValueError("key must be PdfObject")- if not isinstance(value, PdfObject):- raise ValueError("value must be PdfObject")- return dict.setdefault(self, key, value)-- def __getitem__(self, key):- return dict.__getitem__(self, key).getObject()-- ##- # Retrieves XMP (Extensible Metadata Platform) data relevant to the- # this object, if available.- # <p>- # Stability: Added in v1.12, will exist for all future v1.x releases.- # @return Returns a {@link #xmp.XmpInformation XmlInformation} instance- # that can be used to access XMP metadata from the document. Can also- # return None if no metadata was found on the document root.- def getXmpMetadata(self):- metadata = self.get("/Metadata", None)- if metadata == None:- return None- metadata = metadata.getObject()- from . import xmp- if not isinstance(metadata, xmp.XmpInformation):- metadata = xmp.XmpInformation(metadata)- self[NameObject("/Metadata")] = metadata- return metadata-- ##- # Read-only property that accesses the {@link- # #DictionaryObject.getXmpData getXmpData} function.- # <p>- # Stability: Added in v1.12, will exist for all future v1.x releases.- xmpMetadata = property(lambda self: self.getXmpMetadata(), None, None)-- def writeToStream(self, stream, encryption_key):- stream.write(b_("<<\n"))- for key, value in list(self.items()):- key.writeToStream(stream, encryption_key)- stream.write(b_(" "))- value.writeToStream(stream, encryption_key)- stream.write(b_("\n"))- stream.write(b_(">>"))-- def readFromStream(stream, pdf):- debug = False- tmp = stream.read(2)- if tmp != b_("<<"):- raise utils.PdfReadError("Dictionary read error at byte %s: stream must begin with '<<'" % utils.hexStr(stream.tell()))- data = {}- while True:- tok = readNonWhitespace(stream)- if tok == b_('\x00'):- continue- elif tok == b_('%'):- stream.seek(-1, 1)- skipOverComment(stream)- continue- if not tok:- # stream has truncated prematurely- raise PdfStreamError("Stream has ended unexpectedly")-- if debug: print(("Tok:", tok))- if tok == b_(">"):- stream.read(1)- break- stream.seek(-1, 1)- key = readObject(stream, pdf)- tok = readNonWhitespace(stream)- stream.seek(-1, 1)- value = readObject(stream, pdf)- if not data.get(key):- data[key] = value- elif pdf.strict:- # multiple definitions of key not permitted- raise utils.PdfReadError("Multiple definitions in dictionary at byte %s for key %s" \- % (utils.hexStr(stream.tell()), key))- else:- warnings.warn("Multiple definitions in dictionary at byte %s for key %s" \- % (utils.hexStr(stream.tell()), key), utils.PdfReadWarning)-- pos = stream.tell()- s = readNonWhitespace(stream)- if s == b_('s') and stream.read(5) == b_('tream'):- eol = stream.read(1)- # odd PDF file output has spaces after 'stream' keyword but before EOL.- # patch provided by Danial Sandler- while eol == b_(' '):- eol = stream.read(1)- assert eol in (b_("\n"), b_("\r"))- if eol == b_("\r"):- # read \n after- if stream.read(1) != b_('\n'):- stream.seek(-1, 1)- # this is a stream object, not a dictionary- assert "/Length" in data- length = data["/Length"]- if debug: print(data)- if isinstance(length, IndirectObject):- t = stream.tell()- length = pdf.getObject(length)- stream.seek(t, 0)- data["__streamdata__"] = stream.read(length)- if debug: print("here")- #if debug: print(binascii.hexlify(data["__streamdata__"]))- e = readNonWhitespace(stream)- ndstream = stream.read(8)- if (e + ndstream) != b_("endstream"):- # (sigh) - the odd PDF file has a length that is too long, so- # we need to read backwards to find the "endstream" ending.- # ReportLab (unknown version) generates files with this bug,- # and Python users into PDF files tend to be our audience.- # we need to do this to correct the streamdata and chop off- # an extra character.- pos = stream.tell()- stream.seek(-10, 1)- end = stream.read(9)- if end == b_("endstream"):- # we found it by looking back one character further.- data["__streamdata__"] = data["__streamdata__"][:-1]- else:- if debug: print(("E", e, ndstream, debugging.toHex(end)))- stream.seek(pos, 0)- raise utils.PdfReadError("Unable to find 'endstream' marker after stream at byte %s." % utils.hexStr(stream.tell()))- else:- stream.seek(pos, 0)- if "__streamdata__" in data:- return StreamObject.initializeFromDictionary(data)- else:- retval = DictionaryObject()- retval.update(data)- return retval- readFromStream = staticmethod(readFromStream)---class TreeObject(DictionaryObject):- def __init__(self):- DictionaryObject.__init__(self)-- def hasChildren(self):- return '/First' in self-- def __iter__(self):- return self.children()-- def children(self):- if not self.hasChildren():- raise StopIteration-- child = self['/First']- while True:- yield child- if child == self['/Last']:- raise StopIteration- child = child['/Next']-- def addChild(self, child, pdf):- childObj = child.getObject()- child = pdf.getReference(childObj)- assert isinstance(child, IndirectObject)-- if '/First' not in self:- self[NameObject('/First')] = child- self[NameObject('/Count')] = NumberObject(0)- prev = None- else:- prev = self['/Last']-- self[NameObject('/Last')] = child- self[NameObject('/Count')] = NumberObject(self[NameObject('/Count')] + 1)-- if prev:- prevRef = pdf.getReference(prev)- assert isinstance(prevRef, IndirectObject)- childObj[NameObject('/Prev')] = prevRef- prev[NameObject('/Next')] = child-- parentRef = pdf.getReference(self)- assert isinstance(parentRef, IndirectObject)- childObj[NameObject('/Parent')] = parentRef-- def removeChild(self, child):- childObj = child.getObject()-- if NameObject('/Parent') not in childObj:- raise ValueError("Removed child does not appear to be a tree item")- elif childObj[NameObject('/Parent')] != self:- raise ValueError("Removed child is not a member of this tree")-- found = False- prevRef = None- prev = None- curRef = self[NameObject('/First')]- cur = curRef.getObject()- lastRef = self[NameObject('/Last')]- last = lastRef.getObject()- while cur != None:- if cur == childObj:- if prev == None:- if NameObject('/Next') in cur:- # Removing first tree node- nextRef = cur[NameObject('/Next')]- next = nextRef.getObject()- del next[NameObject('/Prev')]- self[NameObject('/First')] = nextRef- self[NameObject('/Count')] = self[NameObject('/Count')] - 1-- else:- # Removing only tree node- assert self[NameObject('/Count')] == 1- del self[NameObject('/Count')]- del self[NameObject('/First')]- if NameObject('/Last') in self:- del self[NameObject('/Last')]- else:- if NameObject('/Next') in cur:- # Removing middle tree node- nextRef = cur[NameObject('/Next')]- next = nextRef.getObject()- next[NameObject('/Prev')] = prevRef- prev[NameObject('/Next')] = nextRef- self[NameObject('/Count')] = self[NameObject('/Count')] - 1- else:- # Removing last tree node- assert cur == last- del prev[NameObject('/Next')]- self[NameObject('/Last')] = prevRef- self[NameObject('/Count')] = self[NameObject('/Count')] - 1- found = True- break-- prevRef = curRef- prev = cur- if NameObject('/Next') in cur:- curRef = cur[NameObject('/Next')]- cur = curRef.getObject()- else:- curRef = None- cur = None-- if not found:- raise ValueError("Removal couldn't find item in tree")-- del childObj[NameObject('/Parent')]- if NameObject('/Next') in childObj:- del childObj[NameObject('/Next')]- if NameObject('/Prev') in childObj:- del childObj[NameObject('/Prev')]-- def emptyTree(self):- for child in self:- childObj = child.getObject()- del childObj[NameObject('/Parent')]- if NameObject('/Next') in childObj:- del childObj[NameObject('/Next')]- if NameObject('/Prev') in childObj:- del childObj[NameObject('/Prev')]-- if NameObject('/Count') in self:- del self[NameObject('/Count')]- if NameObject('/First') in self:- del self[NameObject('/First')]- if NameObject('/Last') in self:- del self[NameObject('/Last')]---class StreamObject(DictionaryObject):- def __init__(self):- self._data = None- self.decodedSelf = None-- def writeToStream(self, stream, encryption_key):- self[NameObject("/Length")] = NumberObject(len(self._data))- DictionaryObject.writeToStream(self, stream, encryption_key)- del self["/Length"]- stream.write(b_("\nstream\n"))- data = self._data- if encryption_key:- data = RC4_encrypt(encryption_key, data)- stream.write(data)- stream.write(b_("\nendstream"))-- def initializeFromDictionary(data):- if "/Filter" in data:- retval = EncodedStreamObject()- else:- retval = DecodedStreamObject()- retval._data = data["__streamdata__"]- del data["__streamdata__"]- del data["/Length"]- retval.update(data)- return retval- initializeFromDictionary = staticmethod(initializeFromDictionary)-- def flateEncode(self):- if "/Filter" in self:- f = self["/Filter"]- if isinstance(f, ArrayObject):- f.insert(0, NameObject("/FlateDecode"))- else:- newf = ArrayObject()- newf.append(NameObject("/FlateDecode"))- newf.append(f)- f = newf- else:- f = NameObject("/FlateDecode")- retval = EncodedStreamObject()- retval[NameObject("/Filter")] = f- retval._data = filters.FlateDecode.encode(self._data)- return retval---class DecodedStreamObject(StreamObject):- def getData(self):- return self._data-- def setData(self, data):- self._data = data---class EncodedStreamObject(StreamObject):- def __init__(self):- self.decodedSelf = None-- def getData(self):- if self.decodedSelf:- # cached version of decoded object- return self.decodedSelf.getData()- else:- # create decoded object- decoded = DecodedStreamObject()-- decoded._data = filters.decodeStreamData(self)- for key, value in list(self.items()):- if not key in ("/Length", "/Filter", "/DecodeParms"):- decoded[key] = value- self.decodedSelf = decoded- return decoded._data-- def setData(self, data):- raise utils.PdfReadError("Creating EncodedStreamObject is not currently supported")---class RectangleObject(ArrayObject):- """- This class is used to represent *page boxes* in PyPDF2. These boxes include:-- * :attr:`artBox <PyPDF2.pdf.PageObject.artBox>`- * :attr:`bleedBox <PyPDF2.pdf.PageObject.bleedBox>`- * :attr:`cropBox <PyPDF2.pdf.PageObject.cropBox>`- * :attr:`mediaBox <PyPDF2.pdf.PageObject.mediaBox>`- * :attr:`trimBox <PyPDF2.pdf.PageObject.trimBox>`- """- def __init__(self, arr):- # must have four points- assert len(arr) == 4- # automatically convert arr[x] into NumberObject(arr[x]) if necessary- ArrayObject.__init__(self, [self.ensureIsNumber(x) for x in arr])-- def ensureIsNumber(self, value):- if not isinstance(value, (NumberObject, FloatObject)):- value = FloatObject(value)- return value-- def __repr__(self):- return "RectangleObject(%s)" % repr(list(self))-- def getLowerLeft_x(self):- return self[0]-- def getLowerLeft_y(self):- return self[1]-- def getUpperRight_x(self):- return self[2]-- def getUpperRight_y(self):- return self[3]-- def getUpperLeft_x(self):- return self.getLowerLeft_x()-- def getUpperLeft_y(self):- return self.getUpperRight_y()-- def getLowerRight_x(self):- return self.getUpperRight_x()-- def getLowerRight_y(self):- return self.getLowerLeft_y()-- def getLowerLeft(self):- return self.getLowerLeft_x(), self.getLowerLeft_y()-- def getLowerRight(self):- return self.getLowerRight_x(), self.getLowerRight_y()-- def getUpperLeft(self):- return self.getUpperLeft_x(), self.getUpperLeft_y()-- def getUpperRight(self):- return self.getUpperRight_x(), self.getUpperRight_y()-- def setLowerLeft(self, value):- self[0], self[1] = [self.ensureIsNumber(x) for x in value]-- def setLowerRight(self, value):- self[2], self[1] = [self.ensureIsNumber(x) for x in value]-- def setUpperLeft(self, value):- self[0], self[3] = [self.ensureIsNumber(x) for x in value]-- def setUpperRight(self, value):- self[2], self[3] = [self.ensureIsNumber(x) for x in value]-- def getWidth(self):- return self.getUpperRight_x() - self.getLowerLeft_x()-- def getHeight(self):- return self.getUpperRight_y() - self.getLowerLeft_y()-- lowerLeft = property(getLowerLeft, setLowerLeft, None, None)- """- Property to read and modify the lower left coordinate of this box- in (x,y) form.- """- lowerRight = property(getLowerRight, setLowerRight, None, None)- """- Property to read and modify the lower right coordinate of this box- in (x,y) form.- """- upperLeft = property(getUpperLeft, setUpperLeft, None, None)- """- Property to read and modify the upper left coordinate of this box- in (x,y) form.- """- upperRight = property(getUpperRight, setUpperRight, None, None)- """- Property to read and modify the upper right coordinate of this box- in (x,y) form.- """---class Field(TreeObject):- """- A class representing a field dictionary. This class is accessed through- :meth:`getFields()<PyPDF2.PdfFileReader.getFields>`- """- def __init__(self, data):- DictionaryObject.__init__(self)- attributes = ("/FT", "/Parent", "/Kids", "/T", "/TU", "/TM", "/Ff",- "/V", "/DV", "/AA")- for attr in attributes:- try:- self[NameObject(attr)] = data[attr]- except KeyError:- pass-- fieldType = property(lambda self: self.get("/FT"))- """- Read-only property accessing the type of this field.- """-- parent = property(lambda self: self.get("/Parent"))- """- Read-only property accessing the parent of this field.- """-- kids = property(lambda self: self.get("/Kids"))- """- Read-only property accessing the kids of this field.- """-- name = property(lambda self: self.get("/T"))- """- Read-only property accessing the name of this field.- """-- altName = property(lambda self: self.get("/TU"))- """- Read-only property accessing the alternate name of this field.- """-- mappingName = property(lambda self: self.get("/TM"))- """- Read-only property accessing the mapping name of this field. This- name is used by PyPDF2 as a key in the dictionary returned by- :meth:`getFields()<PyPDF2.PdfFileReader.getFields>`- """-- flags = property(lambda self: self.get("/Ff"))- """- Read-only property accessing the field flags, specifying various- characteristics of the field (see Table 8.70 of the PDF 1.7 reference).- """-- value = property(lambda self: self.get("/V"))- """- Read-only property accessing the value of this field. Format- varies based on field type.- """-- defaultValue = property(lambda self: self.get("/DV"))- """- Read-only property accessing the default value of this field.- """-- additionalActions = property(lambda self: self.get("/AA"))- """- Read-only property accessing the additional actions dictionary.- This dictionary defines the field's behavior in response to trigger events.- See Section 8.5.2 of the PDF 1.7 reference.- """---class Destination(TreeObject):- """- A class representing a destination within a PDF file.- See section 8.2.1 of the PDF 1.6 reference.-- :param str title: Title of this destination.- :param int page: Page number of this destination.- :param str typ: How the destination is displayed.- :param args: Additional arguments may be necessary depending on the type.- :raises PdfReadError: If destination type is invalid.-- Valid ``typ`` arguments (see PDF spec for details):- /Fit No additional arguments- /XYZ [left] [top] [zoomFactor]- /FitH [top]- /FitV [left]- /FitR [left] [bottom] [right] [top]- /FitB No additional arguments- /FitBH [top]- /FitBV [left]- """- def __init__(self, title, page, typ, *args):- DictionaryObject.__init__(self)- self[NameObject("/Title")] = title- self[NameObject("/Page")] = page- self[NameObject("/Type")] = typ-- # from table 8.2 of the PDF 1.7 reference.- if typ == "/XYZ":- (self[NameObject("/Left")], self[NameObject("/Top")],- self[NameObject("/Zoom")]) = args- elif typ == "/FitR":- (self[NameObject("/Left")], self[NameObject("/Bottom")],- self[NameObject("/Right")], self[NameObject("/Top")]) = args- elif typ in ["/FitH", "/FitBH"]:- self[NameObject("/Top")], = args- elif typ in ["/FitV", "/FitBV"]:- self[NameObject("/Left")], = args- elif typ in ["/Fit", "/FitB"]:- pass- else:- raise utils.PdfReadError("Unknown Destination Type: %r" % typ)-- def getDestArray(self):- return ArrayObject([self.raw_get('/Page'), self['/Type']] + [self[x] for x in ['/Left', '/Bottom', '/Right', '/Top', '/Zoom'] if x in self])-- def writeToStream(self, stream, encryption_key):- stream.write(b_("<<\n"))- key = NameObject('/D')- key.writeToStream(stream, encryption_key)- stream.write(b_(" "))- value = self.getDestArray()- value.writeToStream(stream, encryption_key)-- key = NameObject("/S")- key.writeToStream(stream, encryption_key)- stream.write(b_(" "))- value = NameObject("/GoTo")- value.writeToStream(stream, encryption_key)-- stream.write(b_("\n"))- stream.write(b_(">>"))-- title = property(lambda self: self.get("/Title"))- """- Read-only property accessing the destination title.-- :rtype: str- """-- page = property(lambda self: self.get("/Page"))- """- Read-only property accessing the destination page number.-- :rtype: int- """-- typ = property(lambda self: self.get("/Type"))- """- Read-only property accessing the destination type.-- :rtype: str- """-- zoom = property(lambda self: self.get("/Zoom", None))- """- Read-only property accessing the zoom factor.-- :rtype: int, or ``None`` if not available.- """-- left = property(lambda self: self.get("/Left", None))- """- Read-only property accessing the left horizontal coordinate.-- :rtype: int, or ``None`` if not available.- """-- right = property(lambda self: self.get("/Right", None))- """- Read-only property accessing the right horizontal coordinate.-- :rtype: int, or ``None`` if not available.- """-- top = property(lambda self: self.get("/Top", None))- """- Read-only property accessing the top vertical coordinate.-- :rtype: int, or ``None`` if not available.- """-- bottom = property(lambda self: self.get("/Bottom", None))- """- Read-only property accessing the bottom vertical coordinate.-- :rtype: int, or ``None`` if not available.- """---class Bookmark(Destination):- def writeToStream(self, stream, encryption_key):- stream.write(b_("<<\n"))- for key in [NameObject(x) for x in ['/Title', '/Parent', '/First', '/Last', '/Next', '/Prev'] if x in self]:- key.writeToStream(stream, encryption_key)- stream.write(b_(" "))- value = self.raw_get(key)- value.writeToStream(stream, encryption_key)- stream.write(b_("\n"))- key = NameObject('/Dest')- key.writeToStream(stream, encryption_key)- stream.write(b_(" "))- value = self.getDestArray()- value.writeToStream(stream, encryption_key)- stream.write(b_("\n"))- stream.write(b_(">>"))---def encode_pdfdocencoding(unicode_string):- retval = b_('')- for c in unicode_string:- try:- retval += b_(chr(_pdfDocEncoding_rev[c]))- except KeyError:- raise UnicodeEncodeError("pdfdocencoding", c, -1, -1,- "does not exist in translation table")- return retval---def decode_pdfdocencoding(byte_array):- retval = u_('')- for b in byte_array:- c = _pdfDocEncoding[ord_(b)]- if c == u_('\u0000'):- raise UnicodeDecodeError("pdfdocencoding", utils.barray(b), -1, -1,- "does not exist in translation table")- retval += c- return retval--_pdfDocEncoding = (- u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'),- u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'),- u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'), u_('\u0000'),- u_('\u02d8'), u_('\u02c7'), u_('\u02c6'), u_('\u02d9'), u_('\u02dd'), u_('\u02db'), u_('\u02da'), u_('\u02dc'),- u_('\u0020'), u_('\u0021'), u_('\u0022'), u_('\u0023'), u_('\u0024'), u_('\u0025'), u_('\u0026'), u_('\u0027'),- u_('\u0028'), u_('\u0029'), u_('\u002a'), u_('\u002b'), u_('\u002c'), u_('\u002d'), u_('\u002e'), u_('\u002f'),- u_('\u0030'), u_('\u0031'), u_('\u0032'), u_('\u0033'), u_('\u0034'), u_('\u0035'), u_('\u0036'), u_('\u0037'),- u_('\u0038'), u_('\u0039'), u_('\u003a'), u_('\u003b'), u_('\u003c'), u_('\u003d'), u_('\u003e'), u_('\u003f'),- u_('\u0040'), u_('\u0041'), u_('\u0042'), u_('\u0043'), u_('\u0044'), u_('\u0045'), u_('\u0046'), u_('\u0047'),- u_('\u0048'), u_('\u0049'), u_('\u004a'), u_('\u004b'), u_('\u004c'), u_('\u004d'), u_('\u004e'), u_('\u004f'),- u_('\u0050'), u_('\u0051'), u_('\u0052'), u_('\u0053'), u_('\u0054'), u_('\u0055'), u_('\u0056'), u_('\u0057'),- u_('\u0058'), u_('\u0059'), u_('\u005a'), u_('\u005b'), u_('\u005c'), u_('\u005d'), u_('\u005e'), u_('\u005f'),- u_('\u0060'), u_('\u0061'), u_('\u0062'), u_('\u0063'), u_('\u0064'), u_('\u0065'), u_('\u0066'), u_('\u0067'),- u_('\u0068'), u_('\u0069'), u_('\u006a'), u_('\u006b'), u_('\u006c'), u_('\u006d'), u_('\u006e'), u_('\u006f'),- u_('\u0070'), u_('\u0071'), u_('\u0072'), u_('\u0073'), u_('\u0074'), u_('\u0075'), u_('\u0076'), u_('\u0077'),- u_('\u0078'), u_('\u0079'), u_('\u007a'), u_('\u007b'), u_('\u007c'), u_('\u007d'), u_('\u007e'), u_('\u0000'),- u_('\u2022'), u_('\u2020'), u_('\u2021'), u_('\u2026'), u_('\u2014'), u_('\u2013'), u_('\u0192'), u_('\u2044'),- u_('\u2039'), u_('\u203a'), u_('\u2212'), u_('\u2030'), u_('\u201e'), u_('\u201c'), u_('\u201d'), u_('\u2018'),- u_('\u2019'), u_('\u201a'), u_('\u2122'), u_('\ufb01'), u_('\ufb02'), u_('\u0141'), u_('\u0152'), u_('\u0160'),- u_('\u0178'), u_('\u017d'), u_('\u0131'), u_('\u0142'), u_('\u0153'), u_('\u0161'), u_('\u017e'), u_('\u0000'),- u_('\u20ac'), u_('\u00a1'), u_('\u00a2'), u_('\u00a3'), u_('\u00a4'), u_('\u00a5'), u_('\u00a6'), u_('\u00a7'),- u_('\u00a8'), u_('\u00a9'), u_('\u00aa'), u_('\u00ab'), u_('\u00ac'), u_('\u0000'), u_('\u00ae'), u_('\u00af'),- u_('\u00b0'), u_('\u00b1'), u_('\u00b2'), u_('\u00b3'), u_('\u00b4'), u_('\u00b5'), u_('\u00b6'), u_('\u00b7'),- u_('\u00b8'), u_('\u00b9'), u_('\u00ba'), u_('\u00bb'), u_('\u00bc'), u_('\u00bd'), u_('\u00be'), u_('\u00bf'),- u_('\u00c0'), u_('\u00c1'), u_('\u00c2'), u_('\u00c3'), u_('\u00c4'), u_('\u00c5'), u_('\u00c6'), u_('\u00c7'),- u_('\u00c8'), u_('\u00c9'), u_('\u00ca'), u_('\u00cb'), u_('\u00cc'), u_('\u00cd'), u_('\u00ce'), u_('\u00cf'),- u_('\u00d0'), u_('\u00d1'), u_('\u00d2'), u_('\u00d3'), u_('\u00d4'), u_('\u00d5'), u_('\u00d6'), u_('\u00d7'),- u_('\u00d8'), u_('\u00d9'), u_('\u00da'), u_('\u00db'), u_('\u00dc'), u_('\u00dd'), u_('\u00de'), u_('\u00df'),- u_('\u00e0'), u_('\u00e1'), u_('\u00e2'), u_('\u00e3'), u_('\u00e4'), u_('\u00e5'), u_('\u00e6'), u_('\u00e7'),- u_('\u00e8'), u_('\u00e9'), u_('\u00ea'), u_('\u00eb'), u_('\u00ec'), u_('\u00ed'), u_('\u00ee'), u_('\u00ef'),- u_('\u00f0'), u_('\u00f1'), u_('\u00f2'), u_('\u00f3'), u_('\u00f4'), u_('\u00f5'), u_('\u00f6'), u_('\u00f7'),- u_('\u00f8'), u_('\u00f9'), u_('\u00fa'), u_('\u00fb'), u_('\u00fc'), u_('\u00fd'), u_('\u00fe'), u_('\u00ff')-)--assert len(_pdfDocEncoding) == 256--_pdfDocEncoding_rev = {}-for i in range(256):- char = _pdfDocEncoding[i]- if char == u_("\u0000"):- continue- assert char not in _pdfDocEncoding_rev- _pdfDocEncoding_rev[char] = idiff --git a/ext/PyPDF2/merger.py b/ext/PyPDF2/merger.pydeleted file mode 100755index 27702add..00000000--- a/ext/PyPDF2/merger.py+++ /dev/null@@ -1,553 +0,0 @@-# vim: sw=4:expandtab:foldmethod=marker-#-# Copyright (c) 2006, Mathieu Fenniak-# All rights reserved.-#-# Redistribution and use in source and binary forms, with or without-# modification, are permitted provided that the following conditions are-# met:-#-# * Redistributions of source code must retain the above copyright notice,-# this list of conditions and the following disclaimer.-# * Redistributions in binary form must reproduce the above copyright notice,-# this list of conditions and the following disclaimer in the documentation-# and/or other materials provided with the distribution.-# * The name of the author may not be used to endorse or promote products-# derived from this software without specific prior written permission.-#-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE-# POSSIBILITY OF SUCH DAMAGE.--from .generic import *-from .utils import isString, str_-from .pdf import PdfFileReader, PdfFileWriter-from .pagerange import PageRange-from sys import version_info-if version_info < ( 3, 0 ):- from cStringIO import StringIO- StreamIO = StringIO-else:- from io import BytesIO- from io import FileIO as file- StreamIO = BytesIO---class _MergedPage(object):- """- _MergedPage is used internally by PdfFileMerger to collect necessary- information on each page that is being merged.- """- def __init__(self, pagedata, src, id):- self.src = src- self.pagedata = pagedata- self.out_pagedata = None- self.id = id---class PdfFileMerger(object):- """- Initializes a PdfFileMerger object. PdfFileMerger merges multiple PDFs- into a single PDF. It can concatenate, slice, insert, or any combination- of the above.-- See the functions :meth:`merge()<merge>` (or :meth:`append()<append>`)- and :meth:`write()<write>` for usage information.-- :param bool strict: Determines whether user should be warned of all- problems and also causes some correctable problems to be fatal.- Defaults to ``True``.- """-- def __init__(self, strict=True):- self.inputs = []- self.pages = []- self.output = PdfFileWriter()- self.bookmarks = []- self.named_dests = []- self.id_count = 0- self.strict = strict-- def merge(self, position, fileobj, bookmark=None, pages=None, import_bookmarks=True):- """- Merges the pages from the given file into the output file at the- specified page number.-- :param int position: The *page number* to insert this file. File will- be inserted after the given number.-- :param fileobj: A File Object or an object that supports the standard read- and seek methods similar to a File Object. Could also be a- string representing a path to a PDF file.-- :param str bookmark: Optionally, you may specify a bookmark to be applied at- the beginning of the included file by supplying the text of the bookmark.-- :param pages: can be a :ref:`Page Range <page-range>` or a ``(start, stop[, step])`` tuple- to merge only the specified range of pages from the source- document into the output document.-- :param bool import_bookmarks: You may prevent the source document's bookmarks- from being imported by specifying this as ``False``.- """-- # This parameter is passed to self.inputs.append and means- # that the stream used was created in this method.- my_file = False-- # If the fileobj parameter is a string, assume it is a path- # and create a file object at that location. If it is a file,- # copy the file's contents into a BytesIO (or StreamIO) stream object; if- # it is a PdfFileReader, copy that reader's stream into a- # BytesIO (or StreamIO) stream.- # If fileobj is none of the above types, it is not modified- decryption_key = None- if isString(fileobj):- fileobj = file(fileobj, 'rb')- my_file = True- elif isinstance(fileobj, file):- fileobj.seek(0)- filecontent = fileobj.read()- fileobj = StreamIO(filecontent)- my_file = True- elif isinstance(fileobj, PdfFileReader):- orig_tell = fileobj.stream.tell()- fileobj.stream.seek(0)- filecontent = StreamIO(fileobj.stream.read())- fileobj.stream.seek(orig_tell) # reset the stream to its original location- fileobj = filecontent- if hasattr(fileobj, '_decryption_key'):- decryption_key = fileobj._decryption_key- my_file = True-- # Create a new PdfFileReader instance using the stream- # (either file or BytesIO or StringIO) created above- pdfr = PdfFileReader(fileobj, strict=self.strict)- if decryption_key is not None:- pdfr._decryption_key = decryption_key-- # Find the range of pages to merge.- if pages == None:- pages = (0, pdfr.getNumPages())- elif isinstance(pages, PageRange):- pages = pages.indices(pdfr.getNumPages())- elif not isinstance(pages, tuple):- raise TypeError('"pages" must be a tuple of (start, stop[, step])')-- srcpages = []- if bookmark:- bookmark = Bookmark(TextStringObject(bookmark), NumberObject(self.id_count), NameObject('/Fit'))-- outline = []- if import_bookmarks:- outline = pdfr.getOutlines()- outline = self._trim_outline(pdfr, outline, pages)-- if bookmark:- self.bookmarks += [bookmark, outline]- else:- self.bookmarks += outline-- dests = pdfr.namedDestinations- dests = self._trim_dests(pdfr, dests, pages)- self.named_dests += dests-- # Gather all the pages that are going to be merged- for i in range(*pages):- pg = pdfr.getPage(i)-- id = self.id_count- self.id_count += 1-- mp = _MergedPage(pg, pdfr, id)-- srcpages.append(mp)-- self._associate_dests_to_pages(srcpages)- self._associate_bookmarks_to_pages(srcpages)-- # Slice to insert the pages at the specified position- self.pages[position:position] = srcpages-- # Keep track of our input files so we can close them later- self.inputs.append((fileobj, pdfr, my_file))-- def append(self, fileobj, bookmark=None, pages=None, import_bookmarks=True):- """- Identical to the :meth:`merge()<merge>` method, but assumes you want to concatenate- all pages onto the end of the file instead of specifying a position.-- :param fileobj: A File Object or an object that supports the standard read- and seek methods similar to a File Object. Could also be a- string representing a path to a PDF file.-- :param str bookmark: Optionally, you may specify a bookmark to be applied at- the beginning of the included file by supplying the text of the bookmark.-- :param pages: can be a :ref:`Page Range <page-range>` or a ``(start, stop[, step])`` tuple- to merge only the specified range of pages from the source- document into the output document.-- :param bool import_bookmarks: You may prevent the source document's bookmarks- from being imported by specifying this as ``False``.- """-- self.merge(len(self.pages), fileobj, bookmark, pages, import_bookmarks)-- def write(self, fileobj):- """- Writes all data that has been merged to the given output file.-- :param fileobj: Output file. Can be a filename or any kind of- file-like object.- """- my_file = False- if isString(fileobj):- fileobj = file(fileobj, 'wb')- my_file = True-- # Add pages to the PdfFileWriter- # The commented out line below was replaced with the two lines below it to allow PdfFileMerger to work with PyPdf 1.13- for page in self.pages:- self.output.addPage(page.pagedata)- page.out_pagedata = self.output.getReference(self.output._pages.getObject()["/Kids"][-1].getObject())- #idnum = self.output._objects.index(self.output._pages.getObject()["/Kids"][-1].getObject()) + 1- #page.out_pagedata = IndirectObject(idnum, 0, self.output)-- # Once all pages are added, create bookmarks to point at those pages- self._write_dests()- self._write_bookmarks()-- # Write the output to the file- self.output.write(fileobj)-- if my_file:- fileobj.close()-- def close(self):- """- Shuts all file descriptors (input and output) and clears all memory- usage.- """- self.pages = []- for fo, pdfr, mine in self.inputs:- if mine:- fo.close()-- self.inputs = []- self.output = None-- def addMetadata(self, infos):- """- Add custom metadata to the output.-- :param dict infos: a Python dictionary where each key is a field- and each value is your new metadata.- Example: ``{u'/Title': u'My title'}``- """- self.output.addMetadata(infos)-- def setPageLayout(self, layout):- """- Set the page layout-- :param str layout: The page layout to be used-- Valid layouts are:- /NoLayout Layout explicitly not specified- /SinglePage Show one page at a time- /OneColumn Show one column at a time- /TwoColumnLeft Show pages in two columns, odd-numbered pages on the left- /TwoColumnRight Show pages in two columns, odd-numbered pages on the right- /TwoPageLeft Show two pages at a time, odd-numbered pages on the left- /TwoPageRight Show two pages at a time, odd-numbered pages on the right- """- self.output.setPageLayout(layout)-- def setPageMode(self, mode):- """- Set the page mode.-- :param str mode: The page mode to use.-- Valid modes are:- /UseNone Do not show outlines or thumbnails panels- /UseOutlines Show outlines (aka bookmarks) panel- /UseThumbs Show page thumbnails panel- /FullScreen Fullscreen view- /UseOC Show Optional Content Group (OCG) panel- /UseAttachments Show attachments panel- """- self.output.setPageMode(mode)-- def _trim_dests(self, pdf, dests, pages):- """- Removes any named destinations that are not a part of the specified- page set.- """- new_dests = []- prev_header_added = True- for k, o in list(dests.items()):- for j in range(*pages):- if pdf.getPage(j).getObject() == o['/Page'].getObject():- o[NameObject('/Page')] = o['/Page'].getObject()- assert str_(k) == str_(o['/Title'])- new_dests.append(o)- break- return new_dests-- def _trim_outline(self, pdf, outline, pages):- """- Removes any outline/bookmark entries that are not a part of the- specified page set.- """- new_outline = []- prev_header_added = True- for i, o in enumerate(outline):- if isinstance(o, list):- sub = self._trim_outline(pdf, o, pages)- if sub:- if not prev_header_added:- new_outline.append(outline[i-1])- new_outline.append(sub)- else:- prev_header_added = False- for j in range(*pages):- if pdf.getPage(j).getObject() == o['/Page'].getObject():- o[NameObject('/Page')] = o['/Page'].getObject()- new_outline.append(o)- prev_header_added = True- break- return new_outline-- def _write_dests(self):- dests = self.named_dests-- for v in dests:- pageno = None- pdf = None- if '/Page' in v:- for i, p in enumerate(self.pages):- if p.id == v['/Page']:- v[NameObject('/Page')] = p.out_pagedata- pageno = i- pdf = p.src- break- if pageno != None:- self.output.addNamedDestinationObject(v)-- def _write_bookmarks(self, bookmarks=None, parent=None):-- if bookmarks == None:- bookmarks = self.bookmarks-- last_added = None- for b in bookmarks:- if isinstance(b, list):- self._write_bookmarks(b, last_added)- continue-- pageno = None- pdf = None- if '/Page' in b:- for i, p in enumerate(self.pages):- if p.id == b['/Page']:- #b[NameObject('/Page')] = p.out_pagedata- args = [NumberObject(p.id), NameObject(b['/Type'])]- #nothing more to add- #if b['/Type'] == '/Fit' or b['/Type'] == '/FitB'- if b['/Type'] == '/FitH' or b['/Type'] == '/FitBH':- if '/Top' in b and not isinstance(b['/Top'], NullObject):- args.append(FloatObject(b['/Top']))- else:- args.append(FloatObject(0))- del b['/Top']- elif b['/Type'] == '/FitV' or b['/Type'] == '/FitBV':- if '/Left' in b and not isinstance(b['/Left'], NullObject):- args.append(FloatObject(b['/Left']))- else:- args.append(FloatObject(0))- del b['/Left']- elif b['/Type'] == '/XYZ':- if '/Left' in b and not isinstance(b['/Left'], NullObject):- args.append(FloatObject(b['/Left']))- else:- args.append(FloatObject(0))- if '/Top' in b and not isinstance(b['/Top'], NullObject):- args.append(FloatObject(b['/Top']))- else:- args.append(FloatObject(0))- if '/Zoom' in b and not isinstance(b['/Zoom'], NullObject):- args.append(FloatObject(b['/Zoom']))- else:- args.append(FloatObject(0))- del b['/Top'], b['/Zoom'], b['/Left']- elif b['/Type'] == '/FitR':- if '/Left' in b and not isinstance(b['/Left'], NullObject):- args.append(FloatObject(b['/Left']))- else:- args.append(FloatObject(0))- if '/Bottom' in b and not isinstance(b['/Bottom'], NullObject):- args.append(FloatObject(b['/Bottom']))- else:- args.append(FloatObject(0))- if '/Right' in b and not isinstance(b['/Right'], NullObject):- args.append(FloatObject(b['/Right']))- else:- args.append(FloatObject(0))- if '/Top' in b and not isinstance(b['/Top'], NullObject):- args.append(FloatObject(b['/Top']))- else:- args.append(FloatObject(0))- del b['/Left'], b['/Right'], b['/Bottom'], b['/Top']-- b[NameObject('/A')] = DictionaryObject({NameObject('/S'): NameObject('/GoTo'), NameObject('/D'): ArrayObject(args)})-- pageno = i- pdf = p.src- break- if pageno != None:- del b['/Page'], b['/Type']- last_added = self.output.addBookmarkDict(b, parent)-- def _associate_dests_to_pages(self, pages):- for nd in self.named_dests:- pageno = None- np = nd['/Page']-- if isinstance(np, NumberObject):- continue-- for p in pages:- if np.getObject() == p.pagedata.getObject():- pageno = p.id-- if pageno != None:- nd[NameObject('/Page')] = NumberObject(pageno)- else:- raise ValueError("Unresolved named destination '%s'" % (nd['/Title'],))-- def _associate_bookmarks_to_pages(self, pages, bookmarks=None):- if bookmarks == None:- bookmarks = self.bookmarks-- for b in bookmarks:- if isinstance(b, list):- self._associate_bookmarks_to_pages(pages, b)- continue-- pageno = None- bp = b['/Page']-- if isinstance(bp, NumberObject):- continue-- for p in pages:- if bp.getObject() == p.pagedata.getObject():- pageno = p.id-- if pageno != None:- b[NameObject('/Page')] = NumberObject(pageno)- else:- raise ValueError("Unresolved bookmark '%s'" % (b['/Title'],))-- def findBookmark(self, bookmark, root=None):- if root == None:- root = self.bookmarks-- for i, b in enumerate(root):- if isinstance(b, list):- res = self.findBookmark(bookmark, b)- if res:- return [i] + res- elif b == bookmark or b['/Title'] == bookmark:- return [i]-- return None-- def addBookmark(self, title, pagenum, parent=None):- """- Add a bookmark to this PDF file.-- :param str title: Title to use for this bookmark.- :param int pagenum: Page number this bookmark will point to.- :param parent: A reference to a parent bookmark to create nested- bookmarks.- """- if parent == None:- iloc = [len(self.bookmarks)-1]- elif isinstance(parent, list):- iloc = parent- else:- iloc = self.findBookmark(parent)-- dest = Bookmark(TextStringObject(title), NumberObject(pagenum), NameObject('/FitH'), NumberObject(826))-- if parent == None:- self.bookmarks.append(dest)- else:- bmparent = self.bookmarks- for i in iloc[:-1]:- bmparent = bmparent[i]- npos = iloc[-1]+1- if npos < len(bmparent) and isinstance(bmparent[npos], list):- bmparent[npos].append(dest)- else:- bmparent.insert(npos, [dest])- return dest-- def addNamedDestination(self, title, pagenum):- """- Add a destination to the output.-- :param str title: Title to use- :param int pagenum: Page number this destination points at.- """-- dest = Destination(TextStringObject(title), NumberObject(pagenum), NameObject('/FitH'), NumberObject(826))- self.named_dests.append(dest)---class OutlinesObject(list):- def __init__(self, pdf, tree, parent=None):- list.__init__(self)- self.tree = tree- self.pdf = pdf- self.parent = parent-- def remove(self, index):- obj = self[index]- del self[index]- self.tree.removeChild(obj)-- def add(self, title, pagenum):- pageRef = self.pdf.getObject(self.pdf._pages)['/Kids'][pagenum]- action = DictionaryObject()- action.update({- NameObject('/D') : ArrayObject([pageRef, NameObject('/FitH'), NumberObject(826)]),- NameObject('/S') : NameObject('/GoTo')- })- actionRef = self.pdf._addObject(action)- bookmark = TreeObject()-- bookmark.update({- NameObject('/A'): actionRef,- NameObject('/Title'): createStringObject(title),- })-- self.pdf._addObject(bookmark)-- self.tree.addChild(bookmark)-- def removeAll(self):- for child in [x for x in self.tree.children()]:- self.tree.removeChild(child)- self.pop()diff --git a/ext/PyPDF2/pagerange.py b/ext/PyPDF2/pagerange.pydeleted file mode 100755index ce96ec5f..00000000--- a/ext/PyPDF2/pagerange.py+++ /dev/null@@ -1,152 +0,0 @@-#!/usr/bin/env python-"""-Representation and utils for ranges of PDF file pages.--Copyright (c) 2014, Steve Witham <[email protected]>.-All rights reserved. This software is available under a BSD license;-see https://github.com/mstamy2/PyPDF2/blob/master/LICENSE-"""--import re-from .utils import isString--_INT_RE = r"(0|-?[1-9]\d*)" # A decimal int, don't allow "-0".-PAGE_RANGE_RE = "^({int}|({int}?(:{int}?(:{int}?)?)))$".format(int=_INT_RE)-# groups: 12 34 5 6 7 8---class ParseError(Exception):- pass---PAGE_RANGE_HELP = """Remember, page indices start with zero.- Page range expression examples:- : all pages. -1 last page.- 22 just the 23rd page. :-1 all but the last page.- 0:3 the first three pages. -2 second-to-last page.- :3 the first three pages. -2: last two pages.- 5: from the sixth page onward. -3:-1 third & second to last.- The third, "stride" or "step" number is also recognized.- ::2 0 2 4 ... to the end. 3:0:-1 3 2 1 but not 0.- 1:10:2 1 3 5 7 9 2::-1 2 1 0.- ::-1 all pages in reverse order.-"""---class PageRange(object):- """- A slice-like representation of a range of page indices,- i.e. page numbers, only starting at zero.- The syntax is like what you would put between brackets [ ].- The slice is one of the few Python types that can't be subclassed,- but this class converts to and from slices, and allows similar use.- o PageRange(str) parses a string representing a page range.- o PageRange(slice) directly "imports" a slice.- o to_slice() gives the equivalent slice.- o str() and repr() allow printing.- o indices(n) is like slice.indices(n).- """-- def __init__(self, arg):- """- Initialize with either a slice -- giving the equivalent page range,- or a PageRange object -- making a copy,- or a string like- "int", "[int]:[int]" or "[int]:[int]:[int]",- where the brackets indicate optional ints.- {page_range_help}- Note the difference between this notation and arguments to slice():- slice(3) means the first three pages;- PageRange("3") means the range of only the fourth page.- However PageRange(slice(3)) means the first three pages.- """- if isinstance(arg, slice):- self._slice = arg- return-- if isinstance(arg, PageRange):- self._slice = arg.to_slice()- return-- m = isString(arg) and re.match(PAGE_RANGE_RE, arg)- if not m:- raise ParseError(arg)- elif m.group(2):- # Special case: just an int means a range of one page.- start = int(m.group(2))- stop = start + 1 if start != -1 else None- self._slice = slice(start, stop)- else:- self._slice = slice(*[int(g) if g else None- for g in m.group(4, 6, 8)])-- # Just formatting this when there is __doc__ for __init__- if __init__.__doc__:- __init__.__doc__ = __init__.__doc__.format(page_range_help=PAGE_RANGE_HELP)-- @staticmethod- def valid(input):- """ True if input is a valid initializer for a PageRange. """- return isinstance(input, slice) or \- isinstance(input, PageRange) or \- (isString(input)- and bool(re.match(PAGE_RANGE_RE, input)))-- def to_slice(self):- """ Return the slice equivalent of this page range. """- return self._slice-- def __str__(self):- """ A string like "1:2:3". """- s = self._slice- if s.step == None:- if s.start != None and s.stop == s.start + 1:- return str(s.start)-- indices = s.start, s.stop- else:- indices = s.start, s.stop, s.step- return ':'.join("" if i == None else str(i) for i in indices)-- def __repr__(self):- """ A string like "PageRange('1:2:3')". """- return "PageRange(" + repr(str(self)) + ")"-- def indices(self, n):- """- n is the length of the list of pages to choose from.- Returns arguments for range(). See help(slice.indices).- """- return self._slice.indices(n)---PAGE_RANGE_ALL = PageRange(":") # The range of all pages.---def parse_filename_page_ranges(args):- """- Given a list of filenames and page ranges, return a list of- (filename, page_range) pairs.- First arg must be a filename; other ags are filenames, page-range- expressions, slice objects, or PageRange objects.- A filename not followed by a page range indicates all pages of the file.- """- pairs = []- pdf_filename = None- did_page_range = False- for arg in args + [None]:- if PageRange.valid(arg):- if not pdf_filename:- raise ValueError("The first argument must be a filename, " \- "not a page range.")-- pairs.append( (pdf_filename, PageRange(arg)) )- did_page_range = True- else:- # New filename or end of list--do all of the previous file?- if pdf_filename and not did_page_range:- pairs.append( (pdf_filename, PAGE_RANGE_ALL) )-- pdf_filename = arg- did_page_range = False- return pairsdiff --git a/ext/PyPDF2/pdf.py b/ext/PyPDF2/pdf.pydeleted file mode 100755index 9979414f..00000000--- a/ext/PyPDF2/pdf.py+++ /dev/null@@ -1,3004 +0,0 @@-# -*- coding: utf-8 -*--#-# vim: sw=4:expandtab:foldmethod=marker-#-# Copyright (c) 2006, Mathieu Fenniak-# Copyright (c) 2007, Ashish Kulkarni <[email protected]>-#-# All rights reserved.-#-# Redistribution and use in source and binary forms, with or without-# modification, are permitted provided that the following conditions are-# met:-#-# * Redistributions of source code must retain the above copyright notice,-# this list of conditions and the following disclaimer.-# * Redistributions in binary form must reproduce the above copyright notice,-# this list of conditions and the following disclaimer in the documentation-# and/or other materials provided with the distribution.-# * The name of the author may not be used to endorse or promote products-# derived from this software without specific prior written permission.-#-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE-# POSSIBILITY OF SUCH DAMAGE.--"""-A pure-Python PDF library with an increasing number of capabilities.-See README for links to FAQ, documentation, homepage, etc.-"""--__author__ = "Mathieu Fenniak"-__author_email__ = "[email protected]"--__maintainer__ = "Phaseit, Inc."-__maintainer_email = "[email protected]"--import string-import math-import struct-import sys-import uuid-from sys import version_info-if version_info < ( 3, 0 ):- from cStringIO import StringIO-else:- from io import StringIO--if version_info < ( 3, 0 ):- BytesIO = StringIO-else:- from io import BytesIO--from . import filters-from . import utils-import warnings-import codecs-from .generic import *-from .utils import readNonWhitespace, readUntilWhitespace, ConvertFunctionsToVirtualList-from .utils import isString, b_, u_, ord_, chr_, str_, formatWarning--if version_info < ( 2, 4 ):- from sets import ImmutableSet as frozenset--if version_info < ( 2, 5 ):- from md5 import md5-else:- from hashlib import md5-import uuid---class PdfFileWriter(object):- """- This class supports writing PDF files out, given pages produced by another- class (typically :class:`PdfFileReader<PdfFileReader>`).- """- def __init__(self):- self._header = b_("%PDF-1.3")- self._objects = [] # array of indirect objects-- # The root of our page tree node.- pages = DictionaryObject()- pages.update({- NameObject("/Type"): NameObject("/Pages"),- NameObject("/Count"): NumberObject(0),- NameObject("/Kids"): ArrayObject(),- })- self._pages = self._addObject(pages)-- # info object- info = DictionaryObject()- info.update({- NameObject("/Producer"): createStringObject(codecs.BOM_UTF16_BE + u_("PyPDF2").encode('utf-16be'))- })- self._info = self._addObject(info)-- # root object- root = DictionaryObject()- root.update({- NameObject("/Type"): NameObject("/Catalog"),- NameObject("/Pages"): self._pages,- })- self._root = None- self._root_object = root-- def _addObject(self, obj):- self._objects.append(obj)- return IndirectObject(len(self._objects), 0, self)-- def getObject(self, ido):- if ido.pdf != self:- raise ValueError("pdf must be self")- return self._objects[ido.idnum - 1]-- def _addPage(self, page, action):- assert page["/Type"] == "/Page"- page[NameObject("/Parent")] = self._pages- page = self._addObject(page)- pages = self.getObject(self._pages)- action(pages["/Kids"], page)- pages[NameObject("/Count")] = NumberObject(pages["/Count"] + 1)-- def addPage(self, page):- """- Adds a page to this PDF file. The page is usually acquired from a- :class:`PdfFileReader<PdfFileReader>` instance.-- :param PageObject page: The page to add to the document. Should be- an instance of :class:`PageObject<PyPDF2.pdf.PageObject>`- """- self._addPage(page, list.append)-- def insertPage(self, page, index=0):- """- Insert a page in this PDF file. The page is usually acquired from a- :class:`PdfFileReader<PdfFileReader>` instance.-- :param PageObject page: The page to add to the document. This- argument should be an instance of :class:`PageObject<pdf.PageObject>`.- :param int index: Position at which the page will be inserted.- """- self._addPage(page, lambda l, p: l.insert(index, p))-- def getPage(self, pageNumber):- """- Retrieves a page by number from this PDF file.-- :param int pageNumber: The page number to retrieve- (pages begin at zero)- :return: the page at the index given by *pageNumber*- :rtype: :class:`PageObject<pdf.PageObject>`- """- pages = self.getObject(self._pages)- # XXX: crude hack- return pages["/Kids"][pageNumber].getObject()-- def getNumPages(self):- """- :return: the number of pages.- :rtype: int- """- pages = self.getObject(self._pages)- return int(pages[NameObject("/Count")])-- def addBlankPage(self, width=None, height=None):- """- Appends a blank page to this PDF file and returns it. If no page size- is specified, use the size of the last page.-- :param float width: The width of the new page expressed in default user- space units.- :param float height: The height of the new page expressed in default- user space units.- :return: the newly appended page- :rtype: :class:`PageObject<PyPDF2.pdf.PageObject>`- :raises PageSizeNotDefinedError: if width and height are not defined- and previous page does not exist.- """- page = PageObject.createBlankPage(self, width, height)- self.addPage(page)- return page-- def insertBlankPage(self, width=None, height=None, index=0):- """- Inserts a blank page to this PDF file and returns it. If no page size- is specified, use the size of the last page.-- :param float width: The width of the new page expressed in default user- space units.- :param float height: The height of the new page expressed in default- user space units.- :param int index: Position to add the page.- :return: the newly appended page- :rtype: :class:`PageObject<PyPDF2.pdf.PageObject>`- :raises PageSizeNotDefinedError: if width and height are not defined- and previous page does not exist.- """- if width is None or height is None and \- (self.getNumPages() - 1) >= index:- oldpage = self.getPage(index)- width = oldpage.mediaBox.getWidth()- height = oldpage.mediaBox.getHeight()- page = PageObject.createBlankPage(self, width, height)- self.insertPage(page, index)- return page-- def addJS(self, javascript):- """- Add Javascript which will launch upon opening this PDF.-- :param str javascript: Your Javascript.-- >>> output.addJS("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")- # Example: This will launch the print window when the PDF is opened.- """- js = DictionaryObject()- js.update({- NameObject("/Type"): NameObject("/Action"),- NameObject("/S"): NameObject("/JavaScript"),- NameObject("/JS"): NameObject("(%s)" % javascript)- })- js_indirect_object = self._addObject(js)-- # We need a name for parameterized javascript in the pdf file, but it can be anything.- js_string_name = str(uuid.uuid4())-- js_name_tree = DictionaryObject()- js_name_tree.update({- NameObject("/JavaScript"): DictionaryObject({- NameObject("/Names"): ArrayObject([createStringObject(js_string_name), js_indirect_object])- })- })- self._addObject(js_name_tree)-- self._root_object.update({- NameObject("/OpenAction"): js_indirect_object,- NameObject("/Names"): js_name_tree- })-- def addAttachment(self, fname, fdata):- """- Embed a file inside the PDF.-- :param str fname: The filename to display.- :param str fdata: The data in the file.-- Reference:- https://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf- Section 7.11.3- """-- # We need 3 entries:- # * The file's data- # * The /Filespec entry- # * The file's name, which goes in the Catalog--- # The entry for the file- """ Sample:- 8 0 obj- <<- /Length 12- /Type /EmbeddedFile- >>- stream- Hello world!- endstream- endobj- """- file_entry = DecodedStreamObject()- file_entry.setData(fdata)- file_entry.update({- NameObject("/Type"): NameObject("/EmbeddedFile")- })-- # The Filespec entry- """ Sample:- 7 0 obj- <<- /Type /Filespec- /F (hello.txt)- /EF << /F 8 0 R >>- >>- """- efEntry = DictionaryObject()- efEntry.update({ NameObject("/F"):file_entry })-- filespec = DictionaryObject()- filespec.update({- NameObject("/Type"): NameObject("/Filespec"),- NameObject("/F"): createStringObject(fname), # Perhaps also try TextStringObject- NameObject("/EF"): efEntry- })-- # Then create the entry for the root, as it needs a reference to the Filespec- """ Sample:- 1 0 obj- <<- /Type /Catalog- /Outlines 2 0 R- /Pages 3 0 R- /Names << /EmbeddedFiles << /Names [(hello.txt) 7 0 R] >> >>- >>- endobj-- """- embeddedFilesNamesDictionary = DictionaryObject()- embeddedFilesNamesDictionary.update({- NameObject("/Names"): ArrayObject([createStringObject(fname), filespec])- })-- embeddedFilesDictionary = DictionaryObject()- embeddedFilesDictionary.update({- NameObject("/EmbeddedFiles"): embeddedFilesNamesDictionary- })- # Update the root- self._root_object.update({- NameObject("/Names"): embeddedFilesDictionary- })-- def appendPagesFromReader(self, reader, after_page_append=None):- """- Copy pages from reader to writer. Includes an optional callback parameter- which is invoked after pages are appended to the writer.-- :param reader: a PdfFileReader object from which to copy page- annotations to this writer object. The writer's annots- will then be updated- :callback after_page_append (function): Callback function that is invoked after- each page is appended to the writer. Callback signature:-- :param writer_pageref (PDF page reference): Reference to the page- appended to the writer.- """- # Get page count from writer and reader- reader_num_pages = reader.getNumPages()- writer_num_pages = self.getNumPages()-- # Copy pages from reader to writer- for rpagenum in range(0, reader_num_pages):- reader_page = reader.getPage(rpagenum)- self.addPage(reader_page)- writer_page = self.getPage(writer_num_pages+rpagenum)- # Trigger callback, pass writer page as parameter- if callable(after_page_append): after_page_append(writer_page)-- def updatePageFormFieldValues(self, page, fields):- '''- Update the form field values for a given page from a fields dictionary.- Copy field texts and values from fields to page.-- :param page: Page reference from PDF writer where the annotations- and field data will be updated.- :param fields: a Python dictionary of field names (/T) and text- values (/V)- '''- # Iterate through pages, update field values- for j in range(0, len(page['/Annots'])):- writer_annot = page['/Annots'][j].getObject()- for field in fields:- if writer_annot.get('/T') == field:- writer_annot.update({- NameObject("/V"): TextStringObject(fields[field])- })-- def cloneReaderDocumentRoot(self, reader):- '''- Copy the reader document root to the writer.-- :param reader: PdfFileReader from the document root should be copied.- :callback after_page_append- '''- self._root_object = reader.trailer['/Root']-- def cloneDocumentFromReader(self, reader, after_page_append=None):- '''- Create a copy (clone) of a document from a PDF file reader-- :param reader: PDF file reader instance from which the clone- should be created.- :callback after_page_append (function): Callback function that is invoked after- each page is appended to the writer. Signature includes a reference to the- appended page (delegates to appendPagesFromReader). Callback signature:-- :param writer_pageref (PDF page reference): Reference to the page just- appended to the document.- '''- self.cloneReaderDocumentRoot(reader)- self.appendPagesFromReader(reader, after_page_append)-- def encrypt(self, user_pwd, owner_pwd = None, use_128bit = True):- """- Encrypt this PDF file with the PDF Standard encryption handler.-- :param str user_pwd: The "user password", which allows for opening- and reading the PDF file with the restrictions provided.- :param str owner_pwd: The "owner password", which allows for- opening the PDF files without any restrictions. By default,- the owner password is the same as the user password.- :param bool use_128bit: flag as to whether to use 128bit- encryption. When false, 40bit encryption will be used. By default,- this flag is on.- """- import time, random- if owner_pwd == None:- owner_pwd = user_pwd- if use_128bit:- V = 2- rev = 3- keylen = int(128 / 8)- else:- V = 1- rev = 2- keylen = int(40 / 8)- # permit everything:- P = -1- O = ByteStringObject(_alg33(owner_pwd, user_pwd, rev, keylen))- ID_1 = ByteStringObject(md5(b_(repr(time.time()))).digest())- ID_2 = ByteStringObject(md5(b_(repr(random.random()))).digest())- self._ID = ArrayObject((ID_1, ID_2))- if rev == 2:- U, key = _alg34(user_pwd, O, P, ID_1)- else:- assert rev == 3- U, key = _alg35(user_pwd, rev, keylen, O, P, ID_1, False)- encrypt = DictionaryObject()- encrypt[NameObject("/Filter")] = NameObject("/Standard")- encrypt[NameObject("/V")] = NumberObject(V)- if V == 2:- encrypt[NameObject("/Length")] = NumberObject(keylen * 8)- encrypt[NameObject("/R")] = NumberObject(rev)- encrypt[NameObject("/O")] = ByteStringObject(O)- encrypt[NameObject("/U")] = ByteStringObject(U)- encrypt[NameObject("/P")] = NumberObject(P)- self._encrypt = self._addObject(encrypt)- self._encrypt_key = key-- def write(self, stream):- """- Writes the collection of pages added to this object out as a PDF file.-- :param stream: An object to write the file to. The object must support- the write method and the tell method, similar to a file object.- """- if hasattr(stream, 'mode') and 'b' not in stream.mode:- warnings.warn("File <%s> to write to is not in binary mode. It may not be written to correctly." % stream.name)- debug = False- import struct-- if not self._root:- self._root = self._addObject(self._root_object)-- externalReferenceMap = {}-- # PDF objects sometimes have circular references to their /Page objects- # inside their object tree (for example, annotations). Those will be- # indirect references to objects that we've recreated in this PDF. To- # address this problem, PageObject's store their original object- # reference number, and we add it to the external reference map before- # we sweep for indirect references. This forces self-page-referencing- # trees to reference the correct new object location, rather than- # copying in a new copy of the page object.- for objIndex in range(len(self._objects)):- obj = self._objects[objIndex]- if isinstance(obj, PageObject) and obj.indirectRef != None:- data = obj.indirectRef- if data.pdf not in externalReferenceMap:- externalReferenceMap[data.pdf] = {}- if data.generation not in externalReferenceMap[data.pdf]:- externalReferenceMap[data.pdf][data.generation] = {}- externalReferenceMap[data.pdf][data.generation][data.idnum] = IndirectObject(objIndex + 1, 0, self)-- self.stack = []- if debug: print(("ERM:", externalReferenceMap, "root:", self._root))- self._sweepIndirectReferences(externalReferenceMap, self._root)- del self.stack-- # Begin writing:- object_positions = []- stream.write(self._header + b_("\n"))- for i in range(len(self._objects)):- idnum = (i + 1)- obj = self._objects[i]- object_positions.append(stream.tell())- stream.write(b_(str(idnum) + " 0 obj\n"))- key = None- if hasattr(self, "_encrypt") and idnum != self._encrypt.idnum:- pack1 = struct.pack("<i", i + 1)[:3]- pack2 = struct.pack("<i", 0)[:2]- key = self._encrypt_key + pack1 + pack2- assert len(key) == (len(self._encrypt_key) + 5)- md5_hash = md5(key).digest()- key = md5_hash[:min(16, len(self._encrypt_key) + 5)]- obj.writeToStream(stream, key)- stream.write(b_("\nendobj\n"))-- # xref table- xref_location = stream.tell()- stream.write(b_("xref\n"))- stream.write(b_("0 %s\n" % (len(self._objects) + 1)))- stream.write(b_("%010d %05d f \n" % (0, 65535)))- for offset in object_positions:- stream.write(b_("%010d %05d n \n" % (offset, 0)))-- # trailer- stream.write(b_("trailer\n"))- trailer = DictionaryObject()- trailer.update({- NameObject("/Size"): NumberObject(len(self._objects) + 1),- NameObject("/Root"): self._root,- NameObject("/Info"): self._info,- })- if hasattr(self, "_ID"):- trailer[NameObject("/ID")] = self._ID- if hasattr(self, "_encrypt"):- trailer[NameObject("/Encrypt")] = self._encrypt- trailer.writeToStream(stream, None)-- # eof- stream.write(b_("\nstartxref\n%s\n%%%%EOF\n" % (xref_location)))-- def addMetadata(self, infos):- """- Add custom metadata to the output.-- :param dict infos: a Python dictionary where each key is a field- and each value is your new metadata.- """- args = {}- for key, value in list(infos.items()):- args[NameObject(key)] = createStringObject(value)- self.getObject(self._info).update(args)-- def _sweepIndirectReferences(self, externMap, data):- debug = False- if debug: print((data, "TYPE", data.__class__.__name__))- if isinstance(data, DictionaryObject):- for key, value in list(data.items()):- origvalue = value- value = self._sweepIndirectReferences(externMap, value)- if isinstance(value, StreamObject):- # a dictionary value is a stream. streams must be indirect- # objects, so we need to change this value.- value = self._addObject(value)- data[key] = value- return data- elif isinstance(data, ArrayObject):- for i in range(len(data)):- value = self._sweepIndirectReferences(externMap, data[i])- if isinstance(value, StreamObject):- # an array value is a stream. streams must be indirect- # objects, so we need to change this value- value = self._addObject(value)- data[i] = value- return data- elif isinstance(data, IndirectObject):- # internal indirect references are fine- if data.pdf == self:- if data.idnum in self.stack:- return data- else:- self.stack.append(data.idnum)- realdata = self.getObject(data)- self._sweepIndirectReferences(externMap, realdata)- return data- else:- newobj = externMap.get(data.pdf, {}).get(data.generation, {}).get(data.idnum, None)- if newobj == None:- try:- newobj = data.pdf.getObject(data)- self._objects.append(None) # placeholder- idnum = len(self._objects)- newobj_ido = IndirectObject(idnum, 0, self)- if data.pdf not in externMap:- externMap[data.pdf] = {}- if data.generation not in externMap[data.pdf]:- externMap[data.pdf][data.generation] = {}- externMap[data.pdf][data.generation][data.idnum] = newobj_ido- newobj = self._sweepIndirectReferences(externMap, newobj)- self._objects[idnum-1] = newobj- return newobj_ido- except ValueError:- # Unable to resolve the Object, returning NullObject instead.- return NullObject()- return newobj- else:- return data-- def getReference(self, obj):- idnum = self._objects.index(obj) + 1- ref = IndirectObject(idnum, 0, self)- assert ref.getObject() == obj- return ref-- def getOutlineRoot(self):- if '/Outlines' in self._root_object:- outline = self._root_object['/Outlines']- idnum = self._objects.index(outline) + 1- outlineRef = IndirectObject(idnum, 0, self)- assert outlineRef.getObject() == outline- else:- outline = TreeObject()- outline.update({ })- outlineRef = self._addObject(outline)- self._root_object[NameObject('/Outlines')] = outlineRef-- return outline-- def getNamedDestRoot(self):- if '/Names' in self._root_object and isinstance(self._root_object['/Names'], DictionaryObject):- names = self._root_object['/Names']- idnum = self._objects.index(names) + 1- namesRef = IndirectObject(idnum, 0, self)- assert namesRef.getObject() == names- if '/Dests' in names and isinstance(names['/Dests'], DictionaryObject):- dests = names['/Dests']- idnum = self._objects.index(dests) + 1- destsRef = IndirectObject(idnum, 0, self)- assert destsRef.getObject() == dests- if '/Names' in dests:- nd = dests['/Names']- else:- nd = ArrayObject()- dests[NameObject('/Names')] = nd- else:- dests = DictionaryObject()- destsRef = self._addObject(dests)- names[NameObject('/Dests')] = destsRef- nd = ArrayObject()- dests[NameObject('/Names')] = nd-- else:- names = DictionaryObject()- namesRef = self._addObject(names)- self._root_object[NameObject('/Names')] = namesRef- dests = DictionaryObject()- destsRef = self._addObject(dests)- names[NameObject('/Dests')] = destsRef- nd = ArrayObject()- dests[NameObject('/Names')] = nd-- return nd-- def addBookmarkDestination(self, dest, parent=None):- destRef = self._addObject(dest)-- outlineRef = self.getOutlineRoot()-- if parent == None:- parent = outlineRef-- parent = parent.getObject()- #print parent.__class__.__name__- parent.addChild(destRef, self)-- return destRef-- def addBookmarkDict(self, bookmark, parent=None):- bookmarkObj = TreeObject()- for k, v in list(bookmark.items()):- bookmarkObj[NameObject(str(k))] = v- bookmarkObj.update(bookmark)-- if '/A' in bookmark:- action = DictionaryObject()- for k, v in list(bookmark['/A'].items()):- action[NameObject(str(k))] = v- actionRef = self._addObject(action)- bookmarkObj[NameObject('/A')] = actionRef-- bookmarkRef = self._addObject(bookmarkObj)-- outlineRef = self.getOutlineRoot()-- if parent == None:- parent = outlineRef-- parent = parent.getObject()- parent.addChild(bookmarkRef, self)-- return bookmarkRef-- def addBookmark(self, title, pagenum, parent=None, color=None, bold=False, italic=False, fit='/Fit', *args):- """- Add a bookmark to this PDF file.-- :param str title: Title to use for this bookmark.- :param int pagenum: Page number this bookmark will point to.- :param parent: A reference to a parent bookmark to create nested- bookmarks.- :param tuple color: Color of the bookmark as a red, green, blue tuple- from 0.0 to 1.0- :param bool bold: Bookmark is bold- :param bool italic: Bookmark is italic- :param str fit: The fit of the destination page. See- :meth:`addLink()<addLink>` for details.- """- pageRef = self.getObject(self._pages)['/Kids'][pagenum]- action = DictionaryObject()- zoomArgs = []- for a in args:- if a is not None:- zoomArgs.append(NumberObject(a))- else:- zoomArgs.append(NullObject())- dest = Destination(NameObject("/"+title + " bookmark"), pageRef, NameObject(fit), *zoomArgs)- destArray = dest.getDestArray()- action.update({- NameObject('/D') : destArray,- NameObject('/S') : NameObject('/GoTo')- })- actionRef = self._addObject(action)-- outlineRef = self.getOutlineRoot()-- if parent == None:- parent = outlineRef-- bookmark = TreeObject()-- bookmark.update({- NameObject('/A'): actionRef,- NameObject('/Title'): createStringObject(title),- })-- if color is not None:- bookmark.update({NameObject('/C'): ArrayObject([FloatObject(c) for c in color])})-- format = 0- if italic:- format += 1- if bold:- format += 2- if format:- bookmark.update({NameObject('/F'): NumberObject(format)})-- bookmarkRef = self._addObject(bookmark)-- parent = parent.getObject()- parent.addChild(bookmarkRef, self)-- return bookmarkRef-- def addNamedDestinationObject(self, dest):- destRef = self._addObject(dest)-- nd = self.getNamedDestRoot()- nd.extend([dest['/Title'], destRef])-- return destRef-- def addNamedDestination(self, title, pagenum):- pageRef = self.getObject(self._pages)['/Kids'][pagenum]- dest = DictionaryObject()- dest.update({- NameObject('/D') : ArrayObject([pageRef, NameObject('/FitH'), NumberObject(826)]),- NameObject('/S') : NameObject('/GoTo')- })-- destRef = self._addObject(dest)- nd = self.getNamedDestRoot()-- nd.extend([title, destRef])-- return destRef-- def removeLinks(self):- """- Removes links and annotations from this output.- """- pages = self.getObject(self._pages)['/Kids']- for page in pages:- pageRef = self.getObject(page)- if "/Annots" in pageRef:- del pageRef['/Annots']-- def removeImages(self, ignoreByteStringObject=False):- """- Removes images from this output.-- :param bool ignoreByteStringObject: optional parameter- to ignore ByteString Objects.- """- pages = self.getObject(self._pages)['/Kids']- for j in range(len(pages)):- page = pages[j]- pageRef = self.getObject(page)- content = pageRef['/Contents'].getObject()- if not isinstance(content, ContentStream):- content = ContentStream(content, pageRef)-- _operations = []- seq_graphics = False- for operands, operator in content.operations:- if operator == b_('Tj'):- text = operands[0]- if ignoreByteStringObject:- if not isinstance(text, TextStringObject):- operands[0] = TextStringObject()- elif operator == b_("'"):- text = operands[0]- if ignoreByteStringObject:- if not isinstance(text, TextStringObject):- operands[0] = TextStringObject()- elif operator == b_('"'):- text = operands[2]- if ignoreByteStringObject:- if not isinstance(text, TextStringObject):- operands[2] = TextStringObject()- elif operator == b_("TJ"):- for i in range(len(operands[0])):- if ignoreByteStringObject:- if not isinstance(operands[0][i], TextStringObject):- operands[0][i] = TextStringObject()-- if operator == b_('q'):- seq_graphics = True- if operator == b_('Q'):- seq_graphics = False- if seq_graphics:- if operator in [b_('cm'), b_('w'), b_('J'), b_('j'), b_('M'), b_('d'), b_('ri'), b_('i'),- b_('gs'), b_('W'), b_('b'), b_('s'), b_('S'), b_('f'), b_('F'), b_('n'), b_('m'), b_('l'),- b_('c'), b_('v'), b_('y'), b_('h'), b_('B'), b_('Do'), b_('sh')]:- continue- if operator == b_('re'):- continue- _operations.append((operands, operator))-- content.operations = _operations- pageRef.__setitem__(NameObject('/Contents'), content)-- def removeText(self, ignoreByteStringObject=False):- """- Removes images from this output.-- :param bool ignoreByteStringObject: optional parameter- to ignore ByteString Objects.- """- pages = self.getObject(self._pages)['/Kids']- for j in range(len(pages)):- page = pages[j]- pageRef = self.getObject(page)- content = pageRef['/Contents'].getObject()- if not isinstance(content, ContentStream):- content = ContentStream(content, pageRef)- for operands,operator in content.operations:- if operator == b_('Tj'):- text = operands[0]- if not ignoreByteStringObject:- if isinstance(text, TextStringObject):- operands[0] = TextStringObject()- else:- if isinstance(text, TextStringObject) or \- isinstance(text, ByteStringObject):- operands[0] = TextStringObject()- elif operator == b_("'"):- text = operands[0]- if not ignoreByteStringObject:- if isinstance(text, TextStringObject):- operands[0] = TextStringObject()- else:- if isinstance(text, TextStringObject) or \- isinstance(text, ByteStringObject):- operands[0] = TextStringObject()- elif operator == b_('"'):- text = operands[2]- if not ignoreByteStringObject:- if isinstance(text, TextStringObject):- operands[2] = TextStringObject()- else:- if isinstance(text, TextStringObject) or \- isinstance(text, ByteStringObject):- operands[2] = TextStringObject()- elif operator == b_("TJ"):- for i in range(len(operands[0])):- if not ignoreByteStringObject:- if isinstance(operands[0][i], TextStringObject):- operands[0][i] = TextStringObject()- else:- if isinstance(operands[0][i], TextStringObject) or \- isinstance(operands[0][i], ByteStringObject):- operands[0][i] = TextStringObject()-- pageRef.__setitem__(NameObject('/Contents'), content)-- def addLink(self, pagenum, pagedest, rect, border=None, fit='/Fit', *args):- """- Add an internal link from a rectangular area to the specified page.-- :param int pagenum: index of the page on which to place the link.- :param int pagedest: index of the page to which the link should go.- :param rect: :class:`RectangleObject<PyPDF2.generic.RectangleObject>` or array of four- integers specifying the clickable rectangular area- ``[xLL, yLL, xUR, yUR]``, or string in the form ``"[ xLL yLL xUR yUR ]"``.- :param border: if provided, an array describing border-drawing- properties. See the PDF spec for details. No border will be- drawn if this argument is omitted.- :param str fit: Page fit or 'zoom' option (see below). Additional arguments may need- to be supplied. Passing ``None`` will be read as a null value for that coordinate.-- Valid zoom arguments (see Table 8.2 of the PDF 1.7 reference for details):- /Fit No additional arguments- /XYZ [left] [top] [zoomFactor]- /FitH [top]- /FitV [left]- /FitR [left] [bottom] [right] [top]- /FitB No additional arguments- /FitBH [top]- /FitBV [left]- """-- pageLink = self.getObject(self._pages)['/Kids'][pagenum]- pageDest = self.getObject(self._pages)['/Kids'][pagedest] #TODO: switch for external link- pageRef = self.getObject(pageLink)-- if border is not None:- borderArr = [NameObject(n) for n in border[:3]]- if len(border) == 4:- dashPattern = ArrayObject([NameObject(n) for n in border[3]])- borderArr.append(dashPattern)- else:- borderArr = [NumberObject(0)] * 3-- if isString(rect):- rect = NameObject(rect)- elif isinstance(rect, RectangleObject):- pass- else:- rect = RectangleObject(rect)-- zoomArgs = []- for a in args:- if a is not None:- zoomArgs.append(NumberObject(a))- else:- zoomArgs.append(NullObject())- dest = Destination(NameObject("/LinkName"), pageDest, NameObject(fit), *zoomArgs) #TODO: create a better name for the link- destArray = dest.getDestArray()-- lnk = DictionaryObject()- lnk.update({- NameObject('/Type'): NameObject('/Annot'),- NameObject('/Subtype'): NameObject('/Link'),- NameObject('/P'): pageLink,- NameObject('/Rect'): rect,- NameObject('/Border'): ArrayObject(borderArr),- NameObject('/Dest'): destArray- })- lnkRef = self._addObject(lnk)-- if "/Annots" in pageRef:- pageRef['/Annots'].append(lnkRef)- else:- pageRef[NameObject('/Annots')] = ArrayObject([lnkRef])-- _valid_layouts = ['/NoLayout', '/SinglePage', '/OneColumn', '/TwoColumnLeft', '/TwoColumnRight', '/TwoPageLeft', '/TwoPageRight']-- def getPageLayout(self):- """- Get the page layout.- See :meth:`setPageLayout()<PdfFileWriter.setPageLayout>` for a description of valid layouts.-- :return: Page layout currently being used.- :rtype: str, None if not specified- """- try:- return self._root_object['/PageLayout']- except KeyError:- return None-- def setPageLayout(self, layout):- """- Set the page layout-- :param str layout: The page layout to be used-- Valid layouts are:- /NoLayout Layout explicitly not specified- /SinglePage Show one page at a time- /OneColumn Show one column at a time- /TwoColumnLeft Show pages in two columns, odd-numbered pages on the left- /TwoColumnRight Show pages in two columns, odd-numbered pages on the right- /TwoPageLeft Show two pages at a time, odd-numbered pages on the left- /TwoPageRight Show two pages at a time, odd-numbered pages on the right- """- if not isinstance(layout, NameObject):- if layout not in self._valid_layouts:- warnings.warn("Layout should be one of: {}".format(', '.join(self._valid_layouts)))- layout = NameObject(layout)- self._root_object.update({NameObject('/PageLayout'): layout})-- pageLayout = property(getPageLayout, setPageLayout)- """Read and write property accessing the :meth:`getPageLayout()<PdfFileWriter.getPageLayout>`- and :meth:`setPageLayout()<PdfFileWriter.setPageLayout>` methods."""-- _valid_modes = ['/UseNone', '/UseOutlines', '/UseThumbs', '/FullScreen', '/UseOC', '/UseAttachments']-- def getPageMode(self):- """- Get the page mode.- See :meth:`setPageMode()<PdfFileWriter.setPageMode>` for a description- of valid modes.-- :return: Page mode currently being used.- :rtype: str, None if not specified- """- try:- return self._root_object['/PageMode']- except KeyError:- return None-- def setPageMode(self, mode):- """- Set the page mode.-- :param str mode: The page mode to use.-- Valid modes are:- /UseNone Do not show outlines or thumbnails panels- /UseOutlines Show outlines (aka bookmarks) panel- /UseThumbs Show page thumbnails panel- /FullScreen Fullscreen view- /UseOC Show Optional Content Group (OCG) panel- /UseAttachments Show attachments panel- """- if not isinstance(mode, NameObject):- if mode not in self._valid_modes:- warnings.warn("Mode should be one of: {}".format(', '.join(self._valid_modes)))- mode = NameObject(mode)- self._root_object.update({NameObject('/PageMode'): mode})-- pageMode = property(getPageMode, setPageMode)- """Read and write property accessing the :meth:`getPageMode()<PdfFileWriter.getPageMode>`- and :meth:`setPageMode()<PdfFileWriter.setPageMode>` methods."""---class PdfFileReader(object):- """- Initializes a PdfFileReader object. This operation can take some time, as- the PDF stream's cross-reference tables are read into memory.-- :param stream: A File object or an object that supports the standard read- and seek methods similar to a File object. Could also be a- string representing a path to a PDF file.- :param bool strict: Determines whether user should be warned of all- problems and also causes some correctable problems to be fatal.- Defaults to ``True``.- :param warndest: Destination for logging warnings (defaults to- ``sys.stderr``).- :param bool overwriteWarnings: Determines whether to override Python's- ``warnings.py`` module with a custom implementation (defaults to- ``True``).- """- def __init__(self, stream, strict=True, warndest = None, overwriteWarnings = True):- if overwriteWarnings:- # have to dynamically override the default showwarning since there are no- # public methods that specify the 'file' parameter- def _showwarning(message, category, filename, lineno, file=warndest, line=None):- if file is None:- file = sys.stderr- try:- file.write(formatWarning(message, category, filename, lineno, line))- except IOError:- pass- warnings.showwarning = _showwarning- self.strict = strict- self.flattenedPages = None- self.resolvedObjects = {}- self.xrefIndex = 0- self._pageId2Num = None # map page IndirectRef number to Page Number- if hasattr(stream, 'mode') and 'b' not in stream.mode:- warnings.warn("PdfFileReader stream/file object is not in binary mode. It may not be read correctly.", utils.PdfReadWarning)- if isString(stream):- fileobj = open(stream, 'rb')- stream = BytesIO(b_(fileobj.read()))- fileobj.close()- self.read(stream)- self.stream = stream-- self._override_encryption = False-- def getDocumentInfo(self):- """- Retrieves the PDF file's document information dictionary, if it exists.- Note that some PDF files use metadata streams instead of docinfo- dictionaries, and these metadata streams will not be accessed by this- function.-- :return: the document information of this PDF file- :rtype: :class:`DocumentInformation<pdf.DocumentInformation>` or ``None`` if none exists.- """- if "/Info" not in self.trailer:- return None- obj = self.trailer['/Info']- retval = DocumentInformation()- retval.update(obj)- return retval-- documentInfo = property(lambda self: self.getDocumentInfo(), None, None)- """Read-only property that accesses the :meth:`getDocumentInfo()<PdfFileReader.getDocumentInfo>` function."""-- def getXmpMetadata(self):- """- Retrieves XMP (Extensible Metadata Platform) data from the PDF document- root.-- :return: a :class:`XmpInformation<xmp.XmpInformation>`- instance that can be used to access XMP metadata from the document.- :rtype: :class:`XmpInformation<xmp.XmpInformation>` or- ``None`` if no metadata was found on the document root.- """- try:- self._override_encryption = True- return self.trailer["/Root"].getXmpMetadata()- finally:- self._override_encryption = False-- xmpMetadata = property(lambda self: self.getXmpMetadata(), None, None)- """- Read-only property that accesses the- :meth:`getXmpMetadata()<PdfFileReader.getXmpMetadata>` function.- """-- def getNumPages(self):- """- Calculates the number of pages in this PDF file.-- :return: number of pages- :rtype: int- :raises PdfReadError: if file is encrypted and restrictions prevent- this action.- """-- # Flattened pages will not work on an Encrypted PDF;- # the PDF file's page count is used in this case. Otherwise,- # the original method (flattened page count) is used.- if self.isEncrypted:- try:- self._override_encryption = True- self.decrypt('')- return self.trailer["/Root"]["/Pages"]["/Count"]- except:- raise utils.PdfReadError("File has not been decrypted")- finally:- self._override_encryption = False- else:- if self.flattenedPages == None:- self._flatten()- return len(self.flattenedPages)-- numPages = property(lambda self: self.getNumPages(), None, None)- """- Read-only property that accesses the- :meth:`getNumPages()<PdfFileReader.getNumPages>` function.- """-- def getPage(self, pageNumber):- """- Retrieves a page by number from this PDF file.-- :param int pageNumber: The page number to retrieve- (pages begin at zero)- :return: a :class:`PageObject<pdf.PageObject>` instance.- :rtype: :class:`PageObject<pdf.PageObject>`- """- ## ensure that we're not trying to access an encrypted PDF- #assert not self.trailer.has_key("/Encrypt")- if self.flattenedPages == None:- self._flatten()- return self.flattenedPages[pageNumber]-- namedDestinations = property(lambda self:- self.getNamedDestinations(), None, None)- """- Read-only property that accesses the- :meth:`getNamedDestinations()<PdfFileReader.getNamedDestinations>` function.- """-- # A select group of relevant field attributes. For the complete list,- # see section 8.6.2 of the PDF 1.7 reference.-- def getFields(self, tree = None, retval = None, fileobj = None):- """- Extracts field data if this PDF contains interactive form fields.- The *tree* and *retval* parameters are for recursive use.-- :param fileobj: A file object (usually a text file) to write- a report to on all interactive form fields found.- :return: A dictionary where each key is a field name, and each- value is a :class:`Field<PyPDF2.generic.Field>` object. By- default, the mapping name is used for keys.- :rtype: dict, or ``None`` if form data could not be located.- """- fieldAttributes = {"/FT" : "Field Type", "/Parent" : "Parent",- "/T" : "Field Name", "/TU" : "Alternate Field Name",- "/TM" : "Mapping Name", "/Ff" : "Field Flags",- "/V" : "Value", "/DV" : "Default Value"}- if retval == None:- retval = {}- catalog = self.trailer["/Root"]- # get the AcroForm tree- if "/AcroForm" in catalog:- tree = catalog["/AcroForm"]- else:- return None- if tree == None:- return retval-- self._checkKids(tree, retval, fileobj)- for attr in fieldAttributes:- if attr in tree:- # Tree is a field- self._buildField(tree, retval, fileobj, fieldAttributes)- break-- if "/Fields" in tree:- fields = tree["/Fields"]- for f in fields:- field = f.getObject()- self._buildField(field, retval, fileobj, fieldAttributes)-- return retval-- def _buildField(self, field, retval, fileobj, fieldAttributes):- self._checkKids(field, retval, fileobj)- try:- key = field["/TM"]- except KeyError:- try:- key = field["/T"]- except KeyError:- # Ignore no-name field for now- return- if fileobj:- self._writeField(fileobj, field, fieldAttributes)- fileobj.write("\n")- retval[key] = Field(field)-- def _checkKids(self, tree, retval, fileobj):- if "/Kids" in tree:- # recurse down the tree- for kid in tree["/Kids"]:- self.getFields(kid.getObject(), retval, fileobj)-- def _writeField(self, fileobj, field, fieldAttributes):- order = ["/TM", "/T", "/FT", "/Parent", "/TU", "/Ff", "/V", "/DV"]- for attr in order:- attrName = fieldAttributes[attr]- try:- if attr == "/FT":- # Make the field type value more clear- types = {"/Btn":"Button", "/Tx":"Text", "/Ch": "Choice",- "/Sig":"Signature"}- if field[attr] in types:- fileobj.write(attrName + ": " + types[field[attr]] + "\n")- elif attr == "/Parent":- # Let's just write the name of the parent- try:- name = field["/Parent"]["/TM"]- except KeyError:- name = field["/Parent"]["/T"]- fileobj.write(attrName + ": " + name + "\n")- else:- fileobj.write(attrName + ": " + str(field[attr]) + "\n")- except KeyError:- # Field attribute is N/A or unknown, so don't write anything- pass-- def getFormTextFields(self):- ''' Retrieves form fields from the document with textual data (inputs, dropdowns)- '''- # Retrieve document form fields- formfields = self.getFields()- return dict(- (formfields[field]['/T'], formfields[field].get('/V')) for field in formfields \- if formfields[field].get('/FT') == '/Tx'- )-- def getNamedDestinations(self, tree=None, retval=None):- """- Retrieves the named destinations present in the document.-- :return: a dictionary which maps names to- :class:`Destinations<PyPDF2.generic.Destination>`.- :rtype: dict- """- if retval == None:- retval = {}- catalog = self.trailer["/Root"]-- # get the name tree- if "/Dests" in catalog:- tree = catalog["/Dests"]- elif "/Names" in catalog:- names = catalog['/Names']- if "/Dests" in names:- tree = names['/Dests']-- if tree == None:- return retval-- if "/Kids" in tree:- # recurse down the tree- for kid in tree["/Kids"]:- self.getNamedDestinations(kid.getObject(), retval)-- if "/Names" in tree:- names = tree["/Names"]- for i in range(0, len(names), 2):- key = names[i].getObject()- val = names[i+1].getObject()- if isinstance(val, DictionaryObject) and '/D' in val:- val = val['/D']- dest = self._buildDestination(key, val)- if dest != None:- retval[key] = dest-- return retval-- outlines = property(lambda self: self.getOutlines(), None, None)- """- Read-only property that accesses the- :meth:`getOutlines()<PdfFileReader.getOutlines>` function.- """-- def getOutlines(self, node=None, outlines=None):- """- Retrieves the document outline present in the document.-- :return: a nested list of :class:`Destinations<PyPDF2.generic.Destination>`.- """- if outlines == None:- outlines = []- catalog = self.trailer["/Root"]-- # get the outline dictionary and named destinations- if "/Outlines" in catalog:- try:- lines = catalog["/Outlines"]- except utils.PdfReadError:- # this occurs if the /Outlines object reference is incorrect- # for an example of such a file, see https://unglueit-files.s3.amazonaws.com/ebf/7552c42e9280b4476e59e77acc0bc812.pdf- # so continue to load the file without the Bookmarks- return outlines-- if "/First" in lines:- node = lines["/First"]- self._namedDests = self.getNamedDestinations()-- if node == None:- return outlines-- # see if there are any more outlines- while True:- outline = self._buildOutline(node)- if outline:- outlines.append(outline)-- # check for sub-outlines- if "/First" in node:- subOutlines = []- self.getOutlines(node["/First"], subOutlines)- if subOutlines:- outlines.append(subOutlines)-- if "/Next" not in node:- break- node = node["/Next"]-- return outlines-- def _getPageNumberByIndirect(self, indirectRef):- """Generate _pageId2Num"""- if self._pageId2Num is None:- id2num = {}- for i, x in enumerate(self.pages):- id2num[x.indirectRef.idnum] = i- self._pageId2Num = id2num-- if isinstance(indirectRef, int):- idnum = indirectRef- else:- idnum = indirectRef.idnum-- ret = self._pageId2Num.get(idnum, -1)- return ret-- def getPageNumber(self, page):- """- Retrieve page number of a given PageObject-- :param PageObject page: The page to get page number. Should be- an instance of :class:`PageObject<PyPDF2.pdf.PageObject>`- :return: the page number or -1 if page not found- :rtype: int- """- indirectRef = page.indirectRef- ret = self._getPageNumberByIndirect(indirectRef)- return ret-- def getDestinationPageNumber(self, destination):- """- Retrieve page number of a given Destination object-- :param Destination destination: The destination to get page number.- Should be an instance of- :class:`Destination<PyPDF2.pdf.Destination>`- :return: the page number or -1 if page not found- :rtype: int- """- indirectRef = destination.page- ret = self._getPageNumberByIndirect(indirectRef)- return ret-- def _buildDestination(self, title, array):- page, typ = array[0:2]- array = array[2:]- return Destination(title, page, typ, *array)-- def _buildOutline(self, node):- dest, title, outline = None, None, None-- if "/A" in node and "/Title" in node:- # Action, section 8.5 (only type GoTo supported)- title = node["/Title"]- action = node["/A"]- if action["/S"] == "/GoTo":- dest = action["/D"]- elif "/Dest" in node and "/Title" in node:- # Destination, section 8.2.1- title = node["/Title"]- dest = node["/Dest"]-- # if destination found, then create outline- if dest:- if isinstance(dest, ArrayObject):- outline = self._buildDestination(title, dest)- elif isString(dest) and dest in self._namedDests:- outline = self._namedDests[dest]- outline[NameObject("/Title")] = title- else:- raise utils.PdfReadError("Unexpected destination %r" % dest)- return outline-- pages = property(lambda self: ConvertFunctionsToVirtualList(self.getNumPages, self.getPage),- None, None)- """- Read-only property that emulates a list based upon the- :meth:`getNumPages()<PdfFileReader.getNumPages>` and- :meth:`getPage()<PdfFileReader.getPage>` methods.- """-- def getPageLayout(self):- """- Get the page layout.- See :meth:`setPageLayout()<PdfFileWriter.setPageLayout>`- for a description of valid layouts.-- :return: Page layout currently being used.- :rtype: ``str``, ``None`` if not specified- """- try:- return self.trailer['/Root']['/PageLayout']- except KeyError:- return None-- pageLayout = property(getPageLayout)- """Read-only property accessing the- :meth:`getPageLayout()<PdfFileReader.getPageLayout>` method."""-- def getPageMode(self):- """- Get the page mode.- See :meth:`setPageMode()<PdfFileWriter.setPageMode>`- for a description of valid modes.-- :return: Page mode currently being used.- :rtype: ``str``, ``None`` if not specified- """- try:- return self.trailer['/Root']['/PageMode']- except KeyError:- return None-- pageMode = property(getPageMode)- """Read-only property accessing the- :meth:`getPageMode()<PdfFileReader.getPageMode>` method."""-- def _flatten(self, pages=None, inherit=None, indirectRef=None):- inheritablePageAttributes = (- NameObject("/Resources"), NameObject("/MediaBox"),- NameObject("/CropBox"), NameObject("/Rotate")- )- if inherit == None:- inherit = dict()- if pages == None:- self.flattenedPages = []- catalog = self.trailer["/Root"].getObject()- pages = catalog["/Pages"].getObject()-- t = "/Pages"- if "/Type" in pages:- t = pages["/Type"]-- if t == "/Pages":- for attr in inheritablePageAttributes:- if attr in pages:- inherit[attr] = pages[attr]- for page in pages["/Kids"]:- addt = {}- if isinstance(page, IndirectObject):- addt["indirectRef"] = page- self._flatten(page.getObject(), inherit, **addt)- elif t == "/Page":- for attr, value in list(inherit.items()):- # if the page has it's own value, it does not inherit the- # parent's value:- if attr not in pages:- pages[attr] = value- pageObj = PageObject(self, indirectRef)- pageObj.update(pages)- self.flattenedPages.append(pageObj)-- def _getObjectFromStream(self, indirectReference):- # indirect reference to object in object stream- # read the entire object stream into memory- debug = False- stmnum, idx = self.xref_objStm[indirectReference.idnum]- if debug: print(("Here1: %s %s"%(stmnum, idx)))- objStm = IndirectObject(stmnum, 0, self).getObject()- if debug: print(("Here2: objStm=%s.. stmnum=%s data=%s"%(objStm, stmnum, objStm.getData())))- # This is an xref to a stream, so its type better be a stream- assert objStm['/Type'] == '/ObjStm'- # /N is the number of indirect objects in the stream- assert idx < objStm['/N']- streamData = BytesIO(b_(objStm.getData()))- for i in range(objStm['/N']):- readNonWhitespace(streamData)- streamData.seek(-1, 1)- objnum = NumberObject.readFromStream(streamData)- readNonWhitespace(streamData)- streamData.seek(-1, 1)- offset = NumberObject.readFromStream(streamData)- readNonWhitespace(streamData)- streamData.seek(-1, 1)- if objnum != indirectReference.idnum:- # We're only interested in one object- continue- if self.strict and idx != i:- raise utils.PdfReadError("Object is in wrong index.")- streamData.seek(objStm['/First']+offset, 0)- if debug:- pos = streamData.tell()- streamData.seek(0, 0)- lines = streamData.readlines()- for i in range(0, len(lines)):- print((lines[i]))- streamData.seek(pos, 0)- try:- obj = readObject(streamData, self)- except utils.PdfStreamError as e:- # Stream object cannot be read. Normally, a critical error, but- # Adobe Reader doesn't complain, so continue (in strict mode?)- e = sys.exc_info()[1]- warnings.warn("Invalid stream (index %d) within object %d %d: %s" % \- (i, indirectReference.idnum, indirectReference.generation, e), utils.PdfReadWarning)-- if self.strict:- raise utils.PdfReadError("Can't read object stream: %s"%e)- # Replace with null. Hopefully it's nothing important.- obj = NullObject()- return obj-- if self.strict: raise utils.PdfReadError("This is a fatal error in strict mode.")- return NullObject()-- def getObject(self, indirectReference):- debug = False- if debug: print(("looking at:", indirectReference.idnum, indirectReference.generation))- retval = self.cacheGetIndirectObject(indirectReference.generation,- indirectReference.idnum)- if retval != None:- return retval- if indirectReference.generation == 0 and \- indirectReference.idnum in self.xref_objStm:- retval = self._getObjectFromStream(indirectReference)- elif indirectReference.generation in self.xref and \- indirectReference.idnum in self.xref[indirectReference.generation]:- start = self.xref[indirectReference.generation][indirectReference.idnum]- if debug: print((" Uncompressed Object", indirectReference.idnum, indirectReference.generation, ":", start))- self.stream.seek(start, 0)- idnum, generation = self.readObjectHeader(self.stream)- if idnum != indirectReference.idnum and self.xrefIndex:- # Xref table probably had bad indexes due to not being zero-indexed- if self.strict:- raise utils.PdfReadError("Expected object ID (%d %d) does not match actual (%d %d); xref table not zero-indexed." \- % (indirectReference.idnum, indirectReference.generation, idnum, generation))- else: pass # xref table is corrected in non-strict mode- elif idnum != indirectReference.idnum:- # some other problem- raise utils.PdfReadError("Expected object ID (%d %d) does not match actual (%d %d)." \- % (indirectReference.idnum, indirectReference.generation, idnum, generation))- assert generation == indirectReference.generation- retval = readObject(self.stream, self)-- # override encryption is used for the /Encrypt dictionary- if not self._override_encryption and self.isEncrypted:- # if we don't have the encryption key:- if not hasattr(self, '_decryption_key'):- raise utils.PdfReadError("file has not been decrypted")- # otherwise, decrypt here...- import struct- pack1 = struct.pack("<i", indirectReference.idnum)[:3]- pack2 = struct.pack("<i", indirectReference.generation)[:2]- key = self._decryption_key + pack1 + pack2- assert len(key) == (len(self._decryption_key) + 5)- md5_hash = md5(key).digest()- key = md5_hash[:min(16, len(self._decryption_key) + 5)]- retval = self._decryptObject(retval, key)- else:- warnings.warn("Object %d %d not defined."%(indirectReference.idnum,- indirectReference.generation), utils.PdfReadWarning)- #if self.strict:- raise utils.PdfReadError("Could not find object.")- self.cacheIndirectObject(indirectReference.generation,- indirectReference.idnum, retval)- return retval-- def _decryptObject(self, obj, key):- if isinstance(obj, ByteStringObject) or isinstance(obj, TextStringObject):- obj = createStringObject(utils.RC4_encrypt(key, obj.original_bytes))- elif isinstance(obj, StreamObject):- obj._data = utils.RC4_encrypt(key, obj._data)- elif isinstance(obj, DictionaryObject):- for dictkey, value in list(obj.items()):- obj[dictkey] = self._decryptObject(value, key)- elif isinstance(obj, ArrayObject):- for i in range(len(obj)):- obj[i] = self._decryptObject(obj[i], key)- return obj-- def readObjectHeader(self, stream):- # Should never be necessary to read out whitespace, since the- # cross-reference table should put us in the right spot to read the- # object header. In reality... some files have stupid cross reference- # tables that are off by whitespace bytes.- extra = False- utils.skipOverComment(stream)- extra |= utils.skipOverWhitespace(stream); stream.seek(-1, 1)- idnum = readUntilWhitespace(stream)- extra |= utils.skipOverWhitespace(stream); stream.seek(-1, 1)- generation = readUntilWhitespace(stream)- obj = stream.read(3)- readNonWhitespace(stream)- stream.seek(-1, 1)- if (extra and self.strict):- #not a fatal error- warnings.warn("Superfluous whitespace found in object header %s %s" % \- (idnum, generation), utils.PdfReadWarning)- return int(idnum), int(generation)-- def cacheGetIndirectObject(self, generation, idnum):- debug = False- out = self.resolvedObjects.get((generation, idnum))- if debug and out: print(("cache hit: %d %d"%(idnum, generation)))- elif debug: print(("cache miss: %d %d"%(idnum, generation)))- return out-- def cacheIndirectObject(self, generation, idnum, obj):- # return None # Sometimes we want to turn off cache for debugging.- if (generation, idnum) in self.resolvedObjects:- msg = "Overwriting cache for %s %s"%(generation, idnum)- if self.strict: raise utils.PdfReadError(msg)- else: warnings.warn(msg)- self.resolvedObjects[(generation, idnum)] = obj- return obj-- def read(self, stream):- debug = False- if debug: print(">>read", stream)- # start at the end:- stream.seek(-1, 2)- if not stream.tell():- raise utils.PdfReadError('Cannot read an empty file')- last1K = stream.tell() - 1024 + 1 # offset of last 1024 bytes of stream- line = b_('')- while line[:5] != b_("%%EOF"):- if stream.tell() < last1K:- raise utils.PdfReadError("EOF marker not found")- line = self.readNextEndLine(stream)- if debug: print(" line:",line)-- # find startxref entry - the location of the xref table- line = self.readNextEndLine(stream)- try:- startxref = int(line)- except ValueError:- # 'startxref' may be on the same line as the location- if not line.startswith(b_("startxref")):- raise utils.PdfReadError("startxref not found")- startxref = int(line[9:].strip())- warnings.warn("startxref on same line as offset")- else:- line = self.readNextEndLine(stream)- if line[:9] != b_("startxref"):- raise utils.PdfReadError("startxref not found")-- # read all cross reference tables and their trailers- self.xref = {}- self.xref_objStm = {}- self.trailer = DictionaryObject()- while True:- # load the xref table- stream.seek(startxref, 0)- x = stream.read(1)- if x == b_("x"):- # standard cross-reference table- ref = stream.read(4)- if ref[:3] != b_("ref"):- raise utils.PdfReadError("xref table read error")- readNonWhitespace(stream)- stream.seek(-1, 1)- firsttime = True; # check if the first time looking at the xref table- while True:- num = readObject(stream, self)- if firsttime and num != 0:- self.xrefIndex = num- if self.strict:- warnings.warn("Xref table not zero-indexed. ID numbers for objects will be corrected.", utils.PdfReadWarning)- #if table not zero indexed, could be due to error from when PDF was created- #which will lead to mismatched indices later on, only warned and corrected if self.strict=True- firsttime = False- readNonWhitespace(stream)- stream.seek(-1, 1)- size = readObject(stream, self)- readNonWhitespace(stream)- stream.seek(-1, 1)- cnt = 0- while cnt < size:- line = stream.read(20)-- # It's very clear in section 3.4.3 of the PDF spec- # that all cross-reference table lines are a fixed- # 20 bytes (as of PDF 1.7). However, some files have- # 21-byte entries (or more) due to the use of \r\n- # (CRLF) EOL's. Detect that case, and adjust the line- # until it does not begin with a \r (CR) or \n (LF).- while line[0] in b_("\x0D\x0A"):- stream.seek(-20 + 1, 1)- line = stream.read(20)-- # On the other hand, some malformed PDF files- # use a single character EOL without a preceeding- # space. Detect that case, and seek the stream- # back one character. (0-9 means we've bled into- # the next xref entry, t means we've bled into the- # text "trailer"):- if line[-1] in b_("0123456789t"):- stream.seek(-1, 1)-- offset, generation = line[:16].split(b_(" "))- offset, generation = int(offset), int(generation)- if generation not in self.xref:- self.xref[generation] = {}- if num in self.xref[generation]:- # It really seems like we should allow the last- # xref table in the file to override previous- # ones. Since we read the file backwards, assume- # any existing key is already set correctly.- pass- else:- self.xref[generation][num] = offset- cnt += 1- num += 1- readNonWhitespace(stream)- stream.seek(-1, 1)- trailertag = stream.read(7)- if trailertag != b_("trailer"):- # more xrefs!- stream.seek(-7, 1)- else:- break- readNonWhitespace(stream)- stream.seek(-1, 1)- newTrailer = readObject(stream, self)- for key, value in list(newTrailer.items()):- if key not in self.trailer:- self.trailer[key] = value- if "/Prev" in newTrailer:- startxref = newTrailer["/Prev"]- else:- break- elif x.isdigit():- # PDF 1.5+ Cross-Reference Stream- stream.seek(-1, 1)- idnum, generation = self.readObjectHeader(stream)- xrefstream = readObject(stream, self)- assert xrefstream["/Type"] == "/XRef"- self.cacheIndirectObject(generation, idnum, xrefstream)- streamData = BytesIO(b_(xrefstream.getData()))- # Index pairs specify the subsections in the dictionary. If- # none create one subsection that spans everything.- idx_pairs = xrefstream.get("/Index", [0, xrefstream.get("/Size")])- if debug: print(("read idx_pairs=%s"%list(self._pairs(idx_pairs))))- entrySizes = xrefstream.get("/W")- assert len(entrySizes) >= 3- if self.strict and len(entrySizes) > 3:- raise utils.PdfReadError("Too many entry sizes: %s" %entrySizes)-- def getEntry(i):- # Reads the correct number of bytes for each entry. See the- # discussion of the W parameter in PDF spec table 17.- if entrySizes[i] > 0:- d = streamData.read(entrySizes[i])- return convertToInt(d, entrySizes[i])-- # PDF Spec Table 17: A value of zero for an element in the- # W array indicates...the default value shall be used- if i == 0: return 1 # First value defaults to 1- else: return 0-- def used_before(num, generation):- # We move backwards through the xrefs, don't replace any.- return num in self.xref.get(generation, []) or \- num in self.xref_objStm-- # Iterate through each subsection- last_end = 0- for start, size in self._pairs(idx_pairs):- # The subsections must increase- assert start >= last_end- last_end = start + size- for num in range(start, start+size):- # The first entry is the type- xref_type = getEntry(0)- # The rest of the elements depend on the xref_type- if xref_type == 0:- # linked list of free objects- next_free_object = getEntry(1)- next_generation = getEntry(2)- elif xref_type == 1:- # objects that are in use but are not compressed- byte_offset = getEntry(1)- generation = getEntry(2)- if generation not in self.xref:- self.xref[generation] = {}- if not used_before(num, generation):- self.xref[generation][num] = byte_offset- if debug: print(("XREF Uncompressed: %s %s"%(- num, generation)))- elif xref_type == 2:- # compressed objects- objstr_num = getEntry(1)- obstr_idx = getEntry(2)- generation = 0 # PDF spec table 18, generation is 0- if not used_before(num, generation):- if debug: print(("XREF Compressed: %s %s %s"%(- num, objstr_num, obstr_idx)))- self.xref_objStm[num] = (objstr_num, obstr_idx)- elif self.strict:- raise utils.PdfReadError("Unknown xref type: %s"%- xref_type)-- trailerKeys = "/Root", "/Encrypt", "/Info", "/ID"- for key in trailerKeys:- if key in xrefstream and key not in self.trailer:- self.trailer[NameObject(key)] = xrefstream.raw_get(key)- if "/Prev" in xrefstream:- startxref = xrefstream["/Prev"]- else:- break- else:- # bad xref character at startxref. Let's see if we can find- # the xref table nearby, as we've observed this error with an- # off-by-one before.- stream.seek(-11, 1)- tmp = stream.read(20)- xref_loc = tmp.find(b_("xref"))- if xref_loc != -1:- startxref -= (10 - xref_loc)- continue- # No explicit xref table, try finding a cross-reference stream.- stream.seek(startxref, 0)- found = False- for look in range(5):- if stream.read(1).isdigit():- # This is not a standard PDF, consider adding a warning- startxref += look- found = True- break- if found:- continue- # no xref table found at specified location- raise utils.PdfReadError("Could not find xref table at specified location")- #if not zero-indexed, verify that the table is correct; change it if necessary- if self.xrefIndex and not self.strict:- loc = stream.tell()- for gen in self.xref:- if gen == 65535: continue- for id in self.xref[gen]:- stream.seek(self.xref[gen][id], 0)- try:- pid, pgen = self.readObjectHeader(stream)- except ValueError:- break- if pid == id - self.xrefIndex:- self._zeroXref(gen)- break- #if not, then either it's just plain wrong, or the non-zero-index is actually correct- stream.seek(loc, 0) #return to where it was-- def _zeroXref(self, generation):- self.xref[generation] = dict( (k-self.xrefIndex, v) for (k, v) in list(self.xref[generation].items()) )-- def _pairs(self, array):- i = 0- while True:- yield array[i], array[i+1]- i += 2- if (i+1) >= len(array):- break-- def readNextEndLine(self, stream):- debug = False- if debug: print(">>readNextEndLine")- line = b_("")- while True:- # Prevent infinite loops in malformed PDFs- if stream.tell() == 0:- raise utils.PdfReadError("Could not read malformed PDF file")- x = stream.read(1)- if debug: print((" x:", x, "%x"%ord(x)))- if stream.tell() < 2:- raise utils.PdfReadError("EOL marker not found")- stream.seek(-2, 1)- if x == b_('\n') or x == b_('\r'): ## \n = LF; \r = CR- crlf = False- while x == b_('\n') or x == b_('\r'):- if debug:- if ord(x) == 0x0D: print(" x is CR 0D")- elif ord(x) == 0x0A: print(" x is LF 0A")- x = stream.read(1)- if x == b_('\n') or x == b_('\r'): # account for CR+LF- stream.seek(-1, 1)- crlf = True- if stream.tell() < 2:- raise utils.PdfReadError("EOL marker not found")- stream.seek(-2, 1)- stream.seek(2 if crlf else 1, 1) #if using CR+LF, go back 2 bytes, else 1- break- else:- if debug: print(" x is neither")- line = x + line- if debug: print((" RNEL line:", line))- if debug: print("leaving RNEL")- return line-- def decrypt(self, password):- """- When using an encrypted / secured PDF file with the PDF Standard- encryption handler, this function will allow the file to be decrypted.- It checks the given password against the document's user password and- owner password, and then stores the resulting decryption key if either- password is correct.-- It does not matter which password was matched. Both passwords provide- the correct decryption key that will allow the document to be used with- this library.-- :param str password: The password to match.- :return: ``0`` if the password failed, ``1`` if the password matched the user- password, and ``2`` if the password matched the owner password.- :rtype: int- :raises NotImplementedError: if document uses an unsupported encryption- method.- """-- self._override_encryption = True- try:- return self._decrypt(password)- finally:- self._override_encryption = False-- def _decrypt(self, password):- encrypt = self.trailer['/Encrypt'].getObject()- if encrypt['/Filter'] != '/Standard':- raise NotImplementedError("only Standard PDF encryption handler is available")- if not (encrypt['/V'] in (1, 2)):- raise NotImplementedError("only algorithm code 1 and 2 are supported")- user_password, key = self._authenticateUserPassword(password)- if user_password:- self._decryption_key = key- return 1- else:- rev = encrypt['/R'].getObject()- if rev == 2:- keylen = 5- else:- keylen = encrypt['/Length'].getObject() // 8- key = _alg33_1(password, rev, keylen)- real_O = encrypt["/O"].getObject()- if rev == 2:- userpass = utils.RC4_encrypt(key, real_O)- else:- val = real_O- for i in range(19, -1, -1):- new_key = b_('')- for l in range(len(key)):- new_key += b_(chr(utils.ord_(key[l]) ^ i))- val = utils.RC4_encrypt(new_key, val)- userpass = val- owner_password, key = self._authenticateUserPassword(userpass)- if owner_password:- self._decryption_key = key- return 2- return 0-- def _authenticateUserPassword(self, password):- encrypt = self.trailer['/Encrypt'].getObject()- rev = encrypt['/R'].getObject()- owner_entry = encrypt['/O'].getObject()- p_entry = encrypt['/P'].getObject()- id_entry = self.trailer['/ID'].getObject()- id1_entry = id_entry[0].getObject()- real_U = encrypt['/U'].getObject().original_bytes- if rev == 2:- U, key = _alg34(password, owner_entry, p_entry, id1_entry)- elif rev >= 3:- U, key = _alg35(password, rev,- encrypt["/Length"].getObject() // 8, owner_entry,- p_entry, id1_entry,- encrypt.get("/EncryptMetadata", BooleanObject(False)).getObject())- U, real_U = U[:16], real_U[:16]- return U == real_U, key-- def getIsEncrypted(self):- return "/Encrypt" in self.trailer-- isEncrypted = property(lambda self: self.getIsEncrypted(), None, None)- """- Read-only boolean property showing whether this PDF file is encrypted.- Note that this property, if true, will remain true even after the- :meth:`decrypt()<PdfFileReader.decrypt>` method is called.- """---def getRectangle(self, name, defaults):- retval = self.get(name)- if isinstance(retval, RectangleObject):- return retval- if retval == None:- for d in defaults:- retval = self.get(d)- if retval != None:- break- if isinstance(retval, IndirectObject):- retval = self.pdf.getObject(retval)- retval = RectangleObject(retval)- setRectangle(self, name, retval)- return retval---def setRectangle(self, name, value):- if not isinstance(name, NameObject):- name = NameObject(name)- self[name] = value---def deleteRectangle(self, name):- del self[name]---def createRectangleAccessor(name, fallback):- return \- property(- lambda self: getRectangle(self, name, fallback),- lambda self, value: setRectangle(self, name, value),- lambda self: deleteRectangle(self, name)- )---class PageObject(DictionaryObject):- """- This class represents a single page within a PDF file. Typically this- object will be created by accessing the- :meth:`getPage()<PyPDF2.PdfFileReader.getPage>` method of the- :class:`PdfFileReader<PyPDF2.PdfFileReader>` class, but it is- also possible to create an empty page with the- :meth:`createBlankPage()<PageObject.createBlankPage>` static method.-- :param pdf: PDF file the page belongs to.- :param indirectRef: Stores the original indirect reference to- this object in its source PDF- """- def __init__(self, pdf=None, indirectRef=None):- DictionaryObject.__init__(self)- self.pdf = pdf- self.indirectRef = indirectRef-- def createBlankPage(pdf=None, width=None, height=None):- """- Returns a new blank page.- If ``width`` or ``height`` is ``None``, try to get the page size- from the last page of *pdf*.-- :param pdf: PDF file the page belongs to- :param float width: The width of the new page expressed in default user- space units.- :param float height: The height of the new page expressed in default user- space units.- :return: the new blank page:- :rtype: :class:`PageObject<PageObject>`- :raises PageSizeNotDefinedError: if ``pdf`` is ``None`` or contains- no page- """- page = PageObject(pdf)-- # Creates a new page (cf PDF Reference 7.7.3.3)- page.__setitem__(NameObject('/Type'), NameObject('/Page'))- page.__setitem__(NameObject('/Parent'), NullObject())- page.__setitem__(NameObject('/Resources'), DictionaryObject())- if width is None or height is None:- if pdf is not None and pdf.getNumPages() > 0:- lastpage = pdf.getPage(pdf.getNumPages() - 1)- width = lastpage.mediaBox.getWidth()- height = lastpage.mediaBox.getHeight()- else:- raise utils.PageSizeNotDefinedError()- page.__setitem__(NameObject('/MediaBox'),- RectangleObject([0, 0, width, height]))-- return page- createBlankPage = staticmethod(createBlankPage)-- def rotateClockwise(self, angle):- """- Rotates a page clockwise by increments of 90 degrees.-- :param int angle: Angle to rotate the page. Must be an increment- of 90 deg.- """- assert angle % 90 == 0- self._rotate(angle)- return self-- def rotateCounterClockwise(self, angle):- """- Rotates a page counter-clockwise by increments of 90 degrees.-- :param int angle: Angle to rotate the page. Must be an increment- of 90 deg.- """- assert angle % 90 == 0- self._rotate(-angle)- return self-- def _rotate(self, angle):- currentAngle = self.get("/Rotate", 0)- self[NameObject("/Rotate")] = NumberObject(currentAngle + angle)-- def _mergeResources(res1, res2, resource):- newRes = DictionaryObject()- newRes.update(res1.get(resource, DictionaryObject()).getObject())- page2Res = res2.get(resource, DictionaryObject()).getObject()- renameRes = {}- for key in list(page2Res.keys()):- if key in newRes and newRes.raw_get(key) != page2Res.raw_get(key):- newname = NameObject(key + str(uuid.uuid4()))- renameRes[key] = newname- newRes[newname] = page2Res[key]- elif key not in newRes:- newRes[key] = page2Res.raw_get(key)- return newRes, renameRes- _mergeResources = staticmethod(_mergeResources)-- def _contentStreamRename(stream, rename, pdf):- if not rename:- return stream- stream = ContentStream(stream, pdf)- for operands, operator in stream.operations:- for i in range(len(operands)):- op = operands[i]- if isinstance(op, NameObject):- operands[i] = rename.get(op,op)- return stream- _contentStreamRename = staticmethod(_contentStreamRename)-- def _pushPopGS(contents, pdf):- # adds a graphics state "push" and "pop" to the beginning and end- # of a content stream. This isolates it from changes such as- # transformation matricies.- stream = ContentStream(contents, pdf)- stream.operations.insert(0, [[], "q"])- stream.operations.append([[], "Q"])- return stream- _pushPopGS = staticmethod(_pushPopGS)-- def _addTransformationMatrix(contents, pdf, ctm):- # adds transformation matrix at the beginning of the given- # contents stream.- a, b, c, d, e, f = ctm- contents = ContentStream(contents, pdf)- contents.operations.insert(0, [[FloatObject(a), FloatObject(b),- FloatObject(c), FloatObject(d), FloatObject(e),- FloatObject(f)], " cm"])- return contents- _addTransformationMatrix = staticmethod(_addTransformationMatrix)-- def getContents(self):- """- Accesses the page contents.-- :return: the ``/Contents`` object, or ``None`` if it doesn't exist.- ``/Contents`` is optional, as described in PDF Reference 7.7.3.3- """- if "/Contents" in self:- return self["/Contents"].getObject()- else:- return None-- def mergePage(self, page2):- """- Merges the content streams of two pages into one. Resource references- (i.e. fonts) are maintained from both pages. The mediabox/cropbox/etc- of this page are not altered. The parameter page's content stream will- be added to the end of this page's content stream, meaning that it will- be drawn after, or "on top" of this page.-- :param PageObject page2: The page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- """- self._mergePage(page2)-- def _mergePage(self, page2, page2transformation=None, ctm=None, expand=False):- # First we work on merging the resource dictionaries. This allows us- # to find out what symbols in the content streams we might need to- # rename.-- newResources = DictionaryObject()- rename = {}- originalResources = self["/Resources"].getObject()- page2Resources = page2["/Resources"].getObject()- newAnnots = ArrayObject()-- for page in (self, page2):- if "/Annots" in page:- annots = page["/Annots"]- if isinstance(annots, ArrayObject):- for ref in annots:- newAnnots.append(ref)-- for res in "/ExtGState", "/Font", "/XObject", "/ColorSpace", "/Pattern", "/Shading", "/Properties":- new, newrename = PageObject._mergeResources(originalResources, page2Resources, res)- if new:- newResources[NameObject(res)] = new- rename.update(newrename)-- # Combine /ProcSet sets.- newResources[NameObject("/ProcSet")] = ArrayObject(- frozenset(originalResources.get("/ProcSet", ArrayObject()).getObject()).union(- frozenset(page2Resources.get("/ProcSet", ArrayObject()).getObject())- )- )-- newContentArray = ArrayObject()-- originalContent = self.getContents()- if originalContent is not None:- newContentArray.append(PageObject._pushPopGS(- originalContent, self.pdf))-- page2Content = page2.getContents()- if page2Content is not None:- if page2transformation is not None:- page2Content = page2transformation(page2Content)- page2Content = PageObject._contentStreamRename(- page2Content, rename, self.pdf)- page2Content = PageObject._pushPopGS(page2Content, self.pdf)- newContentArray.append(page2Content)-- # if expanding the page to fit a new page, calculate the new media box size- if expand:- corners1 = [self.mediaBox.getLowerLeft_x().as_numeric(), self.mediaBox.getLowerLeft_y().as_numeric(),- self.mediaBox.getUpperRight_x().as_numeric(), self.mediaBox.getUpperRight_y().as_numeric()]- corners2 = [page2.mediaBox.getLowerLeft_x().as_numeric(), page2.mediaBox.getLowerLeft_y().as_numeric(),- page2.mediaBox.getUpperLeft_x().as_numeric(), page2.mediaBox.getUpperLeft_y().as_numeric(),- page2.mediaBox.getUpperRight_x().as_numeric(), page2.mediaBox.getUpperRight_y().as_numeric(),- page2.mediaBox.getLowerRight_x().as_numeric(), page2.mediaBox.getLowerRight_y().as_numeric()]- if ctm is not None:- ctm = [float(x) for x in ctm]- new_x = [ctm[0]*corners2[i] + ctm[2]*corners2[i+1] + ctm[4] for i in range(0, 8, 2)]- new_y = [ctm[1]*corners2[i] + ctm[3]*corners2[i+1] + ctm[5] for i in range(0, 8, 2)]- else:- new_x = corners2[0:8:2]- new_y = corners2[1:8:2]- lowerleft = [min(new_x), min(new_y)]- upperright = [max(new_x), max(new_y)]- lowerleft = [min(corners1[0], lowerleft[0]), min(corners1[1], lowerleft[1])]- upperright = [max(corners1[2], upperright[0]), max(corners1[3], upperright[1])]-- self.mediaBox.setLowerLeft(lowerleft)- self.mediaBox.setUpperRight(upperright)-- self[NameObject('/Contents')] = ContentStream(newContentArray, self.pdf)- self[NameObject('/Resources')] = newResources- self[NameObject('/Annots')] = newAnnots-- def mergeTransformedPage(self, page2, ctm, expand=False):- """- This is similar to mergePage, but a transformation matrix is- applied to the merged stream.-- :param PageObject page2: The page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- :param tuple ctm: a 6-element tuple containing the operands of the- transformation matrix- :param bool expand: Whether the page should be expanded to fit the dimensions- of the page to be merged.- """- self._mergePage(page2, lambda page2Content:- PageObject._addTransformationMatrix(page2Content, page2.pdf, ctm), ctm, expand)-- def mergeScaledPage(self, page2, scale, expand=False):- """- This is similar to mergePage, but the stream to be merged is scaled- by appling a transformation matrix.-- :param PageObject page2: The page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- :param float scale: The scaling factor- :param bool expand: Whether the page should be expanded to fit the- dimensions of the page to be merged.- """- # CTM to scale : [ sx 0 0 sy 0 0 ]- return self.mergeTransformedPage(page2, [scale, 0,- 0, scale,- 0, 0], expand)-- def mergeRotatedPage(self, page2, rotation, expand=False):- """- This is similar to mergePage, but the stream to be merged is rotated- by appling a transformation matrix.-- :param PageObject page2: the page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- :param float rotation: The angle of the rotation, in degrees- :param bool expand: Whether the page should be expanded to fit the- dimensions of the page to be merged.- """- rotation = math.radians(rotation)- return self.mergeTransformedPage(page2,- [math.cos(rotation), math.sin(rotation),- -math.sin(rotation), math.cos(rotation),- 0, 0], expand)-- def mergeTranslatedPage(self, page2, tx, ty, expand=False):- """- This is similar to mergePage, but the stream to be merged is translated- by appling a transformation matrix.-- :param PageObject page2: the page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- :param float tx: The translation on X axis- :param float ty: The translation on Y axis- :param bool expand: Whether the page should be expanded to fit the- dimensions of the page to be merged.- """- return self.mergeTransformedPage(page2, [1, 0,- 0, 1,- tx, ty], expand)-- def mergeRotatedTranslatedPage(self, page2, rotation, tx, ty, expand=False):- """- This is similar to mergePage, but the stream to be merged is rotated- and translated by appling a transformation matrix.-- :param PageObject page2: the page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- :param float tx: The translation on X axis- :param float ty: The translation on Y axis- :param float rotation: The angle of the rotation, in degrees- :param bool expand: Whether the page should be expanded to fit the- dimensions of the page to be merged.- """-- translation = [[1, 0, 0],- [0, 1, 0],- [-tx, -ty, 1]]- rotation = math.radians(rotation)- rotating = [[math.cos(rotation), math.sin(rotation), 0],- [-math.sin(rotation), math.cos(rotation), 0],- [0, 0, 1]]- rtranslation = [[1, 0, 0],- [0, 1, 0],- [tx, ty, 1]]- ctm = utils.matrixMultiply(translation, rotating)- ctm = utils.matrixMultiply(ctm, rtranslation)-- return self.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],- ctm[1][0], ctm[1][1],- ctm[2][0], ctm[2][1]], expand)-- def mergeRotatedScaledPage(self, page2, rotation, scale, expand=False):- """- This is similar to mergePage, but the stream to be merged is rotated- and scaled by appling a transformation matrix.-- :param PageObject page2: the page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- :param float rotation: The angle of the rotation, in degrees- :param float scale: The scaling factor- :param bool expand: Whether the page should be expanded to fit the- dimensions of the page to be merged.- """- rotation = math.radians(rotation)- rotating = [[math.cos(rotation), math.sin(rotation), 0],- [-math.sin(rotation), math.cos(rotation), 0],- [0, 0, 1]]- scaling = [[scale, 0, 0],- [0, scale, 0],- [0, 0, 1]]- ctm = utils.matrixMultiply(rotating, scaling)-- return self.mergeTransformedPage(page2,- [ctm[0][0], ctm[0][1],- ctm[1][0], ctm[1][1],- ctm[2][0], ctm[2][1]], expand)-- def mergeScaledTranslatedPage(self, page2, scale, tx, ty, expand=False):- """- This is similar to mergePage, but the stream to be merged is translated- and scaled by appling a transformation matrix.-- :param PageObject page2: the page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- :param float scale: The scaling factor- :param float tx: The translation on X axis- :param float ty: The translation on Y axis- :param bool expand: Whether the page should be expanded to fit the- dimensions of the page to be merged.- """-- translation = [[1, 0, 0],- [0, 1, 0],- [tx, ty, 1]]- scaling = [[scale, 0, 0],- [0, scale, 0],- [0, 0, 1]]- ctm = utils.matrixMultiply(scaling, translation)-- return self.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],- ctm[1][0], ctm[1][1],- ctm[2][0], ctm[2][1]], expand)-- def mergeRotatedScaledTranslatedPage(self, page2, rotation, scale, tx, ty, expand=False):- """- This is similar to mergePage, but the stream to be merged is translated,- rotated and scaled by appling a transformation matrix.-- :param PageObject page2: the page to be merged into this one. Should be- an instance of :class:`PageObject<PageObject>`.- :param float tx: The translation on X axis- :param float ty: The translation on Y axis- :param float rotation: The angle of the rotation, in degrees- :param float scale: The scaling factor- :param bool expand: Whether the page should be expanded to fit the- dimensions of the page to be merged.- """- translation = [[1, 0, 0],- [0, 1, 0],- [tx, ty, 1]]- rotation = math.radians(rotation)- rotating = [[math.cos(rotation), math.sin(rotation), 0],- [-math.sin(rotation), math.cos(rotation), 0],- [0, 0, 1]]- scaling = [[scale, 0, 0],- [0, scale, 0],- [0, 0, 1]]- ctm = utils.matrixMultiply(rotating, scaling)- ctm = utils.matrixMultiply(ctm, translation)-- return self.mergeTransformedPage(page2, [ctm[0][0], ctm[0][1],- ctm[1][0], ctm[1][1],- ctm[2][0], ctm[2][1]], expand)-- ##- # Applys a transformation matrix the page.- #- # @param ctm A 6 elements tuple containing the operands of the- # transformation matrix- def addTransformation(self, ctm):- """- Applies a transformation matrix to the page.-- :param tuple ctm: A 6-element tuple containing the operands of the- transformation matrix.- """- originalContent = self.getContents()- if originalContent is not None:- newContent = PageObject._addTransformationMatrix(- originalContent, self.pdf, ctm)- newContent = PageObject._pushPopGS(newContent, self.pdf)- self[NameObject('/Contents')] = newContent-- def scale(self, sx, sy):- """- Scales a page by the given factors by appling a transformation- matrix to its content and updating the page size.-- :param float sx: The scaling factor on horizontal axis.- :param float sy: The scaling factor on vertical axis.- """- self.addTransformation([sx, 0,- 0, sy,- 0, 0])- self.mediaBox = RectangleObject([- float(self.mediaBox.getLowerLeft_x()) * sx,- float(self.mediaBox.getLowerLeft_y()) * sy,- float(self.mediaBox.getUpperRight_x()) * sx,- float(self.mediaBox.getUpperRight_y()) * sy])- if "/VP" in self:- viewport = self["/VP"]- if isinstance(viewport, ArrayObject):- bbox = viewport[0]["/BBox"]- else:- bbox = viewport["/BBox"]- scaled_bbox = RectangleObject([- float(bbox[0]) * sx,- float(bbox[1]) * sy,- float(bbox[2]) * sx,- float(bbox[3]) * sy])- if isinstance(viewport, ArrayObject):- self[NameObject("/VP")][NumberObject(0)][NameObject("/BBox")] = scaled_bbox- else:- self[NameObject("/VP")][NameObject("/BBox")] = scaled_bbox-- def scaleBy(self, factor):- """- Scales a page by the given factor by appling a transformation- matrix to its content and updating the page size.-- :param float factor: The scaling factor (for both X and Y axis).- """- self.scale(factor, factor)-- def scaleTo(self, width, height):- """- Scales a page to the specified dimentions by appling a- transformation matrix to its content and updating the page size.-- :param float width: The new width.- :param float height: The new heigth.- """- sx = width / float(self.mediaBox.getUpperRight_x() -- self.mediaBox.getLowerLeft_x ())- sy = height / float(self.mediaBox.getUpperRight_y() -- self.mediaBox.getLowerLeft_y ())- self.scale(sx, sy)-- def compressContentStreams(self):- """- Compresses the size of this page by joining all content streams and- applying a FlateDecode filter.-- However, it is possible that this function will perform no action if- content stream compression becomes "automatic" for some reason.- """- content = self.getContents()- if content is not None:- if not isinstance(content, ContentStream):- content = ContentStream(content, self.pdf)- self[NameObject("/Contents")] = content.flateEncode()-- def extractText(self):- """- Locate all text drawing commands, in the order they are provided in the- content stream, and extract the text. This works well for some PDF- files, but poorly for others, depending on the generator used. This will- be refined in the future. Do not rely on the order of text coming out of- this function, as it will change if this function is made more- sophisticated.-- :return: a unicode string object.- """- text = u_("")- content = self["/Contents"].getObject()- if not isinstance(content, ContentStream):- content = ContentStream(content, self.pdf)- # Note: we check all strings are TextStringObjects. ByteStringObjects- # are strings where the byte->string encoding was unknown, so adding- # them to the text here would be gibberish.- for operands, operator in content.operations:- if operator == b_("Tj"):- _text = operands[0]- if isinstance(_text, TextStringObject):- text += _text- elif operator == b_("T*"):- text += "\n"- elif operator == b_("'"):- text += "\n"- _text = operands[0]- if isinstance(_text, TextStringObject):- text += operands[0]- elif operator == b_('"'):- _text = operands[2]- if isinstance(_text, TextStringObject):- text += "\n"- text += _text- elif operator == b_("TJ"):- for i in operands[0]:- if isinstance(i, TextStringObject):- text += i- text += "\n"- return text-- mediaBox = createRectangleAccessor("/MediaBox", ())- """- A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,- defining the boundaries of the physical medium on which the page is- intended to be displayed or printed.- """-- cropBox = createRectangleAccessor("/CropBox", ("/MediaBox",))- """- A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,- defining the visible region of default user space. When the page is- displayed or printed, its contents are to be clipped (cropped) to this- rectangle and then imposed on the output medium in some- implementation-defined manner. Default value: same as :attr:`mediaBox<mediaBox>`.- """-- bleedBox = createRectangleAccessor("/BleedBox", ("/CropBox", "/MediaBox"))- """- A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,- defining the region to which the contents of the page should be clipped- when output in a production enviroment.- """-- trimBox = createRectangleAccessor("/TrimBox", ("/CropBox", "/MediaBox"))- """- A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,- defining the intended dimensions of the finished page after trimming.- """-- artBox = createRectangleAccessor("/ArtBox", ("/CropBox", "/MediaBox"))- """- A :class:`RectangleObject<PyPDF2.generic.RectangleObject>`, expressed in default user space units,- defining the extent of the page's meaningful content as intended by the- page's creator.- """---class ContentStream(DecodedStreamObject):- def __init__(self, stream, pdf):- self.pdf = pdf- self.operations = []- # stream may be a StreamObject or an ArrayObject containing- # multiple StreamObjects to be cat'd together.- stream = stream.getObject()- if isinstance(stream, ArrayObject):- data = b_("")- for s in stream:- data += s.getObject().getData()- stream = BytesIO(b_(data))- else:- stream = BytesIO(b_(stream.getData()))- self.__parseContentStream(stream)-- def __parseContentStream(self, stream):- # file("f:\\tmp.txt", "w").write(stream.read())- stream.seek(0, 0)- operands = []- while True:- peek = readNonWhitespace(stream)- if peek == b_('') or ord_(peek) == 0:- break- stream.seek(-1, 1)- if peek.isalpha() or peek == b_("'") or peek == b_('"'):- operator = utils.readUntilRegex(stream,- NameObject.delimiterPattern, True)- if operator == b_("BI"):- # begin inline image - a completely different parsing- # mechanism is required, of course... thanks buddy...- assert operands == []- ii = self._readInlineImage(stream)- self.operations.append((ii, b_("INLINE IMAGE")))- else:- self.operations.append((operands, operator))- operands = []- elif peek == b_('%'):- # If we encounter a comment in the content stream, we have to- # handle it here. Typically, readObject will handle- # encountering a comment -- but readObject assumes that- # following the comment must be the object we're trying to- # read. In this case, it could be an operator instead.- while peek not in (b_('\r'), b_('\n')):- peek = stream.read(1)- else:- operands.append(readObject(stream, None))-- def _readInlineImage(self, stream):- # begin reading just after the "BI" - begin image- # first read the dictionary of settings.- settings = DictionaryObject()- while True:- tok = readNonWhitespace(stream)- stream.seek(-1, 1)- if tok == b_("I"):- # "ID" - begin of image data- break- key = readObject(stream, self.pdf)- tok = readNonWhitespace(stream)- stream.seek(-1, 1)- value = readObject(stream, self.pdf)- settings[key] = value- # left at beginning of ID- tmp = stream.read(3)- assert tmp[:2] == b_("ID")- data = b_("")- while True:- # Read the inline image, while checking for EI (End Image) operator.- tok = stream.read(1)- if tok == b_("E"):- # Check for End Image- tok2 = stream.read(1)- if tok2 == b_("I"):- # Data can contain EI, so check for the Q operator.- tok3 = stream.read(1)- info = tok + tok2- # We need to find whitespace between EI and Q.- has_q_whitespace = False- while tok3 in utils.WHITESPACES:- has_q_whitespace = True- info += tok3- tok3 = stream.read(1)- if tok3 == b_("Q") and has_q_whitespace:- stream.seek(-1, 1)- break- else:- stream.seek(-1,1)- data += info- else:- stream.seek(-1, 1)- data += tok- else:- data += tok- return {"settings": settings, "data": data}-- def _getData(self):- newdata = BytesIO()- for operands, operator in self.operations:- if operator == b_("INLINE IMAGE"):- newdata.write(b_("BI"))- dicttext = BytesIO()- operands["settings"].writeToStream(dicttext, None)- newdata.write(dicttext.getvalue()[2:-2])- newdata.write(b_("ID "))- newdata.write(operands["data"])- newdata.write(b_("EI"))- else:- for op in operands:- op.writeToStream(newdata, None)- newdata.write(b_(" "))- newdata.write(b_(operator))- newdata.write(b_("\n"))- return newdata.getvalue()-- def _setData(self, value):- self.__parseContentStream(BytesIO(b_(value)))-- _data = property(_getData, _setData)---class DocumentInformation(DictionaryObject):- """- A class representing the basic document metadata provided in a PDF File.- This class is accessible through- :meth:`getDocumentInfo()<PyPDF2.PdfFileReader.getDocumentInfo()>`-- All text properties of the document metadata have- *two* properties, eg. author and author_raw. The non-raw property will- always return a ``TextStringObject``, making it ideal for a case where- the metadata is being displayed. The raw property can sometimes return- a ``ByteStringObject``, if PyPDF2 was unable to decode the string's- text encoding; this requires additional safety in the caller and- therefore is not as commonly accessed.- """-- def __init__(self):- DictionaryObject.__init__(self)-- def getText(self, key):- retval = self.get(key, None)- if isinstance(retval, TextStringObject):- return retval- return None-- title = property(lambda self: self.getText("/Title"))- """Read-only property accessing the document's **title**.- Returns a unicode string (``TextStringObject``) or ``None``- if the title is not specified."""- title_raw = property(lambda self: self.get("/Title"))- """The "raw" version of title; can return a ``ByteStringObject``."""-- author = property(lambda self: self.getText("/Author"))- """Read-only property accessing the document's **author**.- Returns a unicode string (``TextStringObject``) or ``None``- if the author is not specified."""- author_raw = property(lambda self: self.get("/Author"))- """The "raw" version of author; can return a ``ByteStringObject``."""-- subject = property(lambda self: self.getText("/Subject"))- """Read-only property accessing the document's **subject**.- Returns a unicode string (``TextStringObject``) or ``None``- if the subject is not specified."""- subject_raw = property(lambda self: self.get("/Subject"))- """The "raw" version of subject; can return a ``ByteStringObject``."""-- creator = property(lambda self: self.getText("/Creator"))- """Read-only property accessing the document's **creator**. If the- document was converted to PDF from another format, this is the name of the- application (e.g. OpenOffice) that created the original document from- which it was converted. Returns a unicode string (``TextStringObject``)- or ``None`` if the creator is not specified."""- creator_raw = property(lambda self: self.get("/Creator"))- """The "raw" version of creator; can return a ``ByteStringObject``."""-- producer = property(lambda self: self.getText("/Producer"))- """Read-only property accessing the document's **producer**.- If the document was converted to PDF from another format, this is- the name of the application (for example, OSX Quartz) that converted- it to PDF. Returns a unicode string (``TextStringObject``)- or ``None`` if the producer is not specified."""- producer_raw = property(lambda self: self.get("/Producer"))- """The "raw" version of producer; can return a ``ByteStringObject``."""---def convertToInt(d, size):- if size > 8:- raise utils.PdfReadError("invalid size in convertToInt")- d = b_("\x00\x00\x00\x00\x00\x00\x00\x00") + b_(d)- d = d[-8:]- return struct.unpack(">q", d)[0]--# ref: pdf1.8 spec section 3.5.2 algorithm 3.2-_encryption_padding = b_('\x28\xbf\x4e\x5e\x4e\x75\x8a\x41\x64\x00\x4e\x56') + \- b_('\xff\xfa\x01\x08\x2e\x2e\x00\xb6\xd0\x68\x3e\x80\x2f\x0c') + \- b_('\xa9\xfe\x64\x53\x69\x7a')---# Implementation of algorithm 3.2 of the PDF standard security handler,-# section 3.5.2 of the PDF 1.6 reference.-def _alg32(password, rev, keylen, owner_entry, p_entry, id1_entry, metadata_encrypt=True):- # 1. Pad or truncate the password string to exactly 32 bytes. If the- # password string is more than 32 bytes long, use only its first 32 bytes;- # if it is less than 32 bytes long, pad it by appending the required number- # of additional bytes from the beginning of the padding string- # (_encryption_padding).- password = b_((str_(password) + str_(_encryption_padding))[:32])- # 2. Initialize the MD5 hash function and pass the result of step 1 as- # input to this function.- import struct- m = md5(password)- # 3. Pass the value of the encryption dictionary's /O entry to the MD5 hash- # function.- m.update(owner_entry.original_bytes)- # 4. Treat the value of the /P entry as an unsigned 4-byte integer and pass- # these bytes to the MD5 hash function, low-order byte first.- p_entry = struct.pack('<i', p_entry)- m.update(p_entry)- # 5. Pass the first element of the file's file identifier array to the MD5- # hash function.- m.update(id1_entry.original_bytes)- # 6. (Revision 3 or greater) If document metadata is not being encrypted,- # pass 4 bytes with the value 0xFFFFFFFF to the MD5 hash function.- if rev >= 3 and not metadata_encrypt:- m.update(b_("\xff\xff\xff\xff"))- # 7. Finish the hash.- md5_hash = m.digest()- # 8. (Revision 3 or greater) Do the following 50 times: Take the output- # from the previous MD5 hash and pass the first n bytes of the output as- # input into a new MD5 hash, where n is the number of bytes of the- # encryption key as defined by the value of the encryption dictionary's- # /Length entry.- if rev >= 3:- for i in range(50):- md5_hash = md5(md5_hash[:keylen]).digest()- # 9. Set the encryption key to the first n bytes of the output from the- # final MD5 hash, where n is always 5 for revision 2 but, for revision 3 or- # greater, depends on the value of the encryption dictionary's /Length- # entry.- return md5_hash[:keylen]---# Implementation of algorithm 3.3 of the PDF standard security handler,-# section 3.5.2 of the PDF 1.6 reference.-def _alg33(owner_pwd, user_pwd, rev, keylen):- # steps 1 - 4- key = _alg33_1(owner_pwd, rev, keylen)- # 5. Pad or truncate the user password string as described in step 1 of- # algorithm 3.2.- user_pwd = b_((user_pwd + str_(_encryption_padding))[:32])- # 6. Encrypt the result of step 5, using an RC4 encryption function with- # the encryption key obtained in step 4.- val = utils.RC4_encrypt(key, user_pwd)- # 7. (Revision 3 or greater) Do the following 19 times: Take the output- # from the previous invocation of the RC4 function and pass it as input to- # a new invocation of the function; use an encryption key generated by- # taking each byte of the encryption key obtained in step 4 and performing- # an XOR operation between that byte and the single-byte value of the- # iteration counter (from 1 to 19).- if rev >= 3:- for i in range(1, 20):- new_key = ''- for l in range(len(key)):- new_key += chr(ord_(key[l]) ^ i)- val = utils.RC4_encrypt(new_key, val)- # 8. Store the output from the final invocation of the RC4 as the value of- # the /O entry in the encryption dictionary.- return val---# Steps 1-4 of algorithm 3.3-def _alg33_1(password, rev, keylen):- # 1. Pad or truncate the owner password string as described in step 1 of- # algorithm 3.2. If there is no owner password, use the user password- # instead.- password = b_((password + str_(_encryption_padding))[:32])- # 2. Initialize the MD5 hash function and pass the result of step 1 as- # input to this function.- m = md5(password)- # 3. (Revision 3 or greater) Do the following 50 times: Take the output- # from the previous MD5 hash and pass it as input into a new MD5 hash.- md5_hash = m.digest()- if rev >= 3:- for i in range(50):- md5_hash = md5(md5_hash).digest()- # 4. Create an RC4 encryption key using the first n bytes of the output- # from the final MD5 hash, where n is always 5 for revision 2 but, for- # revision 3 or greater, depends on the value of the encryption- # dictionary's /Length entry.- key = md5_hash[:keylen]- return key---# Implementation of algorithm 3.4 of the PDF standard security handler,-# section 3.5.2 of the PDF 1.6 reference.-def _alg34(password, owner_entry, p_entry, id1_entry):- # 1. Create an encryption key based on the user password string, as- # described in algorithm 3.2.- key = _alg32(password, 2, 5, owner_entry, p_entry, id1_entry)- # 2. Encrypt the 32-byte padding string shown in step 1 of algorithm 3.2,- # using an RC4 encryption function with the encryption key from the- # preceding step.- U = utils.RC4_encrypt(key, _encryption_padding)- # 3. Store the result of step 2 as the value of the /U entry in the- # encryption dictionary.- return U, key---# Implementation of algorithm 3.4 of the PDF standard security handler,-# section 3.5.2 of the PDF 1.6 reference.-def _alg35(password, rev, keylen, owner_entry, p_entry, id1_entry, metadata_encrypt):- # 1. Create an encryption key based on the user password string, as- # described in Algorithm 3.2.- key = _alg32(password, rev, keylen, owner_entry, p_entry, id1_entry)- # 2. Initialize the MD5 hash function and pass the 32-byte padding string- # shown in step 1 of Algorithm 3.2 as input to this function.- m = md5()- m.update(_encryption_padding)- # 3. Pass the first element of the file's file identifier array (the value- # of the ID entry in the document's trailer dictionary; see Table 3.13 on- # page 73) to the hash function and finish the hash. (See implementation- # note 25 in Appendix H.)- m.update(id1_entry.original_bytes)- md5_hash = m.digest()- # 4. Encrypt the 16-byte result of the hash, using an RC4 encryption- # function with the encryption key from step 1.- val = utils.RC4_encrypt(key, md5_hash)- # 5. Do the following 19 times: Take the output from the previous- # invocation of the RC4 function and pass it as input to a new invocation- # of the function; use an encryption key generated by taking each byte of- # the original encryption key (obtained in step 2) and performing an XOR- # operation between that byte and the single-byte value of the iteration- # counter (from 1 to 19).- for i in range(1, 20):- new_key = b_('')- for l in range(len(key)):- new_key += b_(chr(ord_(key[l]) ^ i))- val = utils.RC4_encrypt(new_key, val)- # 6. Append 16 bytes of arbitrary padding to the output from the final- # invocation of the RC4 function and store the 32-byte result as the value- # of the U entry in the encryption dictionary.- # (implementator note: I don't know what "arbitrary padding" is supposed to- # mean, so I have used null bytes. This seems to match a few other- # people's implementations)- return val + (b_('\x00') * 16), keydiff --git a/ext/PyPDF2/utils.py b/ext/PyPDF2/utils.pydeleted file mode 100755index 718a875c..00000000--- a/ext/PyPDF2/utils.py+++ /dev/null@@ -1,295 +0,0 @@-# Copyright (c) 2006, Mathieu Fenniak-# All rights reserved.-#-# Redistribution and use in source and binary forms, with or without-# modification, are permitted provided that the following conditions are-# met:-#-# * Redistributions of source code must retain the above copyright notice,-# this list of conditions and the following disclaimer.-# * Redistributions in binary form must reproduce the above copyright notice,-# this list of conditions and the following disclaimer in the documentation-# and/or other materials provided with the distribution.-# * The name of the author may not be used to endorse or promote products-# derived from this software without specific prior written permission.-#-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE-# POSSIBILITY OF SUCH DAMAGE.--"""-Utility functions for PDF library.-"""-__author__ = "Mathieu Fenniak"-__author_email__ = "[email protected]"---import sys--try:- import __builtin__ as builtins-except ImportError: # Py3- import builtins---xrange_fn = getattr(builtins, "xrange", range)-_basestring = getattr(builtins, "basestring", str)--bytes_type = type(bytes()) # Works the same in Python 2.X and 3.X-string_type = getattr(builtins, "unicode", str)-int_types = (int, long) if sys.version_info[0] < 3 else (int,)---# Make basic type tests more consistent-def isString(s):- """Test if arg is a string. Compatible with Python 2 and 3."""- return isinstance(s, _basestring)---def isInt(n):- """Test if arg is an int. Compatible with Python 2 and 3."""- return isinstance(n, int_types)---def isBytes(b):- """Test if arg is a bytes instance. Compatible with Python 2 and 3."""- return isinstance(b, bytes_type)---#custom implementation of warnings.formatwarning-def formatWarning(message, category, filename, lineno, line=None):- file = filename.replace("/", "\\").rsplit("\\", 1)[1] # find the file name- return "%s: %s [%s:%s]\n" % (category.__name__, message, file, lineno)---def readUntilWhitespace(stream, maxchars=None):- """- Reads non-whitespace characters and returns them.- Stops upon encountering whitespace or when maxchars is reached.- """- txt = b_("")- while True:- tok = stream.read(1)- if tok.isspace() or not tok:- break- txt += tok- if len(txt) == maxchars:- break- return txt---def readNonWhitespace(stream):- """- Finds and reads the next non-whitespace character (ignores whitespace).- """- tok = WHITESPACES[0]- while tok in WHITESPACES:- tok = stream.read(1)- return tok---def skipOverWhitespace(stream):- """- Similar to readNonWhitespace, but returns a Boolean if more than- one whitespace character was read.- """- tok = WHITESPACES[0]- cnt = 0;- while tok in WHITESPACES:- tok = stream.read(1)- cnt+=1- return (cnt > 1)---def skipOverComment(stream):- tok = stream.read(1)- stream.seek(-1, 1)- if tok == b_('%'):- while tok not in (b_('\n'), b_('\r')):- tok = stream.read(1)---def readUntilRegex(stream, regex, ignore_eof=False):- """- Reads until the regular expression pattern matched (ignore the match)- Raise PdfStreamError on premature end-of-file.- :param bool ignore_eof: If true, ignore end-of-line and return immediately- """- name = b_('')- while True:- tok = stream.read(16)- if not tok:- # stream has truncated prematurely- if ignore_eof == True:- return name- else:- raise PdfStreamError("Stream has ended unexpectedly")- m = regex.search(tok)- if m is not None:- name += tok[:m.start()]- stream.seek(m.start()-len(tok), 1)- break- name += tok- return name---class ConvertFunctionsToVirtualList(object):- def __init__(self, lengthFunction, getFunction):- self.lengthFunction = lengthFunction- self.getFunction = getFunction-- def __len__(self):- return self.lengthFunction()-- def __getitem__(self, index):- if isinstance(index, slice):- indices = xrange_fn(*index.indices(len(self)))- cls = type(self)- return cls(indices.__len__, lambda idx: self[indices[idx]])- if not isInt(index):- raise TypeError("sequence indices must be integers")- len_self = len(self)- if index < 0:- # support negative indexes- index = len_self + index- if index < 0 or index >= len_self:- raise IndexError("sequence index out of range")- return self.getFunction(index)---def RC4_encrypt(key, plaintext):- S = [i for i in range(256)]- j = 0- for i in range(256):- j = (j + S[i] + ord_(key[i % len(key)])) % 256- S[i], S[j] = S[j], S[i]- i, j = 0, 0- retval = b_("")- for x in range(len(plaintext)):- i = (i + 1) % 256- j = (j + S[i]) % 256- S[i], S[j] = S[j], S[i]- t = S[(S[i] + S[j]) % 256]- retval += b_(chr(ord_(plaintext[x]) ^ t))- return retval---def matrixMultiply(a, b):- return [[sum([float(i)*float(j)- for i, j in zip(row, col)]- ) for col in zip(*b)]- for row in a]---def markLocation(stream):- """Creates text file showing current location in context."""- # Mainly for debugging- RADIUS = 5000- stream.seek(-RADIUS, 1)- outputDoc = open('PyPDF2_pdfLocation.txt', 'w')- outputDoc.write(stream.read(RADIUS))- outputDoc.write('HERE')- outputDoc.write(stream.read(RADIUS))- outputDoc.close()- stream.seek(-RADIUS, 1)---class PyPdfError(Exception):- pass---class PdfReadError(PyPdfError):- pass---class PageSizeNotDefinedError(PyPdfError):- pass---class PdfReadWarning(UserWarning):- pass---class PdfStreamError(PdfReadError):- pass---if sys.version_info[0] < 3:- def b_(s):- return s-else:- B_CACHE = {}-- def b_(s):- bc = B_CACHE- if s in bc:- return bc[s]- if type(s) == bytes:- return s- else:- r = s.encode('latin-1')- if len(s) < 2:- bc[s] = r- return r---def u_(s):- if sys.version_info[0] < 3:- return unicode(s, 'unicode_escape')- else:- return s---def str_(b):- if sys.version_info[0] < 3:- return b- else:- if type(b) == bytes:- return b.decode('latin-1')- else:- return b---def ord_(b):- if sys.version_info[0] < 3 or type(b) == str:- return ord(b)- else:- return b---def chr_(c):- if sys.version_info[0] < 3:- return c- else:- return chr(c)---def barray(b):- if sys.version_info[0] < 3:- return b- else:- return bytearray(b)---def hexencode(b):- if sys.version_info[0] < 3:- return b.encode('hex')- else:- import codecs- coder = codecs.getencoder('hex_codec')- return coder(b)[0]---def hexStr(num):- return hex(num).replace('L', '')---WHITESPACES = [b_(x) for x in [' ', '\n', '\r', '\t', '\x00']]diff --git a/ext/PyPDF2/xmp.py b/ext/PyPDF2/xmp.pydeleted file mode 100755index 7ba62f0d..00000000--- a/ext/PyPDF2/xmp.py+++ /dev/null@@ -1,358 +0,0 @@-import re-import datetime-import decimal-from .generic import PdfObject-from xml.dom import getDOMImplementation-from xml.dom.minidom import parseString-from .utils import u_--RDF_NAMESPACE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"-DC_NAMESPACE = "http://purl.org/dc/elements/1.1/"-XMP_NAMESPACE = "http://ns.adobe.com/xap/1.0/"-PDF_NAMESPACE = "http://ns.adobe.com/pdf/1.3/"-XMPMM_NAMESPACE = "http://ns.adobe.com/xap/1.0/mm/"--# What is the PDFX namespace, you might ask? I might ask that too. It's-# a completely undocumented namespace used to place "custom metadata"-# properties, which are arbitrary metadata properties with no semantic or-# documented meaning. Elements in the namespace are key/value-style storage,-# where the element name is the key and the content is the value. The keys-# are transformed into valid XML identifiers by substituting an invalid-# identifier character with \u2182 followed by the unicode hex ID of the-# original character. A key like "my car" is therefore "my\u21820020car".-#-# \u2182, in case you're wondering, is the unicode character-# \u{ROMAN NUMERAL TEN THOUSAND}, a straightforward and obvious choice for-# escaping characters.-#-# Intentional users of the pdfx namespace should be shot on sight. A-# custom data schema and sensical XML elements could be used instead, as is-# suggested by Adobe's own documentation on XMP (under "Extensibility of-# Schemas").-#-# Information presented here on the /pdfx/ schema is a result of limited-# reverse engineering, and does not constitute a full specification.-PDFX_NAMESPACE = "http://ns.adobe.com/pdfx/1.3/"--iso8601 = re.compile("""- (?P<year>[0-9]{4})- (-- (?P<month>[0-9]{2})- (-- (?P<day>[0-9]+)- (T- (?P<hour>[0-9]{2}):- (?P<minute>[0-9]{2})- (:(?P<second>[0-9]{2}(.[0-9]+)?))?- (?P<tzd>Z|[-+][0-9]{2}:[0-9]{2})- )?- )?- )?- """, re.VERBOSE)---class XmpInformation(PdfObject):- """- An object that represents Adobe XMP metadata.- Usually accessed by :meth:`getXmpMetadata()<PyPDF2.PdfFileReader.getXmpMetadata>`- """-- def __init__(self, stream):- self.stream = stream- docRoot = parseString(self.stream.getData())- self.rdfRoot = docRoot.getElementsByTagNameNS(RDF_NAMESPACE, "RDF")[0]- self.cache = {}-- def writeToStream(self, stream, encryption_key):- self.stream.writeToStream(stream, encryption_key)-- def getElement(self, aboutUri, namespace, name):- for desc in self.rdfRoot.getElementsByTagNameNS(RDF_NAMESPACE, "Description"):- if desc.getAttributeNS(RDF_NAMESPACE, "about") == aboutUri:- attr = desc.getAttributeNodeNS(namespace, name)- if attr != None:- yield attr- for element in desc.getElementsByTagNameNS(namespace, name):- yield element-- def getNodesInNamespace(self, aboutUri, namespace):- for desc in self.rdfRoot.getElementsByTagNameNS(RDF_NAMESPACE, "Description"):- if desc.getAttributeNS(RDF_NAMESPACE, "about") == aboutUri:- for i in range(desc.attributes.length):- attr = desc.attributes.item(i)- if attr.namespaceURI == namespace:- yield attr- for child in desc.childNodes:- if child.namespaceURI == namespace:- yield child-- def _getText(self, element):- text = ""- for child in element.childNodes:- if child.nodeType == child.TEXT_NODE:- text += child.data- return text-- def _converter_string(value):- return value-- def _converter_date(value):- m = iso8601.match(value)- year = int(m.group("year"))- month = int(m.group("month") or "1")- day = int(m.group("day") or "1")- hour = int(m.group("hour") or "0")- minute = int(m.group("minute") or "0")- second = decimal.Decimal(m.group("second") or "0")- seconds = second.to_integral(decimal.ROUND_FLOOR)- milliseconds = (second - seconds) * 1000000- tzd = m.group("tzd") or "Z"- dt = datetime.datetime(year, month, day, hour, minute, seconds, milliseconds)- if tzd != "Z":- tzd_hours, tzd_minutes = [int(x) for x in tzd.split(":")]- tzd_hours *= -1- if tzd_hours < 0:- tzd_minutes *= -1- dt = dt + datetime.timedelta(hours=tzd_hours, minutes=tzd_minutes)- return dt- _test_converter_date = staticmethod(_converter_date)-- def _getter_bag(namespace, name, converter):- def get(self):- cached = self.cache.get(namespace, {}).get(name)- if cached:- return cached- retval = []- for element in self.getElement("", namespace, name):- bags = element.getElementsByTagNameNS(RDF_NAMESPACE, "Bag")- if len(bags):- for bag in bags:- for item in bag.getElementsByTagNameNS(RDF_NAMESPACE, "li"):- value = self._getText(item)- value = converter(value)- retval.append(value)- ns_cache = self.cache.setdefault(namespace, {})- ns_cache[name] = retval- return retval- return get-- def _getter_seq(namespace, name, converter):- def get(self):- cached = self.cache.get(namespace, {}).get(name)- if cached:- return cached- retval = []- for element in self.getElement("", namespace, name):- seqs = element.getElementsByTagNameNS(RDF_NAMESPACE, "Seq")- if len(seqs):- for seq in seqs:- for item in seq.getElementsByTagNameNS(RDF_NAMESPACE, "li"):- value = self._getText(item)- value = converter(value)- retval.append(value)- else:- value = converter(self._getText(element))- retval.append(value)- ns_cache = self.cache.setdefault(namespace, {})- ns_cache[name] = retval- return retval- return get-- def _getter_langalt(namespace, name, converter):- def get(self):- cached = self.cache.get(namespace, {}).get(name)- if cached:- return cached- retval = {}- for element in self.getElement("", namespace, name):- alts = element.getElementsByTagNameNS(RDF_NAMESPACE, "Alt")- if len(alts):- for alt in alts:- for item in alt.getElementsByTagNameNS(RDF_NAMESPACE, "li"):- value = self._getText(item)- value = converter(value)- retval[item.getAttribute("xml:lang")] = value- else:- retval["x-default"] = converter(self._getText(element))- ns_cache = self.cache.setdefault(namespace, {})- ns_cache[name] = retval- return retval- return get-- def _getter_single(namespace, name, converter):- def get(self):- cached = self.cache.get(namespace, {}).get(name)- if cached:- return cached- value = None- for element in self.getElement("", namespace, name):- if element.nodeType == element.ATTRIBUTE_NODE:- value = element.nodeValue- else:- value = self._getText(element)- break- if value != None:- value = converter(value)- ns_cache = self.cache.setdefault(namespace, {})- ns_cache[name] = value- return value- return get-- dc_contributor = property(_getter_bag(DC_NAMESPACE, "contributor", _converter_string))- """- Contributors to the resource (other than the authors). An unsorted- array of names.- """-- dc_coverage = property(_getter_single(DC_NAMESPACE, "coverage", _converter_string))- """- Text describing the extent or scope of the resource.- """-- dc_creator = property(_getter_seq(DC_NAMESPACE, "creator", _converter_string))- """- A sorted array of names of the authors of the resource, listed in order- of precedence.- """-- dc_date = property(_getter_seq(DC_NAMESPACE, "date", _converter_date))- """- A sorted array of dates (datetime.datetime instances) of signifigance to- the resource. The dates and times are in UTC.- """-- dc_description = property(_getter_langalt(DC_NAMESPACE, "description", _converter_string))- """- A language-keyed dictionary of textual descriptions of the content of the- resource.- """-- dc_format = property(_getter_single(DC_NAMESPACE, "format", _converter_string))- """- The mime-type of the resource.- """-- dc_identifier = property(_getter_single(DC_NAMESPACE, "identifier", _converter_string))- """- Unique identifier of the resource.- """-- dc_language = property(_getter_bag(DC_NAMESPACE, "language", _converter_string))- """- An unordered array specifying the languages used in the resource.- """-- dc_publisher = property(_getter_bag(DC_NAMESPACE, "publisher", _converter_string))- """- An unordered array of publisher names.- """-- dc_relation = property(_getter_bag(DC_NAMESPACE, "relation", _converter_string))- """- An unordered array of text descriptions of relationships to other- documents.- """-- dc_rights = property(_getter_langalt(DC_NAMESPACE, "rights", _converter_string))- """- A language-keyed dictionary of textual descriptions of the rights the- user has to this resource.- """-- dc_source = property(_getter_single(DC_NAMESPACE, "source", _converter_string))- """- Unique identifier of the work from which this resource was derived.- """-- dc_subject = property(_getter_bag(DC_NAMESPACE, "subject", _converter_string))- """- An unordered array of descriptive phrases or keywrods that specify the- topic of the content of the resource.- """-- dc_title = property(_getter_langalt(DC_NAMESPACE, "title", _converter_string))- """- A language-keyed dictionary of the title of the resource.- """-- dc_type = property(_getter_bag(DC_NAMESPACE, "type", _converter_string))- """- An unordered array of textual descriptions of the document type.- """-- pdf_keywords = property(_getter_single(PDF_NAMESPACE, "Keywords", _converter_string))- """- An unformatted text string representing document keywords.- """-- pdf_pdfversion = property(_getter_single(PDF_NAMESPACE, "PDFVersion", _converter_string))- """- The PDF file version, for example 1.0, 1.3.- """-- pdf_producer = property(_getter_single(PDF_NAMESPACE, "Producer", _converter_string))- """- The name of the tool that created the PDF document.- """-- xmp_createDate = property(_getter_single(XMP_NAMESPACE, "CreateDate", _converter_date))- """- The date and time the resource was originally created. The date and- time are returned as a UTC datetime.datetime object.- """-- xmp_modifyDate = property(_getter_single(XMP_NAMESPACE, "ModifyDate", _converter_date))- """- The date and time the resource was last modified. The date and time- are returned as a UTC datetime.datetime object.- """-- xmp_metadataDate = property(_getter_single(XMP_NAMESPACE, "MetadataDate", _converter_date))- """- The date and time that any metadata for this resource was last- changed. The date and time are returned as a UTC datetime.datetime- object.- """-- xmp_creatorTool = property(_getter_single(XMP_NAMESPACE, "CreatorTool", _converter_string))- """- The name of the first known tool used to create the resource.- """-- xmpmm_documentId = property(_getter_single(XMPMM_NAMESPACE, "DocumentID", _converter_string))- """- The common identifier for all versions and renditions of this resource.- """-- xmpmm_instanceId = property(_getter_single(XMPMM_NAMESPACE, "InstanceID", _converter_string))- """- An identifier for a specific incarnation of a document, updated each- time a file is saved.- """-- def custom_properties(self):- if not hasattr(self, "_custom_properties"):- self._custom_properties = {}- for node in self.getNodesInNamespace("", PDFX_NAMESPACE):- key = node.localName- while True:- # see documentation about PDFX_NAMESPACE earlier in file- idx = key.find(u_("\u2182"))- if idx == -1:- break- key = key[:idx] + chr(int(key[idx+1:idx+5], base=16)) + key[idx+5:]- if node.nodeType == node.ATTRIBUTE_NODE:- value = node.nodeValue- else:- value = self._getText(node)- self._custom_properties[key] = value- return self._custom_properties-- custom_properties = property(custom_properties)- """- Retrieves custom metadata properties defined in the undocumented pdfx- metadata schema.-- :return: a dictionary of key/value items for custom metadata properties.- :rtype: dict- """diff --git a/ext/adblockparser/__init__.py b/ext/adblockparser/__init__.pydeleted file mode 100644index 17e8b2b9..00000000--- a/ext/adblockparser/__init__.py+++ /dev/null@@ -1,3 +0,0 @@-# -*- coding: utf-8 -*--from __future__ import absolute_import-from .parser import AdblockRules, AdblockRulediff --git a/ext/adblockparser/parser.py b/ext/adblockparser/parser.pydeleted file mode 100644index 5c9e1eeb..00000000--- a/ext/adblockparser/parser.py+++ /dev/null@@ -1,415 +0,0 @@-# -*- coding: utf-8 -*--from __future__ import absolute_import-import re-from collections import defaultdict-from functools import partial-from adblockparser.utils import split_data---class AdblockRule(object):- r"""- AdBlock Plus rule.-- Check these links for the format details:-- * https://adblockplus.org/en/filter-cheatsheet- * https://adblockplus.org/en/filters-- Instantiate AdblockRule with a rule line:-- >>> from adblockparser import AdblockRule- >>> rule = AdblockRule("@@||mydomain.no/artikler/$~third-party")-- Parsed data is available as rule attributes:-- >>> rule.is_comment- False- >>> rule.is_exception- True- >>> rule.is_html_rule- False- >>> rule.options- {'third-party': False}- >>> print(rule.regex)- ^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?mydomain\.no/artikler/-- To check if rule applies to an URL, use ``match_url`` method::-- >>> rule = AdblockRule("swf|")- >>> rule.match_url("http://example.com/annoyingflash.swf")- True- >>> rule.match_url("http://example.com/swf/index.html")- False-- Rules involving CSS selectors are detected but not supported well- (``match_url`` doesn't work for them):-- >>> AdblockRule("domain.co.uk,domain2.com#@#.ad_description").is_html_rule- True- >>> AdblockRule("##.spot-ad").is_html_rule- True- """-- BINARY_OPTIONS = [- "script",- "image",- "stylesheet",- "object",- "xmlhttprequest",- "object-subrequest",- "subdocument",- "document",- "elemhide",- "other",- "background",- "xbl",- "ping",- "dtd",- "media",- "third-party",- "match-case",- "collapse",- "donottrack",- ]- OPTIONS_SPLIT_PAT = ',(?=~?(?:%s))' % ('|'.join(BINARY_OPTIONS + ["domain"]))- OPTIONS_SPLIT_RE = re.compile(OPTIONS_SPLIT_PAT)-- __slots__ = ['raw_rule_text', 'is_comment', 'is_html_rule', 'is_exception',- 'raw_options', 'options', '_options_keys', 'rule_text',- 'regex']-- def __init__(self, rule_text):- self.raw_rule_text = rule_text-- rule_text = rule_text.strip()- self.is_comment = rule_text.startswith(('!', '[Adblock'))- if self.is_comment:- self.is_html_rule = self.is_exception = False- else:- self.is_html_rule = '##' in rule_text or '#@#' in rule_text # or rule_text.startswith('#')- self.is_exception = rule_text.startswith('@@')- if self.is_exception:- rule_text = rule_text[2:]-- if not self.is_comment and '$' in rule_text:- rule_text, options_text = rule_text.split('$', 1)- self.raw_options = self._split_options(options_text)- self.options = dict(self._parse_option(opt) for opt in self.raw_options)- else:- self.raw_options = []- self.options = {}- self._options_keys = frozenset(self.options.keys()) - set(['match-case'])-- self.rule_text = rule_text-- if self.is_comment or self.is_html_rule:- # TODO: add support for HTML rules.- # We should split the rule into URL and HTML parts,- # convert URL part to a regex and parse the HTML part.- self.regex = ''- else:- self.regex = self.rule_to_regex(rule_text)-- def match_url(self, url, options=None):- """- Return if this rule matches the URL.-- What to do if rule is matched is up to developer. Most likely- ``.is_exception`` attribute should be taken in account.- """- options = options or {}- for optname in self.options:- if optname == 'match-case': # TODO- continue-- if optname not in options:- raise ValueError("Rule requires option %s" % optname)-- if optname == 'domain':- if not self._domain_matches(options['domain']):- return False- continue-- if options[optname] != self.options[optname]:- return False-- return self._url_matches(url)-- def _domain_matches(self, domain):- domain_rules = self.options['domain']- for domain in _domain_variants(domain):- if domain in domain_rules:- return domain_rules[domain]- return False-- def _url_matches(self, url):- return bool(re.search(self.regex, url))-- def matching_supported(self, options=None):- """- Return whether this rule can return meaningful result,- given the `options` dict. If some options are missing,- then rule shouldn't be matched against, and this function- returns False.-- >>> rule = AdblockRule("swf|")- >>> rule.matching_supported({})- True- >>> rule = AdblockRule("swf|$third-party")- >>> rule.matching_supported({})- False- >>> rule.matching_supported({'domain': 'example.com', 'third-party': False})- True-- """- if self.is_comment:- return False-- if self.is_html_rule: # HTML rules are not supported yet- return False-- options = options or {}- keys = set(options.keys())- if not keys.issuperset(self._options_keys):- # some of the required options are not given- return False-- return True-- @classmethod- def _split_options(cls, options_text):- return cls.OPTIONS_SPLIT_RE.split(options_text)-- @classmethod- def _parse_domain_option(cls, text):- domains = text[len('domain='):]- parts = domains.replace(',', '|').split('|')- return dict(cls._parse_option_negation(p) for p in parts)-- @classmethod- def _parse_option_negation(cls, text):- return (text.lstrip('~'), not text.startswith('~'))-- @classmethod- def _parse_option(cls, text):- if text.startswith("domain="):- return ("domain", cls._parse_domain_option(text))- return cls._parse_option_negation(text)-- @classmethod- def rule_to_regex(cls, rule):- """- Convert AdBlock rule to a regular expression.- """- if not rule:- raise ValueError("Invalid rule")- # return rule-- # escape special regex characters- rule = re.sub(r"([.$+?{}()\[\]\\])", r"\\\1", rule)-- # XXX: the resulting regex must use non-capturing groups (?:- # for performance reasons; also, there is a limit on number- # of capturing groups, no using them would prevent building- # a single regex out of several rules.-- # Separator character ^ matches anything but a letter, a digit, or- # one of the following: _ - . %. The end of the address is also- # accepted as separator.- rule = rule.replace("^", "(?:[^\w\d_\-.%]|$)")-- # * symbol- rule = rule.replace("*", ".*")-- # | in the end means the end of the address- if rule[-1] == '|':- rule = rule[:-1] + '$'-- # || in the beginning means beginning of the domain name- if rule[:2] == '||':- # XXX: it is better to use urlparse for such things,- # but urlparse doesn't give us a single regex.- # Regex is based on http://tools.ietf.org/html/rfc3986#appendix-B- if len(rule) > 2:- # | | complete part |- # | scheme | of the domain |- rule = r"^(?:[^:/?#]+:)?(?://(?:[^/?#]*\.)?)?" + rule[2:]-- elif rule[0] == '|':- # | in the beginning means start of the address- rule = '^' + rule[1:]-- # other | symbols should be escaped- # we have "|$" in our regexp - do not touch it- rule = re.sub("(\|)[^$]", r"\|", rule)-- return rule-- def __repr__(self):- return "AdblockRule(%r)" % self.raw_rule_text---class AdblockRules(object):- """- AdblockRules is a class for checking URLs against multiple AdBlock rules.-- It is more efficient to use AdblockRules instead of creating AdblockRule- instances manually and checking them one-by-one because AdblockRules- optimizes some common cases.- """-- def __init__(self, rules, supported_options=None, skip_unsupported_rules=True,- use_re2='auto', max_mem=256*1024*1024, rule_cls=AdblockRule):-- if supported_options is None:- self.supported_options = rule_cls.BINARY_OPTIONS + ['domain']- else:- self.supported_options = supported_options-- self.uses_re2 = _is_re2_supported() if use_re2 == 'auto' else use_re2- self.re2_max_mem = max_mem- self.rule_cls = rule_cls- self.skip_unsupported_rules = skip_unsupported_rules-- _params = dict((opt, True) for opt in self.supported_options)- self.rules = [- r for r in (self.rule_cls(r) for r in rules)- if r.regex and r.matching_supported(_params)- ]-- # "advanced" rules are rules with options,- # "basic" rules are rules without options- advanced_rules, basic_rules = split_data(self.rules, lambda r: r.options)-- # rules with domain option are handled separately:- # we may discard most rules based on domain information,- # so parser builds an index for that later.- domain_rules, non_domain_rules = split_data(- advanced_rules,- lambda r: 'domain' in r.options- )-- # split rules into blacklists and whitelists- self.blacklist, self.whitelist = self._split_bw(basic_rules)- _combined = partial(_combined_regex, use_re2=self.uses_re2, max_mem=max_mem)- self.blacklist_re = _combined([r.regex for r in self.blacklist])- self.whitelist_re = _combined([r.regex for r in self.whitelist])-- self.blacklist_adv, self.whitelist_adv = self._split_bw(non_domain_rules)- self.blacklist_domains, self.whitelist_domains = self._split_bw_domain(domain_rules)--- def should_block(self, url, options=None):- # TODO: group rules with similar options and match them in bigger steps- options = options or {}- if self._is_whitelisted(url, options):- return False- if self._is_blacklisted(url, options):- return True- return False-- def _is_whitelisted(self, url, options):- return self._matches(- url, options,- self.whitelist_re, self.whitelist_domains, self.whitelist_adv- )-- def _is_blacklisted(self, url, options):- return self._matches(- url, options,- self.blacklist_re, self.blacklist_domains, self.blacklist_adv- )-- def _matches(self, url, options,- general_re, rules_with_domains, rules_with_options):- """- Return if ``url``/``options`` are matched by rules defined by- ``general_re``, ``rules_with_domains`` and ``rules_with_options``.-- ``general_re`` is a compiled regex for rules without options.-- ``rules_with_domains`` is a {domain: [rules]} mapping - per-domain- index of applicable rules which have 'domain' option.-- ``rules_with_options`` is a list of AdblockRule instances that- don't have 'domain' option, but have other options.- """- if general_re and general_re.search(url):- return True-- rules = []- if 'domain' in options and rules_with_domains:- src_domain = options['domain']- for domain in _domain_variants(src_domain):- if domain in rules_with_domains:- rules = rules_with_domains[domain]- break-- rules.extend(rules_with_options)-- if self.skip_unsupported_rules:- rules = [rule for rule in rules if rule.matching_supported(options)]-- return any(rule.match_url(url, options) for rule in rules)-- @classmethod- def _split_bw(cls, rules):- return split_data(rules, lambda r: not r.is_exception)-- @classmethod- def _split_bw_domain(cls, rules):- blacklist, whitelist = cls._split_bw(rules)- return cls._domain_index(blacklist), cls._domain_index(whitelist)-- @classmethod- def _domain_index(cls, rules):- result = defaultdict(list)- for rule in rules:- for domain in rule.options.get('domain', []):- result[domain].append(rule)- return dict(result)---def _domain_variants(domain):- """- >>> list(_domain_variants("foo.bar.example.com"))- ['foo.bar.example.com', 'bar.example.com', 'example.com']- """- parts = domain.split('.')- for i in range(len(parts), 1, -1):- yield ".".join(parts[-i:])---def _combined_regex(regexes, flags=re.IGNORECASE, use_re2=False, max_mem=None):- """- Return a compiled regex combined (using OR) from a list of ``regexes``.- If there is nothing to combine, None is returned.-- re2 library (https://github.com/axiak/pyre2) often can match and compile- large regexes much faster than stdlib re module (10x is not uncommon),- but there are some gotchas:-- * at the moment of writing (Feb 2014) latest re2 pypi release (0.2.20)- doesn't work; pyre2 must be installed from the github repo;- * in case of "DFA out of memory" errors use ``max_mem`` argument- to increase the amount of memory re2 is allowed to use.- """- joined_regexes = "|".join(r for r in regexes if r)- if not joined_regexes:- return None-- if use_re2:- import re2- return re2.compile(joined_regexes, flags=flags, max_mem=max_mem)- return re.compile(joined_regexes, flags=flags)---def _is_re2_supported():- try:- import re2- except ImportError:- return False-- # re2.match doesn't work in re2 v0.2.20 installed from pypi- # (it always returns None).- return re2.match('foo', 'foo') is not Nonediff --git a/ext/adblockparser/utils.py b/ext/adblockparser/utils.pydeleted file mode 100644index bc7e662b..00000000--- a/ext/adblockparser/utils.py+++ /dev/null@@ -1,11 +0,0 @@-# -*- coding: utf-8 -*--from __future__ import absolute_import--def split_data(data, pred):- yes, no = [], []- for d in data:- if pred(d):- yes.append(d)- else:- no.append(d)- return [yes, no]diff --git a/ext/dns/LICENSE b/ext/dns/LICENSEdeleted file mode 100644index 633c18c1..00000000--- a/ext/dns/LICENSE+++ /dev/null@@ -1,14 +0,0 @@-Copyright (C) 2001-2003 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.diff --git a/ext/dns/__init__.py b/ext/dns/__init__.pydeleted file mode 100644index c848e485..00000000--- a/ext/dns/__init__.py+++ /dev/null@@ -1,54 +0,0 @@-# 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',-]diff --git a/ext/dns/dnssec.py b/ext/dns/dnssec.pydeleted file mode 100644index 084f908d..00000000--- a/ext/dns/dnssec.py+++ /dev/null@@ -1,374 +0,0 @@-# 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_candidate_keys(keys, rrsig):- candidate_keys=[]- value = keys.get(rrsig.signer)- if value is None:- return None- if isinstance(value, dns.node.Node):- try:- rdataset = value.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:- candidate_keys.append(rdata)- return candidate_keys--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)-- for candidate_key in _find_candidate_keys(keys, rrsig):- if not candidate_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 = candidate_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 = candidate_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 pubkey.verify(digest, sig):- return- 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_pycryptodiff --git a/ext/dns/e164.py b/ext/dns/e164.pydeleted file mode 100644index 68f0a316..00000000--- a/ext/dns/e164.py+++ /dev/null@@ -1,79 +0,0 @@-# 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 origin: 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 origin: 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.NXDOMAINdiff --git a/ext/dns/edns.py b/ext/dns/edns.pydeleted file mode 100644index e52b6df3..00000000--- a/ext/dns/edns.py+++ /dev/null@@ -1,142 +0,0 @@-# 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 otype: The rdata type- @type otype: 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.edns.Option instance"""- raise NotImplementedError-- from_wire = classmethod(from_wire)-- def _cmp(self, other):- """Compare an EDNS 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 __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.edns.Option instance"""-- cls = get_option_class(otype)- return cls.from_wire(otype, wire, current, olen)diff --git a/ext/dns/entropy.py b/ext/dns/entropy.pydeleted file mode 100644index d380cf8c..00000000--- a/ext/dns/entropy.py+++ /dev/null@@ -1,123 +0,0 @@-# 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:- try:- import sha- self.hash = sha.new()- self.hash_len = 20- except:- 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:- try:- r = file('/dev/urandom', 'r', 0)- try:- seed = r.read(16)- finally:- r.close()- except:- 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)diff --git a/ext/dns/exception.py b/ext/dns/exception.pydeleted file mode 100644index db6ef6e6..00000000--- a/ext/dns/exception.py+++ /dev/null@@ -1,40 +0,0 @@-# 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."""- passdiff --git a/ext/dns/flags.py b/ext/dns/flags.pydeleted file mode 100644index 35a8305e..00000000--- a/ext/dns/flags.py+++ /dev/null@@ -1,106 +0,0 @@-# 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)diff --git a/ext/dns/grange.py b/ext/dns/grange.pydeleted file mode 100644index c0607d60..00000000--- a/ext/dns/grange.py+++ /dev/null@@ -1,65 +0,0 @@-# 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 GENERATE range conversion."""--import dns--def from_text(text):- """Convert the text form of a range in a GENERATE statement to an- integer.-- @param text: the textual range- @type text: string- @return: The start, stop and step values.- @rtype: tuple- """- # TODO, figure out the bounds on start, stop and step.-- import pdb- step = 1- cur = ''- state = 0- # state 0 1 2 3 4- # x - y / z- for c in text:- if c == '-' and state == 0:- start = int(cur)- cur = ''- state = 2- elif c == '/':- stop = int(cur)- cur = ''- state = 4- elif c.isdigit():- cur += c- else:- raise dns.exception.SyntaxError("Could not parse %s" % (c))-- if state in (1, 3):- raise dns.exception.SyntaxError-- if state == 2:- stop = int(cur)-- if state == 4:- step = int(cur)-- assert step >= 1- assert start >= 0- assert start <= stop- # TODO, can start == stop?-- return (start, stop, step)diff --git a/ext/dns/hash.py b/ext/dns/hash.pydeleted file mode 100644index 0c708036..00000000--- a/ext/dns/hash.py+++ /dev/null@@ -1,67 +0,0 @@-# 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()]diff --git a/ext/dns/inet.py b/ext/dns/inet.pydeleted file mode 100644index 3b7e88f7..00000000--- a/ext/dns/inet.py+++ /dev/null@@ -1,108 +0,0 @@-# 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.--"""Generic Internet address helper functions."""--import socket--import dns.ipv4-import dns.ipv6---# We assume that AF_INET is always defined.--AF_INET = socket.AF_INET--# AF_INET6 might not be defined in the socket module, but we need it.-# We'll try to use the socket module's value, and if it doesn't work,-# we'll use our own value.--try:- AF_INET6 = socket.AF_INET6-except AttributeError:- AF_INET6 = 9999--def inet_pton(family, text):- """Convert the textual form of a network address into its binary form.-- @param family: the address family- @type family: int- @param text: the textual address- @type text: string- @raises NotImplementedError: the address family specified is not- implemented.- @rtype: string- """-- if family == AF_INET:- return dns.ipv4.inet_aton(text)- elif family == AF_INET6:- return dns.ipv6.inet_aton(text)- else:- raise NotImplementedError--def inet_ntop(family, address):- """Convert the binary form of a network address into its textual form.-- @param family: the address family- @type family: int- @param address: the binary address- @type address: string- @raises NotImplementedError: the address family specified is not- implemented.- @rtype: string- """- if family == AF_INET:- return dns.ipv4.inet_ntoa(address)- elif family == AF_INET6:- return dns.ipv6.inet_ntoa(address)- else:- raise NotImplementedError--def af_for_address(text):- """Determine the address family of a textual-form network address.-- @param text: the textual address- @type text: string- @raises ValueError: the address family cannot be determined from the input.- @rtype: int- """- try:- junk = dns.ipv4.inet_aton(text)- return AF_INET- except:- try:- junk = dns.ipv6.inet_aton(text)- return AF_INET6- except:- raise ValueError--def is_multicast(text):- """Is the textual-form network address a multicast address?-- @param text: the textual address- @raises ValueError: the address family cannot be determined from the input.- @rtype: bool- """- try:- first = ord(dns.ipv4.inet_aton(text)[0])- return (first >= 224 and first <= 239)- except:- try:- first = ord(dns.ipv6.inet_aton(text)[0])- return (first == 255)- except:- raise ValueError-diff --git a/ext/dns/ipv4.py b/ext/dns/ipv4.pydeleted file mode 100644index 85ab48f7..00000000--- a/ext/dns/ipv4.py+++ /dev/null@@ -1,54 +0,0 @@-# 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 struct--import dns.exception--def inet_ntoa(address):- """Convert an IPv4 address in network form to text form.-- @param address: The IPv4 address- @type address: string- @returns: string- """- if len(address) != 4:- raise dns.exception.SyntaxError- return '%u.%u.%u.%u' % (ord(address[0]), ord(address[1]),- ord(address[2]), ord(address[3]))--def inet_aton(text):- """Convert an IPv4 address in text form to network form.-- @param text: The IPv4 address- @type text: string- @returns: string- """- parts = text.split('.')- if len(parts) != 4:- raise dns.exception.SyntaxError- for part in parts:- if not part.isdigit():- raise dns.exception.SyntaxError- if len(part) > 1 and part[0] == '0':- # No leading zeros- raise dns.exception.SyntaxError- try:- bytes = [int(part) for part in parts]- return struct.pack('BBBB', *bytes)- except:- raise dns.exception.SyntaxErrordiff --git a/ext/dns/ipv6.py b/ext/dns/ipv6.pydeleted file mode 100644index 1ab00da9..00000000--- a/ext/dns/ipv6.py+++ /dev/null@@ -1,163 +0,0 @@-# 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 > 1:- 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:- b = dns.ipv4.inet_aton(m.group(2))- text = "%s:%02x%02x:%02x%02x" % (m.group(1), ord(b[0]), ord(b[1]),- ord(b[2]), ord(b[3]))- #- # 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.SyntaxErrordiff --git a/ext/dns/message.py b/ext/dns/message.pydeleted file mode 100644index 52c0eaea..00000000--- a/ext/dns/message.py+++ /dev/null@@ -1,1107 +0,0 @@-# 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 Messages"""--import cStringIO-import random-import struct-import sys-import time--import dns.edns-import dns.exception-import dns.flags-import dns.name-import dns.opcode-import dns.entropy-import dns.rcode-import dns.rdata-import dns.rdataclass-import dns.rdatatype-import dns.rrset-import dns.renderer-import dns.tsig-import dns.wiredata--class ShortHeader(dns.exception.FormError):- """Raised if the DNS packet passed to from_wire() is too short."""- pass--class TrailingJunk(dns.exception.FormError):- """Raised if the DNS packet passed to from_wire() has extra junk- at the end of it."""- pass--class UnknownHeaderField(dns.exception.DNSException):- """Raised if a header field name is not recognized when converting from- text into a message."""- pass--class BadEDNS(dns.exception.FormError):- """Raised if an OPT record occurs somewhere other than the start of- the additional data section."""- pass--class BadTSIG(dns.exception.FormError):- """Raised if a TSIG record occurs somewhere other than the end of- the additional data section."""- pass--class UnknownTSIGKey(dns.exception.DNSException):- """Raised if we got a TSIG but don't know the key."""- pass--class Message(object):- """A DNS message.-- @ivar id: The query id; the default is a randomly chosen id.- @type id: int- @ivar flags: The DNS flags of the message. @see: RFC 1035 for an- explanation of these flags.- @type flags: int- @ivar question: The question section.- @type question: list of dns.rrset.RRset objects- @ivar answer: The answer section.- @type answer: list of dns.rrset.RRset objects- @ivar authority: The authority section.- @type authority: list of dns.rrset.RRset objects- @ivar additional: The additional data section.- @type additional: list of dns.rrset.RRset objects- @ivar edns: The EDNS level to use. The default is -1, no Edns.- @type edns: int- @ivar ednsflags: The EDNS flags- @type ednsflags: long- @ivar payload: The EDNS payload size. The default is 0.- @type payload: int- @ivar options: The EDNS options- @type options: list of dns.edns.Option objects- @ivar request_payload: The associated request's EDNS payload size.- @type request_payload: int- @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 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- @ivar request_mac: The TSIG MAC of the request message associated with- this message; used when validating TSIG signatures. @see: RFC 2845 for- more information on TSIG fields.- @type request_mac: string- @ivar fudge: TSIG time fudge; default is 300 seconds.- @type fudge: int- @ivar original_id: TSIG original id; defaults to the message's id- @type original_id: int- @ivar tsig_error: TSIG error code; default is 0.- @type tsig_error: int- @ivar other_data: TSIG other data.- @type other_data: string- @ivar mac: The TSIG MAC for this message.- @type mac: string- @ivar xfr: Is the message being used to contain the results of a DNS- zone transfer? The default is False.- @type xfr: bool- @ivar origin: The origin of the zone in messages which are used for- zone transfers or for DNS dynamic updates. The default is None.- @type origin: dns.name.Name object- @ivar tsig_ctx: The TSIG signature context associated with this- message. The default is None.- @type tsig_ctx: hmac.HMAC object- @ivar had_tsig: Did the message decoded from wire format have a TSIG- signature?- @type had_tsig: bool- @ivar multi: Is this message part of a multi-message sequence? The- default is false. This variable is used when validating TSIG signatures- on messages which are part of a zone transfer.- @type multi: bool- @ivar first: Is this message standalone, or the first of a multi- message sequence? This variable is used when validating TSIG signatures- on messages which are part of a zone transfer.- @type first: bool- @ivar index: An index of rrsets in the message. The index key is- (section, name, rdclass, rdtype, covers, deleting). Indexing can be- disabled by setting the index to None.- @type index: dict- """-- def __init__(self, id=None):- if id is None:- self.id = dns.entropy.random_16()- else:- self.id = id- self.flags = 0- self.question = []- self.answer = []- self.authority = []- self.additional = []- self.edns = -1- self.ednsflags = 0- self.payload = 0- self.options = []- self.request_payload = 0- self.keyring = None- self.keyname = None- self.keyalgorithm = dns.tsig.default_algorithm- self.request_mac = ''- self.other_data = ''- self.tsig_error = 0- self.fudge = 300- self.original_id = self.id- self.mac = ''- self.xfr = False- self.origin = None- self.tsig_ctx = None- self.had_tsig = False- self.multi = False- self.first = True- self.index = {}-- def __repr__(self):- return '<DNS message, ID ' + `self.id` + '>'-- def __str__(self):- return self.to_text()-- def to_text(self, origin=None, relativize=True, **kw):- """Convert the message to text.-- The I{origin}, I{relativize}, and any other keyword- arguments are passed to the rrset to_wire() method.-- @rtype: string- """-- s = cStringIO.StringIO()- print >> s, 'id %d' % self.id- print >> s, 'opcode %s' % \- dns.opcode.to_text(dns.opcode.from_flags(self.flags))- rc = dns.rcode.from_flags(self.flags, self.ednsflags)- print >> s, 'rcode %s' % dns.rcode.to_text(rc)- print >> s, 'flags %s' % dns.flags.to_text(self.flags)- if self.edns >= 0:- print >> s, 'edns %s' % self.edns- if self.ednsflags != 0:- print >> s, 'eflags %s' % \- dns.flags.edns_to_text(self.ednsflags)- print >> s, 'payload', self.payload- is_update = dns.opcode.is_update(self.flags)- if is_update:- print >> s, ';ZONE'- else:- print >> s, ';QUESTION'- for rrset in self.question:- print >> s, rrset.to_text(origin, relativize, **kw)- if is_update:- print >> s, ';PREREQ'- else:- print >> s, ';ANSWER'- for rrset in self.answer:- print >> s, rrset.to_text(origin, relativize, **kw)- if is_update:- print >> s, ';UPDATE'- else:- print >> s, ';AUTHORITY'- for rrset in self.authority:- print >> s, rrset.to_text(origin, relativize, **kw)- print >> s, ';ADDITIONAL'- for rrset in self.additional:- print >> s, rrset.to_text(origin, relativize, **kw)- #- # We strip off the final \n so the caller can print the result without- # doing weird things to get around eccentricities in Python print- # formatting- #- return s.getvalue()[:-1]-- def __eq__(self, other):- """Two messages are equal if they have the same content in the- header, question, answer, and authority sections.- @rtype: bool"""- if not isinstance(other, Message):- return False- if self.id != other.id:- return False- if self.flags != other.flags:- return False- for n in self.question:- if n not in other.question:- return False- for n in other.question:- if n not in self.question:- return False- for n in self.answer:- if n not in other.answer:- return False- for n in other.answer:- if n not in self.answer:- return False- for n in self.authority:- if n not in other.authority:- return False- for n in other.authority:- if n not in self.authority:- return False- return True-- def __ne__(self, other):- """Are two messages not equal?- @rtype: bool"""- return not self.__eq__(other)-- def is_response(self, other):- """Is other a response to self?- @rtype: bool"""- if other.flags & dns.flags.QR == 0 or \- self.id != other.id or \- dns.opcode.from_flags(self.flags) != \- dns.opcode.from_flags(other.flags):- return False- if dns.rcode.from_flags(other.flags, other.ednsflags) != \- dns.rcode.NOERROR:- return True- if dns.opcode.is_update(self.flags):- return True- for n in self.question:- if n not in other.question:- return False- for n in other.question:- if n not in self.question:- return False- return True-- def section_number(self, section):- if section is self.question:- return 0- elif section is self.answer:- return 1- elif section is self.authority:- return 2- elif section is self.additional:- return 3- else:- raise ValueError('unknown section')-- def find_rrset(self, section, name, rdclass, rdtype,- covers=dns.rdatatype.NONE, deleting=None, create=False,- force_unique=False):- """Find the RRset with the given attributes in the specified section.-- @param section: the section of the message to look in, e.g.- self.answer.- @type section: list of dns.rrset.RRset objects- @param name: the name of the RRset- @type name: dns.name.Name object- @param rdclass: the class of the RRset- @type rdclass: int- @param rdtype: the type of the RRset- @type rdtype: int- @param covers: the covers value of the RRset- @type covers: int- @param deleting: the deleting value of the RRset- @type deleting: int- @param create: If True, create the RRset if it is not found.- The created RRset is appended to I{section}.- @type create: bool- @param force_unique: If True and create is also True, create a- new RRset regardless of whether a matching RRset exists already.- @type force_unique: bool- @raises KeyError: the RRset was not found and create was False- @rtype: dns.rrset.RRset object"""-- key = (self.section_number(section),- name, rdclass, rdtype, covers, deleting)- if not force_unique:- if not self.index is None:- rrset = self.index.get(key)- if not rrset is None:- return rrset- else:- for rrset in section:- if rrset.match(name, rdclass, rdtype, covers, deleting):- return rrset- if not create:- raise KeyError- rrset = dns.rrset.RRset(name, rdclass, rdtype, covers, deleting)- section.append(rrset)- if not self.index is None:- self.index[key] = rrset- return rrset-- def get_rrset(self, section, name, rdclass, rdtype,- covers=dns.rdatatype.NONE, deleting=None, create=False,- force_unique=False):- """Get the RRset with the given attributes in the specified section.-- If the RRset is not found, None is returned.-- @param section: the section of the message to look in, e.g.- self.answer.- @type section: list of dns.rrset.RRset objects- @param name: the name of the RRset- @type name: dns.name.Name object- @param rdclass: the class of the RRset- @type rdclass: int- @param rdtype: the type of the RRset- @type rdtype: int- @param covers: the covers value of the RRset- @type covers: int- @param deleting: the deleting value of the RRset- @type deleting: int- @param create: If True, create the RRset if it is not found.- The created RRset is appended to I{section}.- @type create: bool- @param force_unique: If True and create is also True, create a- new RRset regardless of whether a matching RRset exists already.- @type force_unique: bool- @rtype: dns.rrset.RRset object or None"""-- try:- rrset = self.find_rrset(section, name, rdclass, rdtype, covers,- deleting, create, force_unique)- except KeyError:- rrset = None- return rrset-- def to_wire(self, origin=None, max_size=0, **kw):- """Return a string containing the message in DNS compressed wire- format.-- Additional keyword arguments are passed to the rrset to_wire()- method.-- @param origin: The origin to be appended to any relative names.- @type origin: dns.name.Name object- @param max_size: The maximum size of the wire format output; default- is 0, which means 'the message's request payload, if nonzero, or- 65536'.- @type max_size: int- @raises dns.exception.TooBig: max_size was exceeded- @rtype: string- """-- if max_size == 0:- if self.request_payload != 0:- max_size = self.request_payload- else:- max_size = 65535- if max_size < 512:- max_size = 512- elif max_size > 65535:- max_size = 65535- r = dns.renderer.Renderer(self.id, self.flags, max_size, origin)- for rrset in self.question:- r.add_question(rrset.name, rrset.rdtype, rrset.rdclass)- for rrset in self.answer:- r.add_rrset(dns.renderer.ANSWER, rrset, **kw)- for rrset in self.authority:- r.add_rrset(dns.renderer.AUTHORITY, rrset, **kw)- if self.edns >= 0:- r.add_edns(self.edns, self.ednsflags, self.payload, self.options)- for rrset in self.additional:- r.add_rrset(dns.renderer.ADDITIONAL, rrset, **kw)- r.write_header()- if not self.keyname is None:- r.add_tsig(self.keyname, self.keyring[self.keyname],- self.fudge, self.original_id, self.tsig_error,- self.other_data, self.request_mac,- self.keyalgorithm)- self.mac = r.mac- return r.get_wire()-- def use_tsig(self, keyring, keyname=None, fudge=300,- original_id=None, tsig_error=0, other_data='',- algorithm=dns.tsig.default_algorithm):- """When sending, a TSIG signature using the specified keyring- and keyname should be added.-- @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 fudge: TSIG time fudge; default is 300 seconds.- @type fudge: int- @param original_id: TSIG original id; defaults to the message's id- @type original_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 algorithm: The TSIG algorithm to use; defaults to- dns.tsig.default_algorithm- """-- self.keyring = keyring- if keyname is None:- self.keyname = self.keyring.keys()[0]- else:- if isinstance(keyname, (str, unicode)):- keyname = dns.name.from_text(keyname)- self.keyname = keyname- self.keyalgorithm = algorithm- self.fudge = fudge- if original_id is None:- self.original_id = self.id- else:- self.original_id = original_id- self.tsig_error = tsig_error- self.other_data = other_data-- def use_edns(self, edns=0, ednsflags=0, payload=1280, request_payload=None, options=None):- """Configure EDNS behavior.- @param edns: The EDNS level to use. Specifying None, False, or -1- means 'do not use EDNS', and in this case the other parameters are- ignored. Specifying True is equivalent to specifying 0, i.e. 'use- EDNS0'.- @type edns: int or bool or None- @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 request_payload: The EDNS payload size to use when sending- this message. If not specified, defaults to the value of payload.- @type request_payload: int or None- @param options: The EDNS options- @type options: None or list of dns.edns.Option objects- @see: RFC 2671- """- if edns is None or edns is False:- edns = -1- if edns is True:- edns = 0- if request_payload is None:- request_payload = payload- if edns < 0:- ednsflags = 0- payload = 0- request_payload = 0- options = []- else:- # make sure the EDNS version in ednsflags agrees with edns- ednsflags &= 0xFF00FFFFL- ednsflags |= (edns << 16)- if options is None:- options = []- self.edns = edns- self.ednsflags = ednsflags- self.payload = payload- self.options = options- self.request_payload = request_payload-- def want_dnssec(self, wanted=True):- """Enable or disable 'DNSSEC desired' flag in requests.- @param wanted: Is DNSSEC desired? If True, EDNS is enabled if- required, and then the DO bit is set. If False, the DO bit is- cleared if EDNS is enabled.- @type wanted: bool- """- if wanted:- if self.edns < 0:- self.use_edns()- self.ednsflags |= dns.flags.DO- elif self.edns >= 0:- self.ednsflags &= ~dns.flags.DO-- def rcode(self):- """Return the rcode.- @rtype: int- """- return dns.rcode.from_flags(self.flags, self.ednsflags)-- def set_rcode(self, rcode):- """Set the rcode.- @param rcode: the rcode- @type rcode: int- """- (value, evalue) = dns.rcode.to_flags(rcode)- self.flags &= 0xFFF0- self.flags |= value- self.ednsflags &= 0x00FFFFFFL- self.ednsflags |= evalue- if self.ednsflags != 0 and self.edns < 0:- self.edns = 0-- def opcode(self):- """Return the opcode.- @rtype: int- """- return dns.opcode.from_flags(self.flags)-- def set_opcode(self, opcode):- """Set the opcode.- @param opcode: the opcode- @type opcode: int- """- self.flags &= 0x87FF- self.flags |= dns.opcode.to_flags(opcode)--class _WireReader(object):- """Wire format reader.-- @ivar wire: the wire-format message.- @type wire: string- @ivar message: The message object being built- @type message: dns.message.Message object- @ivar current: When building a message object from wire format, this- variable contains the offset from the beginning of wire of the next octet- to be read.- @type current: int- @ivar updating: Is the message a dynamic update?- @type updating: bool- @ivar one_rr_per_rrset: Put each RR into its own RRset?- @type one_rr_per_rrset: bool- @ivar ignore_trailing: Ignore trailing junk at end of request?- @type ignore_trailing: bool- @ivar zone_rdclass: The class of the zone in messages which are- DNS dynamic updates.- @type zone_rdclass: int- """-- def __init__(self, wire, message, question_only=False,- one_rr_per_rrset=False, ignore_trailing=False):- self.wire = dns.wiredata.maybe_wrap(wire)- self.message = message- self.current = 0- self.updating = False- self.zone_rdclass = dns.rdataclass.IN- self.question_only = question_only- self.one_rr_per_rrset = one_rr_per_rrset- self.ignore_trailing = ignore_trailing-- def _get_question(self, qcount):- """Read the next I{qcount} records from the wire data and add them to- the question section.- @param qcount: the number of questions in the message- @type qcount: int"""-- if self.updating and qcount > 1:- raise dns.exception.FormError-- for i in xrange(0, qcount):- (qname, used) = dns.name.from_wire(self.wire, self.current)- if not self.message.origin is None:- qname = qname.relativize(self.message.origin)- self.current = self.current + used- (rdtype, rdclass) = \- struct.unpack('!HH',- self.wire[self.current:self.current + 4])- self.current = self.current + 4- self.message.find_rrset(self.message.question, qname,- rdclass, rdtype, create=True,- force_unique=True)- if self.updating:- self.zone_rdclass = rdclass-- def _get_section(self, section, count):- """Read the next I{count} records from the wire data and add them to- the specified section.- @param section: the section of the message to which to add records- @type section: list of dns.rrset.RRset objects- @param count: the number of records to read- @type count: int"""-- if self.updating or self.one_rr_per_rrset:- force_unique = True- else:- force_unique = False- seen_opt = False- for i in xrange(0, count):- rr_start = self.current- (name, used) = dns.name.from_wire(self.wire, self.current)- absolute_name = name- if not self.message.origin is None:- name = name.relativize(self.message.origin)- self.current = self.current + used- (rdtype, rdclass, ttl, rdlen) = \- struct.unpack('!HHIH',- self.wire[self.current:self.current + 10])- self.current = self.current + 10- if rdtype == dns.rdatatype.OPT:- if not section is self.message.additional or seen_opt:- raise BadEDNS- self.message.payload = rdclass- self.message.ednsflags = ttl- self.message.edns = (ttl & 0xff0000) >> 16- self.message.options = []- current = self.current- optslen = rdlen- while optslen > 0:- (otype, olen) = \- struct.unpack('!HH',- self.wire[current:current + 4])- current = current + 4- opt = dns.edns.option_from_wire(otype, self.wire, current, olen)- self.message.options.append(opt)- current = current + olen- optslen = optslen - 4 - olen- seen_opt = True- elif rdtype == dns.rdatatype.TSIG:- if not (section is self.message.additional and- i == (count - 1)):- raise BadTSIG- if self.message.keyring is None:- raise UnknownTSIGKey('got signed message without keyring')- secret = self.message.keyring.get(absolute_name)- if secret is None:- raise UnknownTSIGKey("key '%s' unknown" % name)- self.message.tsig_ctx = \- dns.tsig.validate(self.wire,- absolute_name,- secret,- int(time.time()),- self.message.request_mac,- rr_start,- self.current,- rdlen,- self.message.tsig_ctx,- self.message.multi,- self.message.first)- self.message.had_tsig = True- else:- if ttl < 0:- ttl = 0- if self.updating and \- (rdclass == dns.rdataclass.ANY or- rdclass == dns.rdataclass.NONE):- deleting = rdclass- rdclass = self.zone_rdclass- else:- deleting = None- if deleting == dns.rdataclass.ANY or \- (deleting == dns.rdataclass.NONE and \- section is self.message.answer):- covers = dns.rdatatype.NONE- rd = None- else:- rd = dns.rdata.from_wire(rdclass, rdtype, self.wire,- self.current, rdlen,- self.message.origin)- covers = rd.covers()- if self.message.xfr and rdtype == dns.rdatatype.SOA:- force_unique = True- rrset = self.message.find_rrset(section, name,- rdclass, rdtype, covers,- deleting, True, force_unique)- if not rd is None:- rrset.add(rd, ttl)- self.current = self.current + rdlen-- def read(self):- """Read a wire format DNS message and build a dns.message.Message- object."""-- l = len(self.wire)- if l < 12:- raise ShortHeader- (self.message.id, self.message.flags, qcount, ancount,- aucount, adcount) = struct.unpack('!HHHHHH', self.wire[:12])- self.current = 12- if dns.opcode.is_update(self.message.flags):- self.updating = True- self._get_question(qcount)- if self.question_only:- return- self._get_section(self.message.answer, ancount)- self._get_section(self.message.authority, aucount)- self._get_section(self.message.additional, adcount)- if not self.ignore_trailing and self.current != l:- raise TrailingJunk- if self.message.multi and self.message.tsig_ctx and \- not self.message.had_tsig:- self.message.tsig_ctx.update(self.wire)---def from_wire(wire, keyring=None, request_mac='', xfr=False, origin=None,- tsig_ctx = None, multi = False, first = True,- question_only = False, one_rr_per_rrset = False,- ignore_trailing = False):- """Convert a DNS wire format message into a message- object.-- @param keyring: The keyring to use if the message is signed.- @type keyring: dict- @param request_mac: If the message is a response to a TSIG-signed request,- I{request_mac} should be set to the MAC of that request.- @type request_mac: string- @param xfr: Is this message part of a zone transfer?- @type xfr: bool- @param origin: If the message is part of a zone transfer, I{origin}- should be the origin name of the zone.- @type origin: dns.name.Name object- @param tsig_ctx: The ongoing TSIG context, used when validating zone- transfers.- @type tsig_ctx: hmac.HMAC object- @param multi: Is this message part of a multiple message sequence?- @type multi: bool- @param first: Is this message standalone, or the first of a multi- message sequence?- @type first: bool- @param question_only: Read only up to the end of the question section?- @type question_only: bool- @param one_rr_per_rrset: Put each RR into its own RRset- @type one_rr_per_rrset: bool- @param ignore_trailing: Ignore trailing junk at end of request?- @type ignore_trailing: bool- @raises ShortHeader: The message is less than 12 octets long.- @raises TrailingJunk: There were octets in the message past the end- of the proper DNS message.- @raises BadEDNS: An OPT record was in the wrong section, or occurred more- than once.- @raises BadTSIG: A TSIG record was not the last record of the additional- data section.- @rtype: dns.message.Message object"""-- m = Message(id=0)- m.keyring = keyring- m.request_mac = request_mac- m.xfr = xfr- m.origin = origin- m.tsig_ctx = tsig_ctx- m.multi = multi- m.first = first-- reader = _WireReader(wire, m, question_only, one_rr_per_rrset,- ignore_trailing)- reader.read()-- return m---class _TextReader(object):- """Text format reader.-- @ivar tok: the tokenizer- @type tok: dns.tokenizer.Tokenizer object- @ivar message: The message object being built- @type message: dns.message.Message object- @ivar updating: Is the message a dynamic update?- @type updating: bool- @ivar zone_rdclass: The class of the zone in messages which are- DNS dynamic updates.- @type zone_rdclass: int- @ivar last_name: The most recently read name when building a message object- from text format.- @type last_name: dns.name.Name object- """-- def __init__(self, text, message):- self.message = message- self.tok = dns.tokenizer.Tokenizer(text)- self.last_name = None- self.zone_rdclass = dns.rdataclass.IN- self.updating = False-- def _header_line(self, section):- """Process one line from the text format header section."""-- token = self.tok.get()- what = token.value- if what == 'id':- self.message.id = self.tok.get_int()- elif what == 'flags':- while True:- token = self.tok.get()- if not token.is_identifier():- self.tok.unget(token)- break- self.message.flags = self.message.flags | \- dns.flags.from_text(token.value)- if dns.opcode.is_update(self.message.flags):- self.updating = True- elif what == 'edns':- self.message.edns = self.tok.get_int()- self.message.ednsflags = self.message.ednsflags | \- (self.message.edns << 16)- elif what == 'eflags':- if self.message.edns < 0:- self.message.edns = 0- while True:- token = self.tok.get()- if not token.is_identifier():- self.tok.unget(token)- break- self.message.ednsflags = self.message.ednsflags | \- dns.flags.edns_from_text(token.value)- elif what == 'payload':- self.message.payload = self.tok.get_int()- if self.message.edns < 0:- self.message.edns = 0- elif what == 'opcode':- text = self.tok.get_string()- self.message.flags = self.message.flags | \- dns.opcode.to_flags(dns.opcode.from_text(text))- elif what == 'rcode':- text = self.tok.get_string()- self.message.set_rcode(dns.rcode.from_text(text))- else:- raise UnknownHeaderField- self.tok.get_eol()-- def _question_line(self, section):- """Process one line from the text format question section."""-- token = self.tok.get(want_leading = True)- if not token.is_whitespace():- self.last_name = dns.name.from_text(token.value, None)- name = self.last_name- token = self.tok.get()- if not token.is_identifier():- raise dns.exception.SyntaxError- # 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 dns.exception.SyntaxError- except:- rdclass = dns.rdataclass.IN- # Type- rdtype = dns.rdatatype.from_text(token.value)- self.message.find_rrset(self.message.question, name,- rdclass, rdtype, create=True,- force_unique=True)- if self.updating:- self.zone_rdclass = rdclass- self.tok.get_eol()-- def _rr_line(self, section):- """Process one line from the text format answer, authority, or- additional data sections.- """-- deleting = None- # Name- token = self.tok.get(want_leading = True)- if not token.is_whitespace():- self.last_name = dns.name.from_text(token.value, None)- name = self.last_name- token = self.tok.get()- if not token.is_identifier():- raise dns.exception.SyntaxError- # TTL- try:- ttl = int(token.value, 0)- token = self.tok.get()- if not token.is_identifier():- raise dns.exception.SyntaxError- except dns.exception.SyntaxError:- raise dns.exception.SyntaxError- except:- ttl = 0- # Class- try:- rdclass = dns.rdataclass.from_text(token.value)- token = self.tok.get()- if not token.is_identifier():- raise dns.exception.SyntaxError- if rdclass == dns.rdataclass.ANY or rdclass == dns.rdataclass.NONE:- deleting = rdclass- rdclass = self.zone_rdclass- except dns.exception.SyntaxError:- raise dns.exception.SyntaxError- except:- rdclass = dns.rdataclass.IN- # Type- rdtype = dns.rdatatype.from_text(token.value)- token = self.tok.get()- if not token.is_eol_or_eof():- self.tok.unget(token)- rd = dns.rdata.from_text(rdclass, rdtype, self.tok, None)- covers = rd.covers()- else:- rd = None- covers = dns.rdatatype.NONE- rrset = self.message.find_rrset(section, name,- rdclass, rdtype, covers,- deleting, True, self.updating)- if not rd is None:- rrset.add(rd, ttl)-- def read(self):- """Read a text format DNS message and build a dns.message.Message- object."""-- line_method = self._header_line- section = None- while 1:- token = self.tok.get(True, True)- if token.is_eol_or_eof():- break- if token.is_comment():- u = token.value.upper()- if u == 'HEADER':- line_method = self._header_line- elif u == 'QUESTION' or u == 'ZONE':- line_method = self._question_line- section = self.message.question- elif u == 'ANSWER' or u == 'PREREQ':- line_method = self._rr_line- section = self.message.answer- elif u == 'AUTHORITY' or u == 'UPDATE':- line_method = self._rr_line- section = self.message.authority- elif u == 'ADDITIONAL':- line_method = self._rr_line- section = self.message.additional- self.tok.get_eol()- continue- self.tok.unget(token)- line_method(section)---def from_text(text):- """Convert the text format message into a message object.-- @param text: The text format message.- @type text: string- @raises UnknownHeaderField:- @raises dns.exception.SyntaxError:- @rtype: dns.message.Message 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().-- m = Message()-- reader = _TextReader(text, m)- reader.read()-- return m--def from_file(f):- """Read the next text format message from the specified file.-- @param f: file or string. If I{f} is a string, it is treated- as the name of a file to open.- @raises UnknownHeaderField:- @raises dns.exception.SyntaxError:- @rtype: dns.message.Message 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):- f = file(f, opts)- want_close = True- else:- want_close = False-- try:- m = from_text(f)- finally:- if want_close:- f.close()- return m--def make_query(qname, rdtype, rdclass = dns.rdataclass.IN, use_edns=None,- want_dnssec=False, ednsflags=0, payload=1280,- request_payload=None, options=None):- """Make a query message.-- The query name, type, and class may all be specified either- as objects of the appropriate type, or as strings.-- The query will have a randomly choosen query id, and its DNS flags- will be set to dns.flags.RD.-- @param qname: The query name.- @type qname: dns.name.Name object or string- @param rdtype: The desired rdata type.- @type rdtype: int- @param rdclass: The desired rdata class; the default is class IN.- @type rdclass: int- @param use_edns: The EDNS level to use; the default is None (no EDNS).- See the description of dns.message.Message.use_edns() for the possible- values for use_edns and their meanings.- @type use_edns: int or bool or None- @param want_dnssec: Should the query indicate that DNSSEC is desired?- @type want_dnssec: bool- @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 request_payload: The EDNS payload size to use when sending- this message. If not specified, defaults to the value of payload.- @type request_payload: int or None- @param options: The EDNS options- @type options: None or list of dns.edns.Option objects- @see: RFC 2671- @rtype: dns.message.Message object"""-- if isinstance(qname, (str, unicode)):- qname = dns.name.from_text(qname)- if isinstance(rdtype, (str, unicode)):- rdtype = dns.rdatatype.from_text(rdtype)- if isinstance(rdclass, (str, unicode)):- rdclass = dns.rdataclass.from_text(rdclass)- m = Message()- m.flags |= dns.flags.RD- m.find_rrset(m.question, qname, rdclass, rdtype, create=True,- force_unique=True)- m.use_edns(use_edns, ednsflags, payload, request_payload, options)- m.want_dnssec(want_dnssec)- return m--def make_response(query, recursion_available=False, our_payload=8192):- """Make a message which is a response for the specified query.- The message returned is really a response skeleton; it has all- of the infrastructure required of a response, but none of the- content.-- The response's question section is a shallow copy of the query's- question section, so the query's question RRsets should not be- changed.-- @param query: the query to respond to- @type query: dns.message.Message object- @param recursion_available: should RA be set in the response?- @type recursion_available: bool- @param our_payload: payload size to advertise in EDNS responses; default- is 8192.- @type our_payload: int- @rtype: dns.message.Message object"""-- if query.flags & dns.flags.QR:- raise dns.exception.FormError('specified query message is not a query')- response = dns.message.Message(query.id)- response.flags = dns.flags.QR | (query.flags & dns.flags.RD)- if recursion_available:- response.flags |= dns.flags.RA- response.set_opcode(query.opcode())- response.question = list(query.question)- if query.edns >= 0:- response.use_edns(0, 0, our_payload, query.payload)- if not query.keyname is None:- response.keyname = query.keyname- response.keyring = query.keyring- response.request_mac = query.mac- return responsediff --git a/ext/dns/name.py b/ext/dns/name.pydeleted file mode 100644index 293ab951..00000000--- a/ext/dns/name.py+++ /dev/null@@ -1,702 +0,0 @@-# 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 <= 0x3fff:- 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)diff --git a/ext/dns/namedict.py b/ext/dns/namedict.pydeleted file mode 100644index 9f5a0efb..00000000--- a/ext/dns/namedict.py+++ /dev/null@@ -1,59 +0,0 @@-# 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 self.has_key(n):- return (n, self[n])- v = self[dns.name.empty]- return (dns.name.empty, v)diff --git a/ext/dns/node.py b/ext/dns/node.pydeleted file mode 100644index e74004f6..00000000--- a/ext/dns/node.py+++ /dev/null@@ -1,175 +0,0 @@-# 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:- if len(rds) > 0:- 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.- """-- if not isinstance(replacement, dns.rdataset.Rdataset):- raise ValueError, 'replacement is not an rdataset'- self.delete_rdataset(replacement.rdclass, replacement.rdtype,- replacement.covers)- self.rdatasets.append(replacement)diff --git a/ext/dns/opcode.py b/ext/dns/opcode.pydeleted file mode 100644index 3258c34c..00000000--- a/ext/dns/opcode.py+++ /dev/null@@ -1,104 +0,0 @@-# 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 Falsediff --git a/ext/dns/query.py b/ext/dns/query.pydeleted file mode 100644index 7a1b1f49..00000000--- a/ext/dns/query.py+++ /dev/null@@ -1,487 +0,0 @@-# 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):- """Poll polling backend.- @param fd: File descriptor- @type fd: int- @param readable: Whether to wait for readability- @type readable: bool- @param writable: Whether to wait for writability- @type writable: bool- @param timeout: Deadline timeout (expiration time, in seconds)- @type timeout: 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):- """Select polling backend.- @param fd: File descriptor- @type fd: int- @param readable: Whether to wait for readability- @type readable: bool- @param writable: Whether to wait for writability- @type writable: bool- @param timeout: Deadline timeout (expiration time, in seconds)- @type timeout: 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 _destination_and_source(af, where, port, source, source_port):- # Apply defaults and compute destination and source tuples- # suitable for use in connect(), sendto(), or bind().- if af is None:- try:- af = dns.inet.af_for_address(where)- except:- af = dns.inet.AF_INET- if af == dns.inet.AF_INET:- destination = (where, port)- if source is not None or source_port != 0:- if source is None:- source = '0.0.0.0'- source = (source, source_port)- elif af == dns.inet.AF_INET6:- destination = (where, port, 0, 0)- if source is not None or source_port != 0:- if source is None:- source = '::'- source = (source, source_port, 0, 0)- return (af, destination, source)--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 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()- (af, destination, source) = _destination_and_source(af, where, port, source,- source_port)- 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 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()- (af, destination, source) = _destination_and_source(af, where, port, source,- source_port)- 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.rdataclass.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 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()- (af, destination, source) = _destination_and_source(af, where, port, source,- source_port)- 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()diff --git a/ext/dns/rcode.py b/ext/dns/rcode.pydeleted file mode 100644index 7807782a..00000000--- a/ext/dns/rcode.py+++ /dev/null@@ -1,119 +0,0 @@-# 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 Result Codes."""--import dns.exception--NOERROR = 0-FORMERR = 1-SERVFAIL = 2-NXDOMAIN = 3-NOTIMP = 4-REFUSED = 5-YXDOMAIN = 6-YXRRSET = 7-NXRRSET = 8-NOTAUTH = 9-NOTZONE = 10-BADVERS = 16--_by_text = {- 'NOERROR' : NOERROR,- 'FORMERR' : FORMERR,- 'SERVFAIL' : SERVFAIL,- 'NXDOMAIN' : NXDOMAIN,- 'NOTIMP' : NOTIMP,- 'REFUSED' : REFUSED,- 'YXDOMAIN' : YXDOMAIN,- 'YXRRSET' : YXRRSET,- 'NXRRSET' : NXRRSET,- 'NOTAUTH' : NOTAUTH,- 'NOTZONE' : NOTZONE,- 'BADVERS' : BADVERS-}--# 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 a true inverse.--_by_value = dict([(y, x) for x, y in _by_text.iteritems()])---class UnknownRcode(dns.exception.DNSException):- """Raised if an rcode is unknown."""- pass--def from_text(text):- """Convert text into an rcode.-- @param text: the texual rcode- @type text: string- @raises UnknownRcode: the rcode is unknown- @rtype: int- """-- if text.isdigit():- v = int(text)- if v >= 0 and v <= 4095:- return v- v = _by_text.get(text.upper())- if v is None:- raise UnknownRcode- return v--def from_flags(flags, ednsflags):- """Return the rcode value encoded by flags and ednsflags.-- @param flags: the DNS flags- @type flags: int- @param ednsflags: the EDNS flags- @type ednsflags: int- @raises ValueError: rcode is < 0 or > 4095- @rtype: int- """-- value = (flags & 0x000f) | ((ednsflags >> 20) & 0xff0)- if value < 0 or value > 4095:- raise ValueError('rcode must be >= 0 and <= 4095')- return value--def to_flags(value):- """Return a (flags, ednsflags) tuple which encodes the rcode.-- @param value: the rcode- @type value: int- @raises ValueError: rcode is < 0 or > 4095- @rtype: (int, int) tuple- """-- if value < 0 or value > 4095:- raise ValueError('rcode must be >= 0 and <= 4095')- v = value & 0xf- ev = long(value & 0xff0) << 20- return (v, ev)--def to_text(value):- """Convert rcode into text.-- @param value: the rcode- @type value: int- @rtype: string- """-- text = _by_value.get(value)- if text is None:- text = str(value)- return textdiff --git a/ext/dns/rdata.py b/ext/dns/rdata.pydeleted file mode 100644index 350bf790..00000000--- a/ext/dns/rdata.py+++ /dev/null@@ -1,478 +0,0 @@-# 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.-- If I{tok} is a string, then a tokenizer is created and the string- is used as its input.-- @param rdclass: The rdata class- @type rdclass: int- @param rdtype: The rdata type- @type rdtype: int- @param tok: The tokenizer or input text- @type tok: dns.tokenizer.Tokenizer or string- @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)diff --git a/ext/dns/rdataclass.py b/ext/dns/rdataclass.pydeleted file mode 100644index 7601e70c..00000000--- a/ext/dns/rdataclass.py+++ /dev/null@@ -1,114 +0,0 @@-# 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 Classes.--@var _by_text: The rdata class textual name to value mapping-@type _by_text: dict-@var _by_value: The rdata class value to textual name mapping-@type _by_value: dict-@var _metaclasses: If an rdataclass is a metaclass, there will be a mapping-whose key is the rdatatype value and whose value is True in this dictionary.-@type _metaclasses: dict"""--import re--import dns.exception--RESERVED0 = 0-IN = 1-CH = 3-HS = 4-NONE = 254-ANY = 255--_by_text = {- 'RESERVED0' : RESERVED0,- 'IN' : IN,- 'CH' : CH,- 'HS' : HS,- 'NONE' : NONE,- 'ANY' : ANY- }--# 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()])--# Now that we've built the inverse map, we can add class aliases to-# the _by_text mapping.--_by_text.update({- 'INTERNET' : IN,- 'CHAOS' : CH,- 'HESIOD' : HS- })--_metaclasses = {- NONE : True,- ANY : True- }--_unknown_class_pattern = re.compile('CLASS([0-9]+)$', re.I);--class UnknownRdataclass(dns.exception.DNSException):- """Raised when a class is unknown."""- pass--def from_text(text):- """Convert text into a DNS rdata class value.- @param text: the text- @type text: string- @rtype: int- @raises dns.rdataclass.UnknownRdataclass: the class is unknown- @raises ValueError: the rdata class value is not >= 0 and <= 65535- """-- value = _by_text.get(text.upper())- if value is None:- match = _unknown_class_pattern.match(text)- if match == None:- raise UnknownRdataclass- value = int(match.group(1))- if value < 0 or value > 65535:- raise ValueError("class must be between >= 0 and <= 65535")- return value--def to_text(value):- """Convert a DNS rdata class to text.- @param value: the rdata class value- @type value: int- @rtype: string- @raises ValueError: the rdata class value is not >= 0 and <= 65535- """-- if value < 0 or value > 65535:- raise ValueError("class must be between >= 0 and <= 65535")- text = _by_value.get(value)- if text is None:- text = 'CLASS' + `value`- return text--def is_metaclass(rdclass):- """True if the class is a metaclass.- @param rdclass: the rdata class- @type rdclass: int- @rtype: bool"""-- if _metaclasses.has_key(rdclass):- return True- return Falsediff --git a/ext/dns/rdataset.py b/ext/dns/rdataset.pydeleted file mode 100644index dcd2b401..00000000--- a/ext/dns/rdataset.py+++ /dev/null@@ -1,329 +0,0 @@-# 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 __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)diff --git a/ext/dns/rdatatype.py b/ext/dns/rdatatype.pydeleted file mode 100644index f64307a7..00000000--- a/ext/dns/rdatatype.py+++ /dev/null@@ -1,234 +0,0 @@-# 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-TLSA = 52-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,- 'TLSA' : TLSA,- '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' + `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 _metatypes.has_key(rdtype):- 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 _singletons.has_key(rdtype):- return True- return Falsediff --git a/ext/dns/rdtypes/ANY/AFSDB.py b/ext/dns/rdtypes/ANY/AFSDB.pydeleted file mode 100644index c729789a..00000000--- a/ext/dns/rdtypes/ANY/AFSDB.py+++ /dev/null@@ -1,51 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/ANY/CERT.py b/ext/dns/rdtypes/ANY/CERT.pydeleted file mode 100644index c102521a..00000000--- a/ext/dns/rdtypes/ANY/CERT.py+++ /dev/null@@ -1,131 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/ANY/CNAME.py b/ext/dns/rdtypes/ANY/CNAME.pydeleted file mode 100644index fb8e9be4..00000000--- a/ext/dns/rdtypes/ANY/CNAME.py+++ /dev/null@@ -1,24 +0,0 @@-# 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."""- passdiff --git a/ext/dns/rdtypes/ANY/DLV.py b/ext/dns/rdtypes/ANY/DLV.pydeleted file mode 100644index 8bd79793..00000000--- a/ext/dns/rdtypes/ANY/DLV.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/ANY/DNAME.py b/ext/dns/rdtypes/ANY/DNAME.pydeleted file mode 100644index d8640011..00000000--- a/ext/dns/rdtypes/ANY/DNAME.py+++ /dev/null@@ -1,21 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/ANY/DNSKEY.py b/ext/dns/rdtypes/ANY/DNSKEY.pydeleted file mode 100644index 1d678d2f..00000000--- a/ext/dns/rdtypes/ANY/DNSKEY.py+++ /dev/null@@ -1,94 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/ANY/DS.py b/ext/dns/rdtypes/ANY/DS.pydeleted file mode 100644index 56b6332d..00000000--- a/ext/dns/rdtypes/ANY/DS.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/ANY/GPOS.py b/ext/dns/rdtypes/ANY/GPOS.pydeleted file mode 100644index 38d1d88b..00000000--- a/ext/dns/rdtypes/ANY/GPOS.py+++ /dev/null@@ -1,156 +0,0 @@-# 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")diff --git a/ext/dns/rdtypes/ANY/HINFO.py b/ext/dns/rdtypes/ANY/HINFO.pydeleted file mode 100644index 15fd54e6..00000000--- a/ext/dns/rdtypes/ANY/HINFO.py+++ /dev/null@@ -1,83 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/ANY/HIP.py b/ext/dns/rdtypes/ANY/HIP.pydeleted file mode 100644index 968b36f5..00000000--- a/ext/dns/rdtypes/ANY/HIP.py+++ /dev/null@@ -1,140 +0,0 @@-# 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 - lodiff --git a/ext/dns/rdtypes/ANY/ISDN.py b/ext/dns/rdtypes/ANY/ISDN.pydeleted file mode 100644index 0c2d3cd0..00000000--- a/ext/dns/rdtypes/ANY/ISDN.py+++ /dev/null@@ -1,96 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/ANY/LOC.py b/ext/dns/rdtypes/ANY/LOC.pydeleted file mode 100644index 154546d7..00000000--- a/ext/dns/rdtypes/ANY/LOC.py+++ /dev/null@@ -1,334 +0,0 @@-# 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")diff --git a/ext/dns/rdtypes/ANY/MX.py b/ext/dns/rdtypes/ANY/MX.pydeleted file mode 100644index 92f41532..00000000--- a/ext/dns/rdtypes/ANY/MX.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/ANY/NS.py b/ext/dns/rdtypes/ANY/NS.pydeleted file mode 100644index 6b45d4d4..00000000--- a/ext/dns/rdtypes/ANY/NS.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/ANY/NSEC.py b/ext/dns/rdtypes/ANY/NSEC.pydeleted file mode 100644index ad113a4b..00000000--- a/ext/dns/rdtypes/ANY/NSEC.py+++ /dev/null@@ -1,128 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/ANY/NSEC3.py b/ext/dns/rdtypes/ANY/NSEC3.pydeleted file mode 100644index b42fe4c8..00000000--- a/ext/dns/rdtypes/ANY/NSEC3.py+++ /dev/null@@ -1,184 +0,0 @@-# 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:- if octets != 0:- 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))- if octets != 0:- 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())diff --git a/ext/dns/rdtypes/ANY/NSEC3PARAM.py b/ext/dns/rdtypes/ANY/NSEC3PARAM.pydeleted file mode 100644index 4e687825..00000000--- a/ext/dns/rdtypes/ANY/NSEC3PARAM.py+++ /dev/null@@ -1,88 +0,0 @@-# 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())diff --git a/ext/dns/rdtypes/ANY/PTR.py b/ext/dns/rdtypes/ANY/PTR.pydeleted file mode 100644index 4a037537..00000000--- a/ext/dns/rdtypes/ANY/PTR.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/ANY/RP.py b/ext/dns/rdtypes/ANY/RP.pydeleted file mode 100644index 26c55314..00000000--- a/ext/dns/rdtypes/ANY/RP.py+++ /dev/null@@ -1,86 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/ANY/RRSIG.py b/ext/dns/rdtypes/ANY/RRSIG.pydeleted file mode 100644index 63d389cd..00000000--- a/ext/dns/rdtypes/ANY/RRSIG.py+++ /dev/null@@ -1,155 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/ANY/RT.py b/ext/dns/rdtypes/ANY/RT.pydeleted file mode 100644index f9653fdb..00000000--- a/ext/dns/rdtypes/ANY/RT.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/ANY/SOA.py b/ext/dns/rdtypes/ANY/SOA.pydeleted file mode 100644index 2d6f21b5..00000000--- a/ext/dns/rdtypes/ANY/SOA.py+++ /dev/null@@ -1,127 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/ANY/SPF.py b/ext/dns/rdtypes/ANY/SPF.pydeleted file mode 100644index 8860dd72..00000000--- a/ext/dns/rdtypes/ANY/SPF.py+++ /dev/null@@ -1,22 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/ANY/SSHFP.py b/ext/dns/rdtypes/ANY/SSHFP.pydeleted file mode 100644index 4c439511..00000000--- a/ext/dns/rdtypes/ANY/SSHFP.py+++ /dev/null@@ -1,84 +0,0 @@-# 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()- 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)- fingerprint = ''.join(chunks)- fingerprint = fingerprint.decode('hex_codec')- 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 vdiff --git a/ext/dns/rdtypes/ANY/TLSA.py b/ext/dns/rdtypes/ANY/TLSA.pydeleted file mode 100644index 6ca8c0a5..00000000--- a/ext/dns/rdtypes/ANY/TLSA.py+++ /dev/null@@ -1,89 +0,0 @@-# 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 TLSA(dns.rdata.Rdata):- """TLSA record-- @ivar usage: The certificate usage- @type usage: int- @ivar selector: The selector field- @type selector: int- @ivar mtype: The 'matching type' field- @type mtype: int- @ivar cert: The 'Certificate Association Data' field- @type cert: string- @see: RFC 6698"""-- __slots__ = ['usage', 'selector', 'mtype', 'cert']-- def __init__(self, rdclass, rdtype, usage, selector,- mtype, cert):- super(TLSA, self).__init__(rdclass, rdtype)- self.usage = usage- self.selector = selector- self.mtype = mtype- self.cert = cert-- def to_text(self, origin=None, relativize=True, **kw):- return '%d %d %d %s' % (self.usage,- self.selector,- self.mtype,- dns.rdata._hexify(self.cert,- chunksize=128))-- def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True):- usage = tok.get_uint8()- selector = tok.get_uint8()- mtype = tok.get_uint8()- cert_chunks = []- while 1:- t = tok.get().unescape()- if t.is_eol_or_eof():- break- if not t.is_identifier():- raise dns.exception.SyntaxError- cert_chunks.append(t.value)- cert = ''.join(cert_chunks)- cert = cert.decode('hex_codec')- return cls(rdclass, rdtype, usage, selector, mtype, cert)-- from_text = classmethod(from_text)-- def to_wire(self, file, compress = None, origin = None):- header = struct.pack("!BBB", self.usage, self.selector, self.mtype)- file.write(header)- file.write(self.cert)-- def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None):- header = struct.unpack("!BBB", wire[current : current + 3])- current += 3- rdlen -= 3- cert = wire[current : current + rdlen].unwrap()- return cls(rdclass, rdtype, header[0], header[1], header[2], cert)-- from_wire = classmethod(from_wire)-- def _cmp(self, other):- hs = struct.pack("!BBB", self.usage, self.selector, self.mtype)- ho = struct.pack("!BBB", other.usage, other.selector, other.mtype)- v = cmp(hs, ho)- if v == 0:- v = cmp(self.cert, other.cert)- return vdiff --git a/ext/dns/rdtypes/ANY/TXT.py b/ext/dns/rdtypes/ANY/TXT.pydeleted file mode 100644index 604fd0f4..00000000--- a/ext/dns/rdtypes/ANY/TXT.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/ANY/X25.py b/ext/dns/rdtypes/ANY/X25.pydeleted file mode 100644index ae91295f..00000000--- a/ext/dns/rdtypes/ANY/X25.py+++ /dev/null@@ -1,62 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/ANY/__init__.py b/ext/dns/rdtypes/ANY/__init__.pydeleted file mode 100644index cfb0be62..00000000--- a/ext/dns/rdtypes/ANY/__init__.py+++ /dev/null@@ -1,46 +0,0 @@-# 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',- 'TLSA',- 'PTR',- 'RP',- 'RRSIG',- 'RT',- 'SOA',- 'SPF',- 'SSHFP',- 'TXT',- 'X25',-]diff --git a/ext/dns/rdtypes/IN/A.py b/ext/dns/rdtypes/IN/A.pydeleted file mode 100644index 372d3332..00000000--- a/ext/dns/rdtypes/IN/A.py+++ /dev/null@@ -1,57 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/IN/AAAA.py b/ext/dns/rdtypes/IN/AAAA.pydeleted file mode 100644index e131bd50..00000000--- a/ext/dns/rdtypes/IN/AAAA.py+++ /dev/null@@ -1,58 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/IN/APL.py b/ext/dns/rdtypes/IN/APL.pydeleted file mode 100644index 260fd6f3..00000000--- a/ext/dns/rdtypes/IN/APL.py+++ /dev/null@@ -1,170 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/IN/DHCID.py b/ext/dns/rdtypes/IN/DHCID.pydeleted file mode 100644index 5524bead..00000000--- a/ext/dns/rdtypes/IN/DHCID.py+++ /dev/null@@ -1,60 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/IN/IPSECKEY.py b/ext/dns/rdtypes/IN/IPSECKEY.pydeleted file mode 100644index d85b6fe9..00000000--- a/ext/dns/rdtypes/IN/IPSECKEY.py+++ /dev/null@@ -1,159 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/IN/KX.py b/ext/dns/rdtypes/IN/KX.pydeleted file mode 100644index c7bd5bbe..00000000--- a/ext/dns/rdtypes/IN/KX.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/IN/NAPTR.py b/ext/dns/rdtypes/IN/NAPTR.pydeleted file mode 100644index 7fe04308..00000000--- a/ext/dns/rdtypes/IN/NAPTR.py+++ /dev/null@@ -1,132 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/IN/NSAP.py b/ext/dns/rdtypes/IN/NSAP.pydeleted file mode 100644index 216cb0a8..00000000--- a/ext/dns/rdtypes/IN/NSAP.py+++ /dev/null@@ -1,59 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/IN/NSAP_PTR.py b/ext/dns/rdtypes/IN/NSAP_PTR.pydeleted file mode 100644index df5b989a..00000000--- a/ext/dns/rdtypes/IN/NSAP_PTR.py+++ /dev/null@@ -1,20 +0,0 @@-# 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"""- passdiff --git a/ext/dns/rdtypes/IN/PX.py b/ext/dns/rdtypes/IN/PX.pydeleted file mode 100644index 1422b834..00000000--- a/ext/dns/rdtypes/IN/PX.py+++ /dev/null@@ -1,97 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/IN/SRV.py b/ext/dns/rdtypes/IN/SRV.pydeleted file mode 100644index e101b26b..00000000--- a/ext/dns/rdtypes/IN/SRV.py+++ /dev/null@@ -1,89 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/IN/WKS.py b/ext/dns/rdtypes/IN/WKS.pydeleted file mode 100644index 04c3054e..00000000--- a/ext/dns/rdtypes/IN/WKS.py+++ /dev/null@@ -1,113 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/IN/__init__.py b/ext/dns/rdtypes/IN/__init__.pydeleted file mode 100644index 24cf1ece..00000000--- a/ext/dns/rdtypes/IN/__init__.py+++ /dev/null@@ -1,30 +0,0 @@-# 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',-]diff --git a/ext/dns/rdtypes/__init__.py b/ext/dns/rdtypes/__init__.pydeleted file mode 100644index 49db5a37..00000000--- a/ext/dns/rdtypes/__init__.py+++ /dev/null@@ -1,23 +0,0 @@-# 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',-]diff --git a/ext/dns/rdtypes/dsbase.py b/ext/dns/rdtypes/dsbase.pydeleted file mode 100644index 6f5559a7..00000000--- a/ext/dns/rdtypes/dsbase.py+++ /dev/null@@ -1,92 +0,0 @@-# 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 vdiff --git a/ext/dns/rdtypes/mxbase.py b/ext/dns/rdtypes/mxbase.pydeleted file mode 100644index abc6a9ed..00000000--- a/ext/dns/rdtypes/mxbase.py+++ /dev/null@@ -1,105 +0,0 @@-# 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)diff --git a/ext/dns/rdtypes/nsbase.py b/ext/dns/rdtypes/nsbase.pydeleted file mode 100644index fbd5ef1e..00000000--- a/ext/dns/rdtypes/nsbase.py+++ /dev/null@@ -1,82 +0,0 @@-# 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()diff --git a/ext/dns/rdtypes/txtbase.py b/ext/dns/rdtypes/txtbase.pydeleted file mode 100644index 580f056e..00000000--- a/ext/dns/rdtypes/txtbase.py+++ /dev/null@@ -1,87 +0,0 @@-# 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)diff --git a/ext/dns/renderer.py b/ext/dns/renderer.pydeleted file mode 100644index 1708e92a..00000000--- a/ext/dns/renderer.py+++ /dev/null@@ -1,325 +0,0 @@-# 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 after 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()diff --git a/ext/dns/resolver.py b/ext/dns/resolver.pydeleted file mode 100644index 934d39bd..00000000--- a/ext/dns/resolver.py+++ /dev/null@@ -1,1238 +0,0 @@-# 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 time--try:- import threading as _threading-except ImportError:- import dummy_threading as _threading--import dns.exception-import dns.flags-import dns.ipv4-import dns.ipv6-import dns.message-import dns.name-import dns.query-import dns.rcode-import dns.rdataclass-import dns.rdatatype-import dns.reversename--if sys.platform == 'win32':- import _winreg--class NXDOMAIN(dns.exception.DNSException):- """The query name does not exist."""- pass--class YXDOMAIN(dns.exception.DNSException):- """The query name is too long after DNAME substitution."""- 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- if raise_on_no_answer:- raise NoAnswer- if rrset is None and raise_on_no_answer:- raise NoAnswer- 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 __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- self.lock = _threading.Lock()-- 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- """-- try:- self.lock.acquire()- self._maybe_clean()- v = self.data.get(key)- if v is None or v.expiration <= time.time():- return None- return v- finally:- self.lock.release()-- 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- """-- try:- self.lock.acquire()- self._maybe_clean()- self.data[key] = value- finally:- self.lock.release()-- 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- """-- try:- self.lock.acquire()- if not key is None:- if self.data.has_key(key):- del self.data[key]- else:- self.data = {}- self.next_cleaning = time.time() + self.cleaning_interval- finally:- self.lock.release()--class LRUCacheNode(object):- """LRUCache node.- """- def __init__(self, key, value):- self.key = key- self.value = value- self.prev = self- self.next = self-- def link_before(self, node):- self.prev = node.prev- self.next = node- node.prev.next = self- node.prev = self-- def link_after(self, node):- self.prev = node- self.next = node.next- node.next.prev = self- node.next = self-- def unlink(self):- self.next.prev = self.prev- self.prev.next = self.next--class LRUCache(object):- """Bounded least-recently-used DNS answer cache.-- This cache is better than the simple cache (above) if you're- running a web crawler or other process that does a lot of- resolutions. The LRUCache has a maximum number of nodes, and when- it is full, the least-recently used node is removed to make space- for a new one.-- @ivar data: A dictionary of cached data- @type data: dict- @ivar sentinel: sentinel node for circular doubly linked list of nodes- @type sentinel: LRUCacheNode object- @ivar max_size: The maximum number of nodes- @type max_size: int- """-- def __init__(self, max_size=100000):- """Initialize a DNS cache.-- @param max_size: The maximum number of nodes to cache; the default is 100000. Must be > 1.- @type max_size: int- """- self.data = {}- self.set_max_size(max_size)- self.sentinel = LRUCacheNode(None, None)- self.lock = _threading.Lock()-- def set_max_size(self, max_size):- if max_size < 1:- max_size = 1- self.max_size = max_size-- 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- """- try:- self.lock.acquire()- node = self.data.get(key)- if node is None:- return None- # Unlink because we're either going to move the node to the front- # of the LRU list or we're going to free it.- node.unlink()- if node.value.expiration <= time.time():- del self.data[node.key]- return None- node.link_after(self.sentinel)- return node.value- finally:- self.lock.release()-- 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- """- try:- self.lock.acquire()- node = self.data.get(key)- if not node is None:- node.unlink()- del self.data[node.key]- while len(self.data) >= self.max_size:- node = self.sentinel.prev- node.unlink()- del self.data[node.key]- node = LRUCacheNode(key, value)- node.link_after(self.sentinel)- self.data[key] = node- finally:- self.lock.release()-- 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- """- try:- self.lock.acquire()- if not key is None:- node = self.data.get(key)- if not node is None:- node.unlink()- del self.data[node.key]- else:- node = self.sentinel.next- while node != self.sentinel:- next = node.next- node.prev = None- node.next = None- node = next- self.data = {}- finally:- self.lock.release()--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 flags: The message flags to use. The default is None (i.e. not overwritten)- @type flags: int- @ivar cache: The cache to use. The default is None.- @type cache: dns.resolver.Cache object- @ivar retry_servfail: should we retry a nameserver if it says SERVFAIL?- The default is 'false'.- @type retry_servfail: bool- """- 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)-- 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.search = []- 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- self.flags = None- self.retry_servfail = False-- 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, str) or isinstance(f, unicode):- 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:- if len(l) == 0 or l[0] == '#' or l[0] == ';':- continue- tokens = l.split()- if len(tokens) == 0:- 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.append(dns.name.from_text(suffix))- finally:- if want_close:- f.close()- if len(self.nameservers) == 0:- self.nameservers.append('127.0.0.1')-- 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.append(dns.name.from_text(s))-- def _config_win32_fromkey(self, key):- """Extract DNS info from a registry key."""- 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(dom)- except WindowsError:- pass- else:- 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(dom)- except WindowsError:- pass- 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, source_port=0):- """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- @param source_port: The port from which to send the message.- The default is 0.- @type source_port: int- @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 YXDOMAIN: the query name is too long after DNAME substitution- @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, (str, unicode)):- qname = dns.name.from_text(qname, None)- if isinstance(rdtype, (str, unicode)):- rdtype = dns.rdatatype.from_text(rdtype)- if dns.rdatatype.is_metatype(rdtype):- raise NoMetaqueries- if isinstance(rdclass, (str, unicode)):- 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 not answer is None:- if answer.rrset is None and raise_on_no_answer:- raise NoAnswer- else:- 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)- if self.flags is not None:- request.flags = self.flags- 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- for nameserver in nameservers[:]:- timeout = self._compute_timeout(start)- try:- if tcp:- response = dns.query.tcp(request, nameserver,- timeout, self.port,- source=source,- source_port=source_port)- else:- response = dns.query.udp(request, nameserver,- timeout, self.port,- source=source,- source_port=source_port)- if response.flags & dns.flags.TC:- # Response truncated; retry with TCP.- timeout = self._compute_timeout(start)- response = dns.query.tcp(request, nameserver,- timeout, self.port,- source=source,- source_port=source_port)- 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- except EOFError:- #- # We're using TCP and they hung up on us.- # Probably they don't support TCP (though- # they're supposed to!). Take it out of the- # mix and continue.- #- nameservers.remove(nameserver)- response = None- continue- rcode = response.rcode()- if rcode == dns.rcode.YXDOMAIN:- raise YXDOMAIN- 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 or not self.retry_servfail:- nameservers.remove(nameserver)- response = None- if not response is 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- 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-- def set_flags(self, flags):- """Overrides the default flags with your own-- @param flags: The flags to overwrite the default with- @type flags: int"""- self.flags = flags--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,- source_port=0):- """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."""- return get_default_resolver().query(qname, rdtype, rdclass, tcp, source,- raise_on_no_answer, source_port)--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, (str, unicode)):- 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--#-# Support for overriding the system resolver for all python code in the-# running process.-#--_protocols_for_socktype = {- socket.SOCK_DGRAM : [socket.SOL_UDP],- socket.SOCK_STREAM : [socket.SOL_TCP],- }--_resolver = None-_original_getaddrinfo = socket.getaddrinfo-_original_getnameinfo = socket.getnameinfo-_original_getfqdn = socket.getfqdn-_original_gethostbyname = socket.gethostbyname-_original_gethostbyname_ex = socket.gethostbyname_ex-_original_gethostbyaddr = socket.gethostbyaddr--def _getaddrinfo(host=None, service=None, family=socket.AF_UNSPEC, socktype=0,- proto=0, flags=0):- if flags & (socket.AI_ADDRCONFIG|socket.AI_V4MAPPED) != 0:- raise NotImplementedError- if host is None and service is None:- raise socket.gaierror(socket.EAI_NONAME)- v6addrs = []- v4addrs = []- canonical_name = None- try:- # Is host None or a V6 address literal?- if host is None:- canonical_name = 'localhost'- if flags & socket.AI_PASSIVE != 0:- v6addrs.append('::')- v4addrs.append('0.0.0.0')- else:- v6addrs.append('::1')- v4addrs.append('127.0.0.1')- else:- parts = host.split('%')- if len(parts) == 2:- ahost = parts[0]- else:- ahost = host- addr = dns.ipv6.inet_aton(ahost)- v6addrs.append(host)- canonical_name = host- except:- try:- # Is it a V4 address literal?- addr = dns.ipv4.inet_aton(host)- v4addrs.append(host)- canonical_name = host- except:- if flags & socket.AI_NUMERICHOST == 0:- try:- qname = None- if family == socket.AF_INET6 or family == socket.AF_UNSPEC:- v6 = _resolver.query(host, dns.rdatatype.AAAA,- raise_on_no_answer=False)- # Note that setting host ensures we query the same name- # for A as we did for AAAA.- host = v6.qname- canonical_name = v6.canonical_name.to_text(True)- if v6.rrset is not None:- for rdata in v6.rrset:- v6addrs.append(rdata.address)- if family == socket.AF_INET or family == socket.AF_UNSPEC:- v4 = _resolver.query(host, dns.rdatatype.A,- raise_on_no_answer=False)- host = v4.qname- canonical_name = v4.canonical_name.to_text(True)- if v4.rrset is not None:- for rdata in v4.rrset:- v4addrs.append(rdata.address)- except dns.resolver.NXDOMAIN:- raise socket.gaierror(socket.EAI_NONAME)- except:- raise socket.gaierror(socket.EAI_SYSTEM)- port = None- try:- # Is it a port literal?- if service is None:- port = 0- else:- port = int(service)- except:- if flags & socket.AI_NUMERICSERV == 0:- try:- port = socket.getservbyname(service)- except:- pass- if port is None:- raise socket.gaierror(socket.EAI_NONAME)- tuples = []- if socktype == 0:- socktypes = [socket.SOCK_DGRAM, socket.SOCK_STREAM]- else:- socktypes = [socktype]- if flags & socket.AI_CANONNAME != 0:- cname = canonical_name- else:- cname = ''- if family == socket.AF_INET6 or family == socket.AF_UNSPEC:- for addr in v6addrs:- for socktype in socktypes:- for proto in _protocols_for_socktype[socktype]:- tuples.append((socket.AF_INET6, socktype, proto,- cname, (addr, port, 0, 0)))- if family == socket.AF_INET or family == socket.AF_UNSPEC:- for addr in v4addrs:- for socktype in socktypes:- for proto in _protocols_for_socktype[socktype]:- tuples.append((socket.AF_INET, socktype, proto,- cname, (addr, port)))- if len(tuples) == 0:- raise socket.gaierror(socket.EAI_NONAME)- return tuples--def _getnameinfo(sockaddr, flags=0):- host = sockaddr[0]- port = sockaddr[1]- if len(sockaddr) == 4:- scope = sockaddr[3]- family = socket.AF_INET6- else:- scope = None- family = socket.AF_INET- tuples = _getaddrinfo(host, port, family, socket.SOCK_STREAM,- socket.SOL_TCP, 0)- if len(tuples) > 1:- raise socket.error('sockaddr resolved to multiple addresses')- addr = tuples[0][4][0]- if flags & socket.NI_DGRAM:- pname = 'udp'- else:- pname = 'tcp'- qname = dns.reversename.from_address(addr)- if flags & socket.NI_NUMERICHOST == 0:- try:- answer = _resolver.query(qname, 'PTR')- hostname = answer.rrset[0].target.to_text(True)- except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):- if flags & socket.NI_NAMEREQD:- raise socket.gaierror(socket.EAI_NONAME)- hostname = addr- if scope is not None:- hostname += '%' + str(scope)- else:- hostname = addr- if scope is not None:- hostname += '%' + str(scope)- if flags & socket.NI_NUMERICSERV:- service = str(port)- else:- service = socket.getservbyport(port, pname)- return (hostname, service)--def _getfqdn(name=None):- if name is None:- name = socket.gethostname()- return _getnameinfo(_getaddrinfo(name, 80)[0][4])[0]--def _gethostbyname(name):- return _gethostbyname_ex(name)[2][0]--def _gethostbyname_ex(name):- aliases = []- addresses = []- tuples = _getaddrinfo(name, 0, socket.AF_INET, socket.SOCK_STREAM,- socket.SOL_TCP, socket.AI_CANONNAME)- canonical = tuples[0][3]- for item in tuples:- addresses.append(item[4][0])- # XXX we just ignore aliases- return (canonical, aliases, addresses)--def _gethostbyaddr(ip):- try:- addr = dns.ipv6.inet_aton(ip)- sockaddr = (ip, 80, 0, 0)- family = socket.AF_INET6- except:- sockaddr = (ip, 80)- family = socket.AF_INET- (name, port) = _getnameinfo(sockaddr, socket.NI_NAMEREQD)- aliases = []- addresses = []- tuples = _getaddrinfo(name, 0, family, socket.SOCK_STREAM, socket.SOL_TCP,- socket.AI_CANONNAME)- canonical = tuples[0][3]- for item in tuples:- addresses.append(item[4][0])- # XXX we just ignore aliases- return (canonical, aliases, addresses)--def override_system_resolver(resolver=None):- """Override the system resolver routines in the socket module with- versions which use dnspython's resolver.-- This can be useful in testing situations where you want to control- the resolution behavior of python code without having to change- the system's resolver settings (e.g. /etc/resolv.conf).-- The resolver to use may be specified; if it's not, the default- resolver will be used.-- @param resolver: the resolver to use- @type resolver: dns.resolver.Resolver object or None- """- if resolver is None:- resolver = get_default_resolver()- global _resolver- _resolver = resolver- socket.getaddrinfo = _getaddrinfo- socket.getnameinfo = _getnameinfo- socket.getfqdn = _getfqdn- socket.gethostbyname = _gethostbyname- socket.gethostbyname_ex = _gethostbyname_ex- socket.gethostbyaddr = _gethostbyaddr--def restore_system_resolver():- """Undo the effects of override_system_resolver().- """- global _resolver- _resolver = None- socket.getaddrinfo = _original_getaddrinfo- socket.getnameinfo = _original_getnameinfo- socket.getfqdn = _original_getfqdn- socket.gethostbyname = _original_gethostbyname- socket.gethostbyname_ex = _original_gethostbyname_ex- socket.gethostbyaddr = _original_gethostbyaddrdiff --git a/ext/dns/reversename.py b/ext/dns/reversename.pydeleted file mode 100644index 4925cfd6..00000000--- a/ext/dns/reversename.py+++ /dev/null@@ -1,75 +0,0 @@-# 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:- 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')diff --git a/ext/dns/rrset.py b/ext/dns/rrset.pydeleted file mode 100644index f6051fea..00000000--- a/ext/dns/rrset.py+++ /dev/null@@ -1,175 +0,0 @@-# 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 __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)diff --git a/ext/dns/set.py b/ext/dns/set.pydeleted file mode 100644index 14c76a05..00000000--- a/ext/dns/set.py+++ /dev/null@@ -1,263 +0,0 @@-# 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 __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 Truediff --git a/ext/dns/tokenizer.py b/ext/dns/tokenizer.pydeleted file mode 100644index ab568731..00000000--- a/ext/dns/tokenizer.py+++ /dev/null@@ -1,547 +0,0 @@-# 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- @param value: The token value- @type value: string- @param 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 __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)diff --git a/ext/dns/tsig.py b/ext/dns/tsig.pydeleted file mode 100644index 6e97dcea..00000000--- a/ext/dns/tsig.py+++ /dev/null@@ -1,223 +0,0 @@-# 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, digestmod=digestmod)- 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")diff --git a/ext/dns/tsigkeyring.py b/ext/dns/tsigkeyring.pydeleted file mode 100644index 10de4db5..00000000--- a/ext/dns/tsigkeyring.py+++ /dev/null@@ -1,44 +0,0 @@-# 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 = keyname.to_text()- secret = base64.encodestring(keyring[keyname])- textring[keytext] = secret- return textringdiff --git a/ext/dns/ttl.py b/ext/dns/ttl.pydeleted file mode 100644index ab6ddf4e..00000000--- a/ext/dns/ttl.py+++ /dev/null@@ -1,64 +0,0 @@-# 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 totaldiff --git a/ext/dns/update.py b/ext/dns/update.pydeleted file mode 100644index e6922269..00000000--- a/ext/dns/update.py+++ /dev/null@@ -1,245 +0,0 @@-# 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)diff --git a/ext/dns/version.py b/ext/dns/version.pydeleted file mode 100644index c3d305e2..00000000--- a/ext/dns/version.py+++ /dev/null@@ -1,34 +0,0 @@-# 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 = 11-MICRO = 1-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 | \- SERIALdiff --git a/ext/dns/wiredata.py b/ext/dns/wiredata.pydeleted file mode 100644index 86d954a9..00000000--- a/ext/dns/wiredata.py+++ /dev/null@@ -1,59 +0,0 @@-# 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 wirediff --git a/ext/dns/zone.py b/ext/dns/zone.pydeleted file mode 100644index 9efcf437..00000000--- a/ext/dns/zone.py+++ /dev/null@@ -1,1022 +0,0 @@-# 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 re--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-import dns.grange---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 self.nodes.has_key(name):- 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 dns.exception.SyntaxError- except:- 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:- 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:- # 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 _parse_modify(self, side):- # Here we catch everything in '{' '}' in a group so we can replace it- # with ''.- is_generate1 = re.compile("^.*\$({(\+|-?)(\d+),(\d+),(.)}).*$")- is_generate2 = re.compile("^.*\$({(\+|-?)(\d+)}).*$")- is_generate3 = re.compile("^.*\$({(\+|-?)(\d+),(\d+)}).*$")- # Sometimes there are modifiers in the hostname. These come after- # the dollar sign. They are in the form: ${offset[,width[,base]]}.- # Make names- g1 = is_generate1.match(side)- if g1:- mod, sign, offset, width, base = g1.groups()- if sign == '':- sign = '+'- g2 = is_generate2.match(side)- if g2:- mod, sign, offset = g2.groups()- if sign == '':- sign = '+'- width = 0- base = 'd'- g3 = is_generate3.match(side)- if g3:- mod, sign, offset, width = g1.groups()- if sign == '':- sign = '+'- width = g1.groups()[2]- base = 'd'-- if not (g1 or g2 or g3):- mod = ''- sign = '+'- offset = 0- width = 0- base = 'd'-- if base != 'd':- raise NotImplemented-- return mod, sign, offset, width, base-- def _generate_line(self):- # range lhs [ttl] [class] type rhs [ comment ]- """Process one line containing the GENERATE statement from a DNS- master file."""- if self.current_origin is None:- raise UnknownOrigin-- token = self.tok.get()- # Range (required)- try:- start, stop, step = dns.grange.from_text(token.value)- token = self.tok.get()- if not token.is_identifier():- raise dns.exception.SyntaxError- except:- raise dns.exception.SyntaxError-- # lhs (required)- try:- lhs = token.value- token = self.tok.get()- if not token.is_identifier():- raise dns.exception.SyntaxError- except:- 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 dns.exception.SyntaxError- except:- 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)- token = self.tok.get()- if not token.is_identifier():- raise dns.exception.SyntaxError- except:- raise dns.exception.SyntaxError("unknown rdatatype '%s'" %- token.value)-- # lhs (required)- try:- rhs = token.value- except:- raise dns.exception.SyntaxError--- lmod, lsign, loffset, lwidth, lbase = self._parse_modify(lhs)- rmod, rsign, roffset, rwidth, rbase = self._parse_modify(rhs)- for i in range(start, stop + 1, step):- # +1 because bind is inclusive and python is exclusive-- if lsign == '+':- lindex = i + int(loffset)- elif lsign == '-':- lindex = i - int(loffset)-- if rsign == '-':- rindex = i - int(roffset)- elif rsign == '+':- rindex = i + int(roffset)-- lzfindex = str(lindex).zfill(int(lwidth))- rzfindex = str(rindex).zfill(int(rwidth))--- name = lhs.replace('$%s' % (lmod), lzfindex)- rdata = rhs.replace('$%s' % (rmod), rzfindex)-- self.last_name = dns.name.from_text(name, self.current_origin)- 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)-- 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, rdata,- self.current_origin, False)- except dns.exception.SyntaxError:- # Catch and reraise.- (ty, va) = sys.exc_info()[:2]- raise va- except:- # 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()- 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- elif u == '$GENERATE':- self._generate_line()- 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, check_origin=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- @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- """-- 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)- if check_origin:- z.check_origin()- return zdiff --git a/ext/exifread/__init__.py b/ext/exifread/__init__.pydeleted file mode 100644index f88b94f9..00000000--- a/ext/exifread/__init__.py+++ /dev/null@@ -1,262 +0,0 @@-"""-Read Exif metadata from tiff and jpeg files.-"""--from .exif_log import get_logger-from .classes import *-from .tags import *-from .utils import ord_--__version__ = '2.0.1'--logger = get_logger()---def increment_base(data, base):- return ord_(data[base + 2]) * 256 + ord_(data[base + 3]) + 2---def process_file(f, stop_tag=DEFAULT_STOP_TAG, details=True, strict=False, debug=False):- """- Process an image file (expects an open file object).-- This is the function that has to deal with all the arbitrary nasty bits- of the EXIF standard.- """-- # by default do not fake an EXIF beginning- fake_exif = 0-- # determine whether it's a JPEG or TIFF- data = f.read(12)- if data[0:4] in [b'II*\x00', b'MM\x00*']:- # it's a TIFF file- logger.debug("TIFF format recognized in data[0:4]")- f.seek(0)- endian = f.read(1)- f.read(1)- offset = 0- elif data[0:2] == b'\xFF\xD8':- # it's a JPEG file- logger.debug("JPEG format recognized data[0:2]=0x%X%X", ord_(data[0]), ord_(data[1]))- base = 2- logger.debug("data[2]=0x%X data[3]=0x%X data[6:10]=%s",- ord_(data[2]), ord_(data[3]), data[6:10])- while ord_(data[2]) == 0xFF and data[6:10] in (b'JFIF', b'JFXX', b'OLYM', b'Phot'):- length = ord_(data[4]) * 256 + ord_(data[5])- logger.debug(" Length offset is %s", length)- f.read(length - 8)- # fake an EXIF beginning of file- # I don't think this is used. --gd- data = b'\xFF\x00' + f.read(10)- fake_exif = 1- if base > 2:- logger.debug(" Added to base")- base = base + length + 4 - 2- else:- logger.debug(" Added to zero")- base = length + 4- logger.debug(" Set segment base to 0x%X", base)-- # Big ugly patch to deal with APP2 (or other) data coming before APP1- f.seek(0)- # in theory, this could be insufficient since 64K is the maximum size--gd- data = f.read(base + 4000)- # base = 2- while 1:- logger.debug(" Segment base 0x%X", base)- if data[base:base + 2] == b'\xFF\xE1':- # APP1- logger.debug(" APP1 at base 0x%X", base)- logger.debug(" Length: 0x%X 0x%X", ord_(data[base + 2]),- ord_(data[base + 3]))- logger.debug(" Code: %s", data[base + 4:base + 8])- if data[base + 4:base + 8] == b"Exif":- logger.debug(" Decrement base by 2 to get to pre-segment header (for compatibility with later code)")- base -= 2- break- increment = increment_base(data, base)- logger.debug(" Increment base by %s", increment)- base += increment- elif data[base:base + 2] == b'\xFF\xE0':- # APP0- logger.debug(" APP0 at base 0x%X", base)- logger.debug(" Length: 0x%X 0x%X", ord_(data[base + 2]),- ord_(data[base + 3]))- logger.debug(" Code: %s", data[base + 4:base + 8])- increment = increment_base(data, base)- logger.debug(" Increment base by %s", increment)- base += increment- elif data[base:base + 2] == b'\xFF\xE2':- # APP2- logger.debug(" APP2 at base 0x%X", base)- logger.debug(" Length: 0x%X 0x%X", ord_(data[base + 2]),- ord_(data[base + 3]))- logger.debug(" Code: %s", data[base + 4:base + 8])- increment = increment_base(data, base)- logger.debug(" Increment base by %s", increment)- base += increment- elif data[base:base + 2] == b'\xFF\xEE':- # APP14- logger.debug(" APP14 Adobe segment at base 0x%X", base)- logger.debug(" Length: 0x%X 0x%X", ord_(data[base + 2]),- ord_(data[base + 3]))- logger.debug(" Code: %s", data[base + 4:base + 8])- increment = increment_base(data, base)- logger.debug(" Increment base by %s", increment)- base += increment- logger.debug(" There is useful EXIF-like data here, but we have no parser for it.")- elif data[base:base + 2] == b'\xFF\xDB':- logger.debug(" JPEG image data at base 0x%X No more segments are expected.",- base)- break- elif data[base:base + 2] == b'\xFF\xD8':- # APP12- logger.debug(" FFD8 segment at base 0x%X", base)- logger.debug(" Got 0x%X 0x%X and %s instead",- ord_(data[base]),- ord_(data[base + 1]),- data[4 + base:10 + base])- logger.debug(" Length: 0x%X 0x%X", ord_(data[base + 2]),- ord_(data[base + 3]))- logger.debug(" Code: %s", data[base + 4:base + 8])- increment = increment_base(data, base)- logger.debug(" Increment base by %s", increment)- base += increment- elif data[base:base + 2] == b'\xFF\xEC':- # APP12- logger.debug(" APP12 XMP (Ducky) or Pictureinfo segment at base 0x%X",- base)- logger.debug(" Got 0x%X and 0x%X instead", ord_(data[base]),- ord_(data[base + 1]))- logger.debug(" Length: 0x%X 0x%X",- ord_(data[base + 2]),- ord_(data[base + 3]))- logger.debug("Code: %s", data[base + 4:base + 8])- increment = increment_base(data, base)- logger.debug(" Increment base by %s", increment)- base += increment- logger.debug(- " There is useful EXIF-like data here (quality, comment, copyright), but we have no parser for it.")- else:- try:- increment = increment_base(data, base)- logger.debug(" Got 0x%X and 0x%X instead",- ord_(data[base]),- ord_(data[base + 1]))- except IndexError:- logger.debug(" Unexpected/unhandled segment type or file content.")- return {}- else:- logger.debug(" Increment base by %s", increment)- base += increment- f.seek(base + 12)- if ord_(data[2 + base]) == 0xFF and data[6 + base:10 + base] == b'Exif':- # detected EXIF header- offset = f.tell()- endian = f.read(1)- #HACK TEST: endian = 'M'- elif ord_(data[2 + base]) == 0xFF and data[6 + base:10 + base + 1] == b'Ducky':- # detected Ducky header.- logger.debug("EXIF-like header (normally 0xFF and code): 0x%X and %s",- ord_(data[2 + base]), data[6 + base:10 + base + 1])- offset = f.tell()- endian = f.read(1)- elif ord_(data[2 + base]) == 0xFF and data[6 + base:10 + base + 1] == b'Adobe':- # detected APP14 (Adobe)- logger.debug("EXIF-like header (normally 0xFF and code): 0x%X and %s",- ord_(data[2 + base]), data[6 + base:10 + base + 1])- offset = f.tell()- endian = f.read(1)- else:- # no EXIF information- logger.debug("No EXIF header expected data[2+base]==0xFF and data[6+base:10+base]===Exif (or Duck)")- logger.debug("Did get 0x%X and %s",- ord_(data[2 + base]), data[6 + base:10 + base + 1])- return {}- else:- # file format not recognized- logger.debug("File format not recognized.")- return {}-- endian = chr(ord_(endian[0]))- # deal with the EXIF info we found- logger.debug("Endian format is %s (%s)", endian, {- 'I': 'Intel',- 'M': 'Motorola',- '\x01': 'Adobe Ducky',- 'd': 'XMP/Adobe unknown'- }[endian])-- hdr = ExifHeader(f, endian, offset, fake_exif, strict, debug, details)- ifd_list = hdr.list_ifd()- thumb_ifd = False- ctr = 0- for ifd in ifd_list:- if ctr == 0:- ifd_name = 'Image'- elif ctr == 1:- ifd_name = 'Thumbnail'- thumb_ifd = ifd- else:- ifd_name = 'IFD %d' % ctr- logger.debug('IFD %d (%s) at offset %s:', ctr, ifd_name, ifd)- hdr.dump_ifd(ifd, ifd_name, stop_tag=stop_tag)- ctr += 1- # EXIF IFD- exif_off = hdr.tags.get('Image ExifOffset')- if exif_off:- logger.debug('Exif SubIFD at offset %s:', exif_off.values[0])- hdr.dump_ifd(exif_off.values[0], 'EXIF', stop_tag=stop_tag)-- # deal with MakerNote contained in EXIF IFD- # (Some apps use MakerNote tags but do not use a format for which we- # have a description, do not process these).- if details and 'EXIF MakerNote' in hdr.tags and 'Image Make' in hdr.tags:- hdr.decode_maker_note()-- # extract thumbnails- if details and thumb_ifd:- hdr.extract_tiff_thumbnail(thumb_ifd)- hdr.extract_jpeg_thumbnail()-- # parse XMP tags (experimental)- if debug and details:- xmp_string = b''- # Easy we already have them- if 'Image ApplicationNotes' in hdr.tags:- logger.debug('XMP present in Exif')- xmp_string = make_string(hdr.tags['Image ApplicationNotes'].values)- # We need to look in the entire file for the XML- else:- logger.debug('XMP not in Exif, searching file for XMP info ...')- xml_started = False- xml_finished = False- for line in f:- open_tag = line.find(b'<x:xmpmeta')- close_tag = line.find(b'</x:xmpmeta>')-- if open_tag != -1:- xml_started = True- line = line[open_tag:]- logger.debug('XMP found opening tag at line position %s' % open_tag)-- if close_tag != -1:- logger.debug('XMP found closing tag at line position %s' % close_tag)- line_offset = 0- if open_tag != -1:- line_offset = open_tag- line = line[:(close_tag - line_offset) + 12]- xml_finished = True-- if xml_started:- xmp_string += line-- if xml_finished:- break-- logger.debug('XMP Finished searching for info')- if xmp_string:- hdr.parse_xmp(xmp_string)-- return hdr.tagsdiff --git a/ext/exifread/classes.py b/ext/exifread/classes.pydeleted file mode 100644index 0876b4ce..00000000--- a/ext/exifread/classes.py+++ /dev/null@@ -1,538 +0,0 @@-import struct-import re--from .exif_log import get_logger-from .utils import s2n_motorola, s2n_intel, Ratio-from .tags import *--logger = get_logger()---class IfdTag:- """- Eases dealing with tags.- """-- def __init__(self, printable, tag, field_type, values, field_offset,- field_length):- # printable version of data- self.printable = printable- # tag ID number- self.tag = tag- # field type as index into FIELD_TYPES- self.field_type = field_type- # offset of start of field in bytes from beginning of IFD- self.field_offset = field_offset- # length of data field in bytes- self.field_length = field_length- # either a string or array of data items- self.values = values-- def __str__(self):- return self.printable-- def __repr__(self):- try:- s = '(0x%04X) %s=%s @ %d' % (self.tag,- FIELD_TYPES[self.field_type][2],- self.printable,- self.field_offset)- except:- s = '(%s) %s=%s @ %s' % (str(self.tag),- FIELD_TYPES[self.field_type][2],- self.printable,- str(self.field_offset))- return s---class ExifHeader:- """- Handle an EXIF header.- """-- def __init__(self, file, endian, offset, fake_exif, strict,- debug=False, detailed=True):- self.file = file- self.endian = endian- self.offset = offset- self.fake_exif = fake_exif- self.strict = strict- self.debug = debug- self.detailed = detailed- self.tags = {}-- def s2n(self, offset, length, signed=0):- """- Convert slice to integer, based on sign and endian flags.-- Usually this offset is assumed to be relative to the beginning of the- start of the EXIF information.- For some cameras that use relative tags, this offset may be relative- to some other starting point.- """- self.file.seek(self.offset + offset)- sliced = self.file.read(length)- if self.endian == 'I':- val = s2n_intel(sliced)- else:- val = s2n_motorola(sliced)- # Sign extension?- if signed:- msb = 1 << (8 * length - 1)- if val & msb:- val -= (msb << 1)- return val-- def n2s(self, offset, length):- """Convert offset to string."""- s = ''- for dummy in range(length):- if self.endian == 'I':- s += chr(offset & 0xFF)- else:- s = chr(offset & 0xFF) + s- offset = offset >> 8- return s-- def _first_ifd(self):- """Return first IFD."""- return self.s2n(4, 4)-- def _next_ifd(self, ifd):- """Return the pointer to next IFD."""- entries = self.s2n(ifd, 2)- next_ifd = self.s2n(ifd + 2 + 12 * entries, 4)- if next_ifd == ifd:- return 0- else:- return next_ifd-- def list_ifd(self):- """Return the list of IFDs in the header."""- i = self._first_ifd()- ifds = []- while i:- ifds.append(i)- i = self._next_ifd(i)- return ifds-- def dump_ifd(self, ifd, ifd_name, tag_dict=EXIF_TAGS, relative=0, stop_tag=DEFAULT_STOP_TAG):- """- Return a list of entries in the given IFD.- """- # make sure we can process the entries- try:- entries = self.s2n(ifd, 2)- except TypeError:- logger.warning("Possibly corrupted IFD: %s" % ifd)- return-- for i in range(entries):- # entry is index of start of this IFD in the file- entry = ifd + 2 + 12 * i- tag = self.s2n(entry, 2)-- # get tag name early to avoid errors, help debug- tag_entry = tag_dict.get(tag)- if tag_entry:- tag_name = tag_entry[0]- else:- tag_name = 'Tag 0x%04X' % tag-- # ignore certain tags for faster processing- if not (not self.detailed and tag in IGNORE_TAGS):- field_type = self.s2n(entry + 2, 2)-- # unknown field type- if not 0 < field_type < len(FIELD_TYPES):- if not self.strict:- continue- else:- raise ValueError('Unknown type %d in tag 0x%04X' % (field_type, tag))-- type_length = FIELD_TYPES[field_type][0]- count = self.s2n(entry + 4, 4)- # Adjust for tag id/type/count (2+2+4 bytes)- # Now we point at either the data or the 2nd level offset- offset = entry + 8-- # If the value fits in 4 bytes, it is inlined, else we- # need to jump ahead again.- if count * type_length > 4:- # offset is not the value; it's a pointer to the value- # if relative we set things up so s2n will seek to the right- # place when it adds self.offset. Note that this 'relative'- # is for the Nikon type 3 makernote. Other cameras may use- # other relative offsets, which would have to be computed here- # slightly differently.- if relative:- tmp_offset = self.s2n(offset, 4)- offset = tmp_offset + ifd - 8- if self.fake_exif:- offset += 18- else:- offset = self.s2n(offset, 4)-- field_offset = offset- values = None- if field_type == 2:- # special case: null-terminated ASCII string- # XXX investigate- # sometimes gets too big to fit in int value- if count != 0: # and count < (2**31): # 2E31 is hardware dependant. --gd- try:- self.file.seek(self.offset + offset)- values = self.file.read(count)- #print values- # Drop any garbage after a null.- values = values.split(b'\x00', 1)[0]- if isinstance(values, bytes):- try:- values = values.decode("utf-8")- except UnicodeDecodeError:- logger.warning("Possibly corrupted field %s in %s IFD", tag_name, ifd_name)- except OverflowError:- values = ''- else:- values = []- signed = (field_type in [6, 8, 9, 10])-- # XXX investigate- # some entries get too big to handle could be malformed- # file or problem with self.s2n- if count < 1000:- for dummy in range(count):- if field_type in (5, 10):- # a ratio- value = Ratio(self.s2n(offset, 4, signed),- self.s2n(offset + 4, 4, signed))- else:- value = self.s2n(offset, type_length, signed)- values.append(value)- offset = offset + type_length- # The test above causes problems with tags that are- # supposed to have long values! Fix up one important case.- elif tag_name in ('MakerNote', makernote.canon.CAMERA_INFO_TAG_NAME):- for dummy in range(count):- value = self.s2n(offset, type_length, signed)- values.append(value)- offset = offset + type_length-- # now 'values' is either a string or an array- if count == 1 and field_type != 2:- printable = str(values[0])- elif count > 50 and len(values) > 20:- printable = str(values[0:20])[0:-1] + ", ... ]"- else:- try:- printable = str(values)- # fix for python2's handling of unicode values- except UnicodeEncodeError:- printable = unicode(values)-- # compute printable version of values- if tag_entry:- # optional 2nd tag element is present- if len(tag_entry) != 1:- if callable(tag_entry[1]):- # call mapping function- printable = tag_entry[1](values)- elif type(tag_entry[1]) is tuple:- ifd_info = tag_entry[1]- try:- logger.debug('%s SubIFD at offset %d:', ifd_info[0], values[0])- self.dump_ifd(values[0], ifd_info[0], tag_dict=ifd_info[1], stop_tag=stop_tag)- except IndexError:- logger.warn('No values found for %s SubIFD', ifd_info[0])- else:- printable = ''- for i in values:- # use lookup table for this tag- printable += tag_entry[1].get(i, repr(i))-- self.tags[ifd_name + ' ' + tag_name] = IfdTag(printable, tag,- field_type,- values, field_offset,- count * type_length)- try:- tag_value = repr(self.tags[ifd_name + ' ' + tag_name])- # fix for python2's handling of unicode values- except UnicodeEncodeError:- tag_value = unicode(self.tags[ifd_name + ' ' + tag_name])- logger.debug(' %s: %s', tag_name, tag_value)-- if tag_name == stop_tag:- break-- def extract_tiff_thumbnail(self, thumb_ifd):- """- Extract uncompressed TIFF thumbnail.-- Take advantage of the pre-existing layout in the thumbnail IFD as- much as possible- """- thumb = self.tags.get('Thumbnail Compression')- if not thumb or thumb.printable != 'Uncompressed TIFF':- return-- entries = self.s2n(thumb_ifd, 2)- # this is header plus offset to IFD ...- if self.endian == 'M':- tiff = 'MM\x00*\x00\x00\x00\x08'- else:- tiff = 'II*\x00\x08\x00\x00\x00'- # ... plus thumbnail IFD data plus a null "next IFD" pointer- self.file.seek(self.offset + thumb_ifd)- tiff += self.file.read(entries * 12 + 2) + '\x00\x00\x00\x00'-- # fix up large value offset pointers into data area- for i in range(entries):- entry = thumb_ifd + 2 + 12 * i- tag = self.s2n(entry, 2)- field_type = self.s2n(entry + 2, 2)- type_length = FIELD_TYPES[field_type][0]- count = self.s2n(entry + 4, 4)- old_offset = self.s2n(entry + 8, 4)- # start of the 4-byte pointer area in entry- ptr = i * 12 + 18- # remember strip offsets location- if tag == 0x0111:- strip_off = ptr- strip_len = count * type_length- # is it in the data area?- if count * type_length > 4:- # update offset pointer (nasty "strings are immutable" crap)- # should be able to say "tiff[ptr:ptr+4]=newoff"- newoff = len(tiff)- tiff = tiff[:ptr] + self.n2s(newoff, 4) + tiff[ptr + 4:]- # remember strip offsets location- if tag == 0x0111:- strip_off = newoff- strip_len = 4- # get original data and store it- self.file.seek(self.offset + old_offset)- tiff += self.file.read(count * type_length)-- # add pixel strips and update strip offset info- old_offsets = self.tags['Thumbnail StripOffsets'].values- old_counts = self.tags['Thumbnail StripByteCounts'].values- for i in range(len(old_offsets)):- # update offset pointer (more nasty "strings are immutable" crap)- offset = self.n2s(len(tiff), strip_len)- tiff = tiff[:strip_off] + offset + tiff[strip_off + strip_len:]- strip_off += strip_len- # add pixel strip to end- self.file.seek(self.offset + old_offsets[i])- tiff += self.file.read(old_counts[i])-- self.tags['TIFFThumbnail'] = tiff-- def extract_jpeg_thumbnail(self):- """- Extract JPEG thumbnail.-- (Thankfully the JPEG data is stored as a unit.)- """- thumb_offset = self.tags.get('Thumbnail JPEGInterchangeFormat')- if thumb_offset:- self.file.seek(self.offset + thumb_offset.values[0])- size = self.tags['Thumbnail JPEGInterchangeFormatLength'].values[0]- self.tags['JPEGThumbnail'] = self.file.read(size)-- # Sometimes in a TIFF file, a JPEG thumbnail is hidden in the MakerNote- # since it's not allowed in a uncompressed TIFF IFD- if 'JPEGThumbnail' not in self.tags:- thumb_offset = self.tags.get('MakerNote JPEGThumbnail')- if thumb_offset:- self.file.seek(self.offset + thumb_offset.values[0])- self.tags['JPEGThumbnail'] = self.file.read(thumb_offset.field_length)-- def decode_maker_note(self):- """- Decode all the camera-specific MakerNote formats-- Note is the data that comprises this MakerNote.- The MakerNote will likely have pointers in it that point to other- parts of the file. We'll use self.offset as the starting point for- most of those pointers, since they are relative to the beginning- of the file.- If the MakerNote is in a newer format, it may use relative addressing- within the MakerNote. In that case we'll use relative addresses for- the pointers.- As an aside: it's not just to be annoying that the manufacturers use- relative offsets. It's so that if the makernote has to be moved by the- picture software all of the offsets don't have to be adjusted. Overall,- this is probably the right strategy for makernotes, though the spec is- ambiguous.- The spec does not appear to imagine that makernotes would- follow EXIF format internally. Once they did, it's ambiguous whether- the offsets should be from the header at the start of all the EXIF info,- or from the header at the start of the makernote.- """- note = self.tags['EXIF MakerNote']-- # Some apps use MakerNote tags but do not use a format for which we- # have a description, so just do a raw dump for these.- make = self.tags['Image Make'].printable-- # Nikon- # The maker note usually starts with the word Nikon, followed by the- # type of the makernote (1 or 2, as a short). If the word Nikon is- # not at the start of the makernote, it's probably type 2, since some- # cameras work that way.- if 'NIKON' in make:- if note.values[0:7] == [78, 105, 107, 111, 110, 0, 1]:- logger.debug("Looks like a type 1 Nikon MakerNote.")- self.dump_ifd(note.field_offset + 8, 'MakerNote',- tag_dict=makernote.NIKON_OLD)- elif note.values[0:7] == [78, 105, 107, 111, 110, 0, 2]:- if self.debug:- logger.debug("Looks like a labeled type 2 Nikon MakerNote")- if note.values[12:14] != [0, 42] and note.values[12:14] != [42, 0]:- raise ValueError("Missing marker tag '42' in MakerNote.")- # skip the Makernote label and the TIFF header- self.dump_ifd(note.field_offset + 10 + 8, 'MakerNote',- tag_dict=makernote.NIKON_NEW, relative=1)- else:- # E99x or D1- logger.debug("Looks like an unlabeled type 2 Nikon MakerNote")- self.dump_ifd(note.field_offset, 'MakerNote',- tag_dict=makernote.NIKON_NEW)- return-- # Olympus- if make.startswith('OLYMPUS'):- self.dump_ifd(note.field_offset + 8, 'MakerNote',- tag_dict=makernote.OLYMPUS)- # TODO- #for i in (('MakerNote Tag 0x2020', makernote.OLYMPUS_TAG_0x2020),):- # self.decode_olympus_tag(self.tags[i[0]].values, i[1])- #return-- # Casio- if 'CASIO' in make or 'Casio' in make:- self.dump_ifd(note.field_offset, 'MakerNote',- tag_dict=makernote.CASIO)- return-- # Fujifilm- if make == 'FUJIFILM':- # bug: everything else is "Motorola" endian, but the MakerNote- # is "Intel" endian- endian = self.endian- self.endian = 'I'- # bug: IFD offsets are from beginning of MakerNote, not- # beginning of file header- offset = self.offset- self.offset += note.field_offset- # process note with bogus values (note is actually at offset 12)- self.dump_ifd(12, 'MakerNote', tag_dict=makernote.FUJIFILM)- # reset to correct values- self.endian = endian- self.offset = offset- return-- # Canon- if make == 'Canon':- self.dump_ifd(note.field_offset, 'MakerNote',- tag_dict=makernote.canon.TAGS)- for i in (('MakerNote Tag 0x0001', makernote.canon.CAMERA_SETTINGS),- ('MakerNote Tag 0x0002', makernote.canon.FOCAL_LENGTH),- ('MakerNote Tag 0x0004', makernote.canon.SHOT_INFO),- ('MakerNote Tag 0x0026', makernote.canon.AF_INFO_2),- ('MakerNote Tag 0x0093', makernote.canon.FILE_INFO)):- if i[0] in self.tags:- logger.debug('Canon ' + i[0])- self._canon_decode_tag(self.tags[i[0]].values, i[1])- del self.tags[i[0]]- if makernote.canon.CAMERA_INFO_TAG_NAME in self.tags:- tag = self.tags[makernote.canon.CAMERA_INFO_TAG_NAME]- logger.debug('Canon CameraInfo')- self._canon_decode_camera_info(tag)- del self.tags[makernote.canon.CAMERA_INFO_TAG_NAME]- return-- def _olympus_decode_tag(self, value, mn_tags):- """ TODO Decode Olympus MakerNote tag based on offset within tag."""- pass-- def _canon_decode_tag(self, value, mn_tags):- """- Decode Canon MakerNote tag based on offset within tag.-- See http://www.burren.cx/david/canon.html by David Burren- """- for i in range(1, len(value)):- tag = mn_tags.get(i, ('Unknown', ))- name = tag[0]- if len(tag) > 1:- val = tag[1].get(value[i], 'Unknown')- else:- val = value[i]- try:- logger.debug(" %s %s %s", i, name, hex(value[i]))- except TypeError:- logger.debug(" %s %s %s", i, name, value[i])-- # it's not a real IFD Tag but we fake one to make everybody- # happy. this will have a "proprietary" type- self.tags['MakerNote ' + name] = IfdTag(str(val), None, 0, None,- None, None)-- def _canon_decode_camera_info(self, camera_info_tag):- """- Decode the variable length encoded camera info section.- """- model = self.tags.get('Image Model', None)- if not model:- return- model = str(model.values)-- camera_info_tags = None- for (model_name_re, tag_desc) in makernote.canon.CAMERA_INFO_MODEL_MAP.items():- if re.search(model_name_re, model):- camera_info_tags = tag_desc- break- else:- return-- # We are assuming here that these are all unsigned bytes (Byte or- # Unknown)- if camera_info_tag.field_type not in (1, 7):- return- camera_info = struct.pack('<%dB' % len(camera_info_tag.values),- *camera_info_tag.values)-- # Look for each data value and decode it appropriately.- for offset, tag in camera_info_tags.items():- tag_format = tag[1]- tag_size = struct.calcsize(tag_format)- if len(camera_info) < offset + tag_size:- continue- packed_tag_value = camera_info[offset:offset + tag_size]- tag_value = struct.unpack(tag_format, packed_tag_value)[0]-- tag_name = tag[0]- if len(tag) > 2:- if callable(tag[2]):- tag_value = tag[2](tag_value)- else:- tag_value = tag[2].get(tag_value, tag_value)- logger.debug(" %s %s", tag_name, tag_value)-- self.tags['MakerNote ' + tag_name] = IfdTag(str(tag_value), None,- 0, None, None, None)-- def parse_xmp(self, xmp_string):- import xml.dom.minidom-- logger.debug('XMP cleaning data')-- xml = xml.dom.minidom.parseString(xmp_string)- pretty = xml.toprettyxml()- cleaned = []- for line in pretty.splitlines():- if line.strip():- cleaned.append(line)- self.tags['Image ApplicationNotes'] = IfdTag('\n'.join(cleaned), None,- 1, None, None, None)\ No newline at end of filediff --git a/ext/exifread/exif_log.py b/ext/exifread/exif_log.pydeleted file mode 100644index 82d5aea2..00000000--- a/ext/exifread/exif_log.py+++ /dev/null@@ -1,76 +0,0 @@-"""-Custom log output-"""--import sys-import logging--TEXT_NORMAL = 0-TEXT_BOLD = 1-TEXT_RED = 31-TEXT_GREEN = 32-TEXT_YELLOW = 33-TEXT_BLUE = 34-TEXT_MAGENTA = 35-TEXT_CYAN = 36---def get_logger():- return logging.getLogger('exifread')---def setup_logger(debug, color):- """Configure the logger."""- if debug:- log_level = logging.DEBUG- else:- log_level = logging.INFO-- logger = logging.getLogger('exifread')- stream = Handler(log_level, debug, color)- logger.addHandler(stream)- logger.setLevel(log_level)---class Formatter(logging.Formatter):-- def __init__(self, debug=False, color=False):- self.color = color- self.debug = debug- if self.debug:- log_format = '%(levelname)-6s %(message)s'- else:- log_format = '%(message)s'- logging.Formatter.__init__(self, log_format)-- def format(self, record):- if self.debug and self.color:- if record.levelno >= logging.CRITICAL:- color = TEXT_RED- elif record.levelno >= logging.ERROR:- color = TEXT_RED- elif record.levelno >= logging.WARNING:- color = TEXT_YELLOW- elif record.levelno >= logging.INFO:- color = TEXT_GREEN- elif record.levelno >= logging.DEBUG:- color = TEXT_CYAN- else:- color = TEXT_NORMAL- record.levelname = "\x1b[%sm%s\x1b[%sm" % (color, record.levelname, TEXT_NORMAL)- return logging.Formatter.format(self, record)---class Handler(logging.StreamHandler):-- def __init__(self, log_level, debug=False, color=False):- self.color = color- self.debug = debug- logging.StreamHandler.__init__(self, sys.stdout)- self.setFormatter(Formatter(debug, color))- self.setLevel(log_level)-"""- def emit(self, record):- record.msg = "\x1b[%sm%s\x1b[%sm" % (TEXT_BOLD, record.msg, TEXT_NORMAL)- logging.StreamHandler.emit(self, record)-"""\ No newline at end of filediff --git a/ext/exifread/tags/__init__.py b/ext/exifread/tags/__init__.pydeleted file mode 100644index cac69214..00000000--- a/ext/exifread/tags/__init__.py+++ /dev/null@@ -1,30 +0,0 @@-"""-Tag definitions-"""--from .exif import *-from . import makernote--DEFAULT_STOP_TAG = 'UNDEF'--# field type descriptions as (length, abbreviation, full name) tuples-FIELD_TYPES = (- (0, 'X', 'Proprietary'), # no such type- (1, 'B', 'Byte'),- (1, 'A', 'ASCII'),- (2, 'S', 'Short'),- (4, 'L', 'Long'),- (8, 'R', 'Ratio'),- (1, 'SB', 'Signed Byte'),- (1, 'U', 'Undefined'),- (2, 'SS', 'Signed Short'),- (4, 'SL', 'Signed Long'),- (8, 'SR', 'Signed Ratio'),-)--# To ignore when quick processing-IGNORE_TAGS = (- 0x9286, # user comment- 0x927C, # MakerNote Tags- 0x02BC, # XPM-)diff --git a/ext/exifread/tags/exif.py b/ext/exifread/tags/exif.pydeleted file mode 100644index 4b0d9336..00000000--- a/ext/exifread/tags/exif.py+++ /dev/null@@ -1,441 +0,0 @@-"""-Standard tag definitions.-"""--from exifread.utils import make_string, make_string_uc--# Interoperability tags-INTEROP_TAGS = {- 0x0001: ('InteroperabilityIndex', ),- 0x0002: ('InteroperabilityVersion', ),- 0x1000: ('RelatedImageFileFormat', ),- 0x1001: ('RelatedImageWidth', ),- 0x1002: ('RelatedImageLength', ),-}-INTEROP_INFO = (- 'Interoperability',- INTEROP_TAGS-)--# GPS tags-GPS_TAGS = {- 0x0000: ('GPSVersionID', ),- 0x0001: ('GPSLatitudeRef', ),- 0x0002: ('GPSLatitude', ),- 0x0003: ('GPSLongitudeRef', ),- 0x0004: ('GPSLongitude', ),- 0x0005: ('GPSAltitudeRef', ),- 0x0006: ('GPSAltitude', ),- 0x0007: ('GPSTimeStamp', ),- 0x0008: ('GPSSatellites', ),- 0x0009: ('GPSStatus', ),- 0x000A: ('GPSMeasureMode', ),- 0x000B: ('GPSDOP', ),- 0x000C: ('GPSSpeedRef', ),- 0x000D: ('GPSSpeed', ),- 0x000E: ('GPSTrackRef', ),- 0x000F: ('GPSTrack', ),- 0x0010: ('GPSImgDirectionRef', ),- 0x0011: ('GPSImgDirection', ),- 0x0012: ('GPSMapDatum', ),- 0x0013: ('GPSDestLatitudeRef', ),- 0x0014: ('GPSDestLatitude', ),- 0x0015: ('GPSDestLongitudeRef', ),- 0x0016: ('GPSDestLongitude', ),- 0x0017: ('GPSDestBearingRef', ),- 0x0018: ('GPSDestBearing', ),- 0x0019: ('GPSDestDistanceRef', ),- 0x001A: ('GPSDestDistance', ),- 0x001B: ('GPSProcessingMethod', ),- 0x001C: ('GPSAreaInformation', ),- 0x001D: ('GPSDate', ),- 0x001E: ('GPSDifferential', ),-}-GPS_INFO = (- 'GPS',- GPS_TAGS-)--# Main Exif tag names-EXIF_TAGS = {- 0x00FE: ('SubfileType', {- 0x0: 'Full-resolution Image',- 0x1: 'Reduced-resolution image',- 0x2: 'Single page of multi-page image',- 0x3: 'Single page of multi-page reduced-resolution image',- 0x4: 'Transparency mask',- 0x5: 'Transparency mask of reduced-resolution image',- 0x6: 'Transparency mask of multi-page image',- 0x7: 'Transparency mask of reduced-resolution multi-page image',- 0x10001: 'Alternate reduced-resolution image',- 0xffffffff: 'invalid ',- }),- 0x00FF: ('OldSubfileType', {- 1: 'Full-resolution image',- 2: 'Reduced-resolution image',- 3: 'Single page of multi-page image',- }),- 0x0100: ('ImageWidth', ),- 0x0101: ('ImageLength', ),- 0x0102: ('BitsPerSample', ),- 0x0103: ('Compression', {- 1: 'Uncompressed',- 2: 'CCITT 1D',- 3: 'T4/Group 3 Fax',- 4: 'T6/Group 4 Fax',- 5: 'LZW',- 6: 'JPEG (old-style)',- 7: 'JPEG',- 8: 'Adobe Deflate',- 9: 'JBIG B&W',- 10: 'JBIG Color',- 32766: 'Next',- 32769: 'Epson ERF Compressed',- 32771: 'CCIRLEW',- 32773: 'PackBits',- 32809: 'Thunderscan',- 32895: 'IT8CTPAD',- 32896: 'IT8LW',- 32897: 'IT8MP',- 32898: 'IT8BL',- 32908: 'PixarFilm',- 32909: 'PixarLog',- 32946: 'Deflate',- 32947: 'DCS',- 34661: 'JBIG',- 34676: 'SGILog',- 34677: 'SGILog24',- 34712: 'JPEG 2000',- 34713: 'Nikon NEF Compressed',- 65000: 'Kodak DCR Compressed',- 65535: 'Pentax PEF Compressed'- }),- 0x0106: ('PhotometricInterpretation', ),- 0x0107: ('Thresholding', ),- 0x0108: ('CellWidth', ),- 0x0109: ('CellLength', ),- 0x010A: ('FillOrder', ),- 0x010D: ('DocumentName', ),- 0x010E: ('ImageDescription', ),- 0x010F: ('Make', ),- 0x0110: ('Model', ),- 0x0111: ('StripOffsets', ),- 0x0112: ('Orientation', {- 1: 'Horizontal (normal)',- 2: 'Mirrored horizontal',- 3: 'Rotated 180',- 4: 'Mirrored vertical',- 5: 'Mirrored horizontal then rotated 90 CCW',- 6: 'Rotated 90 CCW',- 7: 'Mirrored horizontal then rotated 90 CW',- 8: 'Rotated 90 CW'- }),- 0x0115: ('SamplesPerPixel', ),- 0x0116: ('RowsPerStrip', ),- 0x0117: ('StripByteCounts', ),- 0x0118: ('MinSampleValue', ),- 0x0119: ('MaxSampleValue', ),- 0x011A: ('XResolution', ),- 0x011B: ('YResolution', ),- 0x011C: ('PlanarConfiguration', ),- 0x011D: ('PageName', make_string),- 0x011E: ('XPosition', ),- 0x011F: ('YPosition', ),- 0x0122: ('GrayResponseUnit', {- 1: '0.1',- 2: '0.001',- 3: '0.0001',- 4: '1e-05',- 5: '1e-06',- }),- 0x0123: ('GrayResponseCurve', ),- 0x0124: ('T4Options', ),- 0x0125: ('T6Options', ),- 0x0128: ('ResolutionUnit', {- 1: 'Not Absolute',- 2: 'Pixels/Inch',- 3: 'Pixels/Centimeter'- }),- 0x0129: ('PageNumber', ),- 0x012C: ('ColorResponseUnit', ),- 0x012D: ('TransferFunction', ),- 0x0131: ('Software', ),- 0x0132: ('DateTime', ),- 0x013B: ('Artist', ),- 0x013C: ('HostComputer', ),- 0x013D: ('Predictor', {- 1: 'None',- 2: 'Horizontal differencing'- }),- 0x013E: ('WhitePoint', ),- 0x013F: ('PrimaryChromaticities', ),- 0x0140: ('ColorMap', ),- 0x0141: ('HalftoneHints', ),- 0x0142: ('TileWidth', ),- 0x0143: ('TileLength', ),- 0x0144: ('TileOffsets', ),- 0x0145: ('TileByteCounts', ),- 0x0146: ('BadFaxLines', ),- 0x0147: ('CleanFaxData', {- 0: 'Clean',- 1: 'Regenerated',- 2: 'Unclean'- }),- 0x0148: ('ConsecutiveBadFaxLines', ),- 0x014C: ('InkSet', {- 1: 'CMYK',- 2: 'Not CMYK'- }),- 0x014D: ('InkNames', ),- 0x014E: ('NumberofInks', ),- 0x0150: ('DotRange', ),- 0x0151: ('TargetPrinter', ),- 0x0152: ('ExtraSamples', {- 0: 'Unspecified',- 1: 'Associated Alpha',- 2: 'Unassociated Alpha'- }),- 0x0153: ('SampleFormat', {- 1: 'Unsigned',- 2: 'Signed',- 3: 'Float',- 4: 'Undefined',- 5: 'Complex int',- 6: 'Complex float'- }),- 0x0154: ('SMinSampleValue', ),- 0x0155: ('SMaxSampleValue', ),- 0x0156: ('TransferRange', ),- 0x0157: ('ClipPath', ),- 0x0200: ('JPEGProc', ),- 0x0201: ('JPEGInterchangeFormat', ),- 0x0202: ('JPEGInterchangeFormatLength', ),- 0x0211: ('YCbCrCoefficients', ),- 0x0212: ('YCbCrSubSampling', ),- 0x0213: ('YCbCrPositioning', {- 1: 'Centered',- 2: 'Co-sited'- }),- 0x0214: ('ReferenceBlackWhite', ),- 0x02BC: ('ApplicationNotes', ), # XPM Info- 0x4746: ('Rating', ),- 0x828D: ('CFARepeatPatternDim', ),- 0x828E: ('CFAPattern', ),- 0x828F: ('BatteryLevel', ),- 0x8298: ('Copyright', ),- 0x829A: ('ExposureTime', ),- 0x829D: ('FNumber', ),- 0x83BB: ('IPTC/NAA', ),- 0x8769: ('ExifOffset', ), # Exif Tags- 0x8773: ('InterColorProfile', ),- 0x8822: ('ExposureProgram', {- 0: 'Unidentified',- 1: 'Manual',- 2: 'Program Normal',- 3: 'Aperture Priority',- 4: 'Shutter Priority',- 5: 'Program Creative',- 6: 'Program Action',- 7: 'Portrait Mode',- 8: 'Landscape Mode'- }),- 0x8824: ('SpectralSensitivity', ),- 0x8825: ('GPSInfo', GPS_INFO), # GPS tags- 0x8827: ('ISOSpeedRatings', ),- 0x8828: ('OECF', ),- 0x8830: ('SensitivityType', {- 0: 'Unknown',- 1: 'Standard Output Sensitivity',- 2: 'Recommended Exposure Index',- 3: 'ISO Speed',- 4: 'Standard Output Sensitivity and Recommended Exposure Index',- 5: 'Standard Output Sensitivity and ISO Speed',- 6: 'Recommended Exposure Index and ISO Speed',- 7: 'Standard Output Sensitivity, Recommended Exposure Index and ISO Speed'- }),- 0x8832: ('RecommendedExposureIndex', ),- 0x8833: ('ISOSpeed', ),- 0x9000: ('ExifVersion', make_string),- 0x9003: ('DateTimeOriginal', ),- 0x9004: ('DateTimeDigitized', ),- 0x9101: ('ComponentsConfiguration', {- 0: '',- 1: 'Y',- 2: 'Cb',- 3: 'Cr',- 4: 'Red',- 5: 'Green',- 6: 'Blue'- }),- 0x9102: ('CompressedBitsPerPixel', ),- 0x9201: ('ShutterSpeedValue', ),- 0x9202: ('ApertureValue', ),- 0x9203: ('BrightnessValue', ),- 0x9204: ('ExposureBiasValue', ),- 0x9205: ('MaxApertureValue', ),- 0x9206: ('SubjectDistance', ),- 0x9207: ('MeteringMode', {- 0: 'Unidentified',- 1: 'Average',- 2: 'CenterWeightedAverage',- 3: 'Spot',- 4: 'MultiSpot',- 5: 'Pattern',- 6: 'Partial',- 255: 'other'- }),- 0x9208: ('LightSource', {- 0: 'Unknown',- 1: 'Daylight',- 2: 'Fluorescent',- 3: 'Tungsten (incandescent light)',- 4: 'Flash',- 9: 'Fine weather',- 10: 'Cloudy weather',- 11: 'Shade',- 12: 'Daylight fluorescent (D 5700 - 7100K)',- 13: 'Day white fluorescent (N 4600 - 5400K)',- 14: 'Cool white fluorescent (W 3900 - 4500K)',- 15: 'White fluorescent (WW 3200 - 3700K)',- 17: 'Standard light A',- 18: 'Standard light B',- 19: 'Standard light C',- 20: 'D55',- 21: 'D65',- 22: 'D75',- 23: 'D50',- 24: 'ISO studio tungsten',- 255: 'other light source'- }),- 0x9209: ('Flash', {- 0: 'Flash did not fire',- 1: 'Flash fired',- 5: 'Strobe return light not detected',- 7: 'Strobe return light detected',- 9: 'Flash fired, compulsory flash mode',- 13: 'Flash fired, compulsory flash mode, return light not detected',- 15: 'Flash fired, compulsory flash mode, return light detected',- 16: 'Flash did not fire, compulsory flash mode',- 24: 'Flash did not fire, auto mode',- 25: 'Flash fired, auto mode',- 29: 'Flash fired, auto mode, return light not detected',- 31: 'Flash fired, auto mode, return light detected',- 32: 'No flash function',- 65: 'Flash fired, red-eye reduction mode',- 69: 'Flash fired, red-eye reduction mode, return light not detected',- 71: 'Flash fired, red-eye reduction mode, return light detected',- 73: 'Flash fired, compulsory flash mode, red-eye reduction mode',- 77: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',- 79: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',- 89: 'Flash fired, auto mode, red-eye reduction mode',- 93: 'Flash fired, auto mode, return light not detected, red-eye reduction mode',- 95: 'Flash fired, auto mode, return light detected, red-eye reduction mode'- }),- 0x920A: ('FocalLength', ),- 0x9214: ('SubjectArea', ),- 0x927C: ('MakerNote', ),- 0x9286: ('UserComment', make_string_uc),- 0x9290: ('SubSecTime', ),- 0x9291: ('SubSecTimeOriginal', ),- 0x9292: ('SubSecTimeDigitized', ),-- # used by Windows Explorer- 0x9C9B: ('XPTitle', ),- 0x9C9C: ('XPComment', ),- 0x9C9D: ('XPAuthor', make_string), # (ignored by Windows Explorer if Artist exists)- 0x9C9E: ('XPKeywords', ),- 0x9C9F: ('XPSubject', ),- 0xA000: ('FlashPixVersion', make_string),- 0xA001: ('ColorSpace', {- 1: 'sRGB',- 2: 'Adobe RGB',- 65535: 'Uncalibrated'- }),- 0xA002: ('ExifImageWidth', ),- 0xA003: ('ExifImageLength', ),- 0xA004: ('RelatedSoundFile', ),- 0xA005: ('InteroperabilityOffset', INTEROP_INFO),- 0xA20B: ('FlashEnergy', ), # 0x920B in TIFF/EP- 0xA20C: ('SpatialFrequencyResponse', ), # 0x920C- 0xA20E: ('FocalPlaneXResolution', ), # 0x920E- 0xA20F: ('FocalPlaneYResolution', ), # 0x920F- 0xA210: ('FocalPlaneResolutionUnit', ), # 0x9210- 0xA214: ('SubjectLocation', ), # 0x9214- 0xA215: ('ExposureIndex', ), # 0x9215- 0xA217: ('SensingMethod', { # 0x9217- 1: 'Not defined',- 2: 'One-chip color area',- 3: 'Two-chip color area',- 4: 'Three-chip color area',- 5: 'Color sequential area',- 7: 'Trilinear',- 8: 'Color sequential linear'- }),- 0xA300: ('FileSource', {- 1: 'Film Scanner',- 2: 'Reflection Print Scanner',- 3: 'Digital Camera'- }),- 0xA301: ('SceneType', {- 1: 'Directly Photographed'- }),- 0xA302: ('CVAPattern', ),- 0xA401: ('CustomRendered', {- 0: 'Normal',- 1: 'Custom'- }),- 0xA402: ('ExposureMode', {- 0: 'Auto Exposure',- 1: 'Manual Exposure',- 2: 'Auto Bracket'- }),- 0xA403: ('WhiteBalance', {- 0: 'Auto',- 1: 'Manual'- }),- 0xA404: ('DigitalZoomRatio', ),- 0xA405: ('FocalLengthIn35mmFilm', ),- 0xA406: ('SceneCaptureType', {- 0: 'Standard',- 1: 'Landscape',- 2: 'Portrait',- 3: 'Night)'- }),- 0xA407: ('GainControl', {- 0: 'None',- 1: 'Low gain up',- 2: 'High gain up',- 3: 'Low gain down',- 4: 'High gain down'- }),- 0xA408: ('Contrast', {- 0: 'Normal',- 1: 'Soft',- 2: 'Hard'- }),- 0xA409: ('Saturation', {- 0: 'Normal',- 1: 'Soft',- 2: 'Hard'- }),- 0xA40A: ('Sharpness', {- 0: 'Normal',- 1: 'Soft',- 2: 'Hard'- }),- 0xA40B: ('DeviceSettingDescription', ),- 0xA40C: ('SubjectDistanceRange', ),- 0xA420: ('ImageUniqueID', ),- 0xA430: ('CameraOwnerName', ),- 0xA431: ('BodySerialNumber', ),- 0xA432: ('LensSpecification', ),- 0xA433: ('LensMake', ),- 0xA434: ('LensModel', ),- 0xA435: ('LensSerialNumber', ),- 0xA500: ('Gamma', ),- 0xC4A5: ('PrintIM', ),- 0xEA1C: ('Padding', ),- 0xEA1D: ('OffsetSchema', ),- 0xFDE8: ('OwnerName', ),- 0xFDE9: ('SerialNumber', ),-}diff --git a/ext/exifread/tags/makernote.py b/ext/exifread/tags/makernote.pydeleted file mode 100644index 71701476..00000000--- a/ext/exifread/tags/makernote.py+++ /dev/null@@ -1,684 +0,0 @@-"""-Makernote tag definitions.-"""--from exifread.utils import make_string, make_string_uc, Ratio-from . import makernote_canon as canon---def nikon_ev_bias(seq):- """- First digit seems to be in steps of 1/6 EV.- Does the third value mean the step size? It is usually 6,- but it is 12 for the ExposureDifference.- Check for an error condition that could cause a crash.- This only happens if something has gone really wrong in- reading the Nikon MakerNote.- http://tomtia.plala.jp/DigitalCamera/MakerNote/index.asp- """- if len(seq) < 4:- return ''- if seq == [252, 1, 6, 0]:- return '-2/3 EV'- if seq == [253, 1, 6, 0]:- return '-1/2 EV'- if seq == [254, 1, 6, 0]:- return '-1/3 EV'- if seq == [0, 1, 6, 0]:- return '0 EV'- if seq == [2, 1, 6, 0]:- return '+1/3 EV'- if seq == [3, 1, 6, 0]:- return '+1/2 EV'- if seq == [4, 1, 6, 0]:- return '+2/3 EV'- # Handle combinations not in the table.- a = seq[0]- # Causes headaches for the +/- logic, so special case it.- if a == 0:- return '0 EV'- if a > 127:- a = 256 - a- ret_str = '-'- else:- ret_str = '+'- step = seq[2] # Assume third value means the step size- whole = a / step- a = a % step- if whole != 0:- ret_str = '%s%s ' % (ret_str, str(whole))- if a == 0:- ret_str += 'EV'- else:- r = Ratio(a, step)- ret_str = ret_str + r.__repr__() + ' EV'- return ret_str--# Nikon E99x MakerNote Tags-NIKON_NEW = {- 0x0001: ('MakernoteVersion', make_string), # Sometimes binary- 0x0002: ('ISOSetting', make_string),- 0x0003: ('ColorMode', ),- 0x0004: ('Quality', ),- 0x0005: ('Whitebalance', ),- 0x0006: ('ImageSharpening', ),- 0x0007: ('FocusMode', ),- 0x0008: ('FlashSetting', ),- 0x0009: ('AutoFlashMode', ),- 0x000B: ('WhiteBalanceBias', ),- 0x000C: ('WhiteBalanceRBCoeff', ),- 0x000D: ('ProgramShift', nikon_ev_bias),- # Nearly the same as the other EV vals, but step size is 1/12 EV (?)- 0x000E: ('ExposureDifference', nikon_ev_bias),- 0x000F: ('ISOSelection', ),- 0x0010: ('DataDump', ),- 0x0011: ('NikonPreview', ),- 0x0012: ('FlashCompensation', nikon_ev_bias),- 0x0013: ('ISOSpeedRequested', ),- 0x0016: ('PhotoCornerCoordinates', ),- 0x0017: ('ExternalFlashExposureComp', nikon_ev_bias),- 0x0018: ('FlashBracketCompensationApplied', nikon_ev_bias),- 0x0019: ('AEBracketCompensationApplied', ),- 0x001A: ('ImageProcessing', ),- 0x001B: ('CropHiSpeed', ),- 0x001C: ('ExposureTuning', ),- 0x001D: ('SerialNumber', ), # Conflict with 0x00A0 ?- 0x001E: ('ColorSpace', ),- 0x001F: ('VRInfo', ),- 0x0020: ('ImageAuthentication', ),- 0x0022: ('ActiveDLighting', ),- 0x0023: ('PictureControl', ),- 0x0024: ('WorldTime', ),- 0x0025: ('ISOInfo', ),- 0x0080: ('ImageAdjustment', ),- 0x0081: ('ToneCompensation', ),- 0x0082: ('AuxiliaryLens', ),- 0x0083: ('LensType', ),- 0x0084: ('LensMinMaxFocalMaxAperture', ),- 0x0085: ('ManualFocusDistance', ),- 0x0086: ('DigitalZoomFactor', ),- 0x0087: ('FlashMode', {- 0x00: 'Did Not Fire',- 0x01: 'Fired, Manual',- 0x07: 'Fired, External',- 0x08: 'Fired, Commander Mode ',- 0x09: 'Fired, TTL Mode',- }),- 0x0088: ('AFFocusPosition', {- 0x0000: 'Center',- 0x0100: 'Top',- 0x0200: 'Bottom',- 0x0300: 'Left',- 0x0400: 'Right',- }),- 0x0089: ('BracketingMode', {- 0x00: 'Single frame, no bracketing',- 0x01: 'Continuous, no bracketing',- 0x02: 'Timer, no bracketing',- 0x10: 'Single frame, exposure bracketing',- 0x11: 'Continuous, exposure bracketing',- 0x12: 'Timer, exposure bracketing',- 0x40: 'Single frame, white balance bracketing',- 0x41: 'Continuous, white balance bracketing',- 0x42: 'Timer, white balance bracketing'- }),- 0x008A: ('AutoBracketRelease', ),- 0x008B: ('LensFStops', ),- 0x008C: ('NEFCurve1', ), # ExifTool calls this 'ContrastCurve'- 0x008D: ('ColorMode', ),- 0x008F: ('SceneMode', ),- 0x0090: ('LightingType', ),- 0x0091: ('ShotInfo', ), # First 4 bytes are a version number in ASCII- 0x0092: ('HueAdjustment', ),- # ExifTool calls this 'NEFCompression', should be 1-4- 0x0093: ('Compression', ),- 0x0094: ('Saturation', {- -3: 'B&W',- -2: '-2',- -1: '-1',- 0: '0',- 1: '1',- 2: '2',- }),- 0x0095: ('NoiseReduction', ),- 0x0096: ('NEFCurve2', ), # ExifTool calls this 'LinearizationTable'- 0x0097: ('ColorBalance', ), # First 4 bytes are a version number in ASCII- 0x0098: ('LensData', ), # First 4 bytes are a version number in ASCII- 0x0099: ('RawImageCenter', ),- 0x009A: ('SensorPixelSize', ),- 0x009C: ('Scene Assist', ),- 0x009E: ('RetouchHistory', ),- 0x00A0: ('SerialNumber', ),- 0x00A2: ('ImageDataSize', ),- # 00A3: unknown - a single byte 0- # 00A4: In NEF, looks like a 4 byte ASCII version number ('0200')- 0x00A5: ('ImageCount', ),- 0x00A6: ('DeletedImageCount', ),- 0x00A7: ('TotalShutterReleases', ),- # First 4 bytes are a version number in ASCII, with version specific- # info to follow. Its hard to treat it as a string due to embedded nulls.- 0x00A8: ('FlashInfo', ),- 0x00A9: ('ImageOptimization', ),- 0x00AA: ('Saturation', ),- 0x00AB: ('DigitalVariProgram', ),- 0x00AC: ('ImageStabilization', ),- 0x00AD: ('AFResponse', ),- 0x00B0: ('MultiExposure', ),- 0x00B1: ('HighISONoiseReduction', ),- 0x00B6: ('PowerUpTime', ),- 0x00B7: ('AFInfo2', ),- 0x00B8: ('FileInfo', ),- 0x00B9: ('AFTune', ),- 0x0100: ('DigitalICE', ),- 0x0103: ('PreviewCompression', {- 1: 'Uncompressed',- 2: 'CCITT 1D',- 3: 'T4/Group 3 Fax',- 4: 'T6/Group 4 Fax',- 5: 'LZW',- 6: 'JPEG (old-style)',- 7: 'JPEG',- 8: 'Adobe Deflate',- 9: 'JBIG B&W',- 10: 'JBIG Color',- 32766: 'Next',- 32769: 'Epson ERF Compressed',- 32771: 'CCIRLEW',- 32773: 'PackBits',- 32809: 'Thunderscan',- 32895: 'IT8CTPAD',- 32896: 'IT8LW',- 32897: 'IT8MP',- 32898: 'IT8BL',- 32908: 'PixarFilm',- 32909: 'PixarLog',- 32946: 'Deflate',- 32947: 'DCS',- 34661: 'JBIG',- 34676: 'SGILog',- 34677: 'SGILog24',- 34712: 'JPEG 2000',- 34713: 'Nikon NEF Compressed',- 65000: 'Kodak DCR Compressed',- 65535: 'Pentax PEF Compressed',- }),- 0x0201: ('PreviewImageStart', ),- 0x0202: ('PreviewImageLength', ),- 0x0213: ('PreviewYCbCrPositioning', {- 1: 'Centered',- 2: 'Co-sited',- }),- 0x0E09: ('NikonCaptureVersion', ),- 0x0E0E: ('NikonCaptureOffsets', ),- 0x0E10: ('NikonScan', ),- 0x0E22: ('NEFBitDepth', ),-}--NIKON_OLD = {- 0x0003: ('Quality', {- 1: 'VGA Basic',- 2: 'VGA Normal',- 3: 'VGA Fine',- 4: 'SXGA Basic',- 5: 'SXGA Normal',- 6: 'SXGA Fine',- }),- 0x0004: ('ColorMode', {- 1: 'Color',- 2: 'Monochrome',- }),- 0x0005: ('ImageAdjustment', {- 0: 'Normal',- 1: 'Bright+',- 2: 'Bright-',- 3: 'Contrast+',- 4: 'Contrast-',- }),- 0x0006: ('CCDSpeed', {- 0: 'ISO 80',- 2: 'ISO 160',- 4: 'ISO 320',- 5: 'ISO 100',- }),- 0x0007: ('WhiteBalance', {- 0: 'Auto',- 1: 'Preset',- 2: 'Daylight',- 3: 'Incandescent',- 4: 'Fluorescent',- 5: 'Cloudy',- 6: 'Speed Light',- }),-}---def olympus_special_mode(v):- """decode Olympus SpecialMode tag in MakerNote"""- mode1 = {- 0: 'Normal',- 1: 'Unknown',- 2: 'Fast',- 3: 'Panorama',- }- mode2 = {- 0: 'Non-panoramic',- 1: 'Left to right',- 2: 'Right to left',- 3: 'Bottom to top',- 4: 'Top to bottom',- }- if v[0] not in mode1 or v[2] not in mode2:- return v- return '%s - sequence %d - %s' % (mode1[v[0]], v[1], mode2[v[2]])---OLYMPUS = {- # ah HAH! those sneeeeeaky bastids! this is how they get past the fact- # that a JPEG thumbnail is not allowed in an uncompressed TIFF file- 0x0100: ('JPEGThumbnail', ),- 0x0200: ('SpecialMode', olympus_special_mode),- 0x0201: ('JPEGQual', {- 1: 'SQ',- 2: 'HQ',- 3: 'SHQ',- }),- 0x0202: ('Macro', {- 0: 'Normal',- 1: 'Macro',- 2: 'SuperMacro'- }),- 0x0203: ('BWMode', {- 0: 'Off',- 1: 'On'- }),- 0x0204: ('DigitalZoom', ),- 0x0205: ('FocalPlaneDiagonal', ),- 0x0206: ('LensDistortionParams', ),- 0x0207: ('SoftwareRelease', ),- 0x0208: ('PictureInfo', ),- 0x0209: ('CameraID', make_string), # print as string- 0x0F00: ('DataDump', ),- 0x0300: ('PreCaptureFrames', ),- 0x0404: ('SerialNumber', ),- 0x1000: ('ShutterSpeedValue', ),- 0x1001: ('ISOValue', ),- 0x1002: ('ApertureValue', ),- 0x1003: ('BrightnessValue', ),- 0x1004: ('FlashMode', {- 2: 'On',- 3: 'Off'- }),- 0x1005: ('FlashDevice', {- 0: 'None',- 1: 'Internal',- 4: 'External',- 5: 'Internal + External'- }),- 0x1006: ('ExposureCompensation', ),- 0x1007: ('SensorTemperature', ),- 0x1008: ('LensTemperature', ),- 0x100b: ('FocusMode', {- 0: 'Auto',- 1: 'Manual'- }),- 0x1017: ('RedBalance', ),- 0x1018: ('BlueBalance', ),- 0x101a: ('SerialNumber', ),- 0x1023: ('FlashExposureComp', ),- 0x1026: ('ExternalFlashBounce', {- 0: 'No',- 1: 'Yes'- }),- 0x1027: ('ExternalFlashZoom', ),- 0x1028: ('ExternalFlashMode', ),- 0x1029: ('Contrast int16u', {- 0: 'High',- 1: 'Normal',- 2: 'Low'- }),- 0x102a: ('SharpnessFactor', ),- 0x102b: ('ColorControl', ),- 0x102c: ('ValidBits', ),- 0x102d: ('CoringFilter', ),- 0x102e: ('OlympusImageWidth', ),- 0x102f: ('OlympusImageHeight', ),- 0x1034: ('CompressionRatio', ),- 0x1035: ('PreviewImageValid', {- 0: 'No',- 1: 'Yes'- }),- 0x1036: ('PreviewImageStart', ),- 0x1037: ('PreviewImageLength', ),- 0x1039: ('CCDScanMode', {- 0: 'Interlaced',- 1: 'Progressive'- }),- 0x103a: ('NoiseReduction', {- 0: 'Off',- 1: 'On'- }),- 0x103b: ('InfinityLensStep', ),- 0x103c: ('NearLensStep', ),-- # TODO - these need extra definitions- # http://search.cpan.org/src/EXIFTOOL/Image-ExifTool-6.90/html/TagNames/Olympus.html- 0x2010: ('Equipment', ),- 0x2020: ('CameraSettings', ),- 0x2030: ('RawDevelopment', ),- 0x2040: ('ImageProcessing', ),- 0x2050: ('FocusInfo', ),- 0x3000: ('RawInfo ', ),-}--# 0x2020 CameraSettings-OLYMPUS_TAG_0x2020 = {- 0x0100: ('PreviewImageValid', {- 0: 'No',- 1: 'Yes'- }),- 0x0101: ('PreviewImageStart', ),- 0x0102: ('PreviewImageLength', ),- 0x0200: ('ExposureMode', {- 1: 'Manual',- 2: 'Program',- 3: 'Aperture-priority AE',- 4: 'Shutter speed priority AE',- 5: 'Program-shift'- }),- 0x0201: ('AELock', {- 0: 'Off',- 1: 'On'- }),- 0x0202: ('MeteringMode', {- 2: 'Center Weighted',- 3: 'Spot',- 5: 'ESP',- 261: 'Pattern+AF',- 515: 'Spot+Highlight control',- 1027: 'Spot+Shadow control'- }),- 0x0300: ('MacroMode', {- 0: 'Off',- 1: 'On'- }),- 0x0301: ('FocusMode', {- 0: 'Single AF',- 1: 'Sequential shooting AF',- 2: 'Continuous AF',- 3: 'Multi AF',- 10: 'MF'- }),- 0x0302: ('FocusProcess', {- 0: 'AF Not Used',- 1: 'AF Used'- }),- 0x0303: ('AFSearch', {- 0: 'Not Ready',- 1: 'Ready'- }),- 0x0304: ('AFAreas', ),- 0x0401: ('FlashExposureCompensation', ),- 0x0500: ('WhiteBalance2', {- 0: 'Auto',- 16: '7500K (Fine Weather with Shade)',- 17: '6000K (Cloudy)',- 18: '5300K (Fine Weather)',- 20: '3000K (Tungsten light)',- 21: '3600K (Tungsten light-like)',- 33: '6600K (Daylight fluorescent)',- 34: '4500K (Neutral white fluorescent)',- 35: '4000K (Cool white fluorescent)',- 48: '3600K (Tungsten light-like)',- 256: 'Custom WB 1',- 257: 'Custom WB 2',- 258: 'Custom WB 3',- 259: 'Custom WB 4',- 512: 'Custom WB 5400K',- 513: 'Custom WB 2900K',- 514: 'Custom WB 8000K',- }),- 0x0501: ('WhiteBalanceTemperature', ),- 0x0502: ('WhiteBalanceBracket', ),- 0x0503: ('CustomSaturation', ), # (3 numbers: 1. CS Value, 2. Min, 3. Max)- 0x0504: ('ModifiedSaturation', {- 0: 'Off',- 1: 'CM1 (Red Enhance)',- 2: 'CM2 (Green Enhance)',- 3: 'CM3 (Blue Enhance)',- 4: 'CM4 (Skin Tones)',- }),- 0x0505: ('ContrastSetting', ), # (3 numbers: 1. Contrast, 2. Min, 3. Max)- 0x0506: ('SharpnessSetting', ), # (3 numbers: 1. Sharpness, 2. Min, 3. Max)- 0x0507: ('ColorSpace', {- 0: 'sRGB',- 1: 'Adobe RGB',- 2: 'Pro Photo RGB'- }),- 0x0509: ('SceneMode', {- 0: 'Standard',- 6: 'Auto',- 7: 'Sport',- 8: 'Portrait',- 9: 'Landscape+Portrait',- 10: 'Landscape',- 11: 'Night scene',- 13: 'Panorama',- 16: 'Landscape+Portrait',- 17: 'Night+Portrait',- 19: 'Fireworks',- 20: 'Sunset',- 22: 'Macro',- 25: 'Documents',- 26: 'Museum',- 28: 'Beach&Snow',- 30: 'Candle',- 35: 'Underwater Wide1',- 36: 'Underwater Macro',- 39: 'High Key',- 40: 'Digital Image Stabilization',- 44: 'Underwater Wide2',- 45: 'Low Key',- 46: 'Children',- 48: 'Nature Macro',- }),- 0x050a: ('NoiseReduction', {- 0: 'Off',- 1: 'Noise Reduction',- 2: 'Noise Filter',- 3: 'Noise Reduction + Noise Filter',- 4: 'Noise Filter (ISO Boost)',- 5: 'Noise Reduction + Noise Filter (ISO Boost)'- }),- 0x050b: ('DistortionCorrection', {- 0: 'Off',- 1: 'On'- }),- 0x050c: ('ShadingCompensation', {- 0: 'Off',- 1: 'On'- }),- 0x050d: ('CompressionFactor', ),- 0x050f: ('Gradation', {- '-1 -1 1': 'Low Key',- '0 -1 1': 'Normal',- '1 -1 1': 'High Key'- }),- 0x0520: ('PictureMode', {- 1: 'Vivid',- 2: 'Natural',- 3: 'Muted',- 256: 'Monotone',- 512: 'Sepia'- }),- 0x0521: ('PictureModeSaturation', ),- 0x0522: ('PictureModeHue?', ),- 0x0523: ('PictureModeContrast', ),- 0x0524: ('PictureModeSharpness', ),- 0x0525: ('PictureModeBWFilter', {- 0: 'n/a',- 1: 'Neutral',- 2: 'Yellow',- 3: 'Orange',- 4: 'Red',- 5: 'Green'- }),- 0x0526: ('PictureModeTone', {- 0: 'n/a',- 1: 'Neutral',- 2: 'Sepia',- 3: 'Blue',- 4: 'Purple',- 5: 'Green'- }),- 0x0600: ('Sequence', ), # 2 or 3 numbers: 1. Mode, 2. Shot number, 3. Mode bits- 0x0601: ('PanoramaMode', ), # (2 numbers: 1. Mode, 2. Shot number)- 0x0603: ('ImageQuality2', {- 1: 'SQ',- 2: 'HQ',- 3: 'SHQ',- 4: 'RAW',- }),- 0x0901: ('ManometerReading', ),-}--CASIO = {- 0x0001: ('RecordingMode', {- 1: 'Single Shutter',- 2: 'Panorama',- 3: 'Night Scene',- 4: 'Portrait',- 5: 'Landscape',- }),- 0x0002: ('Quality', {- 1: 'Economy',- 2: 'Normal',- 3: 'Fine'- }),- 0x0003: ('FocusingMode', {- 2: 'Macro',- 3: 'Auto Focus',- 4: 'Manual Focus',- 5: 'Infinity'- }),- 0x0004: ('FlashMode', {- 1: 'Auto',- 2: 'On',- 3: 'Off',- 4: 'Red Eye Reduction',- }),- 0x0005: ('FlashIntensity', {- 11: 'Weak',- 13: 'Normal',- 15: 'Strong'- }),- 0x0006: ('Object Distance', ),- 0x0007: ('WhiteBalance', {- 1: 'Auto',- 2: 'Tungsten',- 3: 'Daylight',- 4: 'Fluorescent',- 5: 'Shade',- 129: 'Manual'- }),- 0x000B: ('Sharpness', {- 0: 'Normal',- 1: 'Soft',- 2: 'Hard',- }),- 0x000C: ('Contrast', {- 0: 'Normal',- 1: 'Low',- 2: 'High',- }),- 0x000D: ('Saturation', {- 0: 'Normal',- 1: 'Low',- 2: 'High',- }),- 0x0014: ('CCDSpeed', {- 64: 'Normal',- 80: 'Normal',- 100: 'High',- 125: '+1.0',- 244: '+3.0',- 250: '+2.0'- }),-}--FUJIFILM = {- 0x0000: ('NoteVersion', make_string),- 0x1000: ('Quality', ),- 0x1001: ('Sharpness', {- 1: 'Soft',- 2: 'Soft',- 3: 'Normal',- 4: 'Hard',- 5: 'Hard'- }),- 0x1002: ('WhiteBalance', {- 0: 'Auto',- 256: 'Daylight',- 512: 'Cloudy',- 768: 'DaylightColor-Fluorescent',- 769: 'DaywhiteColor-Fluorescent',- 770: 'White-Fluorescent',- 1024: 'Incandescent',- 3840: 'Custom'- }),- 0x1003: ('Color', {- 0: 'Normal',- 256: 'High',- 512: 'Low'- }),- 0x1004: ('Tone', {- 0: 'Normal',- 256: 'High',- 512: 'Low'- }),- 0x1010: ('FlashMode', {- 0: 'Auto',- 1: 'On',- 2: 'Off',- 3: 'Red Eye Reduction'- }),- 0x1011: ('FlashStrength', ),- 0x1020: ('Macro', {- 0: 'Off',- 1: 'On'- }),- 0x1021: ('FocusMode', {- 0: 'Auto',- 1: 'Manual'- }),- 0x1030: ('SlowSync', {- 0: 'Off',- 1: 'On'- }),- 0x1031: ('PictureMode', {- 0: 'Auto',- 1: 'Portrait',- 2: 'Landscape',- 4: 'Sports',- 5: 'Night',- 6: 'Program AE',- 256: 'Aperture Priority AE',- 512: 'Shutter Priority AE',- 768: 'Manual Exposure'- }),- 0x1100: ('MotorOrBracket', {- 0: 'Off',- 1: 'On'- }),- 0x1300: ('BlurWarning', {- 0: 'Off',- 1: 'On'- }),- 0x1301: ('FocusWarning', {- 0: 'Off',- 1: 'On'- }),- 0x1302: ('AEWarning', {- 0: 'Off',- 1: 'On'- }),-}diff --git a/ext/exifread/tags/makernote_canon.py b/ext/exifread/tags/makernote_canon.pydeleted file mode 100644index 7b465357..00000000--- a/ext/exifread/tags/makernote_canon.py+++ /dev/null@@ -1,698 +0,0 @@-"""-Makernote (proprietary) tag definitions for Canon.--http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Canon.html-"""--TAGS = {- 0x0003: ('FlashInfo',),- 0x0006: ('ImageType', ),- 0x0007: ('FirmwareVersion', ),- 0x0008: ('ImageNumber', ),- 0x0009: ('OwnerName', ),- 0x000C: ('SerialNumber', ),- 0x000E: ('FileLength', ),- 0x0010: ('ModelID', {- 0x1010000: 'PowerShot A30',- 0x1040000: 'PowerShot S300 / Digital IXUS 300 / IXY Digital 300',- 0x1060000: 'PowerShot A20',- 0x1080000: 'PowerShot A10',- 0x1090000: 'PowerShot S110 / Digital IXUS v / IXY Digital 200',- 0x1100000: 'PowerShot G2',- 0x1110000: 'PowerShot S40',- 0x1120000: 'PowerShot S30',- 0x1130000: 'PowerShot A40',- 0x1140000: 'EOS D30',- 0x1150000: 'PowerShot A100',- 0x1160000: 'PowerShot S200 / Digital IXUS v2 / IXY Digital 200a',- 0x1170000: 'PowerShot A200',- 0x1180000: 'PowerShot S330 / Digital IXUS 330 / IXY Digital 300a',- 0x1190000: 'PowerShot G3',- 0x1210000: 'PowerShot S45',- 0x1230000: 'PowerShot SD100 / Digital IXUS II / IXY Digital 30',- 0x1240000: 'PowerShot S230 / Digital IXUS v3 / IXY Digital 320',- 0x1250000: 'PowerShot A70',- 0x1260000: 'PowerShot A60',- 0x1270000: 'PowerShot S400 / Digital IXUS 400 / IXY Digital 400',- 0x1290000: 'PowerShot G5',- 0x1300000: 'PowerShot A300',- 0x1310000: 'PowerShot S50',- 0x1340000: 'PowerShot A80',- 0x1350000: 'PowerShot SD10 / Digital IXUS i / IXY Digital L',- 0x1360000: 'PowerShot S1 IS',- 0x1370000: 'PowerShot Pro1',- 0x1380000: 'PowerShot S70',- 0x1390000: 'PowerShot S60',- 0x1400000: 'PowerShot G6',- 0x1410000: 'PowerShot S500 / Digital IXUS 500 / IXY Digital 500',- 0x1420000: 'PowerShot A75',- 0x1440000: 'PowerShot SD110 / Digital IXUS IIs / IXY Digital 30a',- 0x1450000: 'PowerShot A400',- 0x1470000: 'PowerShot A310',- 0x1490000: 'PowerShot A85',- 0x1520000: 'PowerShot S410 / Digital IXUS 430 / IXY Digital 450',- 0x1530000: 'PowerShot A95',- 0x1540000: 'PowerShot SD300 / Digital IXUS 40 / IXY Digital 50',- 0x1550000: 'PowerShot SD200 / Digital IXUS 30 / IXY Digital 40',- 0x1560000: 'PowerShot A520',- 0x1570000: 'PowerShot A510',- 0x1590000: 'PowerShot SD20 / Digital IXUS i5 / IXY Digital L2',- 0x1640000: 'PowerShot S2 IS',- 0x1650000: 'PowerShot SD430 / Digital IXUS Wireless / IXY Digital Wireless',- 0x1660000: 'PowerShot SD500 / Digital IXUS 700 / IXY Digital 600',- 0x1668000: 'EOS D60',- 0x1700000: 'PowerShot SD30 / Digital IXUS i Zoom / IXY Digital L3',- 0x1740000: 'PowerShot A430',- 0x1750000: 'PowerShot A410',- 0x1760000: 'PowerShot S80',- 0x1780000: 'PowerShot A620',- 0x1790000: 'PowerShot A610',- 0x1800000: 'PowerShot SD630 / Digital IXUS 65 / IXY Digital 80',- 0x1810000: 'PowerShot SD450 / Digital IXUS 55 / IXY Digital 60',- 0x1820000: 'PowerShot TX1',- 0x1870000: 'PowerShot SD400 / Digital IXUS 50 / IXY Digital 55',- 0x1880000: 'PowerShot A420',- 0x1890000: 'PowerShot SD900 / Digital IXUS 900 Ti / IXY Digital 1000',- 0x1900000: 'PowerShot SD550 / Digital IXUS 750 / IXY Digital 700',- 0x1920000: 'PowerShot A700',- 0x1940000: 'PowerShot SD700 IS / Digital IXUS 800 IS / IXY Digital 800 IS',- 0x1950000: 'PowerShot S3 IS',- 0x1960000: 'PowerShot A540',- 0x1970000: 'PowerShot SD600 / Digital IXUS 60 / IXY Digital 70',- 0x1980000: 'PowerShot G7',- 0x1990000: 'PowerShot A530',- 0x2000000: 'PowerShot SD800 IS / Digital IXUS 850 IS / IXY Digital 900 IS',- 0x2010000: 'PowerShot SD40 / Digital IXUS i7 / IXY Digital L4',- 0x2020000: 'PowerShot A710 IS',- 0x2030000: 'PowerShot A640',- 0x2040000: 'PowerShot A630',- 0x2090000: 'PowerShot S5 IS',- 0x2100000: 'PowerShot A460',- 0x2120000: 'PowerShot SD850 IS / Digital IXUS 950 IS / IXY Digital 810 IS',- 0x2130000: 'PowerShot A570 IS',- 0x2140000: 'PowerShot A560',- 0x2150000: 'PowerShot SD750 / Digital IXUS 75 / IXY Digital 90',- 0x2160000: 'PowerShot SD1000 / Digital IXUS 70 / IXY Digital 10',- 0x2180000: 'PowerShot A550',- 0x2190000: 'PowerShot A450',- 0x2230000: 'PowerShot G9',- 0x2240000: 'PowerShot A650 IS',- 0x2260000: 'PowerShot A720 IS',- 0x2290000: 'PowerShot SX100 IS',- 0x2300000: 'PowerShot SD950 IS / Digital IXUS 960 IS / IXY Digital 2000 IS',- 0x2310000: 'PowerShot SD870 IS / Digital IXUS 860 IS / IXY Digital 910 IS',- 0x2320000: 'PowerShot SD890 IS / Digital IXUS 970 IS / IXY Digital 820 IS',- 0x2360000: 'PowerShot SD790 IS / Digital IXUS 90 IS / IXY Digital 95 IS',- 0x2370000: 'PowerShot SD770 IS / Digital IXUS 85 IS / IXY Digital 25 IS',- 0x2380000: 'PowerShot A590 IS',- 0x2390000: 'PowerShot A580',- 0x2420000: 'PowerShot A470',- 0x2430000: 'PowerShot SD1100 IS / Digital IXUS 80 IS / IXY Digital 20 IS',- 0x2460000: 'PowerShot SX1 IS',- 0x2470000: 'PowerShot SX10 IS',- 0x2480000: 'PowerShot A1000 IS',- 0x2490000: 'PowerShot G10',- 0x2510000: 'PowerShot A2000 IS',- 0x2520000: 'PowerShot SX110 IS',- 0x2530000: 'PowerShot SD990 IS / Digital IXUS 980 IS / IXY Digital 3000 IS',- 0x2540000: 'PowerShot SD880 IS / Digital IXUS 870 IS / IXY Digital 920 IS',- 0x2550000: 'PowerShot E1',- 0x2560000: 'PowerShot D10',- 0x2570000: 'PowerShot SD960 IS / Digital IXUS 110 IS / IXY Digital 510 IS',- 0x2580000: 'PowerShot A2100 IS',- 0x2590000: 'PowerShot A480',- 0x2600000: 'PowerShot SX200 IS',- 0x2610000: 'PowerShot SD970 IS / Digital IXUS 990 IS / IXY Digital 830 IS',- 0x2620000: 'PowerShot SD780 IS / Digital IXUS 100 IS / IXY Digital 210 IS',- 0x2630000: 'PowerShot A1100 IS',- 0x2640000: 'PowerShot SD1200 IS / Digital IXUS 95 IS / IXY Digital 110 IS',- 0x2700000: 'PowerShot G11',- 0x2710000: 'PowerShot SX120 IS',- 0x2720000: 'PowerShot S90',- 0x2750000: 'PowerShot SX20 IS',- 0x2760000: 'PowerShot SD980 IS / Digital IXUS 200 IS / IXY Digital 930 IS',- 0x2770000: 'PowerShot SD940 IS / Digital IXUS 120 IS / IXY Digital 220 IS',- 0x2800000: 'PowerShot A495',- 0x2810000: 'PowerShot A490',- 0x2820000: 'PowerShot A3100 IS / A3150 IS',- 0x2830000: 'PowerShot A3000 IS',- 0x2840000: 'PowerShot SD1400 IS / IXUS 130 / IXY 400F',- 0x2850000: 'PowerShot SD1300 IS / IXUS 105 / IXY 200F',- 0x2860000: 'PowerShot SD3500 IS / IXUS 210 / IXY 10S',- 0x2870000: 'PowerShot SX210 IS',- 0x2880000: 'PowerShot SD4000 IS / IXUS 300 HS / IXY 30S',- 0x2890000: 'PowerShot SD4500 IS / IXUS 1000 HS / IXY 50S',- 0x2920000: 'PowerShot G12',- 0x2930000: 'PowerShot SX30 IS',- 0x2940000: 'PowerShot SX130 IS',- 0x2950000: 'PowerShot S95',- 0x2980000: 'PowerShot A3300 IS',- 0x2990000: 'PowerShot A3200 IS',- 0x3000000: 'PowerShot ELPH 500 HS / IXUS 310 HS / IXY 31S',- 0x3010000: 'PowerShot Pro90 IS',- 0x3010001: 'PowerShot A800',- 0x3020000: 'PowerShot ELPH 100 HS / IXUS 115 HS / IXY 210F',- 0x3030000: 'PowerShot SX230 HS',- 0x3040000: 'PowerShot ELPH 300 HS / IXUS 220 HS / IXY 410F',- 0x3050000: 'PowerShot A2200',- 0x3060000: 'PowerShot A1200',- 0x3070000: 'PowerShot SX220 HS',- 0x3080000: 'PowerShot G1 X',- 0x3090000: 'PowerShot SX150 IS',- 0x3100000: 'PowerShot ELPH 510 HS / IXUS 1100 HS / IXY 51S',- 0x3110000: 'PowerShot S100 (new)',- 0x3120000: 'PowerShot ELPH 310 HS / IXUS 230 HS / IXY 600F',- 0x3130000: 'PowerShot SX40 HS',- 0x3140000: 'IXY 32S',- 0x3160000: 'PowerShot A1300',- 0x3170000: 'PowerShot A810',- 0x3180000: 'PowerShot ELPH 320 HS / IXUS 240 HS / IXY 420F',- 0x3190000: 'PowerShot ELPH 110 HS / IXUS 125 HS / IXY 220F',- 0x3200000: 'PowerShot D20',- 0x3210000: 'PowerShot A4000 IS',- 0x3220000: 'PowerShot SX260 HS',- 0x3230000: 'PowerShot SX240 HS',- 0x3240000: 'PowerShot ELPH 530 HS / IXUS 510 HS / IXY 1',- 0x3250000: 'PowerShot ELPH 520 HS / IXUS 500 HS / IXY 3',- 0x3260000: 'PowerShot A3400 IS',- 0x3270000: 'PowerShot A2400 IS',- 0x3280000: 'PowerShot A2300',- 0x3330000: 'PowerShot G15',- 0x3340000: 'PowerShot SX50',- 0x3350000: 'PowerShot SX160 IS',- 0x3360000: 'PowerShot S110 (new)',- 0x3370000: 'PowerShot SX500 IS',- 0x3380000: 'PowerShot N',- 0x3390000: 'IXUS 245 HS / IXY 430F',- 0x3400000: 'PowerShot SX280 HS',- 0x3410000: 'PowerShot SX270 HS',- 0x3420000: 'PowerShot A3500 IS',- 0x3430000: 'PowerShot A2600',- 0x3450000: 'PowerShot A1400',- 0x3460000: 'PowerShot ELPH 130 IS / IXUS 140 / IXY 110F',- 0x3470000: 'PowerShot ELPH 115/120 IS / IXUS 132/135 / IXY 90F/100F',- 0x3490000: 'PowerShot ELPH 330 HS / IXUS 255 HS / IXY 610F',- 0x3510000: 'PowerShot A2500',- 0x3540000: 'PowerShot G16',- 0x3550000: 'PowerShot S120',- 0x3560000: 'PowerShot SX170 IS',- 0x3580000: 'PowerShot SX510 HS',- 0x3590000: 'PowerShot S200 (new)',- 0x3600000: 'IXY 620F',- 0x3610000: 'PowerShot N100',- 0x3640000: 'PowerShot G1 X Mark II',- 0x3650000: 'PowerShot D30',- 0x3660000: 'PowerShot SX700 HS',- 0x3670000: 'PowerShot SX600 HS',- 0x3680000: 'PowerShot ELPH 140 IS / IXUS 150',- 0x3690000: 'PowerShot ELPH 135 / IXUS 145 / IXY 120',- 0x3700000: 'PowerShot ELPH 340 HS / IXUS 265 HS / IXY 630',- 0x3710000: 'PowerShot ELPH 150 IS / IXUS 155 / IXY 140',- 0x3750000: 'PowerShot SX60 HS',- 0x3760000: 'PowerShot SX520 HS',- 0x3780000: 'PowerShot G7 X',- 0x4040000: 'PowerShot G1',- 0x6040000: 'PowerShot S100 / Digital IXUS / IXY Digital',- 0x4007d673: 'DC19/DC21/DC22',- 0x4007d674: 'XH A1',- 0x4007d675: 'HV10',- 0x4007d676: 'MD130/MD140/MD150/MD160/ZR850',- 0x4007d777: 'DC50',- 0x4007d778: 'HV20',- 0x4007d779: 'DC211',- 0x4007d77a: 'HG10',- 0x4007d77b: 'HR10',- 0x4007d77d: 'MD255/ZR950',- 0x4007d81c: 'HF11',- 0x4007d878: 'HV30',- 0x4007d87c: 'XH A1S',- 0x4007d87e: 'DC301/DC310/DC311/DC320/DC330',- 0x4007d87f: 'FS100',- 0x4007d880: 'HF10',- 0x4007d882: 'HG20/HG21',- 0x4007d925: 'HF21',- 0x4007d926: 'HF S11',- 0x4007d978: 'HV40',- 0x4007d987: 'DC410/DC411/DC420',- 0x4007d988: 'FS19/FS20/FS21/FS22/FS200',- 0x4007d989: 'HF20/HF200',- 0x4007d98a: 'HF S10/S100',- 0x4007da8e: 'HF R10/R16/R17/R18/R100/R106',- 0x4007da8f: 'HF M30/M31/M36/M300/M306',- 0x4007da90: 'HF S20/S21/S200',- 0x4007da92: 'FS31/FS36/FS37/FS300/FS305/FS306/FS307',- 0x4007dda9: 'HF G25',- 0x80000001: 'EOS-1D',- 0x80000167: 'EOS-1DS',- 0x80000168: 'EOS 10D',- 0x80000169: 'EOS-1D Mark III',- 0x80000170: 'EOS Digital Rebel / 300D / Kiss Digital',- 0x80000174: 'EOS-1D Mark II',- 0x80000175: 'EOS 20D',- 0x80000176: 'EOS Digital Rebel XSi / 450D / Kiss X2',- 0x80000188: 'EOS-1Ds Mark II',- 0x80000189: 'EOS Digital Rebel XT / 350D / Kiss Digital N',- 0x80000190: 'EOS 40D',- 0x80000213: 'EOS 5D',- 0x80000215: 'EOS-1Ds Mark III',- 0x80000218: 'EOS 5D Mark II',- 0x80000219: 'WFT-E1',- 0x80000232: 'EOS-1D Mark II N',- 0x80000234: 'EOS 30D',- 0x80000236: 'EOS Digital Rebel XTi / 400D / Kiss Digital X',- 0x80000241: 'WFT-E2',- 0x80000246: 'WFT-E3',- 0x80000250: 'EOS 7D',- 0x80000252: 'EOS Rebel T1i / 500D / Kiss X3',- 0x80000254: 'EOS Rebel XS / 1000D / Kiss F',- 0x80000261: 'EOS 50D',- 0x80000269: 'EOS-1D X',- 0x80000270: 'EOS Rebel T2i / 550D / Kiss X4',- 0x80000271: 'WFT-E4',- 0x80000273: 'WFT-E5',- 0x80000281: 'EOS-1D Mark IV',- 0x80000285: 'EOS 5D Mark III',- 0x80000286: 'EOS Rebel T3i / 600D / Kiss X5',- 0x80000287: 'EOS 60D',- 0x80000288: 'EOS Rebel T3 / 1100D / Kiss X50',- 0x80000289: 'EOS 7D Mark II',- 0x80000297: 'WFT-E2 II',- 0x80000298: 'WFT-E4 II',- 0x80000301: 'EOS Rebel T4i / 650D / Kiss X6i',- 0x80000302: 'EOS 6D',- 0x80000324: 'EOS-1D C',- 0x80000325: 'EOS 70D',- 0x80000326: 'EOS Rebel T5i / 700D / Kiss X7i',- 0x80000327: 'EOS Rebel T5 / 1200D / Kiss X70',- 0x80000331: 'EOS M',- 0x80000346: 'EOS Rebel SL1 / 100D / Kiss X7',- 0x80000355: 'EOS M2'- }),- 0x0013: ('ThumbnailImageValidArea', ),- 0x0015: ('SerialNumberFormat', {- 0x90000000: 'Format 1',- 0xA0000000: 'Format 2'- }),- 0x001A: ('SuperMacro', {- 0: 'Off',- 1: 'On (1)',- 2: 'On (2)'- }),- 0x001C: ('DateStampMode', {- 0: 'Off',- 1: 'Date',- 2: 'Date & Time',- }),- 0x001E: ('FirmwareRevision', ),- 0x0028: ('ImageUniqueID', ),- 0x0095: ('LensModel', ),- 0x0096: ('InternalSerialNumber ', ),- 0x0097: ('DustRemovalData ', ),- 0x0098: ('CropInfo ', ),- 0x009A: ('AspectInfo', ),- 0x00b4: ('ColorSpace', {- 1: 'sRGB',- 2: 'Adobe RGB'- }),-}--# this is in element offset, name, optional value dictionary format-# 0x0001-CAMERA_SETTINGS = {- 1: ('Macromode', {- 1: 'Macro',- 2: 'Normal'- }),- 2: ('SelfTimer', ),- 3: ('Quality', {- 1: 'Economy',- 2: 'Normal',- 3: 'Fine',- 5: 'Superfine'- }),- 4: ('FlashMode', {- 0: 'Flash Not Fired',- 1: 'Auto',- 2: 'On',- 3: 'Red-Eye Reduction',- 4: 'Slow Synchro',- 5: 'Auto + Red-Eye Reduction',- 6: 'On + Red-Eye Reduction',- 16: 'external flash'- }),- 5: ('ContinuousDriveMode', {- 0: 'Single Or Timer',- 1: 'Continuous',- 2: 'Movie',- }),- 7: ('FocusMode', {- 0: 'One-Shot',- 1: 'AI Servo',- 2: 'AI Focus',- 3: 'MF',- 4: 'Single',- 5: 'Continuous',- 6: 'MF'- }),- 9: ('RecordMode', {- 1: 'JPEG',- 2: 'CRW+THM',- 3: 'AVI+THM',- 4: 'TIF',- 5: 'TIF+JPEG',- 6: 'CR2',- 7: 'CR2+JPEG',- 9: 'Video'- }),- 10: ('ImageSize', {- 0: 'Large',- 1: 'Medium',- 2: 'Small'- }),- 11: ('EasyShootingMode', {- 0: 'Full Auto',- 1: 'Manual',- 2: 'Landscape',- 3: 'Fast Shutter',- 4: 'Slow Shutter',- 5: 'Night',- 6: 'B&W',- 7: 'Sepia',- 8: 'Portrait',- 9: 'Sports',- 10: 'Macro/Close-Up',- 11: 'Pan Focus'- }),- 12: ('DigitalZoom', {- 0: 'None',- 1: '2x',- 2: '4x',- 3: 'Other'- }),- 13: ('Contrast', {- 0xFFFF: 'Low',- 0: 'Normal',- 1: 'High'- }),- 14: ('Saturation', {- 0xFFFF: 'Low',- 0: 'Normal',- 1: 'High'- }),- 15: ('Sharpness', {- 0xFFFF: 'Low',- 0: 'Normal',- 1: 'High'- }),- 16: ('ISO', {- 0: 'See ISOSpeedRatings Tag',- 15: 'Auto',- 16: '50',- 17: '100',- 18: '200',- 19: '400'- }),- 17: ('MeteringMode', {- 0: 'Default',- 1: 'Spot',- 2: 'Average',- 3: 'Evaluative',- 4: 'Partial',- 5: 'Center-weighted'- }),- 18: ('FocusType', {- 0: 'Manual',- 1: 'Auto',- 3: 'Close-Up (Macro)',- 8: 'Locked (Pan Mode)'- }),- 19: ('AFPointSelected', {- 0x3000: 'None (MF)',- 0x3001: 'Auto-Selected',- 0x3002: 'Right',- 0x3003: 'Center',- 0x3004: 'Left'- }),- 20: ('ExposureMode', {- 0: 'Easy Shooting',- 1: 'Program',- 2: 'Tv-priority',- 3: 'Av-priority',- 4: 'Manual',- 5: 'A-DEP'- }),- 22: ('LensType', ),- 23: ('LongFocalLengthOfLensInFocalUnits', ),- 24: ('ShortFocalLengthOfLensInFocalUnits', ),- 25: ('FocalUnitsPerMM', ),- 28: ('FlashActivity', {- 0: 'Did Not Fire',- 1: 'Fired'- }),- 29: ('FlashDetails', {- 0: 'Manual',- 1: 'TTL',- 2: 'A-TTL',- 3: 'E-TTL',- 4: 'FP Sync Enabled',- 7: '2nd("Rear")-Curtain Sync Used',- 11: 'FP Sync Used',- 13: 'Internal Flash',- 14: 'External E-TTL'- }),- 32: ('FocusMode', {- 0: 'Single',- 1: 'Continuous',- 8: 'Manual'- }),- 33: ('AESetting', {- 0: 'Normal AE',- 1: 'Exposure Compensation',- 2: 'AE Lock',- 3: 'AE Lock + Exposure Comp.',- 4: 'No AE'- }),- 34: ('ImageStabilization', {- 0: 'Off',- 1: 'On',- 2: 'Shoot Only',- 3: 'Panning',- 4: 'Dynamic',- 256: 'Off',- 257: 'On',- 258: 'Shoot Only',- 259: 'Panning',- 260: 'Dynamic'- }),- 39: ('SpotMeteringMode', {- 0: 'Center',- 1: 'AF Point'- }),- 41: ('ManualFlashOutput', {- 0x0: 'n/a',- 0x500: 'Full',- 0x502: 'Medium',- 0x504: 'Low',- 0x7FFF: 'n/a'- }),-}--# 0x0002-FOCAL_LENGTH = {- 1: ('FocalType', {- 1: 'Fixed',- 2: 'Zoom',- }),- 2: ('FocalLength', ),-}--# 0x0004-SHOT_INFO = {- 7: ('WhiteBalance', {- 0: 'Auto',- 1: 'Sunny',- 2: 'Cloudy',- 3: 'Tungsten',- 4: 'Fluorescent',- 5: 'Flash',- 6: 'Custom'- }),- 8: ('SlowShutter', {- -1: 'n/a',- 0: 'Off',- 1: 'Night Scene',- 2: 'On',- 3: 'None'- }),- 9: ('SequenceNumber', ),- 14: ('AFPointUsed', ),- 15: ('FlashBias', {- 0xFFC0: '-2 EV',- 0xFFCC: '-1.67 EV',- 0xFFD0: '-1.50 EV',- 0xFFD4: '-1.33 EV',- 0xFFE0: '-1 EV',- 0xFFEC: '-0.67 EV',- 0xFFF0: '-0.50 EV',- 0xFFF4: '-0.33 EV',- 0x0000: '0 EV',- 0x000C: '0.33 EV',- 0x0010: '0.50 EV',- 0x0014: '0.67 EV',- 0x0020: '1 EV',- 0x002C: '1.33 EV',- 0x0030: '1.50 EV',- 0x0034: '1.67 EV',- 0x0040: '2 EV'- }),- 19: ('SubjectDistance', ),-}--# 0x0026-AF_INFO_2 = {- 2: ('AFAreaMode', {- 0: 'Off (Manual Focus)',- 2: 'Single-point AF',- 4: 'Multi-point AF or AI AF',- 5: 'Face Detect AF',- 6: 'Face + Tracking',- 7: 'Zone AF',- 8: 'AF Point Expansion',- 9: 'Spot AF',- 11: 'Flexizone Multi',- 13: 'Flexizone Single',- }),- 3: ('NumAFPoints', ),- 4: ('ValidAFPoints', ),- 5: ('CanonImageWidth', ),-}--# 0x0093-FILE_INFO = {- 1: ('FileNumber', ),- 3: ('BracketMode', {- 0: 'Off',- 1: 'AEB',- 2: 'FEB',- 3: 'ISO',- 4: 'WB',- }),- 4: ('BracketValue', ),- 5: ('BracketShotNumber', ),- 6: ('RawJpgQuality', {- 0xFFFF: 'n/a',- 1: 'Economy',- 2: 'Normal',- 3: 'Fine',- 4: 'RAW',- 5: 'Superfine',- 130: 'Normal Movie'- }),- 7: ('RawJpgSize', {- 0: 'Large',- 1: 'Medium',- 2: 'Small',- 5: 'Medium 1',- 6: 'Medium 2',- 7: 'Medium 3',- 8: 'Postcard',- 9: 'Widescreen',- 10: 'Medium Widescreen',- 14: 'Small 1',- 15: 'Small 2',- 16: 'Small 3',- 128: '640x480 Movie',- 129: 'Medium Movie',- 130: 'Small Movie',- 137: '1280x720 Movie',- 142: '1920x1080 Movie',- }),- 8: ('LongExposureNoiseReduction2', {- 0: 'Off',- 1: 'On (1D)',- 2: 'On',- 3: 'Auto'- }),- 9: ('WBBracketMode', {- 0: 'Off',- 1: 'On (shift AB)',- 2: 'On (shift GM)'- }),- 12: ('WBBracketValueAB', ),- 13: ('WBBracketValueGM', ),- 14: ('FilterEffect', {- 0: 'None',- 1: 'Yellow',- 2: 'Orange',- 3: 'Red',- 4: 'Green'- }),- 15: ('ToningEffect', {- 0: 'None',- 1: 'Sepia',- 2: 'Blue',- 3: 'Purple',- 4: 'Green',- }),- 16: ('MacroMagnification', ),- 19: ('LiveViewShooting', {- 0: 'Off',- 1: 'On'- }),- 25: ('FlashExposureLock', {- 0: 'Off',- 1: 'On'- })-}---def add_one(value):- return value + 1---def subtract_one(value):- return value - 1---def convert_temp(value):- return '%d C' % (value - 128)--# CameraInfo data structures have variable sized members. Each entry here is:-# byte offset: (item name, data item type, decoding map).-# Note that the data item type is fed directly to struct.unpack at the-# specified offset.-CAMERA_INFO_TAG_NAME = 'MakerNote Tag 0x000D'--CAMERA_INFO_5D = {- 23: ('CameraTemperature', '<B', convert_temp),- 204: ('DirectoryIndex', '<L', subtract_one),- 208: ('FileIndex', '<H', add_one),-}--CAMERA_INFO_5DMKII = {- 25: ('CameraTemperature', '<B', convert_temp),- 443: ('FileIndex', '<L', add_one),- 455: ('DirectoryIndex', '<L', subtract_one),-}--CAMERA_INFO_5DMKIII = {- 27: ('CameraTemperature', '<B', convert_temp),- 652: ('FileIndex', '<L', add_one),- 656: ('FileIndex2', '<L', add_one),- 664: ('DirectoryIndex', '<L', subtract_one),- 668: ('DirectoryIndex2', '<L', subtract_one),-}--CAMERA_INFO_600D = {- 25: ('CameraTemperature', '<B', convert_temp),- 475: ('FileIndex', '<L', add_one),- 487: ('DirectoryIndex', '<L', subtract_one),-}--# A map of regular expressions on 'Image Model' to the CameraInfo spec-CAMERA_INFO_MODEL_MAP = {- r'EOS 5D$': CAMERA_INFO_5D,- r'EOS 5D Mark II$': CAMERA_INFO_5DMKII,- r'EOS 5D Mark III$': CAMERA_INFO_5DMKIII,- r'\b(600D|REBEL T3i|Kiss X5)\b': CAMERA_INFO_600D,-}diff --git a/ext/exifread/utils.py b/ext/exifread/utils.pydeleted file mode 100644index f5e0d7fe..00000000--- a/ext/exifread/utils.py+++ /dev/null@@ -1,86 +0,0 @@-"""-Misc utilities.-"""---def ord_(dta):- if isinstance(dta, str):- return ord(dta)- return dta---def make_string(seq):- """- Don't throw an exception when given an out of range character.- """- string = ''- for c in seq:- # Screen out non-printing characters- try:- if 32 <= c and c < 256:- string += chr(c)- except TypeError:- pass- # If no printing chars- if not string:- return str(seq)- return string---def make_string_uc(seq):- """- Special version to deal with the code in the first 8 bytes of a user comment.- First 8 bytes gives coding system e.g. ASCII vs. JIS vs Unicode.- """- seq = seq[8:]- # Of course, this is only correct if ASCII, and the standard explicitly- # allows JIS and Unicode.- return make_string(seq)---def s2n_motorola(string):- """Extract multi-byte integer in Motorola format (little endian)."""- x = 0- for c in string:- x = (x << 8) | ord_(c)- return x---def s2n_intel(string):- """Extract multi-byte integer in Intel format (big endian)."""- x = 0- y = 0- for c in string:- x = x | (ord_(c) << y)- y += + 8- return x---class Ratio:- """- Ratio object that eventually will be able to reduce itself to lowest- common denominator for printing.- """-- def __init__(self, num, den):- self.num = num- self.den = den-- def __repr__(self):- self.reduce()- if self.den == 1:- return str(self.num)- return '%d/%d' % (self.num, self.den)-- def _gcd(self, a, b):- if b == 0:- return a- else:- return self._gcd(b, a % b)-- def reduce(self):- div = self._gcd(self.num, self.den)- if div > 1:- self.num = self.num // div- self.den = self.den // div-diff --git a/ext/gexf/__init__.py b/ext/gexf/__init__.pydeleted file mode 100644index 99603eff..00000000--- a/ext/gexf/__init__.py+++ /dev/null@@ -1,5 +0,0 @@-from _gexf import Gexf-from _gexf import Node-from _gexf import Edge-from _gexf import Graph-from _gexf import GexfImport\ No newline at end of filediff --git a/ext/gexf/_gexf.py b/ext/gexf/_gexf.pydeleted file mode 100755index 5f406aa4..00000000--- a/ext/gexf/_gexf.py+++ /dev/null@@ -1,1067 +0,0 @@-# -*- coding: utf-8 -*---#-# Gexf library in python-# see gephi.org and gexf.net-#-# repository : http://github.com/paulgirard/pygexf-# documentation : http://packages.python.org/pygexf-#-# main developper : Paul Girard, médialab Sciences Po-# licence : GPL v3-#--from lxml import etree-from datetime import date-import itertools-import traceback--- # missing features :- # data validation regarding attribute types- # phylogeny--- # evolution ideas :- # add display stats on graph composition when exportingto xml- # add anti-paralell edges test--def msg_unexpected_tag(expected, got) :- print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)--def ns_clean(token) :- i = token.find('}')- return token[i+1:]--class Gexf :-- def __init__(self,creator,description):- self.creator=creator- self.description=description- self.graphs=[]- self.xmlns="http://www.gephi.org/gexf/1.2draft"- self.xsi="http://www.w3.org/2001/XMLSchema-instance"- self.schemaLocation="http://www.gephi.org/gexf/1.1draft http://gephi.org/gexf/1.2draft.xsd"- self.viz="http://www.gexf.net/1.2draft/viz"- self.version="1.2"-- def addGraph(self,type,mode,label,timeformat=""):- g = Graph(type,mode,label,timeformat)- self.graphs.append(g)- return g-- def getXML(self):- gexfXML = etree.Element("{"+self.xmlns+"}gexf",version=self.version,nsmap={None:self.xmlns,'viz':self.viz,'xsi':self.xsi})-# gexfXML.set("xmlnsxsi",)- gexfXML.set("{xsi}schemaLocation",self.schemaLocation)- meta = etree.SubElement(gexfXML, "meta")- meta.set("lastmodified",date.today().isoformat())- etree.SubElement(meta, "creator").text=self.creator- etree.SubElement(meta, "description").text=self.description- for graph in self.graphs :- gexfXML.append(graph.getXML())-- return gexfXML-- def write(self,file, print_stat=True):- file.write(etree.tostring(self.getXML(),pretty_print=True,encoding='utf-8',xml_declaration=True))- if print_stat == True:- self.print_stat()-- def print_stat(self) :- for graph in self.graphs :- graph.print_stat()-- @staticmethod- def importXML(gexf_file) :- """ import gexf xml meta tags to create a Gexf Object and delegate Graph extraction to Graph class"""- # parse the gexf file- parser = etree.XMLParser(ns_clean=True)- tree = etree.parse((gexf_file), parser)- # start create Gexf Object- gexf_xml = tree.getroot()- tag = ns_clean(gexf_xml.tag).lower()- if tag <> "gexf" :- msg_unexpected_tag("gexf", tag)- return- gexf_obj = None- for child in gexf_xml :- tag = ns_clean(child.tag).lower()- # create a gexf object by importing meta tag- if tag == "meta" :- meta_xml = child- for child in meta_xml :- tag = ns_clean(child.tag).lower()- if tag == "creator" :- creator = child.text- if tag == "description" :- description = child.text- gexf_obj=Gexf(creator=creator, description=description)- # export graph xml through Graph Class- if tag == "graph" :- graph_xml = child- if gexf_obj == None :- msg_unexpected_tag("meta", tag)- return- Graph.importXML(graph_xml,gexf_obj)- return gexf_obj--class Graph :-- def __init__(self,type,mode,label,time_format="double",start="",end="") :-- # control variable- self.authorizedType=("directed","undirected")- self.authorizedMode=("dynamic","static")- # time format- # Discrete: integer or double- # Continuous : date (yyyy-mm-dd) or dateTime- # default : double- self.authorizedTimeFormat=("integer","double","date","dateTime")-- self.defaultTimeFormat="double"- self.defaultType="directed"- self.defaultMode="static"-- self.label=label-- if type in self.authorizedType :- self.type=type- else :- self.type=self.defaultType- if mode in self.authorizedMode :- self.mode=mode- else :- self.mode=self.defaultMode-- if time_format in self.authorizedTimeFormat :- self.time_format=time_format- else :- self.time_format=self.defaultTimeFormat-- self.start=start- self.end = end--- self._attributes= Attributes()- self.attributes = self._attributes- self._nodes={}- self.nodes=self._nodes- self._edges={}- self.edges=self._edges-- def addNode(self,id,label,start="",end="",startopen=False,endopen=False,pid="",r="",g="",b="",spells=[]) :- self._nodes[str(id)]=Node(self,id,label,start,end,pid,r,g,b,spells,startopen,endopen)- return self._nodes[str(id)]-- def nodeExists(self,id) :- if id in self._nodes.keys():- return 1- else :- return 0-- def addEdge(self,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :- self._edges[str(id)]=Edge(self,id,source,target,weight,start,end,label,r,g,b,spells,startopen,endopen)- return self._edges[str(id)]-- def addNodeAttribute(self,title,defaultValue=None,type="integer",mode="static", force_id="") :- # add to NodeAttributes- return self._attributes.declareAttribute("node",type,defaultValue,title,mode,force_id)-- def addDefaultAttributesToNode(self,node) :- """ deprecated """- pass-- def checkNodeAttribute(self,id,value,start,end):- """deprecated"""- pass- # check conformity with type is missing- # if id in self._nodesAttributes.keys() :-# if self._nodesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :-# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")-# return 1-# else :-# raise Exception("attribute id unknown. Add Attribute to graph first")--- def addEdgeAttribute(self,title,defaultValue,type="integer",mode="static", force_id=""):- return self._attributes.declareAttribute("edge",type,defaultValue,title,mode,force_id)--- def addDefaultAttributesToEdge(self,edge) :- """ deprecated """- pass-- def checkEdgeAttribute(self,id,value,start,end):- """deprecated """- pass-# # check conformity with type is missing-# if id in self._edgesAttributes.keys() :-# if self._edgesAttributes[id]["mode"]=="static" and ( not start=="" or not end=="") :-# raise Exception("attribute "+str(id)+" is static you can't specify start or end dates. Declare Attribute as dynamic")-# return 1-# else :-# raise Exception("attribute id unknown. Add Attribute to graph first")--- def getXML(self) :- # return lxml etree element- graphXML = etree.Element("graph",defaultedgetype=self.type,mode=self.mode,label=self.label,timeformat=self.time_format)-- for attributesElement in self.attributes.getAttributesDeclarationXML() :- graphXML.append(attributesElement)-- nodesXML = etree.SubElement(graphXML, "nodes")- node_ids=self._nodes.keys()- node_ids.sort()- for id in node_ids :- nodesXML.append(self._nodes[id].getXML())-- edgesXML = etree.SubElement(graphXML, "edges")- edge_ids=self._edges.keys()- edge_ids.sort()- for id in edge_ids :- edgesXML.append(self._edges[id].getXML())-- return graphXML-- @staticmethod- def importXML(graph_xml,gexf_obj) :- """ import graph xml tag to create a Graph Object and delegate Node/Edges extraction to Edge/Node class"""- # get Graph attributes- type = ""- mode = ""- label = ""- timeformat="double"- for attr in graph_xml.attrib :- attr = attr.lower()- if attr == "defaultedgetype" :- type = graph_xml.attrib[attr]- if attr == "mode" :- mode = graph_xml.attrib[attr]- if attr == "label" :- label = graph_xml.attrib[attr]- if attr == "timeformat" :- timeformat = graph_xml.attrib[attr]- # create and attache the graph object to the Gexf object- graph_obj = gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)-- for child in graph_xml :- tag = ns_clean(child.tag).lower()-- if tag == "attributes" :- attributes_xml = child- # Delegate Attributes declaration to the attribute object- graph_obj.attributes.importAttributesXML(attributes_xml)-- if tag == "nodes" :- nodes_xml = child- # Delegate nodes creation to the Node class- Node.importXML(nodes_xml,graph_obj)- if tag == "edges" :- edges_xml = child- # Delegate edges creation to the Edge class- Edge.importXML(edges_xml,graph_obj)-- def print_stat(self):- print self.label+" "+self.type+" "+self.mode+" "+self.start+" "+self.end- print "number of nodes : "+str(len(self._nodes))- print "number of edges : "+str(len(self._edges))--class Attributes(dict):- """- attributes=- {- "node" :- { "id1" : {"id":"id1","title":"age","type":"integer","defaultValue":50,"mode":"static"}, },- "edge" :- { "id2" : {"id":"id2","title":"relationship","type":"string","defaultValue":"friend",mode:"dynamic"}, },- }--- """- def __init__(self):- self.type_choices=["integer","string","float","double","boolean","date","URI"]- self.attClass_choices=["node","edge"]- self.mode_choices=["static","dynamic"]- for attClass in self.attClass_choices :- self[attClass]={}-- def declareAttribute(self,attClass,type,defaultValue,title="",mode="static",id=None) :- """- add a new attribute declaration to the graph- """- if attClass in self.attClass_choices :- # should add quality control here on type and defaultValue- # if no id given generating a numerical one based on dict length- if not id :- id = str(len(self[attClass]))- self[attClass][id]={"id":id,"type":type,"defaultValue":defaultValue,"mode":mode,"title":title}- return id- else :- raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(type_choices))--- def makeAttributeInstance(self,attClass,id=None,value=None,start=None,end=None,startopen=False,endopen=False) :- """- generate an attribute to be include to a node or edge.- copied from the declared attributes, thus any attribute has to be declared first- """- if attClass in self.attClass_choices :- if id in self[attClass].keys() :- att={"id":id}- att["value"]=value if value else self[attClass][id]["defaultValue"]- if self[attClass][id]["mode"]=="dynamic" and start or end :- # start & end will be discarded if the mode is set to static- if start :- att["start"]=start- if startopen :- att["startopen"]=startopen- if end :- att["end"]=end- if endopen :- att["endopen"]=endopen- return att- else :- raise Exception("wrong attribute id (%s), declare the attribute first with declareAttribute"%(id,))- else :- raise Exception("wrong attClass : "+str(attClass)+" Should be in "+str(self.type_choices))-- def getAttributesDeclarationXML(self) :- """ generate attributes declaration XML """- # return lxml etree element- allAttributesXML=[]- if len(self)>0 :- # iter on node and then edge atts- for attClass,atts in self.iteritems() :- # group by mode- key_mode=lambda att : att["mode"]- atts_sorted_by_mode=sorted(atts.values(),key=key_mode,reverse=True)- for mode,atts in itertools.groupby(atts_sorted_by_mode,key_mode) :- # generate on attributes by mode- attributesXML = etree.Element("attributes")- attributesXML.set("class",attClass)- attributesXML.set("mode",mode)- # generate attribute by id order- for att in sorted(atts,key=lambda att: att["id"]) :- attributeXML=etree.SubElement(attributesXML, "attribute")- attributeXML.set("id",str(att["id"]))- attributeXML.set("title",att["title"])- attributeXML.set("type",att["type"])- if att["defaultValue"] :- etree.SubElement(attributeXML, "default").text=att["defaultValue"]- allAttributesXML.append(attributesXML)- return allAttributesXML-- @staticmethod- def getAttributesXML(atts) :- """ get XML attValues for an element (Node or Edge) by passing an attribute values list (stored in Nodes and Edges)"""- if len(atts)>0:- attValuesXML = etree.Element("attvalues")- for att in atts :- attValueXML=etree.SubElement(attValuesXML, "attvalue")- attValueXML.set("for",str(att["id"]))- attValueXML.set("value",att["value"])- if "start" in att.keys() and not att["start"]=="" :- attValueXML.set("start" if not "startopen" in att.keys() or not att["startopen"] else "startopen",att["start"])- if "end" in att.keys() and not att["end"]=="" :- attValueXML.set("end" if not "endopen" in att.keys() or not att["endopen"] else "endopen",att["end"])- return attValuesXML- else :- return None-- def importAttributesXML(self,attributes_xml):- """ get XML attributes declaration of a graph gexf"""- attr_class = None- mode = ""- for attr in attributes_xml.attrib :- attr = attr.lower()- if attr == "class" :- attr_class = attributes_xml.attrib[attr].lower()- if attr == "mode" :- mode = attributes_xml.attrib[attr]-- for child in attributes_xml :- tag = ns_clean(child.tag).lower()- if tag == "attribute" :- attribute_xml = child- id = ""- title = ""- type = ""-- for attr in attribute_xml.attrib :- attr = attr.lower()- if attr == "id" :- id = attribute_xml.attrib[attr]- if attr == "title" :- title = attribute_xml.attrib[attr]- if attr == "type" :- type = attribute_xml.attrib[attr]-- default = ""-- for child in attribute_xml :- tag = ns_clean(child.tag).lower()- if tag == "default" :- default = child.text-- self.declareAttribute(attr_class,type,default,title,mode,id)-- def importAttributesValuesXML(self,attClass,attvalues_xml):- """ import attributes values from attvalues gexf xml tag attached to nodes or edges"""- atts=[]- for attvalues in attvalues_xml :- for child in attvalues :- tag = ns_clean(child.tag).lower()- if tag == "attvalue" :- attvalue_xml = child- id = ""- value = ""- start = ""- startopen=False- end = ""- endopen=False- for attr in attvalue_xml.attrib :- if attr == "for" :- id = attvalue_xml.attrib[attr]- if attr == "value" :- value = attvalue_xml.attrib[attr]- if attr == "start" :- start = attvalue_xml.attrib[attr]- if attr == "end" :- end = attvalue_xml.attrib[attr]- if attr == "startopen" :- start = attvalue_xml.attrib[attr]- startopen = True- if attr == "endopen" :- end = attvalue_xml.attrib[attr]- endopen = True-- atts.append(self.makeAttributeInstance(attClass,id,value,start,end,startopen,endopen))- return atts--class Spells(list):- '''- spells are time periods- spells is a list of dictionaries- a spell is a dict : {"start":"YYYY-MM-DD","end":"YYYY-MM-DD"}- '''--- def getXML(self):-- spellsXML=etree.Element("spells")- for spell in self :- spellXML=etree.SubElement(spellsXML, "spell")- if "start" in spell.keys() :- spellXML.set("start",spell["start"])- if "end" in spell.keys() :- spellXML.set("end",spell["end"])- return spellsXML-- @staticmethod- def importXML(spellsxmltree):- return Spells([ spell.attrib for spell in spellsxmltree])---class Node :-- def __init__(self,graph,id,label,start="",end="",pid="",r="",g="",b="",spells=[],startopen=False,endopen=False) :- self.id =id- self.label=label- self.start=start- self.startopen=startopen- self.end=end- self.endopen=endopen- self.pid=pid- self._graph=graph- self.setColor(r,g,b)-- #spells expecting format = [{start:"",end:""},...]- self.spells= spells-- if not self.pid=="" :- if not self._graph.nodeExists(self.pid) :- raise Exception("pid "+self.pid+" node unknown, add nodes to graph first")-- self._attributes=[]- self.attributes=self._attributes-- # add existing nodesattributes default values : bad idea and unecessary- #self._graph.addDefaultAttributesToNode(self)-- def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :- self._attributes.append(self._graph.attributes.makeAttributeInstance("node",id,value,start,end,startopen,endopen))-- def getXML(self) :- # return lxml etree element- try :- nodeXML = etree.Element("node",id=str(self.id),label=self.label)- if not self.start == "":- nodeXML.set("start" if not self.startopen else "startopen",self.start)- if not self.end == "":- nodeXML.set("end" if not self.endopen else "endopen" ,self.end)- if not self.pid == "":- nodeXML.set("pid",self.pid)-- # attributes- if self._attributes :- nodeXML.append(Attributes.getAttributesXML(self._attributes))-- # spells- if self.spells :- print "found spells in node "+self.id- nodeXML.append(self.spells.getXML())--- if not self.r=="" and not self.g=="" and not self.b=="" :- #color : <viz:color r="239" g="173" b="66"/>- colorXML = etree.SubElement(nodeXML, "{http://www.gexf.net/1.1draft/viz}color")- colorXML.set("r",self.r)- colorXML.set("g",self.g)- colorXML.set("b",self.b)-- return nodeXML- except Exception, e:- print self.label- print self._attributes- print e- traceback.print_exc()- exit()-- def getAttributes(self):- attsFull=[]- for att in self._attributes :- attFull=self._graph.attributes["node"][att["id"]].copy()- attFull.update(att)- attsFull.append(attFull)- return attsFull-- @staticmethod- def importXML(nodes_xml,graph_obj) :-- for child in nodes_xml :- tag = ns_clean(child.tag).lower()- if tag == "node" :- node_xml = child- id = ""- label = ""- start = ""- startopen=False- end = ""- endopen=False- pid = ""- r = ""- g = ""- b = ""-- for attr in node_xml.attrib :- attr = attr.lower()- if attr == "id" :- id = node_xml.attrib[attr]- if attr == "label" :- label = node_xml.attrib[attr]- if attr == "start" :- start = node_xml.attrib[attr]- if attr == "end" :- start = node_xml.attrib[attr]- if attr == "startopen" :- start = attvalue_xml.attrib[attr]- startopen=True- if attr == "endopen" :- end = attvalue_xml.attrib[attr]- endopen=True- if attr == "pid" :- pid = node_xml.attrib[attr]--- attvalues_xml = []- spells=[]-- for child in node_xml :- tag = ns_clean(child.tag).lower()- if tag == "attvalues" :- attvalues_xml.append(child)- if tag == "viz:color" :- r = child.attrib["r"]- g = child.attrib["g"]- b = child.attrib["b"]- if tag =="spells" :- spells=Spells.importXML(child)---- node_obj = graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)- node_obj._attributes =graph_obj.attributes.importAttributesValuesXML("node",attvalues_xml)---- def setColor(self,r,g,b) :- self.r=r- self.g=g- self.b=b-- def __str__(self):- return self.label--class Edge :-- def __init__(self,graph,id,source,target,weight="",start="",end="",label="",r="",g="",b="",spells=[],startopen=False,endopen=False) :-- self.id =id- self._graph=graph--- if self._graph.nodeExists(source) :- self._source=source- self.source=self._source- else :- raise Exception("source "+source+" node unknown, add nodes to graph first")-- if self._graph.nodeExists(target) :- self._target=target- self.target=self._target- else:- raise Exception("target "+target+" node unknown, add nodes to graph first")-- self.start=start- self.startopen=startopen- self.end=end- self.endopen=endopen-- self.weight=weight- self.label=label- self._attributes=[]- self.attributes=self._attributes- # COLOR on edges now supported in GEXF 1.2- self.setColor(r,g,b)-- #spells expecting format = [{start:"",end:""},...]- self.spells= Spells(spells)-- # add existing nodesattributes default values : bad idea and unecessary- #self._graph.addDefaultAttributesToEdge(self)--- def addAttribute(self,id,value,start="",end="",startopen=False,endopen=False) :- self._attributes.append(self._graph.attributes.makeAttributeInstance("edge",id,value,start,end,startopen,endopen))--- def getXML(self) :- # return lxml etree element- try :- edgeXML = etree.Element("edge",id=str(self.id),source=str(self._source),target=str(self._target))- if not self.start == "":- edgeXML.set("start" if not self.startopen else "startopen",self.start)- if not self.end == "":- edgeXML.set("end" if not self.endopen else "endopen" ,self.end)- if not self.weight == "":- edgeXML.set("weight",str(self.weight))- if not self.label == "":- edgeXML.set("label",self.label)-- # attributes- if self._attributes :- edgeXML.append(Attributes.getAttributesXML(self._attributes))-- # spells- if self.spells :- #spellsXML = etree.SubElement(edgeXML, "spells")- #spellsXML.append(self.spells.getXML())- edgeXML.append(self.spells.getXML())-- # COLOR on edges is supported in GEXF since 1.2- if not self.r=="" and not self.g=="" and not self.b=="" :- #color : <viz:color r="239" g="173" b="66"/>- colorXML = etree.SubElement(edgeXML, "{http://www.gexf.net/1.2draft/viz}color")- colorXML.set("r",self.r)- colorXML.set("g",self.g)- colorXML.set("b",self.b)---- return edgeXML- except Exception, e:- print self._source+" "+self._target- print e- exit()-- def getAttributes(self):- attsFull=[]- for att in self._attributes :- attFull=self._graph.attributes["edge"][att["id"]].copy()- attFull.update(att)- attsFull.append(attFull)- return attsFull-- @staticmethod- def importXML(edges_xml,graph_obj) :-- for child in edges_xml :-- tag = ns_clean(child.tag).lower()- if tag == "edge" :- edge_xml = child- id = ""- source = ""- target = ""- weight = ""- start = ""- startopen=False- end = ""- endopen=False- label = ""- r = ""- g = ""- b = ""-- for attr in edge_xml.attrib :- attr = attr.lower()- if attr == "id" :- id = edge_xml.attrib[attr]- if attr == "source" :- source = edge_xml.attrib[attr]- if attr == "target" :- target = edge_xml.attrib[attr]- if attr == "weight" :- weight = edge_xml.attrib[attr]- if attr == "start" :- start = edge_xml.attrib[attr]- if attr == "end" :- end = edge_xml.attrib[attr]- if attr == "startopen" :- start = edge_xml.attrib[attr]- startopen=True- if attr == "endopen" :- end = edge_xml.attrib[attr]- endopen=True- if attr == "label" :- label = edge_xml.attrib[attr]-- spells=[]- attvalues_xml=[]- for child in edge_xml :- tag = ns_clean(child.tag).lower()- if tag == "attvalues" :- attvalues_xml.append(child)- if tag =="spells" :- spells=Spells.importXML(child)- if tag == "viz:color" :- r = child.attrib["r"]- g = child.attrib["g"]- b = child.attrib["b"]-- edge_obj = graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)- edge_obj._attributes=graph_obj.attributes.importAttributesValuesXML("edge",attvalues_xml)----# COLOR on edges is supported in GEXF since 1.2- def setColor(self,r,g,b) :- self.r=r- self.g=g- self.b=b---class GexfImport :-# class coded by elie Rotenberg, médialab 20/07/2010-# deprecated : import XML codes are now included to the Gexf, Graph, Attribute, Node, Edge classes-- def __init__(self, file_like) :- parser = etree.XMLParser(ns_clean=True)- tree = etree.parse(file_like, parser)- gexf_xml = tree.getroot()- tag = self.ns_clean(gexf_xml.tag).lower()- if tag <> "gexf" :- self.msg_unexpected_tag("gexf", tag)- return- self.gexf_obj = None- for child in gexf_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "meta" :- meta_xml = child- self.gexf_obj = self.extract_gexf_obj(meta_xml)- if tag == "graph" :- graph_xml = child- if self.gexf_obj == None :- self.msg_unexpected_tag("meta", tag)- return- self.graph_obj = self.extract_graph_obj(graph_xml)--- def ns_clean(self, token) :- i = token.find('}')- return token[i+1:]-- def msg_unexpected_tag(self, expected, got) :- print "Error : incorrect xml. Expected tag {expected}, not {got}.".format(expected=expected, got=got)-- def extract_gexf_obj(self, meta_xml) :- for child in meta_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "creator" :- creator = child.text- if tag == "description" :- description = child.text- return Gexf(creator=creator, description=description)-- def extract_graph_obj(self, graph_xml) :- type = ""- mode = ""- label = ""- timeformat="double"- for attr in graph_xml.attrib :- attr = attr.lower()- if attr == "defaultedgetype" :- type = graph_xml.attrib[attr]- if attr == "mode" :- mode = graph_xml.attrib[attr]- if attr == "label" :- label = graph_xml.attrib[attr]- if attr == "timeformat" :- timeformat = graph_xml.attrib[attr]-- self.graph_obj = self.gexf_obj.addGraph(type=type, mode=mode, label=label,timeformat=timeformat)-- for child in graph_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "attributes" :- attributes_xml = child- self.extract_attributes(attributes_xml)- if tag == "nodes" :- nodes_xml = child- self.extract_nodes(nodes_xml)- if tag == "edges" :- edges_xml = child- self.extract_edges(edges_xml)-- def extract_attributes(self, attributes_xml) :- attr_class = None- mode = ""- for attr in attributes_xml.attrib :- attr = attr.lower()- if attr == "class" :- attr_class = attributes_xml.attrib[attr].lower()- if attr == "mode" :- mode = attributes_xml.attrib[attr]-- for child in attributes_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "attribute" :- attribute_xml = child- self.extract_attribute(attribute_xml, attr_class, mode)-- def extract_attribute(self, attribute_xml, attr_class, mode) :- id = ""- title = ""- type = ""-- for attr in attribute_xml.attrib :- attr = attr.lower()- if attr == "id" :- id = attribute_xml.attrib[attr]- if attr == "title" :- title = attribute_xml.attrib[attr]- if attr == "type" :- type = attribute_xml.attrib[attr]-- default = ""-- for child in attribute_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "default" :- default = child.text--- if attr_class == "node" :- self.graph_obj.addNodeAttribute(title, default, type, mode, force_id=id)-- if attr_class == "edge" :- self.graph_obj.addEdgeAttribute(title, default, type, mode, force_id=id)-- def extract_nodes(self, nodes_xml) :- for child in nodes_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "node" :- node_xml = child- self.extract_node(node_xml)-- def extract_node(self, node_xml) :- id = ""- label = ""- start = ""- startopen=False- end = ""- endopen=False- pid = ""- r = ""- g = ""- b = ""-- for attr in node_xml.attrib :- attr = attr.lower()- if attr == "id" :- id = node_xml.attrib[attr]- if attr == "label" :- label = node_xml.attrib[attr]- if attr == "start" :- start = node_xml.attrib[attr]- if attr == "end" :- start = node_xml.attrib[attr]- if attr == "startopen" :- start = attvalue_xml.attrib[attr]- startopen=True- if attr == "endopen" :- end = attvalue_xml.attrib[attr]- endopen=True- if attr == "pid" :- pid = node_xml.attrib[attr]--- attvalues_xmls = []- spells=[]-- for child in node_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "attvalues" :- attvalues_xmls.append(child)- if tag == "viz:color" :- r = child.attrib["r"]- g = child.attrib["g"]- b = child.attrib["b"]- if tag =="spells" :- spells=[ spell.attrib for spell in child ]--- self.node_obj = self.graph_obj.addNode(id=id, label=label, start=start, end=end, startopen=startopen, endopen=endopen, pid=pid, r=r, g=g, b=b,spells=spells)-- for attvalues_xml in attvalues_xmls :- self.extract_node_attvalues(attvalues_xml)-- def extract_node_attvalues(self, attvalues_xml) :- for child in attvalues_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "attvalue" :- attvalue_xml = child- self.extract_node_attvalue(attvalue_xml)-- def extract_node_attvalue(self, attvalue_xml) :- id = ""- value = ""- start = ""- startopen=False- end = ""- endopen=False- for attr in attvalue_xml.attrib :- attr = attr.lower()- if attr == "for" :- id = attvalue_xml.attrib[attr]- if attr == "value" :- value = attvalue_xml.attrib[attr]- if attr == "start" :- start = attvalue_xml.attrib[attr]- if attr == "end" :- end = attvalue_xml.attrib[attr]- if attr == "startopen" :- start = attvalue_xml.attrib[attr]- startopen=True- if attr == "endopen" :- end = attvalue_xml.attrib[attr]- endopen=True- self.node_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)-- def extract_edges(self, edges_xml) :- for child in edges_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "edge" :- edge_xml = child- self.extract_edge(edge_xml)-- def extract_edge(self, edge_xml) :- id = ""- source = ""- target = ""- weight = ""- start = ""- startopen=False- end = ""- endopen=False- label = ""- r = ""- g = ""- b = ""-- for attr in edge_xml.attrib :- attr = attr.lower()- if attr == "id" :- id = edge_xml.attrib[attr]- if attr == "source" :- source = edge_xml.attrib[attr]- if attr == "target" :- target = edge_xml.attrib[attr]- if attr == "weight" :- weight = edge_xml.attrib[attr]- if attr == "start" :- start = edge_xml.attrib[attr]- if attr == "end" :- end = edge_xml.attrib[attr]- if attr == "startopen" :- start = edge_xml.attrib[attr]- startopen=True- if attr == "endopen" :- end = edge_xml.attrib[attr]- endopen=True- if attr == "label" :- label = edge_xml.attrib[attr]-- spells=[]- attvalues_xml=[]- for child in edge_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "attvalues" :- attvalues_xml = child- if tag =="spells" :- spells=[ spell.attrib for spell in child]- if tag == "viz:color" :- r = child.attrib["r"]- g = child.attrib["g"]- b = child.attrib["b"]-- self.edge_obj = self.graph_obj.addEdge(id=id, source=source, target=target, weight=weight, start=start, end=end,startopen=startopen,endopen=endopen,label=label,r=r,g=g,b=b, spells=spells)- self.extract_edge_attvalues(attvalues_xml)-- def extract_edge_attvalues(self, attvalues_xml) :- for child in attvalues_xml :- tag = self.ns_clean(child.tag).lower()- if tag == "attvalue" :- attvalue_xml = child- self.extract_edge_attvalue(attvalue_xml)---# def addAttribute(self,id,value,start="",end="") :-- def extract_edge_attvalue(self, attvalue_xml) :- id = ""- value = ""- start = ""- startopen=True- end = ""- endopen=True- for attr in attvalue_xml.attrib :- if attr == "for" :- id = attvalue_xml.attrib[attr]- if attr == "value" :- value = attvalue_xml.attrib[attr]- if attr == "start" :- start = attvalue_xml.attrib[attr]- if attr == "end" :- end = attvalue_xml.attrib[attr]- if attr == "startopen" :- startopen = attvalue_xml.attrib[attr]- if attr == "endopen" :- endopen = attvalue_xml.attrib[attr]-- self.edge_obj.addAttribute(id=id, value=value, start=start, end=end,startopen=startopen,endopen=endopen)-- def gexf(self) :- return self.gexf_objdiff --git a/ext/openxmllib/__init__.py b/ext/openxmllib/__init__.pydeleted file mode 100644index d716b038..00000000--- a/ext/openxmllib/__init__.py+++ /dev/null@@ -1,76 +0,0 @@-# -*- coding: utf-8 -*--# $Id$-"""-The Open XML document library-Open XML document is defined by the ECMA-376 standard-http://www.ecma-international.org/publications/standards/Ecma-376.htm-"""--import os-import cStringIO-import urllib2-import mimetypes--import wordprocessing-import spreadsheet-import presentation--version = None-if version is None:- version = open(os.path.join(os.path.dirname(__file__), 'version.txt')).read().strip()--_document_classes = (- wordprocessing.WordprocessingDocument,- spreadsheet.SpreadsheetDocument,- presentation.PresentationDocument)--def openXmlDocument(path=None, file_=None, data=None, url=None, mime_type=None):- """Factory function- Will guess what document type is best suited and return the appropriate- document type.- User must provide either `path`, `file_`, `data` or `url` parameter- @param path: file path in the local filesystem to a document.- @param file_: a file (like) object to a document (must be opened in 'rb' mode')- @param data: the binary data of a document- @param url: the URL of a document- @param mime_type: mime type if known- @return : Document subclass object- Warning, when passing a file data, the mime_type is required- """- if path is not None:- file_ = open(path, 'rb')- elif file_ is not None:- assert hasattr(file_, 'read')- elif url is not None:- file_ = urllib2.urlopen(url)- if mime_type is None:- mime_type = file_.headers.gettype()- elif data is not None:- file_ = cStringIO.StringIO(data)- assert mime_type is not None- else:- raise ValueError("Either path, file_, data, or url should be provided")-- # Mime type based document- if mime_type is not None:- for class_ in _document_classes:- if class_.canProcessMime(mime_type):- return class_(file_, mime_type=mime_type)- raise ValueError("%s MIME type is unknown." % mime_type)-- else:- assert hasattr(file_, 'name')-- for class_ in _document_classes:- if class_.canProcessFilename(file_.name):- return class_(file_, mime_type=mime_type)- raise ValueError("Can't guess mime_type. You should set the mime_type param")- return--###-## Extending standard mimetypes-###--for class_ in _document_classes:- for pattern, mime_type in class_._extpattern_to_mime.items():- mimetypes.add_type(mime_type, pattern[1:], True)diff --git a/ext/openxmllib/contenttypes.py b/ext/openxmllib/contenttypes.pydeleted file mode 100644index f25387d5..00000000--- a/ext/openxmllib/contenttypes.py+++ /dev/null@@ -1,116 +0,0 @@-# -*- coding: utf-8 -*--"""-The various inner content types in an open XML document-"""-# $Id: contenttypes.py 6800 2007-12-04 11:17:01Z glenfant $--import os-from lxml import etree-import namespaces as ns-import utils--# Common properties-CT_CORE_PROPS = 'application/vnd.openxmlformats-package.core-properties+xml'-CT_EXT_PROPS = 'application/vnd.openxmlformats-officedocument.extended-properties+xml'-CT_CUSTOM_PROPS = 'application/vnd.openxmlformats-officedocument.custom-properties+xml'--# Wordprocessing document-# See...-# http://technet2.microsoft.com/Office/en-us/library/e077da98-0216-45eb-b6a7-957f9c510a851033.mspx?pf=true-# ...for the various-CT_WORDPROC_DOCX_PUBLIC = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'-CT_WORDPROC_DOTX_PUBLIC = 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'-CT_WORDPROC_DOCM_PUBLIC = 'application/vnd.ms-word.document.macroEnabled.12'-CT_WORDPROC_DOTM_PUBLIC = 'application/vnd.ms-word.template.macroEnabled.12'--CT_WORDPROC_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'-CT_WORDPROC_NUMBERING = 'application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml'-CT_WORDPROC_STYPES = 'application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml'-CT_WORDPROC_FONTS = 'application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml'-CT_WORDPROC_SETINGS = 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml'-CT_WORDPROC_FOOTNOTES = 'application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml'-CT_WORDPROC_ENDNOTES = 'application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml'-CT_WORDPROC_COMMENTS = 'application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml'--# Presentation document-CT_PRESENTATION_PPTX_PUBLIC = 'application/vnd.openxmlformats-officedocument.presentationml.presentation'-CT_PRESENTATION_PPTM_PUBLIC = 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'-CT_PRESENTATION_PPSX_PUBLIC = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'-CT_PRESENTATION_PPSM_PUBLIC = 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'-CT_PRESENTATION_PPAM_PUBLIC = 'application/vnd.ms-powerpoint.addin.macroEnabled.12'-CT_PRESENTATION_POTX_PUBLIC = 'application/vnd.openxmlformats-officedocument.presentationml.template'-CT_PRESENTATION_POTM_PUBLIC = 'application/vnd.ms-powerpoint.template.macroEnabled.12'--# FIXME: Other presentation inner content types but useless for now...-CT_PRESENTATION_SLIDE = 'application/vnd.openxmlformats-officedocument.presentationml.slide+xml'--# Spreadsheet document-CT_SPREADSHEET_XLAM_PUBLIC = 'application/vnd.ms-excel.addin.macroEnabled.12'-CT_SPREADSHEET_XLSB_PUBLIC = 'application/vnd.ms-excel.sheet.binary.macroEnabled.12'-CT_SPREADSHEET_XLSM_PUBLIC = 'application/vnd.ms-excel.sheet.macroEnabled.12'-CT_SPREADSHEET_XLSX_PUBLIC = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'-CT_SPREADSHEET_XLTM_PUBLIC = 'application/vnd.ms-excel.template.macroEnabled.12'-CT_SPREADSHEET_XLTX_PUBLIC = 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'--# FIXME: Other spreadsheet inner content types but useless for now...-CT_SPREADSHEET_WORKSHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'-CT_SPREADSHEET_SHAREDSTRINGS = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'---class ContentTypes(object):- """Handles features from the [Content_Types].xml file"""-- def __init__(self, content_types_file):- """Constructor- @param content_types_file: a file like object of [Content_Types].xml- """-- self.overrides = {} # {subpart content type: [xml file, ...], ...}- context = etree.iterparse(content_types_file, tag='{%s}Override' % ns.CONTENT_TYPES)- for dummy, override in context:- key = override.get('ContentType')- if self.overrides.has_key(key):- self.overrides[key].append(override.get('PartName'))- else:- self.overrides[key] = [override.get('PartName')]- return--- def getPathsForContentType(self, content_type):- """Finds the path in the document to that content type- @param content_type: a MIME content type- @return: list of paths in the content type- """-- return self.overrides.get(content_type, [])--- def getTreesFor(self, document, content_type):- """Provides all XML documents for that content type- @param document: a Document or subclass object- @param content_type: a MIME content type- @return: list of etree._ElementTree of that content type- """-- # Relative path without potential leading path separator- # otherwise os.path.join doesn't work- for rel_path in self.overrides[content_type]:- if rel_path[0] in ('/', '\\'):- rel_path = rel_path[1:]- file_path = os.path.join(document._cache_dir, rel_path)- yield etree.parse(utils.xmlFile(file_path, 'rb'))- return--- @property- def listMetaContentTypes(self):- """The content types with metadata- @return: ['application/xxx', ...]- """-- all_md_content_types = (- CT_CORE_PROPS,- CT_EXT_PROPS,- CT_CUSTOM_PROPS)- return [k for k in self.overrides.keys() if k in all_md_content_types]-diff --git a/ext/openxmllib/document.py b/ext/openxmllib/document.pydeleted file mode 100644index a4f0ecaf..00000000--- a/ext/openxmllib/document.py+++ /dev/null@@ -1,228 +0,0 @@-# -*- coding: utf-8 -*--"""-The document modules handles an Open XML document-"""-# $Id$--import os-import tempfile-import zipfile-import shutil-import fnmatch-import urllib--import lxml--import contenttypes-from namespaces import ns_map-from utils import xmlFile-from utils import toUnicode---class Document(object):- """Handling of Open XML document (all types)- Must be subclassed for various types of documents (word processing, ...)- Subclasses must provide these attributes:- - _extpattern_to_mime: a mapping ({'*.ext': 'aplication/xxx'}, ...}- - _text_extractors: a sequence of extractor objects that have:- - content_type: attribute that the extractor can handle- - indexableText(tree): method that returns a sequence of words from an lxml- ElementTree object.- """- # These properties must be overriden by subclasses- _extpattern_to_mime = {}- _text_extractors = []-- def __init__(self, file_, mime_type=None):- """Creating a new document- @param file_: An opened file(like) obj to the document- A file must be opened in 'rb' mode- """- self.mime_type = mime_type-- # Some shortcuts- op_sep = os.path.sep- op_join = os.path.join- op_isdir = os.path.isdir- op_dirname = os.path.dirname-- # Preliminary settings depending on input- self.filename = getattr(file_, 'name', None)- if self.filename is None and mime_type is None:- raise ValueError("Cannot guess mime type from such object, you should use the mime_type constructor arg.")-- # Need to make a real file for urllib.urlopen objects- if isinstance(file_, urllib.addinfourl):- fh, self._cache_file = tempfile.mkstemp()- fh = os.fdopen(fh, 'wb')- fh.write(file_.read())- fh.close()- file_.close()- file_ = open(self._cache_file, 'rb')-- # Inflating the file- self._cache_dir = tempfile.mkdtemp()- openxmldoc = zipfile.ZipFile(file_, 'r', zipfile.ZIP_DEFLATED)- for outpath in openxmldoc.namelist():- # We need to be sure that target dir exists- rel_outpath = op_sep.join(outpath.split('/'))- abs_outpath = op_join(self._cache_dir, rel_outpath)- abs_outdir = op_dirname(abs_outpath)- if not op_isdir(abs_outdir):- os.makedirs(abs_outdir)- fh = file(abs_outpath, 'wb')- fh.write(openxmldoc.read(outpath))- fh.close()- openxmldoc.close()- file_.close()-- # Getting the content types decl- ct_file = op_join(self._cache_dir, '[Content_Types].xml')- self.content_types = contenttypes.ContentTypes(xmlFile(ct_file, 'rb'))--- @property- def mimeType(self):- """The official MIME type for this document- @return: 'application/xxx' for this file- """- if self.mime_type:- # Supposed validated by the factory- return self.mime_type- for pattern, mime_type in self._extpattern_to_mime.items():- if fnmatch.fnmatch(self.filename, pattern):- return mime_type--- @property- def coreProperties(self):- """Document core properties- @return: mapping of metadata- """- return self._tagValuedProperties(contenttypes.CT_CORE_PROPS)--- @property- def extendedProperties(self):- """Document extended properties- @return: mapping of metadata- """- return self._tagValuedProperties(contenttypes.CT_EXT_PROPS)--- def _tagValuedProperties(self, content_type):- """Document properties for property files having constructs like- <ns:name>value</ns:name>- @param content_type: contenttypes.CT_CORE_PROPS or contenttypes.CT_EXT_PROPS- @return: mapping like {'property name': 'property value', ...}- """- rval = {}- if not content_type in self.content_types.listMetaContentTypes:- # We fail silently- return rval- for tree in self.content_types.getTreesFor(self, content_type):- for elt in tree.getroot().getchildren():- tag = elt.tag.split('}')[-1] # Removing namespace if any- rval[toUnicode(tag)] = toUnicode(elt.text)- return rval--- @property- def customProperties(self):- """Document custom properties- @return: mapping of metadata- FIXME: This is ugly. We do not convert the properties as indicated- with the http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes- namespace- """- rval = {}- if len(self.content_types.getPathsForContentType(contenttypes.CT_CUSTOM_PROPS)) == 0:- # We may have no custom properties at all.- return rval- XPath = lxml.etree.XPath # Class shortcut- properties_xpath = XPath('custom-properties:property', namespaces=ns_map)- propname_xpath = XPath('@name')- propvalue_xpath = XPath('*/text()')- for tree in self.content_types.getTreesFor(self, contenttypes.CT_CUSTOM_PROPS):- for elt in properties_xpath(tree.getroot()):- rval[toUnicode(propname_xpath(elt)[0])] = u" ".join(propvalue_xpath(elt))- return rval--- @property- def allProperties(self):- """Helper that merges core, extended and custom properties- @return: mapping of metadata- """- rval = {}- rval.update(self.coreProperties)- rval.update(self.extendedProperties)- rval.update(self.customProperties)- return rval--- def indexableText(self, include_properties=True):- """Note that self._text_extractors must be overriden by subclasses- """- text = set()- for extractor in self._text_extractors:- for tree in self.content_types.getTreesFor(self, extractor.content_type):- words = extractor.indexableText(tree)- text |= words-- if include_properties:- for prop_value in self.allProperties.values():- if prop_value is not None:- text.add(prop_value)- return u' '.join([word for word in text])-- def allText(self):- trees = set()- for content_type in self.content_types.overrides.keys():- for tree in self.content_types.getTreesFor(self, content_type):- trees.add(tree)- for tree in trees:- # textFromTree must be provided by subclasses- yield self.textFromTree(tree)--- def __del__(self):- """Cleanup at Document object deletion- """- self._cleanup()- return--- def _cleanup(self):- """Removing all temporary files- Be warned that "cleanuping" your document makes it unusable.- """- if hasattr(self, '_cache_dir'):- shutil.rmtree(self._cache_dir, ignore_errors=True)- if hasattr(self, '_cache_file'):- os.remove(self._cache_file)- return--- @classmethod- def canProcessMime(cls, mime_type):- """Check if we can process such mime type- @param mime_type: Mime type as 'application/xxx'- @return: True if we can process such mime- """- supported_mimes = cls._extpattern_to_mime.values()- return mime_type in supported_mimes--- @classmethod- def canProcessFilename(cls, filename):- """Check if we can process such file based on name- @param filename: File name as 'mydoc.docx'- @return: True if we can process such file- """- supported_patterns = cls._extpattern_to_mime.keys()- for pattern in supported_patterns:- if fnmatch.fnmatch(filename, pattern):- return True- return False-diff --git a/ext/openxmllib/namespaces.py b/ext/openxmllib/namespaces.pydeleted file mode 100644index 4aed448d..00000000--- a/ext/openxmllib/namespaces.py+++ /dev/null@@ -1,32 +0,0 @@-# -*- coding: utf-8 -*--"""-Namespaces that may be used in various XML files-"""-# $Id: namespaces.py 6800 2007-12-04 11:17:01Z glenfant $--CONTENT_TYPES = 'http://schemas.openxmlformats.org/package/2006/content-types'--# Properties (common for all openxml types)-CORE_PROPERTIES = 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'-EXTENDED_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'-CUSTOM_PROPERTIES = 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties'--# Wordprocessing-WP_MAIN = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'--# Spreadsheet-SS_MAIN = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'--# Presentation-PR_MAIN = 'http://schemas.openxmlformats.org/drawingml/2006/main'--# Namespaces mapping useful for XPath expression shortcuts-ns_map = {- 'content-types': CONTENT_TYPES,- 'core-properties': CORE_PROPERTIES,- 'extended-properties': EXTENDED_PROPERTIES,- 'custom-properties': CUSTOM_PROPERTIES,- 'wordprocessing-main': WP_MAIN,- 'spreadsheet-main': SS_MAIN,- 'presentation-main': PR_MAIN- }diff --git a/ext/openxmllib/presentation.py b/ext/openxmllib/presentation.pydeleted file mode 100644index 0942d731..00000000--- a/ext/openxmllib/presentation.py+++ /dev/null@@ -1,33 +0,0 @@-# -*- coding: utf-8 -*--"""-The presentation module handles a PresentationML Open XML document (read *.pptx)-"""-# $Id: presentation.py 6800 2007-12-04 11:17:01Z glenfant $--import document-from utils import IndexableTextExtractor-import contenttypes as ct-import namespaces--class PresentationDocument(document.Document):- """Handles specific features of a PresentationML document- """- _extpattern_to_mime = {- '*.pptx': ct.CT_PRESENTATION_PPTX_PUBLIC,- '*.pptm': ct.CT_PRESENTATION_PPTM_PUBLIC,- '*.potx': ct.CT_PRESENTATION_POTX_PUBLIC,- '*.potm': ct.CT_PRESENTATION_POTM_PUBLIC,- '*.ppsx': ct.CT_PRESENTATION_PPSX_PUBLIC,- '*.ppsm': ct.CT_PRESENTATION_PPSM_PUBLIC,- # FIXME: Not sure we can honour below types-# '*.ppam': ct.CT_PRESENTATION_PPAM_PUBLIC- }-- _text_extractors = (- IndexableTextExtractor(ct.CT_PRESENTATION_SLIDE, 'presentation-main:t', separator=' '),- )-- def textFromTree(self, tree):- for text in tree.xpath('//presentation-main:t/text()', namespaces=namespaces.ns_map):- yield ''.join(t.encode('utf-8') for t in text)-diff --git a/ext/openxmllib/shell.py b/ext/openxmllib/shell.pydeleted file mode 100644index 351cb2c7..00000000--- a/ext/openxmllib/shell.py+++ /dev/null@@ -1,125 +0,0 @@-#! python-# -*- coding: utf-8 -*--# $Id: shell.py 61 2009-12-18 10:53:19Z gilles.lenfant $-"""Command line tool"""--import os-import optparse-import time-import codecs-import locale-import types-import openxmllib--DEFAULT_CHARSET = locale.getpreferredencoding()-USAGE = """%%prog [options] command file-Version: %s-%s-Commands:-* `metadata' shows the file's metadata.-* `words' shows all words from file."""-VERSION = openxmllib.version---class Application(object):- """Command line utility showing openxml document informations."""-- def __init__(self):-- def check_charset_option(option, opt_str, value, parser):- """Value must be a valid charset"""- try:- dummy = codecs.lookup(value)- except LookupError, e:- raise optparse.OptionValueError(- "Charset '%s' in unknown or not supported by your sytem."- % value)- setattr(parser.values, option.dest, value)- return-- parser = optparse.OptionParser(- usage=USAGE % (VERSION, self.__class__.__doc__),- version=VERSION)- parser.add_option(- '-c', '--charset', dest='charset', default=DEFAULT_CHARSET,- type='string', action='callback', callback=check_charset_option,- help="Converts output to this charset (default %s)" % DEFAULT_CHARSET- )- parser.add_option(- '-v', '--verbosity', dest='verbosity', default=0, action='count',- help="Adds verbosity for each '-v'")- self.options, self.args = parser.parse_args()- if (len(self.args) < 2- or self.args[0] not in self.commands.keys()):- parser.error("Invalid arguments")- self.filenames = self.args[1:]- return-- def run(self):- self.commands[self.args[0]](self)- return-- def metadataCmd(self):- self.log(1, "Showing metadata of %s.", ", ".join(self.filenames))- for filename in self.filenames:- self.showMetadata(filename)- return-- def wordsCmd(self):- self.log(1, "Showing words of %s.", ", ".join(self.filenames))- for filename in self.filenames:- self.showWords(filename)- return-- commands = {- 'metadata': metadataCmd,- 'words': wordsCmd- }-- def showMetadata(self, filename):- if not self.checkfile(filename):- return- self.log(1, "Processing %s...", filename)- doc = openxmllib.openXmlDocument(path=filename)- self.log(2, "Core properties:")- for k, v in doc.coreProperties.items():- print "%s: %s" % (self.recode(k), self.recode(v))- self.log(2, "Extended properties:")- for k, v in doc.extendedProperties.items():- print "%s: %s" % (self.recode(k), self.recode(v))- self.log(2, "Custom properties:")- for k, v in doc.customProperties.items():- print "%s: %s" % (self.recode(k), self.recode(v))- return-- def showWords(self, filename):- if not self.checkfile(filename):- return- self.log(1, "Processing %s...", filename)- start_time = time.time()- doc = openxmllib.openXmlDocument(path=filename)- text = doc.indexableText(include_properties=False)- duration = time.time() - start_time- print self.recode(text)- self.log(1, "Words extracted in %s second(s)", duration)- return-- def checkfile(self, filename):- if not os.path.isfile(filename):- self.log(0, "'%s' is not a file, skipped", filename)- return False- return True-- def log(self, required_verbosity, message, *args):- if self.options.verbosity >= required_verbosity:- print message % args- return-- def recode(self, utext):- if type(utext) is types.UnicodeType:- return utext.encode(self.options.charset, 'replace')- return utext--def openxmlinfo():- Application().run()- returndiff --git a/ext/openxmllib/spreadsheet.py b/ext/openxmllib/spreadsheet.pydeleted file mode 100644index f40c00e6..00000000--- a/ext/openxmllib/spreadsheet.py+++ /dev/null@@ -1,35 +0,0 @@-# -*- coding: utf-8 -*--"""-The spreadsheet module handles a SpreadsheetML Open XML document (read *.xlsx)-"""-# $Id: spreadsheet.py 6800 2007-12-04 11:17:01Z glenfant $--import document-from utils import IndexableTextExtractor-import contenttypes as ct-import namespaces---class SpreadsheetDocument(document.Document):- """Handles specific features of a SpreadsheetML document- """- _extpattern_to_mime = {- '*.xlsx': ct.CT_SPREADSHEET_XLSX_PUBLIC,- '*.xlsm': ct.CT_SPREADSHEET_XLSM_PUBLIC,- '*.xltx': ct.CT_SPREADSHEET_XLTX_PUBLIC,- '*.xltm': ct.CT_SPREADSHEET_XLTM_PUBLIC,- # FIXME: note sure we can honour below types...-# '*.xlam': ct.CT_SPREADSHEET_XLAM_PUBLIC,-# '*.xlsb': ct.CT_SPREADSHEET_XLSB_PUBLIC- }-- _text_extractors = (- IndexableTextExtractor(ct.CT_SPREADSHEET_SHAREDSTRINGS, 'spreadsheet-main:t', separator=' '),- )--- def textFromTree(self, tree):-- for text in tree.xpath('//spreadsheet-main:t/text()', namespaces=namespaces.ns_map):- yield ''.join(t.encode('utf-8') for t in text)-diff --git a/ext/openxmllib/utils.py b/ext/openxmllib/utils.pydeleted file mode 100644index 6a83e8b8..00000000--- a/ext/openxmllib/utils.py+++ /dev/null@@ -1,74 +0,0 @@-# -*- coding: utf-8 -*--"""Various utilities for openxmllib"""-# $Id: utils.py 6800 2007-12-04 11:17:01Z glenfant $--import re-from lxml import etree--from namespaces import ns_map--def xmlFile(path, mode='r'):- """lxml cannot parse XML files starting with a BOM- (see http://www.w3.org/TR/2000/REC-xml-20001006 in F.1.)- In case such XML file is used, we must skip these characters- So we open all XML files for read with 'xmlFile'.- TODO: File this issue to lxml ML or tracker (feature or bug ?)- """- fh = file(path, mode)- while fh.read(1) != '<': # Ignoring everything before '<?xml...'- pass- fh.seek(-1, 1)- return fh---def toUnicode(objekt):- """Safely converts anything returned by lxml services to unicode- @param objekt: anything- @return: the object itself if not a string, otherwise the unicode of the string- """- if not isinstance(objekt, str):- return objekt- return unicode(objekt, 'utf-8')---class IndexableTextExtractor(object):-- wordssearch_rx = re.compile(r'\w+', re.UNICODE)- text_extract_xpath = etree.XPath('text()')-- def __init__(self, content_type, *text_elements, **kwargs):- """Building the extractor- @param content_type: content_type of the part for which the extractor is defined- @param text_elements: default text elements. See self.addTextElement(...)- """- self.content_type = content_type- self.text_elts_xpaths = [etree.XPath('//' + te, namespaces=ns_map)- for te in text_elements]- if 'separator' in kwargs:- self.separator = kwargs['separator']- else:- self.separator = ''- return--- def indexableText(self, tree):- """Provides the indexable - search engine oriented - raw text- @param tree: an ElementTree- @return: set(["foo", "bar", ...])- """- rval = set()- root = tree.getroot()- for txp in self.text_elts_xpaths:- elts = txp(root)- texts = []- # Texts in element may be empty- for elt in elts:- text = self.text_extract_xpath(elt)- if len(text) > 0:- texts.append(text[0])- texts = self.separator.join(texts)- texts = [toUnicode(x) for x in self.wordssearch_rx.findall(texts)- if len(x) > 0]- rval |= set(texts)- return rval-diff --git a/ext/openxmllib/version.txt b/ext/openxmllib/version.txtdeleted file mode 100644index 238d6e88..00000000--- a/ext/openxmllib/version.txt+++ /dev/null@@ -1 +0,0 @@-1.0.7diff --git a/ext/openxmllib/wordprocessing.py b/ext/openxmllib/wordprocessing.pydeleted file mode 100644index 7c9a3179..00000000--- a/ext/openxmllib/wordprocessing.py+++ /dev/null@@ -1,32 +0,0 @@-# -*- coding: utf-8 -*--"""The wordprocessing module handles a WordprocessingML Open XML document (read *.docx)"""-# $Id: wordprocessing.py 6800 2007-12-04 11:17:01Z glenfant $--import document-from utils import IndexableTextExtractor-import contenttypes as ct-import namespaces---class WordprocessingDocument(document.Document):- """Handles specific features of a WordprocessingML document- """- _extpattern_to_mime = {- '*.docx': ct.CT_WORDPROC_DOCX_PUBLIC,- '*.docm': ct.CT_WORDPROC_DOCM_PUBLIC,- '*.dotx': ct.CT_WORDPROC_DOTX_PUBLIC,- '*.dotm': ct.CT_WORDPROC_DOTM_PUBLIC- }-- _text_extractors = (- IndexableTextExtractor(ct.CT_WORDPROC_DOCUMENT, 'wordprocessing-main:t', separator=''),- )-- def textFromTree(self, tree):- for paragraph in tree.xpath('//wordprocessing-main:p', namespaces=namespaces.ns_map):- path = '%s//wordprocessing-main:t/text()' % tree.getpath(paragraph)- nsmap = dict(paragraph.nsmap)- nsmap.update(namespaces.ns_map)- text = tree.xpath(path, namespaces=nsmap)- yield ''.join(t.encode('utf-8') for t in text)-diff --git a/ext/stem/LICENSE b/ext/stem/LICENSEdeleted file mode 100644index 65c5ca88..00000000--- a/ext/stem/LICENSE+++ /dev/null@@ -1,165 +0,0 @@- GNU LESSER GENERAL PUBLIC LICENSE- Version 3, 29 June 2007-- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>- Everyone is permitted to copy and distribute verbatim copies- of this license document, but changing it is not allowed.--- This version of the GNU Lesser General Public License incorporates-the terms and conditions of version 3 of the GNU General Public-License, supplemented by the additional permissions listed below.-- 0. Additional Definitions.-- As used herein, "this License" refers to version 3 of the GNU Lesser-General Public License, and the "GNU GPL" refers to version 3 of the GNU-General Public License.-- "The Library" refers to a covered work governed by this License,-other than an Application or a Combined Work as defined below.-- An "Application" is any work that makes use of an interface provided-by the Library, but which is not otherwise based on the Library.-Defining a subclass of a class defined by the Library is deemed a mode-of using an interface provided by the Library.-- A "Combined Work" is a work produced by combining or linking an-Application with the Library. The particular version of the Library-with which the Combined Work was made is also called the "Linked-Version".-- The "Minimal Corresponding Source" for a Combined Work means the-Corresponding Source for the Combined Work, excluding any source code-for portions of the Combined Work that, considered in isolation, are-based on the Application, and not on the Linked Version.-- The "Corresponding Application Code" for a Combined Work means the-object code and/or source code for the Application, including any data-and utility programs needed for reproducing the Combined Work from the-Application, but excluding the System Libraries of the Combined Work.-- 1. Exception to Section 3 of the GNU GPL.-- You may convey a covered work under sections 3 and 4 of this License-without being bound by section 3 of the GNU GPL.-- 2. Conveying Modified Versions.-- If you modify a copy of the Library, and, in your modifications, a-facility refers to a function or data to be supplied by an Application-that uses the facility (other than as an argument passed when the-facility is invoked), then you may convey a copy of the modified-version:-- a) under this License, provided that you make a good faith effort to- ensure that, in the event an Application does not supply the- function or data, the facility still operates, and performs- whatever part of its purpose remains meaningful, or-- b) under the GNU GPL, with none of the additional permissions of- this License applicable to that copy.-- 3. Object Code Incorporating Material from Library Header Files.-- The object code form of an Application may incorporate material from-a header file that is part of the Library. You may convey such object-code under terms of your choice, provided that, if the incorporated-material is not limited to numerical parameters, data structure-layouts and accessors, or small macros, inline functions and templates-(ten or fewer lines in length), you do both of the following:-- a) Give prominent notice with each copy of the object code that the- Library is used in it and that the Library and its use are- covered by this License.-- b) Accompany the object code with a copy of the GNU GPL and this license- document.-- 4. Combined Works.-- You may convey a Combined Work under terms of your choice that,-taken together, effectively do not restrict modification of the-portions of the Library contained in the Combined Work and reverse-engineering for debugging such modifications, if you also do each of-the following:-- a) Give prominent notice with each copy of the Combined Work that- the Library is used in it and that the Library and its use are- covered by this License.-- b) Accompany the Combined Work with a copy of the GNU GPL and this license- document.-- c) For a Combined Work that displays copyright notices during- execution, include the copyright notice for the Library among- these notices, as well as a reference directing the user to the- copies of the GNU GPL and this license document.-- d) Do one of the following:-- 0) Convey the Minimal Corresponding Source under the terms of this- License, and the Corresponding Application Code in a form- suitable for, and under terms that permit, the user to- recombine or relink the Application with a modified version of- the Linked Version to produce a modified Combined Work, in the- manner specified by section 6 of the GNU GPL for conveying- Corresponding Source.-- 1) Use a suitable shared library mechanism for linking with the- Library. A suitable mechanism is one that (a) uses at run time- a copy of the Library already present on the user's computer- system, and (b) will operate properly with a modified version- of the Library that is interface-compatible with the Linked- Version.-- e) Provide Installation Information, but only if you would otherwise- be required to provide such information under section 6 of the- GNU GPL, and only to the extent that such information is- necessary to install and execute a modified version of the- Combined Work produced by recombining or relinking the- Application with a modified version of the Linked Version. (If- you use option 4d0, the Installation Information must accompany- the Minimal Corresponding Source and Corresponding Application- Code. If you use option 4d1, you must provide the Installation- Information in the manner specified by section 6 of the GNU GPL- for conveying Corresponding Source.)-- 5. Combined Libraries.-- You may place library facilities that are a work based on the-Library side by side in a single library together with other library-facilities that are not Applications and are not covered by this-License, and convey such a combined library under terms of your-choice, if you do both of the following:-- a) Accompany the combined library with a copy of the same work based- on the Library, uncombined with any other library facilities,- conveyed under the terms of this License.-- b) Give prominent notice with the combined library that part of it- is a work based on the Library, and explaining where to find the- accompanying uncombined form of the same work.-- 6. Revised Versions of the GNU Lesser General Public License.-- The Free Software Foundation may publish revised and/or new versions-of the GNU Lesser General Public License from time to time. Such new-versions will be similar in spirit to the present version, but may-differ in detail to address new problems or concerns.-- Each version is given a distinguishing version number. If the-Library as you received it specifies that a certain numbered version-of the GNU Lesser General Public License "or any later version"-applies to it, you have the option of following the terms and-conditions either of that published version or of any later version-published by the Free Software Foundation. If the Library as you-received it does not specify a version number of the GNU Lesser-General Public License, you may choose any version of the GNU Lesser-General Public License ever published by the Free Software Foundation.-- If the Library as you received it specifies that a proxy can decide-whether future versions of the GNU Lesser General Public License shall-apply, that proxy's public statement of acceptance of any version is-permanent authorization for you to choose that version for the-Library.diff --git a/ext/stem/__init__.py b/ext/stem/__init__.pydeleted file mode 100644index 9ff12636..00000000--- a/ext/stem/__init__.py+++ /dev/null@@ -1,833 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Library for working with the tor process.--**Module Overview:**--::-- ControllerError - Base exception raised when using the controller.- |- ProtocolError - Malformed socket data.- |- OperationFailed - Tor was unable to successfully complete the operation.- | |- UnsatisfiableRequest - Tor was unable to satisfy a valid request.- | | +- CircuitExtensionFailed - Attempt to make or extend a circuit failed.- | |- DescriptorUnavailable - The given relay descriptor is unavailable.- | +- InvalidRequest - Invalid request.- | +- InvalidArguments - Invalid request parameters.- +- SocketError - Communication with the socket failed.- +- SocketClosed - Socket has been shut down.--.. data:: Runlevel (enum)-- Rating of importance used for event logging.-- =========== ===========- Runlevel Description- =========== ===========- **ERR** critical issues that impair tor's ability to function- **WARN** non-critical issues the user should be aware of- **NOTICE** information that may be helpful to the user- **INFO** high level runtime information- **DEBUG** low level runtime information- =========== ===========--.. data:: Signal (enum)-- Signals that the tor process will accept.-- ========================= ===========- Signal Description- ========================= ===========- **RELOAD** or **HUP** reloads our torrc- **SHUTDOWN** or **INT** shut down, waiting ShutdownWaitLength first if we're a relay- **DUMP** or **USR1** dumps information about open connections and circuits to our log- **DEBUG** or **USR2** switch our logging to the DEBUG runlevel- **HALT** or **TERM** exit tor immediately- **NEWNYM** switch to new circuits, so new application requests don't share any circuits with old ones (this also clears our DNS cache)- **CLEARDNSCACHE** clears cached DNS results- **HEARTBEAT** trigger a heartbeat log message- ========================= ===========--.. data:: Flag (enum)-- Flag assigned to tor relays by the authorities to indicate various- characteristics.-- **Note:** The BADDIRECTORY flag was `removed from tor <https://gitweb.torproject.org/torspec.git/commit/dir-spec.txt?id=2f012f1>`_.-- ================= ===========- Flag Description- ================= ===========- **AUTHORITY** relay is a directory authority- **BADEXIT** relay shouldn't be used as an exit due to being either problematic or malicious (`wiki <https://trac.torproject.org/projects/tor/wiki/doc/badRelays>`_)- **BADDIRECTORY** relay shouldn't be used for directory information- **EXIT** relay's exit policy makes it more useful as an exit rather than middle hop- **FAST** relay's suitable for high-bandwidth circuits- **GUARD** relay's suitable for being an entry guard (first hop)- **HSDIR** relay is being used as a v2 hidden service directory- **NAMED** relay can be referred to by its nickname- **RUNNING** relay is currently usable- **STABLE** relay's suitable for long-lived circuits- **UNNAMED** relay isn't currently bound to a nickname- **V2DIR** relay supports the v2 directory protocol- **VALID** relay has been validated- ================= ===========--.. data:: CircStatus (enum)-- Statuses that a circuit can be in. Tor may provide statuses not in this enum.-- ============ ===========- CircStatus Description- ============ ===========- **LAUNCHED** new circuit was created- **BUILT** circuit finished being created and can accept traffic- **EXTENDED** circuit has been extended by a hop- **FAILED** circuit construction failed- **CLOSED** circuit has been closed- ============ ===========--.. data:: CircBuildFlag (enum)-- Attributes about how a circuit is built. These were introduced in tor version- 0.2.3.11. Tor may provide flags not in this enum.-- ================= ===========- CircBuildFlag Description- ================= ===========- **ONEHOP_TUNNEL** single hop circuit to fetch directory information- **IS_INTERNAL** circuit that won't be used for client traffic- **NEED_CAPACITY** circuit only includes high capacity relays- **NEED_UPTIME** circuit only includes relays with a high uptime- ================= ===========--.. data:: CircPurpose (enum)-- Description of what a circuit is intended for. These were introduced in tor- version 0.2.1.6. Tor may provide purposes not in this enum.-- ==================== ===========- CircPurpose Description- ==================== ===========- **GENERAL** client traffic or fetching directory information- **HS_CLIENT_INTRO** client side introduction point for a hidden service circuit- **HS_CLIENT_REND** client side hidden service rendezvous circuit- **HS_SERVICE_INTRO** server side introduction point for a hidden service circuit- **HS_SERVICE_REND** server side hidden service rendezvous circuit- **TESTING** testing to see if we're reachable, so we can be used as a relay- **CONTROLLER** circuit that was built by a controller- **MEASURE_TIMEOUT** circuit being kept around to see how long it takes- ==================== ===========--.. data:: CircClosureReason (enum)-- Reason that a circuit is being closed or failed to be established. Tor may- provide reasons not in this enum.-- ========================= ===========- CircClosureReason Description- ========================= ===========- **NONE** no reason given- **TORPROTOCOL** violation in the tor protocol- **INTERNAL** internal error- **REQUESTED** requested by the client via a TRUNCATE command- **HIBERNATING** relay is currently hibernating- **RESOURCELIMIT** relay is out of memory, sockets, or circuit IDs- **CONNECTFAILED** unable to contact the relay- **OR_IDENTITY** relay had the wrong OR identification- **OR_CONN_CLOSED** connection failed after being established- **FINISHED** circuit has expired (see tor's MaxCircuitDirtiness config option)- **TIMEOUT** circuit construction timed out- **DESTROYED** circuit unexpectedly closed- **NOPATH** not enough relays to make a circuit- **NOSUCHSERVICE** requested hidden service does not exist- **MEASUREMENT_EXPIRED** same as **TIMEOUT** except that it was left open for measurement purposes- ========================= ===========--.. data:: CircEvent (enum)-- Type of change reflected in a circuit by a CIRC_MINOR event. Tor may provide- event types not in this enum.-- ===================== ===========- CircEvent Description- ===================== ===========- **PURPOSE_CHANGED** circuit purpose or hidden service state has changed- **CANNIBALIZED** circuit connections are being reused for a different circuit- ===================== ===========--.. data:: HiddenServiceState (enum)-- State that a hidden service circuit can have. These were introduced in tor- version 0.2.3.11. Tor may provide states not in this enum.-- Enumerations fall into four groups based on their prefix...-- ======= ===========- Prefix Description- ======= ===========- HSCI_* client-side introduction-point- HSCR_* client-side rendezvous-point- HSSI_* service-side introduction-point- HSSR_* service-side rendezvous-point- ======= ===========-- ============================= ===========- HiddenServiceState Description- ============================= ===========- **HSCI_CONNECTING** connecting to the introductory point- **HSCI_INTRO_SENT** sent INTRODUCE1 and awaiting a reply- **HSCI_DONE** received a reply, circuit is closing- **HSCR_CONNECTING** connecting to the introductory point- **HSCR_ESTABLISHED_IDLE** rendezvous-point established, awaiting an introduction- **HSCR_ESTABLISHED_WAITING** introduction received, awaiting a rend- **HSCR_JOINED** connected to the hidden service- **HSSI_CONNECTING** connecting to the introductory point- **HSSI_ESTABLISHED** established introductory point- **HSSR_CONNECTING** connecting to the introductory point- **HSSR_JOINED** connected to the rendezvous-point- ============================= ===========--.. data:: RelayEndReason (enum)-- Reasons why the stream is to be closed.-- =================== ===========- RelayEndReason Description- =================== ===========- **MISC** none of the following reasons- **RESOLVEFAILED** unable to resolve the hostname- **CONNECTREFUSED** remote host refused the connection- **EXITPOLICY** OR refuses to connect to the destination- **DESTROY** circuit is being shut down- **DONE** connection has been closed- **TIMEOUT** connection timed out- **NOROUTE** routing error while contacting the destination- **HIBERNATING** relay is temporarily hibernating- **INTERNAL** internal error at the relay- **RESOURCELIMIT** relay has insufficient resources to service the request- **CONNRESET** connection was unexpectedly reset- **TORPROTOCOL** violation in the tor protocol- **NOTDIRECTORY** directory information requested from a relay that isn't mirroring it- =================== ===========--.. data:: StreamStatus (enum)-- State that a stream going through tor can have. Tor may provide states not in- this enum.-- ================= ===========- StreamStatus Description- ================= ===========- **NEW** request for a new connection- **NEWRESOLVE** request to resolve an address- **REMAP** address is being re-mapped to another- **SENTCONNECT** sent a connect cell along a circuit- **SENTRESOLVE** sent a resolve cell along a circuit- **SUCCEEDED** stream has been established- **FAILED** stream is detached, and won't be re-established- **DETACHED** stream is detached, but might be re-established- **CLOSED** stream has closed- ================= ===========--.. data:: StreamClosureReason (enum)-- Reason that a stream is being closed or failed to be established. This- includes all values in the :data:`~stem.RelayEndReason` enumeration as- well as the following. Tor may provide reasons not in this enum.-- ===================== ===========- StreamClosureReason Description- ===================== ===========- **END** endpoint has sent a RELAY_END cell- **PRIVATE_ADDR** endpoint was a private address (127.0.0.1, 10.0.0.1, etc)- ===================== ===========--.. data:: StreamSource (enum)-- Cause of a stream being remapped to another address. Tor may provide sources- not in this enum.-- ============= ===========- StreamSource Description- ============= ===========- **CACHE** tor is remapping because of a cached answer- **EXIT** exit relay requested the remap- ============= ===========--.. data:: StreamPurpose (enum)-- Purpsoe of the stream. This is only provided with new streams and tor may- provide purposes not in this enum.-- ================= ===========- StreamPurpose Description- ================= ===========- **DIR_FETCH** fetching directory information (descriptors, consensus, etc)- **DIR_UPLOAD** uploading our descriptor to an authority- **DNS_REQUEST** user initiated DNS request- **DIRPORT_TEST** checking that our directory port is reachable externally- **USER** either relaying user traffic or not one of the above categories- ================= ===========--.. data:: ORStatus (enum)-- State that an OR connection can have. Tor may provide states not in this- enum.-- =============== ===========- ORStatus Description- =============== ===========- **NEW** received OR connection, starting server-side handshake- **LAUNCHED** launched outbound OR connection, starting client-side handshake- **CONNECTED** OR connection has been established- **FAILED** attempt to establish OR connection failed- **CLOSED** OR connection has been closed- =============== ===========--.. data:: ORClosureReason (enum)-- Reason that an OR connection is being closed or failed to be established. Tor- may provide reasons not in this enum.-- =================== ===========- ORClosureReason Description- =================== ===========- **DONE** OR connection shut down cleanly- **CONNECTREFUSED** got a ECONNREFUSED when connecting to the relay- **IDENTITY** identity of the relay wasn't what we expected- **CONNECTRESET** got a ECONNRESET or similar error from relay- **TIMEOUT** got a ETIMEOUT or similar error from relay- **NOROUTE** got a ENOTCONN, ENETUNREACH, ENETDOWN, EHOSTUNREACH, or similar error from relay- **IOERROR** got a different kind of error from relay- **RESOURCELIMIT** relay has insufficient resources to service the request- **MISC** connection refused for another reason- **PT_MISSING** no pluggable transport was available- =================== ===========--.. data:: AuthDescriptorAction (enum)-- Actions that directory authorities might take with relay descriptors. Tor may- provide reasons not in this enum.-- ===================== ===========- AuthDescriptorAction Description- ===================== ===========- **ACCEPTED** accepting the descriptor as the newest version- **DROPPED** descriptor rejected without notifying the relay- **REJECTED** relay notified that its descriptor has been rejected- ===================== ===========--.. data:: StatusType (enum)-- Sources for tor status events. Tor may provide types not in this enum.-- ============= ===========- StatusType Description- ============= ===========- **GENERAL** general tor activity, not specifically as a client or relay- **CLIENT** related to our activity as a tor client- **SERVER** related to our activity as a tor relay- ============= ===========--.. data:: GuardType (enum)-- Use a guard relay can be for. Tor may provide types not in this enum.-- =========== ===========- GuardType Description- =========== ===========- **ENTRY** used to connect to the tor network- =========== ===========--.. data:: GuardStatus (enum)-- Status a guard relay can have. Tor may provide types not in this enum.-- ============= ===========- GuardStatus Description- ============= ===========- **NEW** new guard that we weren't previously using- **DROPPED** removed from use as one of our guards- **UP** guard is now reachable- **DOWN** guard is now unreachable- **BAD** consensus or relay considers this relay to be unusable as a guard- **GOOD** consensus or relay considers this relay to be usable as a guard- ============= ===========--.. data:: TimeoutSetType (enum)-- Way in which the timeout value of a circuit is changing. Tor may provide- types not in this enum.-- =============== ===========- TimeoutSetType Description- =============== ===========- **COMPUTED** tor has computed a new timeout based on prior circuits- **RESET** timeout reverted to its default- **SUSPENDED** timeout reverted to its default until network connectivity has recovered- **DISCARD** throwing out timeout value from when the network was down- **RESUME** resumed calculations to determine the proper timeout- =============== ===========--.. data:: ConnectionType (enum)-- Purpose for a tor connection. Tor may provide types not in this enum.-- The meaning behind these values is a bit unclear, pending :trac:`10086`.-- =============== ===========- ConnectionType Description- =============== ===========- **OR** carrying traffic within the tor network- **DIR** fetching or sending tor descriptor data- **EXIT** carrying traffic between the tor network and an external destination- =============== ===========--.. data:: TokenBucket (enum)-- Bucket categories of TB_EMPTY events.-- =============== ===========- TokenBucket Description- =============== ===========- **GLOBAL** global token bucket- **RELAY** relay token bucket- **ORCONN** bucket used for OR connections- =============== ===========--.. data:: HSDescAction (enum)-- Action beeing taken in a HS_DESC event.-- =============== ===========- HSDescAction Description- =============== ===========- **REQUESTED** uncached hidden service descriptor is being requested- **UPLOAD** descriptor is being uploaded with HSPOST- **RECEIVED** hidden service descriptor has been retrieved- **UPLOADED** descriptor was uploaded with HSPOST- **IGNORE** fetched descriptor was ignored because we already have its v0 descriptor- **FAILED** we were unable to retrieve the descriptor- =============== ===========--.. data:: HSDescReason (enum)-- Reason for the hidden service descriptor to fail to be fetched.-- =================== ===========- HSDescReason Description- =================== ===========- **BAD_DESC** descriptor was unparseable- **QUERY_REJECTED** hidden service directory refused to provide the descriptor- **UPLOAD_REJECTED** descriptor was rejected by the hidden service directory- **NOT_FOUND** descriptor with the given identifier wasn't found- **UNEXPECTED** failure type is unknown- =================== ===========--.. data:: HSAuth (enum)-- Type of authentication being used for a HS_DESC event.-- ================= ===========- HSAuth Description- ================= ===========- **NO_AUTH** no authentication- **BASIC_AUTH** general hidden service authentication- **STEALTH_AUTH** authentication method that hides service activity from unauthorized clients- **UNKNOWN** unrecognized method of authentication- ================= ===========-"""--__version__ = '1.4.1'-__author__ = 'Damian Johnson'-__contact__ = '[email protected]'-__url__ = 'https://stem.torproject.org/'-__license__ = 'LGPLv3'--__all__ = [- 'descriptor',- 'response',- 'util',- 'connection',- 'control',- 'exit_policy',- 'prereq',- 'process',- 'socket',- 'version',- 'ControllerError',- 'ProtocolError',- 'OperationFailed',- 'UnsatisfiableRequest',- 'CircuitExtensionFailed',- 'DescriptorUnavailable',- 'InvalidRequest',- 'InvalidArguments',- 'SocketError',- 'SocketClosed',- 'Runlevel',- 'Signal',- 'Flag',- 'CircStatus',- 'CircBuildFlag',- 'CircPurpose',- 'CircClosureReason',- 'CircEvent',- 'HiddenServiceState',- 'HSAuth',- 'HSDescAction',- 'HSDescReason',- 'RelayEndReason',- 'StreamStatus',- 'StreamClosureReason',- 'StreamSource',- 'StreamPurpose',- 'ORStatus',- 'ORClosureReason',- 'AuthDescriptorAction',- 'StatusType',- 'GuardType',- 'GuardStatus',- 'TimeoutSetType',-]--import stem.prereq--if stem.prereq.is_python_3():- str_type = str- int_type = int-else:- str_type = unicode- int_type = long--import stem.util.enum--# Constant to indicate an undefined argument default. Usually we'd use None for-# this, but users will commonly provide None as the argument so need something-# else fairly unique...--UNDEFINED = '<Undefined_ >'---class ControllerError(Exception):- 'Base error for controller communication issues.'---class ProtocolError(ControllerError):- 'Malformed content from the control socket.'---class OperationFailed(ControllerError):- """- Base exception class for failed operations that return an error code-- :var str code: error code returned by Tor- :var str message: error message returned by Tor or a human readable error- message- """-- def __init__(self, code = None, message = None):- super(ControllerError, self).__init__(message)- self.code = code- self.message = message---class UnsatisfiableRequest(OperationFailed):- """- Exception raised if Tor was unable to process our request.- """---class CircuitExtensionFailed(UnsatisfiableRequest):- """- An attempt to create or extend a circuit failed.-- :var stem.response.CircuitEvent circ: response notifying us of the failure- """-- def __init__(self, message, circ = None):- super(CircuitExtensionFailed, self).__init__(message = message)- self.circ = circ---class DescriptorUnavailable(OperationFailed):- """- Tor was unable to provide a descriptor for the given relay.- """-- def __init__(self, message):- super(DescriptorUnavailable, self).__init__(message = message)---class InvalidRequest(OperationFailed):- """- Exception raised when the request was invalid or malformed.- """---class InvalidArguments(InvalidRequest):- """- Exception class for requests which had invalid arguments.-- :var str code: error code returned by Tor- :var str message: error message returned by Tor or a human readable error- message- :var list arguments: a list of arguments which were invalid- """-- def __init__(self, code = None, message = None, arguments = None):- super(InvalidArguments, self).__init__(code, message)- self.arguments = arguments---class SocketError(ControllerError):- 'Error arose while communicating with the control socket.'---class SocketClosed(SocketError):- 'Control socket was closed before completing the message.'--Runlevel = stem.util.enum.UppercaseEnum(- 'DEBUG',- 'INFO',- 'NOTICE',- 'WARN',- 'ERR',-)--Flag = stem.util.enum.Enum(- ('AUTHORITY', 'Authority'),- ('BADEXIT', 'BadExit'),- ('BADDIRECTORY', 'BadDirectory'),- ('EXIT', 'Exit'),- ('FAST', 'Fast'),- ('GUARD', 'Guard'),- ('HSDIR', 'HSDir'),- ('NAMED', 'Named'),- ('RUNNING', 'Running'),- ('STABLE', 'Stable'),- ('UNNAMED', 'Unnamed'),- ('V2DIR', 'V2Dir'),- ('V3DIR', 'V3Dir'),- ('VALID', 'Valid'),-)--Signal = stem.util.enum.UppercaseEnum(- 'RELOAD',- 'HUP',- 'SHUTDOWN',- 'INT',- 'DUMP',- 'USR1',- 'DEBUG',- 'USR2',- 'HALT',- 'TERM',- 'NEWNYM',- 'CLEARDNSCACHE',- 'HEARTBEAT',-)--CircStatus = stem.util.enum.UppercaseEnum(- 'LAUNCHED',- 'BUILT',- 'EXTENDED',- 'FAILED',- 'CLOSED',-)--CircBuildFlag = stem.util.enum.UppercaseEnum(- 'ONEHOP_TUNNEL',- 'IS_INTERNAL',- 'NEED_CAPACITY',- 'NEED_UPTIME',-)--CircPurpose = stem.util.enum.UppercaseEnum(- 'GENERAL',- 'HS_CLIENT_INTRO',- 'HS_CLIENT_REND',- 'HS_SERVICE_INTRO',- 'HS_SERVICE_REND',- 'TESTING',- 'CONTROLLER',- 'MEASURE_TIMEOUT',-)--CircClosureReason = stem.util.enum.UppercaseEnum(- 'NONE',- 'TORPROTOCOL',- 'INTERNAL',- 'REQUESTED',- 'HIBERNATING',- 'RESOURCELIMIT',- 'CONNECTFAILED',- 'OR_IDENTITY',- 'OR_CONN_CLOSED',- 'FINISHED',- 'TIMEOUT',- 'DESTROYED',- 'NOPATH',- 'NOSUCHSERVICE',- 'MEASUREMENT_EXPIRED',-)--CircEvent = stem.util.enum.UppercaseEnum(- 'PURPOSE_CHANGED',- 'CANNIBALIZED',-)--HiddenServiceState = stem.util.enum.UppercaseEnum(- 'HSCI_CONNECTING',- 'HSCI_INTRO_SENT',- 'HSCI_DONE',- 'HSCR_CONNECTING',- 'HSCR_ESTABLISHED_IDLE',- 'HSCR_ESTABLISHED_WAITING',- 'HSCR_JOINED',- 'HSSI_CONNECTING',- 'HSSI_ESTABLISHED',- 'HSSR_CONNECTING',- 'HSSR_JOINED',-)--RelayEndReason = stem.util.enum.UppercaseEnum(- 'MISC',- 'RESOLVEFAILED',- 'CONNECTREFUSED',- 'EXITPOLICY',- 'DESTROY',- 'DONE',- 'TIMEOUT',- 'NOROUTE',- 'HIBERNATING',- 'INTERNAL',- 'RESOURCELIMIT',- 'CONNRESET',- 'TORPROTOCOL',- 'NOTDIRECTORY',-)--StreamStatus = stem.util.enum.UppercaseEnum(- 'NEW',- 'NEWRESOLVE',- 'REMAP',- 'SENTCONNECT',- 'SENTRESOLVE',- 'SUCCEEDED',- 'FAILED',- 'DETACHED',- 'CLOSED',-)--# StreamClosureReason is a superset of RelayEndReason-StreamClosureReason = stem.util.enum.UppercaseEnum(*(RelayEndReason.keys() + [- 'END',- 'PRIVATE_ADDR',-]))--StreamSource = stem.util.enum.UppercaseEnum(- 'CACHE',- 'EXIT',-)--StreamPurpose = stem.util.enum.UppercaseEnum(- 'DIR_FETCH',- 'DIR_UPLOAD',- 'DNS_REQUEST',- 'DIRPORT_TEST',- 'USER',-)--ORStatus = stem.util.enum.UppercaseEnum(- 'NEW',- 'LAUNCHED',- 'CONNECTED',- 'FAILED',- 'CLOSED',-)--ORClosureReason = stem.util.enum.UppercaseEnum(- 'DONE',- 'CONNECTREFUSED',- 'IDENTITY',- 'CONNECTRESET',- 'TIMEOUT',- 'NOROUTE',- 'IOERROR',- 'RESOURCELIMIT',- 'MISC',- 'PT_MISSING',-)--AuthDescriptorAction = stem.util.enum.UppercaseEnum(- 'ACCEPTED',- 'DROPPED',- 'REJECTED',-)--StatusType = stem.util.enum.UppercaseEnum(- 'GENERAL',- 'CLIENT',- 'SERVER',-)--GuardType = stem.util.enum.UppercaseEnum(- 'ENTRY',-)--GuardStatus = stem.util.enum.UppercaseEnum(- 'NEW',- 'UP',- 'DOWN',- 'BAD',- 'GOOD',- 'DROPPED',-)--TimeoutSetType = stem.util.enum.UppercaseEnum(- 'COMPUTED',- 'RESET',- 'SUSPENDED',- 'DISCARD',- 'RESUME',-)--ConnectionType = stem.util.enum.UppercaseEnum(- 'OR',- 'DIR',- 'EXIT',-)--TokenBucket = stem.util.enum.UppercaseEnum(- 'GLOBAL',- 'RELAY',- 'ORCONN',-)--HSDescAction = stem.util.enum.UppercaseEnum(- 'REQUESTED',- 'UPLOAD',- 'RECEIVED',- 'UPLOADED',- 'IGNORE',- 'FAILED',-)--HSDescReason = stem.util.enum.UppercaseEnum(- 'BAD_DESC',- 'QUERY_REJECTED',- 'UPLOAD_REJECTED',- 'NOT_FOUND',- 'UNEXPECTED',-)--HSAuth = stem.util.enum.UppercaseEnum(- 'NO_AUTH',- 'BASIC_AUTH',- 'STEALTH_AUTH',- 'UNKNOWN',-)diff --git a/ext/stem/connection.py b/ext/stem/connection.pydeleted file mode 100644index fb85225e..00000000--- a/ext/stem/connection.py+++ /dev/null@@ -1,1284 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Functions for connecting and authenticating to the tor process.--The :func:`~stem.connection.connect` function give an easy, one line-method for getting an authenticated control connection. This is handy for CLI-applications and the python interactive interpreter, but does several things-that makes it undesirable for applications (uses stdin/stdout, suppresses-exceptions, etc).--::-- import sys-- from stem.connection import connect-- if __name__ == '__main__':- controller = connect()-- if not controller:- sys.exit(1) # unable to get a connection-- print 'Tor is running version %s' % controller.get_version()- controller.close()--::-- % python example.py- Tor is running version 0.2.4.10-alpha-dev (git-8be6058d8f31e578)--... or if Tor isn't running...--::-- % python example.py- [Errno 111] Connection refused--The :func:`~stem.connection.authenticate` function, however, gives easy but-fine-grained control over the authentication process. For instance...--::-- import sys- import getpass- import stem.connection- import stem.socket-- try:- control_socket = stem.socket.ControlPort(port = 9051)- except stem.SocketError as exc:- print 'Unable to connect to port 9051 (%s)' % exc- sys.exit(1)-- try:- stem.connection.authenticate(control_socket)- except stem.connection.IncorrectSocketType:- print 'Please check in your torrc that 9051 is the ControlPort.'- print 'Maybe you configured it to be the ORPort or SocksPort instead?'- sys.exit(1)- except stem.connection.MissingPassword:- controller_password = getpass.getpass('Controller password: ')-- try:- stem.connection.authenticate_password(control_socket, controller_password)- except stem.connection.PasswordAuthFailed:- print 'Unable to authenticate, password is incorrect'- sys.exit(1)- except stem.connection.AuthenticationFailure as exc:- print 'Unable to authenticate: %s' % exc- sys.exit(1)--**Module Overview:**--::-- connect - Simple method for getting authenticated control connection-- authenticate - Main method for authenticating to a control socket- authenticate_none - Authenticates to an open control socket- authenticate_password - Authenticates to a socket supporting password auth- authenticate_cookie - Authenticates to a socket supporting cookie auth- authenticate_safecookie - Authenticates to a socket supporting safecookie auth-- get_protocolinfo - Issues a PROTOCOLINFO query-- AuthenticationFailure - Base exception raised for authentication failures- |- UnrecognizedAuthMethods - Authentication methods are unsupported- |- IncorrectSocketType - Socket does not speak the tor control protocol- |- |- OpenAuthFailed - Failure when authenticating by an open socket- | +- OpenAuthRejected - Tor rejected this method of authentication- |- |- PasswordAuthFailed - Failure when authenticating by a password- | |- PasswordAuthRejected - Tor rejected this method of authentication- | |- IncorrectPassword - Password was rejected- | +- MissingPassword - Socket supports password auth but wasn't attempted- |- |- CookieAuthFailed - Failure when authenticating by a cookie- | |- CookieAuthRejected - Tor rejected this method of authentication- | |- IncorrectCookieValue - Authentication cookie was rejected- | |- IncorrectCookieSize - Size of the cookie file is incorrect- | |- UnreadableCookieFile - Unable to read the contents of the auth cookie- | +- AuthChallengeFailed - Failure completing the authchallenge request- | |- AuthChallengeUnsupported - Tor doesn't recognize the AUTHCHALLENGE command- | |- AuthSecurityFailure - Server provided the wrong nonce credentials- | |- InvalidClientNonce - The client nonce is invalid- | +- UnrecognizedAuthChallengeMethod - AUTHCHALLENGE does not support the given methods.- |- +- MissingAuthInfo - Unexpected PROTOCOLINFO response, missing auth info- |- NoAuthMethods - Missing any methods for authenticating- +- NoAuthCookie - Supports cookie auth but doesn't have its path--.. data:: AuthMethod (enum)-- Enumeration of PROTOCOLINFO responses for supported authentication methods.-- ============== ===========- AuthMethod Description- ============== ===========- **NONE** No authentication required.- **PASSWORD** Password required, see tor's HashedControlPassword option.- **COOKIE** Contents of the cookie file required, see tor's CookieAuthentication option.- **SAFECOOKIE** Need to reply to a hmac challenge using the contents of the cookie file.- **UNKNOWN** Tor provided one or more authentication methods that we don't recognize, probably something new.- ============== ===========-"""--import binascii-import getpass-import os--import stem.control-import stem.response-import stem.socket-import stem.util.connection-import stem.util.enum-import stem.util.str_tools-import stem.util.system-import stem.version--from stem.util import log--AuthMethod = stem.util.enum.Enum('NONE', 'PASSWORD', 'COOKIE', 'SAFECOOKIE', 'UNKNOWN')--CLIENT_HASH_CONSTANT = b'Tor safe cookie authentication controller-to-server hash'-SERVER_HASH_CONSTANT = b'Tor safe cookie authentication server-to-controller hash'--MISSING_PASSWORD_BUG_MSG = """-BUG: You provided a password but despite this stem reported that it was-missing. This shouldn't happen - please let us know about it!-- http://bugs.torproject.org-"""--UNRECOGNIZED_AUTH_TYPE_MSG = """-Tor is using a type of authentication we do not recognize...-- {auth_methods}--Please check that stem is up to date and if there is an existing issue on-'http://bugs.torproject.org'. If there isn't one then let us know!-"""---UNREADABLE_COOKIE_FILE_MSG = """-We were unable to read tor's authentication cookie...-- Path: {path}- Issue: {issue}-"""--WRONG_PORT_TYPE_MSG = """-Please check in your torrc that {port} is the ControlPort. Maybe you-configured it to be the ORPort or SocksPort instead?-"""--WRONG_SOCKET_TYPE_MSG = """-Unable to connect to tor. Are you sure the interface you specified belongs to-tor?-"""--CONNECT_MESSAGES = {- 'general_auth_failure': 'Unable to authenticate: {error}',- 'incorrect_password': 'Incorrect password',- 'no_control_port': "Unable to connect to tor. Maybe it's running without a ControlPort?",- 'password_prompt': 'Tor controller password:',- 'needs_password': 'Tor requires a password to authenticate',- 'socket_doesnt_exist': "The socket file you specified ({path}) doesn't exist",- 'tor_isnt_running': "Unable to connect to tor. Are you sure it's running?",- 'unable_to_use_port': 'Unable to connect to {address}:{port}: {error}',- 'unable_to_use_socket': "Unable to connect to '{path}': {error}",- 'missing_password_bug': MISSING_PASSWORD_BUG_MSG.strip(),- 'uncrcognized_auth_type': UNRECOGNIZED_AUTH_TYPE_MSG.strip(),- 'unreadable_cookie_file': UNREADABLE_COOKIE_FILE_MSG.strip(),- 'wrong_port_type': WRONG_PORT_TYPE_MSG.strip(),- 'wrong_socket_type': WRONG_SOCKET_TYPE_MSG.strip(),-}---def connect(control_port = ('127.0.0.1', 9051), control_socket = '/var/run/tor/control', password = None, password_prompt = False, chroot_path = None, controller = stem.control.Controller):- """- Convenience function for quickly getting a control connection. This is very- handy for debugging or CLI setup, handling setup and prompting for a password- if necessary (and none is provided). If any issues arise this prints a- description of the problem and returns **None**.-- If both a **control_port** and **control_socket** are provided then the- **control_socket** is tried first, and this provides a generic error message- if they're both unavailable.-- In much the same vein as git porcelain commands, users should not rely on- details of how this works. Messages and details of this function's behavior- could change in the future.-- .. versionadded:: 1.2.0-- :param tuple contol_port: address and port tuple, for instance **('127.0.0.1', 9051)**- :param str path: path where the control socket is located- :param str password: passphrase to authenticate to the socket- :param bool password_prompt: prompt for the controller password if it wasn't- supplied- :param str chroot_path: path prefix if in a chroot environment- :param Class controller: :class:`~stem.control.BaseController` subclass to be- returned, this provides a :class:`~stem.socket.ControlSocket` if **None**-- :returns: authenticated control connection, the type based on the controller argument-- :raises: **ValueError** if given an invalid control_port, or both- **control_port** and **control_socket** are **None**- """-- if control_port is None and control_socket is None:- raise ValueError('Neither a control port nor control socket were provided. Nothing to connect to.')- elif control_port:- if len(control_port) != 2:- raise ValueError('The control_port argument for connect() should be an (address, port) tuple.')- elif not stem.util.connection.is_valid_ipv4_address(control_port[0]):- raise ValueError("'%s' isn't a vaid IPv4 address" % control_port[0])- elif not stem.util.connection.is_valid_port(control_port[1]):- raise ValueError("'%s' isn't a valid port" % control_port[1])-- control_connection, error_msg = None, ''-- if control_socket:- if os.path.exists(control_socket):- try:- control_connection = stem.socket.ControlSocketFile(control_socket)- except stem.SocketError as exc:- error_msg = CONNECT_MESSAGES['unable_to_use_socket'].format(path = control_socket, error = exc)- else:- error_msg = CONNECT_MESSAGES['socket_doesnt_exist'].format(path = control_socket)-- if control_port and not control_connection:- address, port = control_port-- try:- control_connection = stem.socket.ControlPort(address, port)- except stem.SocketError as exc:- error_msg = CONNECT_MESSAGES['unable_to_use_port'].format(address = address, port = port, error = exc)-- # If unable to connect to either a control socket or port then finally fail- # out. If we only attempted to connect to one of them then provide the error- # output from that. Otherwise we provide a more generic error message.- #- # We check for a 'tor.real' process name because that's what TBB uses.-- if not control_connection:- if control_socket and control_port:- is_tor_running = stem.util.system.is_running('tor') or stem.util.system.is_running('tor.real')- error_msg = CONNECT_MESSAGES['no_control_port'] if is_tor_running else CONNECT_MESSAGES['tor_isnt_running']-- print(error_msg)- return None-- return _connect_auth(control_connection, password, password_prompt, chroot_path, controller)---def connect_port(address = '127.0.0.1', port = 9051, password = None, chroot_path = None, controller = stem.control.Controller):- """- Convenience function for quickly getting a control connection. This is very- handy for debugging or CLI setup, handling setup and prompting for a password- if necessary (and none is provided). If any issues arise this prints a- description of the problem and returns **None**.-- .. deprecated:: 1.2.0- Use :func:`~stem.connection.connect` instead.-- :param str address: ip address of the controller- :param int port: port number of the controller- :param str password: passphrase to authenticate to the socket- :param str chroot_path: path prefix if in a chroot environment- :param Class controller: :class:`~stem.control.BaseController` subclass to be- returned, this provides a :class:`~stem.socket.ControlSocket` if **None**-- :returns: authenticated control connection, the type based on the controller argument- """-- try:- control_port = stem.socket.ControlPort(address, port)- except stem.SocketError as exc:- print(exc)- return None-- return _connect_auth(control_port, password, True, chroot_path, controller)---def connect_socket_file(path = '/var/run/tor/control', password = None, chroot_path = None, controller = stem.control.Controller):- """- Convenience function for quickly getting a control connection. For more- information see the :func:`~stem.connection.connect_port` function.-- In much the same vein as git porcelain commands, users should not rely on- details of how this works. Messages or details of this function's behavior- might change in the future.-- .. deprecated:: 1.2.0- Use :func:`~stem.connection.connect` instead.-- :param str path: path where the control socket is located- :param str password: passphrase to authenticate to the socket- :param str chroot_path: path prefix if in a chroot environment- :param Class controller: :class:`~stem.control.BaseController` subclass to be- returned, this provides a :class:`~stem.socket.ControlSocket` if **None**-- :returns: authenticated control connection, the type based on the controller argument- """-- try:- control_socket = stem.socket.ControlSocketFile(path)- except stem.SocketError as exc:- print(exc)- return None-- return _connect_auth(control_socket, password, True, chroot_path, controller)---def _connect_auth(control_socket, password, password_prompt, chroot_path, controller):- """- Helper for the connect_* functions that authenticates the socket and- constructs the controller.-- :param stem.socket.ControlSocket control_socket: socket being authenticated to- :param str password: passphrase to authenticate to the socket- :param bool password_prompt: prompt for the controller password if it wasn't- supplied- :param str chroot_path: path prefix if in a chroot environment- :param Class controller: :class:`~stem.control.BaseController` subclass to be- returned, this provides a :class:`~stem.socket.ControlSocket` if **None**-- :returns: authenticated control connection, the type based on the controller argument- """-- try:- authenticate(control_socket, password, chroot_path)-- if controller is None:- return control_socket- else:- return controller(control_socket, is_authenticated = True)- except IncorrectSocketType:- if isinstance(control_socket, stem.socket.ControlPort):- print(CONNECT_MESSAGES['wrong_port_type'].format(port = control_socket.get_port()))- else:- print(CONNECT_MESSAGES['wrong_socket_type'])-- control_socket.close()- return None- except UnrecognizedAuthMethods as exc:- print(CONNECT_MESSAGES['uncrcognized_auth_type'].format(auth_methods = ', '.join(exc.unknown_auth_methods)))- control_socket.close()- return None- except IncorrectPassword:- print(CONNECT_MESSAGES['incorrect_password'])- control_socket.close()- return None- except MissingPassword:- if password is not None:- control_socket.close()- raise ValueError(CONNECT_MESSAGES['missing_password_bug'])-- if password_prompt:- try:- password = getpass.getpass(CONNECT_MESSAGES['password_prompt'] + ' ')- except KeyboardInterrupt:- control_socket.close()- return None-- return _connect_auth(control_socket, password, password_prompt, chroot_path, controller)- else:- print(CONNECT_MESSAGES['needs_password'])- control_socket.close()- return None- except UnreadableCookieFile as exc:- print(CONNECT_MESSAGES['unreadable_cookie_file'].format(path = exc.cookie_path, issue = str(exc)))- control_socket.close()- return None- except AuthenticationFailure as exc:- print(CONNECT_MESSAGES['general_auth_failure'].format(error = exc))- control_socket.close()- return None---def authenticate(controller, password = None, chroot_path = None, protocolinfo_response = None):- """- Authenticates to a control socket using the information provided by a- PROTOCOLINFO response. In practice this will often be all we need to- authenticate, raising an exception if all attempts to authenticate fail.-- All exceptions are subclasses of AuthenticationFailure so, in practice,- callers should catch the types of authentication failure that they care- about, then have a :class:`~stem.connection.AuthenticationFailure` catch-all- at the end.-- This can authenticate to either a :class:`~stem.control.BaseController` or- :class:`~stem.socket.ControlSocket`.-- :param controller: tor controller or socket to be authenticated- :param str password: passphrase to present to the socket if it uses password- authentication (skips password auth if **None**)- :param str chroot_path: path prefix if in a chroot environment- :param stem.response.protocolinfo.ProtocolInfoResponse protocolinfo_response:- tor protocolinfo response, this is retrieved on our own if **None**-- :raises: If all attempts to authenticate fails then this will raise a- :class:`~stem.connection.AuthenticationFailure` subclass. Since this may- try multiple authentication methods it may encounter multiple exceptions.- If so then the exception this raises is prioritized as follows...-- * :class:`stem.connection.IncorrectSocketType`-- The controller does not speak the tor control protocol. Most often this- happened because the user confused the SocksPort or ORPort with the- ControlPort.-- * :class:`stem.connection.UnrecognizedAuthMethods`-- All of the authentication methods tor will accept are new and- unrecognized. Please upgrade stem and, if that doesn't work, file a- ticket on 'trac.torproject.org' and I'd be happy to add support.-- * :class:`stem.connection.MissingPassword`-- We were unable to authenticate but didn't attempt password authentication- because none was provided. You should prompt the user for a password and- try again via 'authenticate_password'.-- * :class:`stem.connection.IncorrectPassword`-- We were provided with a password but it was incorrect.-- * :class:`stem.connection.IncorrectCookieSize`-- Tor allows for authentication by reading it a cookie file, but that file- is the wrong size to be an authentication cookie.-- * :class:`stem.connection.UnreadableCookieFile`-- Tor allows for authentication by reading it a cookie file, but we can't- read that file (probably due to permissions).-- * **\***:class:`stem.connection.IncorrectCookieValue`-- Tor allows for authentication by reading it a cookie file, but rejected- the contents of that file.-- * **\***:class:`stem.connection.AuthChallengeUnsupported`-- Tor doesn't recognize the AUTHCHALLENGE command. This is probably a Tor- version prior to SAFECOOKIE being implement, but this exception shouldn't- arise because we won't attempt SAFECOOKIE auth unless Tor claims to- support it.-- * **\***:class:`stem.connection.UnrecognizedAuthChallengeMethod`-- Tor couldn't recognize the AUTHCHALLENGE method Stem sent to it. This- shouldn't happen at all.-- * **\***:class:`stem.connection.InvalidClientNonce`-- Tor says that the client nonce provided by Stem during the AUTHCHALLENGE- process is invalid.-- * **\***:class:`stem.connection.AuthSecurityFailure`-- Nonce value provided by the server was invalid.-- * **\***:class:`stem.connection.OpenAuthRejected`-- Tor says that it allows for authentication without any credentials, but- then rejected our authentication attempt.-- * **\***:class:`stem.connection.MissingAuthInfo`-- Tor provided us with a PROTOCOLINFO reply that is technically valid, but- missing the information we need to authenticate.-- * **\***:class:`stem.connection.AuthenticationFailure`-- There are numerous other ways that authentication could have failed- including socket failures, malformed controller responses, etc. These- mostly constitute transient failures or bugs.-- **\*** In practice it is highly unusual for this to occur, being more of a- theoretical possibility rather than something you should expect. It's fine- to treat these as errors. If you have a use case where this commonly- happens, please file a ticket on 'trac.torproject.org'.-- In the future new :class:`~stem.connection.AuthenticationFailure`- subclasses may be added to allow for better error handling.- """-- if not protocolinfo_response:- try:- protocolinfo_response = get_protocolinfo(controller)- except stem.ProtocolError:- raise IncorrectSocketType('unable to use the control socket')- except stem.SocketError as exc:- raise AuthenticationFailure('socket connection failed (%s)' % exc)-- auth_methods = list(protocolinfo_response.auth_methods)- auth_exceptions = []-- if len(auth_methods) == 0:- raise NoAuthMethods('our PROTOCOLINFO response did not have any methods for authenticating')-- # remove authentication methods that are either unknown or for which we don't- # have an input- if AuthMethod.UNKNOWN in auth_methods:- auth_methods.remove(AuthMethod.UNKNOWN)-- unknown_methods = protocolinfo_response.unknown_auth_methods- plural_label = 's' if len(unknown_methods) > 1 else ''- methods_label = ', '.join(unknown_methods)-- # we... er, can't do anything with only unrecognized auth types- if not auth_methods:- exc_msg = 'unrecognized authentication method%s (%s)' % (plural_label, methods_label)- auth_exceptions.append(UnrecognizedAuthMethods(exc_msg, unknown_methods))- else:- log.debug('Authenticating to a socket with unrecognized auth method%s, ignoring them: %s' % (plural_label, methods_label))-- if protocolinfo_response.cookie_path is None:- for cookie_auth_method in (AuthMethod.COOKIE, AuthMethod.SAFECOOKIE):- if cookie_auth_method in auth_methods:- auth_methods.remove(cookie_auth_method)-- exc_msg = 'our PROTOCOLINFO response did not have the location of our authentication cookie'- auth_exceptions.append(NoAuthCookie(exc_msg, cookie_auth_method == AuthMethod.SAFECOOKIE))-- if AuthMethod.PASSWORD in auth_methods and password is None:- auth_methods.remove(AuthMethod.PASSWORD)- auth_exceptions.append(MissingPassword('no passphrase provided'))-- # iterating over AuthMethods so we can try them in this order- for auth_type in (AuthMethod.NONE, AuthMethod.PASSWORD, AuthMethod.SAFECOOKIE, AuthMethod.COOKIE):- if auth_type not in auth_methods:- continue-- try:- if auth_type == AuthMethod.NONE:- authenticate_none(controller, False)- elif auth_type == AuthMethod.PASSWORD:- authenticate_password(controller, password, False)- elif auth_type in (AuthMethod.COOKIE, AuthMethod.SAFECOOKIE):- cookie_path = protocolinfo_response.cookie_path-- if chroot_path:- cookie_path = os.path.join(chroot_path, cookie_path.lstrip(os.path.sep))-- if auth_type == AuthMethod.SAFECOOKIE:- authenticate_safecookie(controller, cookie_path, False)- else:- authenticate_cookie(controller, cookie_path, False)-- return # success!- except OpenAuthRejected as exc:- auth_exceptions.append(exc)- except IncorrectPassword as exc:- auth_exceptions.append(exc)- except PasswordAuthRejected as exc:- # Since the PROTOCOLINFO says password auth is available we can assume- # that if PasswordAuthRejected is raised it's being raised in error.- log.debug('The authenticate_password method raised a PasswordAuthRejected when password auth should be available. Stem may need to be corrected to recognize this response: %s' % exc)- auth_exceptions.append(IncorrectPassword(str(exc)))- except AuthSecurityFailure as exc:- log.info('Tor failed to provide the nonce expected for safecookie authentication. (%s)' % exc)- auth_exceptions.append(exc)- except (InvalidClientNonce, UnrecognizedAuthChallengeMethod, AuthChallengeFailed) as exc:- auth_exceptions.append(exc)- except (IncorrectCookieSize, UnreadableCookieFile, IncorrectCookieValue) as exc:- auth_exceptions.append(exc)- except CookieAuthRejected as exc:- auth_func = 'authenticate_safecookie' if exc.is_safecookie else 'authenticate_cookie'-- log.debug('The %s method raised a CookieAuthRejected when cookie auth should be available. Stem may need to be corrected to recognize this response: %s' % (auth_func, exc))- auth_exceptions.append(IncorrectCookieValue(str(exc), exc.cookie_path, exc.is_safecookie))- except stem.ControllerError as exc:- auth_exceptions.append(AuthenticationFailure(str(exc)))-- # All authentication attempts failed. Raise the exception that takes priority- # according to our pydocs.-- for exc_type in AUTHENTICATE_EXCEPTIONS:- for auth_exc in auth_exceptions:- if isinstance(auth_exc, exc_type):- raise auth_exc-- # We really, really shouldn't get here. It means that auth_exceptions is- # either empty or contains something that isn't an AuthenticationFailure.-- raise AssertionError('BUG: Authentication failed without providing a recognized exception: %s' % str(auth_exceptions))---def authenticate_none(controller, suppress_ctl_errors = True):- """- Authenticates to an open control socket. All control connections need to- authenticate before they can be used, even if tor hasn't been configured to- use any authentication.-- If authentication fails tor will disconnect and we'll make a best effort- attempt to re-establish the connection. This may not succeed, so check- :func:`~stem.socket.ControlSocket.is_alive` before using the socket further.-- This can authenticate to either a :class:`~stem.control.BaseController` or- :class:`~stem.socket.ControlSocket`.-- For general usage use the :func:`~stem.connection.authenticate` function- instead.-- :param controller: tor controller or socket to be authenticated- :param bool suppress_ctl_errors: reports raised- :class:`~stem.ControllerError` as authentication rejection if- **True**, otherwise they're re-raised-- :raises: :class:`stem.connection.OpenAuthRejected` if the empty authentication credentials aren't accepted- """-- try:- auth_response = _msg(controller, 'AUTHENTICATE')-- # if we got anything but an OK response then error- if str(auth_response) != 'OK':- try:- controller.connect()- except:- pass-- raise OpenAuthRejected(str(auth_response), auth_response)- except stem.ControllerError as exc:- try:- controller.connect()- except:- pass-- if not suppress_ctl_errors:- raise exc- else:- raise OpenAuthRejected('Socket failed (%s)' % exc)---def authenticate_password(controller, password, suppress_ctl_errors = True):- """- Authenticates to a control socket that uses a password (via the- HashedControlPassword torrc option). Quotes in the password are escaped.-- If authentication fails tor will disconnect and we'll make a best effort- attempt to re-establish the connection. This may not succeed, so check- :func:`~stem.socket.ControlSocket.is_alive` before using the socket further.-- If you use this function directly, rather than- :func:`~stem.connection.authenticate`, we may mistakenly raise a- PasswordAuthRejected rather than IncorrectPassword. This is because we rely- on tor's error messaging which is liable to change in future versions- (:trac:`4817`).-- This can authenticate to either a :class:`~stem.control.BaseController` or- :class:`~stem.socket.ControlSocket`.-- For general usage use the :func:`~stem.connection.authenticate` function- instead.-- :param controller: tor controller or socket to be authenticated- :param str password: passphrase to present to the socket- :param bool suppress_ctl_errors: reports raised- :class:`~stem.ControllerError` as authentication rejection if- **True**, otherwise they're re-raised-- :raises:- * :class:`stem.connection.PasswordAuthRejected` if the socket doesn't- accept password authentication- * :class:`stem.connection.IncorrectPassword` if the authentication- credentials aren't accepted- """-- # Escapes quotes. Tor can include those in the password hash, in which case- # it expects escaped quotes from the controller. For more information see...- # https://trac.torproject.org/projects/tor/ticket/4600-- password = password.replace('"', '\\"')-- try:- auth_response = _msg(controller, 'AUTHENTICATE "%s"' % password)-- # if we got anything but an OK response then error- if str(auth_response) != 'OK':- try:- controller.connect()- except:- pass-- # all we have to go on is the error message from tor...- # Password did not match HashedControlPassword value value from configuration...- # Password did not match HashedControlPassword *or*...-- if 'Password did not match HashedControlPassword' in str(auth_response):- raise IncorrectPassword(str(auth_response), auth_response)- else:- raise PasswordAuthRejected(str(auth_response), auth_response)- except stem.ControllerError as exc:- try:- controller.connect()- except:- pass-- if not suppress_ctl_errors:- raise exc- else:- raise PasswordAuthRejected('Socket failed (%s)' % exc)---def authenticate_cookie(controller, cookie_path, suppress_ctl_errors = True):- """- Authenticates to a control socket that uses the contents of an authentication- cookie (generated via the CookieAuthentication torrc option). This does basic- validation that this is a cookie before presenting the contents to the- socket.-- The :class:`~stem.connection.IncorrectCookieSize` and- :class:`~stem.connection.UnreadableCookieFile` exceptions take precedence- over the other types.-- If authentication fails tor will disconnect and we'll make a best effort- attempt to re-establish the connection. This may not succeed, so check- :func:`~stem.socket.ControlSocket.is_alive` before using the socket further.-- If you use this function directly, rather than- :func:`~stem.connection.authenticate`, we may mistakenly raise a- :class:`~stem.connection.CookieAuthRejected` rather than- :class:`~stem.connection.IncorrectCookieValue`. This is because we rely on- tor's error messaging which is liable to change in future versions- (:trac:`4817`).-- This can authenticate to either a :class:`~stem.control.BaseController` or- :class:`~stem.socket.ControlSocket`.-- For general usage use the :func:`~stem.connection.authenticate` function- instead.-- :param controller: tor controller or socket to be authenticated- :param str cookie_path: path of the authentication cookie to send to tor- :param bool suppress_ctl_errors: reports raised- :class:`~stem.ControllerError` as authentication rejection if- **True**, otherwise they're re-raised-- :raises:- * :class:`stem.connection.IncorrectCookieSize` if the cookie file's size- is wrong- * :class:`stem.connection.UnreadableCookieFile` if the cookie file doesn't- exist or we're unable to read it- * :class:`stem.connection.CookieAuthRejected` if cookie authentication is- attempted but the socket doesn't accept it- * :class:`stem.connection.IncorrectCookieValue` if the cookie file's value- is rejected- """-- cookie_data = _read_cookie(cookie_path, False)-- try:- # binascii.b2a_hex() takes a byte string and returns one too. With python 3- # this is a problem because string formatting for byte strings includes the- # b'' wrapper...- #- # >>> "AUTHENTICATE %s" % b'content'- # "AUTHENTICATE b'content'"- #- # This seems dumb but oh well. Converting the result to unicode so it won't- # misbehave.-- auth_token_hex = binascii.b2a_hex(stem.util.str_tools._to_bytes(cookie_data))- msg = 'AUTHENTICATE %s' % stem.util.str_tools._to_unicode(auth_token_hex)- auth_response = _msg(controller, msg)-- # if we got anything but an OK response then error- if str(auth_response) != 'OK':- try:- controller.connect()- except:- pass-- # all we have to go on is the error message from tor...- # ... Authentication cookie did not match expected value.- # ... *or* authentication cookie.-- if '*or* authentication cookie.' in str(auth_response) or \- 'Authentication cookie did not match expected value.' in str(auth_response):- raise IncorrectCookieValue(str(auth_response), cookie_path, False, auth_response)- else:- raise CookieAuthRejected(str(auth_response), cookie_path, False, auth_response)- except stem.ControllerError as exc:- try:- controller.connect()- except:- pass-- if not suppress_ctl_errors:- raise exc- else:- raise CookieAuthRejected('Socket failed (%s)' % exc, cookie_path, False)---def authenticate_safecookie(controller, cookie_path, suppress_ctl_errors = True):- """- Authenticates to a control socket using the safe cookie method, which is- enabled by setting the CookieAuthentication torrc option on Tor client's which- support it.-- Authentication with this is a two-step process...-- 1. send a nonce to the server and receives a challenge from the server for- the cookie's contents- 2. generate a hash digest using the challenge received in the first step, and- use it to authenticate the controller-- The :class:`~stem.connection.IncorrectCookieSize` and- :class:`~stem.connection.UnreadableCookieFile` exceptions take precedence- over the other exception types.-- The :class:`~stem.connection.AuthChallengeUnsupported`,- :class:`~stem.connection.UnrecognizedAuthChallengeMethod`,- :class:`~stem.connection.InvalidClientNonce` and- :class:`~stem.connection.CookieAuthRejected` exceptions are next in the order- of precedence. Depending on the reason, one of these is raised if the first- (AUTHCHALLENGE) step fails.-- In the second (AUTHENTICATE) step,- :class:`~stem.connection.IncorrectCookieValue` or- :class:`~stem.connection.CookieAuthRejected` maybe raised.-- If authentication fails tor will disconnect and we'll make a best effort- attempt to re-establish the connection. This may not succeed, so check- :func:`~stem.socket.ControlSocket.is_alive` before using the socket further.-- For general usage use the :func:`~stem.connection.authenticate` function- instead.-- :param controller: tor controller or socket to be authenticated- :param str cookie_path: path of the authentication cookie to send to tor- :param bool suppress_ctl_errors: reports raised- :class:`~stem.ControllerError` as authentication rejection if- **True**, otherwise they're re-raised-- :raises:- * :class:`stem.connection.IncorrectCookieSize` if the cookie file's size- is wrong- * :class:`stem.connection.UnreadableCookieFile` if the cookie file doesn't- exist or we're unable to read it- * :class:`stem.connection.CookieAuthRejected` if cookie authentication is- attempted but the socket doesn't accept it- * :class:`stem.connection.IncorrectCookieValue` if the cookie file's value- is rejected- * :class:`stem.connection.UnrecognizedAuthChallengeMethod` if the Tor- client fails to recognize the AuthChallenge method- * :class:`stem.connection.AuthChallengeUnsupported` if AUTHCHALLENGE is- unimplemented, or if unable to parse AUTHCHALLENGE response- * :class:`stem.connection.AuthSecurityFailure` if AUTHCHALLENGE's response- looks like a security attack- * :class:`stem.connection.InvalidClientNonce` if stem's AUTHCHALLENGE- client nonce is rejected for being invalid- """-- cookie_data = _read_cookie(cookie_path, True)- client_nonce = os.urandom(32)-- try:- client_nonce_hex = stem.util.str_tools._to_unicode(binascii.b2a_hex(client_nonce))- authchallenge_response = _msg(controller, 'AUTHCHALLENGE SAFECOOKIE %s' % client_nonce_hex)-- if not authchallenge_response.is_ok():- try:- controller.connect()- except:- pass-- authchallenge_response_str = str(authchallenge_response)-- if 'Authentication required.' in authchallenge_response_str:- raise AuthChallengeUnsupported("SAFECOOKIE authentication isn't supported", cookie_path)- elif 'AUTHCHALLENGE only supports' in authchallenge_response_str:- raise UnrecognizedAuthChallengeMethod(authchallenge_response_str, cookie_path)- elif 'Invalid base16 client nonce' in authchallenge_response_str:- raise InvalidClientNonce(authchallenge_response_str, cookie_path)- elif 'Cookie authentication is disabled' in authchallenge_response_str:- raise CookieAuthRejected(authchallenge_response_str, cookie_path, True)- else:- raise AuthChallengeFailed(authchallenge_response, cookie_path)- except stem.ControllerError as exc:- try:- controller.connect()- except:- pass-- if not suppress_ctl_errors:- raise exc- else:- raise AuthChallengeFailed('Socket failed (%s)' % exc, cookie_path, True)-- try:- stem.response.convert('AUTHCHALLENGE', authchallenge_response)- except stem.ProtocolError as exc:- if not suppress_ctl_errors:- raise exc- else:- raise AuthChallengeFailed('Unable to parse AUTHCHALLENGE response: %s' % exc, cookie_path)-- expected_server_hash = stem.util.connection._hmac_sha256(- SERVER_HASH_CONSTANT,- cookie_data + client_nonce + authchallenge_response.server_nonce)-- if not stem.util.connection._cryptovariables_equal(authchallenge_response.server_hash, expected_server_hash):- raise AuthSecurityFailure('Tor provided the wrong server nonce', cookie_path)-- try:- client_hash = stem.util.connection._hmac_sha256(- CLIENT_HASH_CONSTANT,- cookie_data + client_nonce + authchallenge_response.server_nonce)-- auth_response = _msg(controller, 'AUTHENTICATE %s' % stem.util.str_tools._to_unicode(binascii.b2a_hex(client_hash)))- except stem.ControllerError as exc:- try:- controller.connect()- except:- pass-- if not suppress_ctl_errors:- raise exc- else:- raise CookieAuthRejected('Socket failed (%s)' % exc, cookie_path, True, auth_response)-- # if we got anything but an OK response then err- if not auth_response.is_ok():- try:- controller.connect()- except:- pass-- # all we have to go on is the error message from tor...- # ... Safe cookie response did not match expected value- # ... *or* authentication cookie.-- if '*or* authentication cookie.' in str(auth_response) or \- 'Safe cookie response did not match expected value' in str(auth_response):- raise IncorrectCookieValue(str(auth_response), cookie_path, True, auth_response)- else:- raise CookieAuthRejected(str(auth_response), cookie_path, True, auth_response)---def get_protocolinfo(controller):- """- Issues a PROTOCOLINFO query to a control socket, getting information about- the tor process running on it. If the socket is already closed then it is- first reconnected.-- According to the control spec the cookie_file is an absolute path. However,- this often is not the case (especially for the Tor Browser Bundle). If the- path is relative then we'll make an attempt (which may not work) to correct- this (:trac:`1101`).-- This can authenticate to either a :class:`~stem.control.BaseController` or- :class:`~stem.socket.ControlSocket`.-- :param controller: tor controller or socket to be queried-- :returns: :class:`~stem.response.protocolinfo.ProtocolInfoResponse` provided by tor-- :raises:- * :class:`stem.ProtocolError` if the PROTOCOLINFO response is- malformed- * :class:`stem.SocketError` if problems arise in establishing or- using the socket- """-- try:- protocolinfo_response = _msg(controller, 'PROTOCOLINFO 1')- except:- protocolinfo_response = None-- # Tor hangs up on sockets after receiving a PROTOCOLINFO query if it isn't- # next followed by authentication. Transparently reconnect if that happens.-- if not protocolinfo_response or str(protocolinfo_response) == 'Authentication required.':- controller.connect()-- try:- protocolinfo_response = _msg(controller, 'PROTOCOLINFO 1')- except stem.SocketClosed as exc:- raise stem.SocketError(exc)-- stem.response.convert('PROTOCOLINFO', protocolinfo_response)-- # attempt to expand relative cookie paths-- if protocolinfo_response.cookie_path:- _expand_cookie_path(protocolinfo_response, stem.util.system.pid_by_name, 'tor')-- # attempt to expand relative cookie paths via the control port or socket file-- if isinstance(controller, stem.socket.ControlSocket):- control_socket = controller- else:- control_socket = controller.get_socket()-- if isinstance(control_socket, stem.socket.ControlPort):- if control_socket.get_address() == '127.0.0.1':- pid_method = stem.util.system.pid_by_port- _expand_cookie_path(protocolinfo_response, pid_method, control_socket.get_port())- elif isinstance(control_socket, stem.socket.ControlSocketFile):- pid_method = stem.util.system.pid_by_open_file- _expand_cookie_path(protocolinfo_response, pid_method, control_socket.get_socket_path())-- return protocolinfo_response---def _msg(controller, message):- """- Sends and receives a message with either a- :class:`~stem.socket.ControlSocket` or :class:`~stem.control.BaseController`.- """-- if isinstance(controller, stem.socket.ControlSocket):- controller.send(message)- return controller.recv()- else:- return controller.msg(message)---def _read_cookie(cookie_path, is_safecookie):- """- Provides the contents of a given cookie file.-- :param str cookie_path: absolute path of the cookie file- :param bool is_safecookie: **True** if this was for SAFECOOKIE- authentication, **False** if for COOKIE-- :raises:- * :class:`stem.connection.UnreadableCookieFile` if the cookie file is- unreadable- * :class:`stem.connection.IncorrectCookieSize` if the cookie size is- incorrect (not 32 bytes)- """-- if not os.path.exists(cookie_path):- exc_msg = "Authentication failed: '%s' doesn't exist" % cookie_path- raise UnreadableCookieFile(exc_msg, cookie_path, is_safecookie)-- # Abort if the file isn't 32 bytes long. This is to avoid exposing arbitrary- # file content to the port.- #- # Without this a malicious socket could, for instance, claim that- # '~/.bash_history' or '~/.ssh/id_rsa' was its authentication cookie to trick- # us into reading it for them with our current permissions.- #- # https://trac.torproject.org/projects/tor/ticket/4303-- auth_cookie_size = os.path.getsize(cookie_path)-- if auth_cookie_size != 32:- exc_msg = "Authentication failed: authentication cookie '%s' is the wrong size (%i bytes instead of 32)" % (cookie_path, auth_cookie_size)- raise IncorrectCookieSize(exc_msg, cookie_path, is_safecookie)-- try:- with open(cookie_path, 'rb', 0) as f:- return f.read()- except IOError as exc:- exc_msg = "Authentication failed: unable to read '%s' (%s)" % (cookie_path, exc)- raise UnreadableCookieFile(exc_msg, cookie_path, is_safecookie)---def _expand_cookie_path(protocolinfo_response, pid_resolver, pid_resolution_arg):- """- Attempts to expand a relative cookie path with the given pid resolver. This- leaves the cookie_path alone if it's already absolute, **None**, or the- system calls fail.- """-- cookie_path = protocolinfo_response.cookie_path- if cookie_path and not os.path.isabs(cookie_path):- try:- tor_pid = pid_resolver(pid_resolution_arg)-- if not tor_pid:- raise IOError('pid lookup failed')-- tor_cwd = stem.util.system.cwd(tor_pid)-- if not tor_cwd:- raise IOError('cwd lookup failed')-- cookie_path = stem.util.system.expand_path(cookie_path, tor_cwd)- except IOError as exc:- resolver_labels = {- stem.util.system.pid_by_name: ' by name',- stem.util.system.pid_by_port: ' by port',- stem.util.system.pid_by_open_file: ' by socket file',- }-- pid_resolver_label = resolver_labels.get(pid_resolver, '')- log.debug('unable to expand relative tor cookie path%s: %s' % (pid_resolver_label, exc))-- protocolinfo_response.cookie_path = cookie_path---class AuthenticationFailure(Exception):- """- Base error for authentication failures.-- :var stem.socket.ControlMessage auth_response: AUTHENTICATE response from the- control socket, **None** if one wasn't received- """-- def __init__(self, message, auth_response = None):- super(AuthenticationFailure, self).__init__(message)- self.auth_response = auth_response---class UnrecognizedAuthMethods(AuthenticationFailure):- """- All methods for authenticating aren't recognized.-- :var list unknown_auth_methods: authentication methods that weren't recognized- """-- def __init__(self, message, unknown_auth_methods):- super(UnrecognizedAuthMethods, self).__init__(message)- self.unknown_auth_methods = unknown_auth_methods---class IncorrectSocketType(AuthenticationFailure):- 'Socket does not speak the control protocol.'---class OpenAuthFailed(AuthenticationFailure):- 'Failure to authenticate to an open socket.'---class OpenAuthRejected(OpenAuthFailed):- 'Attempt to connect to an open control socket was rejected.'---class PasswordAuthFailed(AuthenticationFailure):- 'Failure to authenticate with a password.'---class PasswordAuthRejected(PasswordAuthFailed):- 'Socket does not support password authentication.'---class IncorrectPassword(PasswordAuthFailed):- 'Authentication password incorrect.'---class MissingPassword(PasswordAuthFailed):- "Password authentication is supported but we weren't provided with one."---class CookieAuthFailed(AuthenticationFailure):- """- Failure to authenticate with an authentication cookie.-- :param str cookie_path: location of the authentication cookie we attempted- :param bool is_safecookie: **True** if this was for SAFECOOKIE- authentication, **False** if for COOKIE- :param stem.response.ControlMessage auth_response: reply to our- authentication attempt- """-- def __init__(self, message, cookie_path, is_safecookie, auth_response = None):- super(CookieAuthFailed, self).__init__(message, auth_response)- self.is_safecookie = is_safecookie- self.cookie_path = cookie_path---class CookieAuthRejected(CookieAuthFailed):- 'Socket does not support password authentication.'---class IncorrectCookieValue(CookieAuthFailed):- 'Authentication cookie value was rejected.'---class IncorrectCookieSize(CookieAuthFailed):- 'Aborted because the cookie file is the wrong size.'---class UnreadableCookieFile(CookieAuthFailed):- 'Error arose in reading the authentication cookie.'---class AuthChallengeFailed(CookieAuthFailed):- """- AUTHCHALLENGE command has failed.- """-- def __init__(self, message, cookie_path):- super(AuthChallengeFailed, self).__init__(message, cookie_path, True)---class AuthChallengeUnsupported(AuthChallengeFailed):- """- AUTHCHALLENGE isn't implemented.- """---class UnrecognizedAuthChallengeMethod(AuthChallengeFailed):- """- Tor couldn't recognize our AUTHCHALLENGE method.-- :var str authchallenge_method: AUTHCHALLENGE method that Tor couldn't recognize- """-- def __init__(self, message, cookie_path, authchallenge_method):- super(UnrecognizedAuthChallengeMethod, self).__init__(message, cookie_path)- self.authchallenge_method = authchallenge_method---class AuthSecurityFailure(AuthChallengeFailed):- 'AUTHCHALLENGE response is invalid.'---class InvalidClientNonce(AuthChallengeFailed):- 'AUTHCHALLENGE request contains an invalid client nonce.'---class MissingAuthInfo(AuthenticationFailure):- """- The PROTOCOLINFO response didn't have enough information to authenticate.- These are valid control responses but really shouldn't happen in practice.- """---class NoAuthMethods(MissingAuthInfo):- "PROTOCOLINFO response didn't have any methods for authenticating."---class NoAuthCookie(MissingAuthInfo):- """- PROTOCOLINFO response supports cookie auth but doesn't have its path.-- :param bool is_safecookie: **True** if this was for SAFECOOKIE- authentication, **False** if for COOKIE- """-- def __init__(self, message, is_safecookie):- super(NoAuthCookie, self).__init__(message)- self.is_safecookie = is_safecookie--# authentication exceptions ordered as per the authenticate function's pydocs-AUTHENTICATE_EXCEPTIONS = (- IncorrectSocketType,- UnrecognizedAuthMethods,- MissingPassword,- IncorrectPassword,- IncorrectCookieSize,- UnreadableCookieFile,- IncorrectCookieValue,- AuthChallengeUnsupported,- UnrecognizedAuthChallengeMethod,- InvalidClientNonce,- AuthSecurityFailure,- OpenAuthRejected,- MissingAuthInfo,- AuthenticationFailure-)diff --git a/ext/stem/control.py b/ext/stem/control.pydeleted file mode 100644index 657f5596..00000000--- a/ext/stem/control.py+++ /dev/null@@ -1,3631 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Module for interacting with the Tor control socket. The-:class:`~stem.control.Controller` is a wrapper around a-:class:`~stem.socket.ControlSocket`, retaining many of its methods (connect,-close, is_alive, etc) in addition to providing its own for working with the-socket at a higher level.--Stem has `several ways <../faq.html#how-do-i-connect-to-tor>`_ of getting a-:class:`~stem.control.Controller`, but the most flexible are-:func:`~stem.control.Controller.from_port` and-:func:`~stem.control.Controller.from_socket_file`. These static-:class:`~stem.control.Controller` methods give you an **unauthenticated**-Controller you can then authenticate yourself using its-:func:`~stem.control.Controller.authenticate` method. For example...--::-- import getpass- import sys-- import stem- import stem.connection-- from stem.control import Controller-- if __name__ == '__main__':- try:- controller = Controller.from_port()- except stem.SocketError as exc:- print("Unable to connect to tor on port 9051: %s" % exc)- sys.exit(1)-- try:- controller.authenticate()- except stem.connection.MissingPassword:- pw = getpass.getpass("Controller password: ")-- try:- controller.authenticate(password = pw)- except stem.connection.PasswordAuthFailed:- print("Unable to authenticate, password is incorrect")- sys.exit(1)- except stem.connection.AuthenticationFailure as exc:- print("Unable to authenticate: %s" % exc)- sys.exit(1)-- print("Tor is running version %s" % controller.get_version())- controller.close()--If you're fine with allowing your script to raise exceptions then this can be more nicely done as...--::-- from stem.control import Controller-- if __name__ == '__main__':- with Controller.from_port() as controller:- controller.authenticate()-- print("Tor is running version %s" % controller.get_version())--**Module Overview:**--::-- Controller - General controller class intended for direct use- | |- from_port - Provides a Controller based on a port connection.- | +- from_socket_file - Provides a Controller based on a socket file connection.- |- |- authenticate - authenticates this controller with tor- |- |- get_info - issues a GETINFO query for a parameter- |- get_version - provides our tor version- |- get_exit_policy - provides our exit policy- |- get_ports - provides the local ports where tor is listening for connections- |- get_listeners - provides the addresses and ports where tor is listening for connections- |- get_accounting_stats - provides stats related to relaying limits- |- get_protocolinfo - information about the controller interface- |- get_user - provides the user tor is running as- |- get_pid - provides the pid of our tor process- |- |- get_microdescriptor - querying the microdescriptor for a relay- |- get_microdescriptors - provides all currently available microdescriptors- |- get_server_descriptor - querying the server descriptor for a relay- |- get_server_descriptors - provides all currently available server descriptors- |- get_network_status - querying the router status entry for a relay- |- get_network_statuses - provides all preently available router status entries- |- get_hidden_service_descriptor - queries the given hidden service descriptor- |- |- get_conf - gets the value of a configuration option- |- get_conf_map - gets the values of multiple configuration options- |- set_conf - sets the value of a configuration option- |- reset_conf - reverts configuration options to their default values- |- set_options - sets or resets the values of multiple configuration options- |- |- get_hidden_service_conf - provides our hidden service configuration- |- set_hidden_service_conf - sets our hidden service configuration- |- create_hidden_service - creates a new hidden service or adds a new port- |- remove_hidden_service - removes a hidden service or drops a port- |- |- list_ephemeral_hidden_services - list ephemeral hidden serivces- |- create_ephemeral_hidden_service - create a new ephemeral hidden service- |- remove_ephemeral_hidden_service - removes an ephemeral hidden service- |- |- add_event_listener - attaches an event listener to be notified of tor events- |- remove_event_listener - removes a listener so it isn't notified of further events- |- |- is_caching_enabled - true if the controller has enabled caching- |- set_caching - enables or disables caching- |- clear_cache - clears any cached results- |- |- load_conf - loads configuration information as if it was in the torrc- |- save_conf - saves configuration information to the torrc- |- |- is_feature_enabled - checks if a given controller feature is enabled- |- enable_feature - enables a controller feature that has been disabled by default- |- |- get_circuit - provides an active circuit- |- get_circuits - provides a list of active circuits- |- new_circuit - create new circuits- |- extend_circuit - create new circuits and extend existing ones- |- repurpose_circuit - change a circuit's purpose- |- close_circuit - close a circuit- |- |- get_streams - provides a list of active streams- |- attach_stream - attach a stream to a circuit- |- close_stream - close a stream- |- |- signal - sends a signal to the tor client- |- is_newnym_available - true if tor would currently accept a NEWNYM signal- |- get_newnym_wait - seconds until tor would accept a NEWNYM signal- |- get_effective_rate - provides our effective relaying rate limit- |- is_geoip_unavailable - true if we've discovered our geoip db to be unavailable- |- map_address - maps one address to another such that connections to the original are replaced with the other- +- drop_guards - drops our set of guard relays and picks a new set-- BaseController - Base controller class asynchronous message handling- |- msg - communicates with the tor process- |- is_alive - reports if our connection to tor is open or closed- |- is_localhost - returns if the connection is for the local system or not- |- connection_time - time when we last connected or disconnected- |- is_authenticated - checks if we're authenticated to tor- |- connect - connects or reconnects to tor- |- close - shuts down our connection to the tor process- |- get_socket - provides the socket used for control communication- |- get_latest_heartbeat - timestamp for when we last heard from tor- |- add_status_listener - notifies a callback of changes in our status- |- remove_status_listener - prevents further notification of status changes- +- __enter__ / __exit__ - manages socket connection--.. data:: State (enum)-- Enumeration for states that a controller can have.-- ========== ===========- State Description- ========== ===========- **INIT** new control connection- **RESET** received a reset/sighup signal- **CLOSED** control connection closed- ========== ===========--.. data:: EventType (enum)-- Known types of events that the- :func:`~stem.control.Controller.add_event_listener` method of the- :class:`~stem.control.Controller` can listen for.-- The most frequently listened for event types tend to be the logging events- (**DEBUG**, **INFO**, **NOTICE**, **WARN**, and **ERR**), bandwidth usage- (**BW**), and circuit or stream changes (**CIRC** and **STREAM**).-- Enums are mapped to :class:`~stem.response.events.Event` subclasses as- follows...-- ======================= ===========- EventType Event Class- ======================= ===========- **ADDRMAP** :class:`stem.response.events.AddrMapEvent`- **AUTHDIR_NEWDESCS** :class:`stem.response.events.AuthDirNewDescEvent`- **BUILDTIMEOUT_SET** :class:`stem.response.events.BuildTimeoutSetEvent`- **BW** :class:`stem.response.events.BandwidthEvent`- **CELL_STATS** :class:`stem.response.events.CellStatsEvent`- **CIRC** :class:`stem.response.events.CircuitEvent`- **CIRC_BW** :class:`stem.response.events.CircuitBandwidthEvent`- **CIRC_MINOR** :class:`stem.response.events.CircMinorEvent`- **CLIENTS_SEEN** :class:`stem.response.events.ClientsSeenEvent`- **CONF_CHANGED** :class:`stem.response.events.ConfChangedEvent`- **CONN_BW** :class:`stem.response.events.ConnectionBandwidthEvent`- **DEBUG** :class:`stem.response.events.LogEvent`- **DESCCHANGED** :class:`stem.response.events.DescChangedEvent`- **ERR** :class:`stem.response.events.LogEvent`- **GUARD** :class:`stem.response.events.GuardEvent`- **HS_DESC** :class:`stem.response.events.HSDescEvent`- **HS_DESC_CONTENT** :class:`stem.response.events.HSDescContentEvent`- **INFO** :class:`stem.response.events.LogEvent`- **NEWCONSENSUS** :class:`stem.response.events.NewConsensusEvent`- **NEWDESC** :class:`stem.response.events.NewDescEvent`- **NOTICE** :class:`stem.response.events.LogEvent`- **NS** :class:`stem.response.events.NetworkStatusEvent`- **ORCONN** :class:`stem.response.events.ORConnEvent`- **SIGNAL** :class:`stem.response.events.SignalEvent`- **STATUS_CLIENT** :class:`stem.response.events.StatusEvent`- **STATUS_GENERAL** :class:`stem.response.events.StatusEvent`- **STATUS_SERVER** :class:`stem.response.events.StatusEvent`- **STREAM** :class:`stem.response.events.StreamEvent`- **STREAM_BW** :class:`stem.response.events.StreamBwEvent`- **TB_EMPTY** :class:`stem.response.events.TokenBucketEmptyEvent`- **TRANSPORT_LAUNCHED** :class:`stem.response.events.TransportLaunchedEvent`- **WARN** :class:`stem.response.events.LogEvent`- ======================= ===========--.. data:: Listener (enum)-- Purposes for inbound connections that Tor handles.-- ============= ===========- Listener Description- ============= ===========- **OR** traffic we're relaying as a member of the network (torrc's **ORPort** and **ORListenAddress**)- **DIR** mirroring for tor descriptor content (torrc's **DirPort** and **DirListenAddress**)- **SOCKS** client traffic we're sending over Tor (torrc's **SocksPort** and **SocksListenAddress**)- **TRANS** transparent proxy handling (torrc's **TransPort** and **TransListenAddress**)- **NATD** forwarding for ipfw NATD connections (torrc's **NatdPort** and **NatdListenAddress**)- **DNS** DNS lookups for our traffic (torrc's **DNSPort** and **DNSListenAddress**)- **CONTROL** controller applications (torrc's **ControlPort** and **ControlListenAddress**)- ============= ===========-"""--import calendar-import collections-import functools-import inspect-import io-import os-import threading-import time--try:- # Added in 2.7- from collections import OrderedDict-except ImportError:- from stem.util.ordereddict import OrderedDict--try:- import queue- from io import StringIO-except ImportError:- import Queue as queue- from StringIO import StringIO--import stem.descriptor.microdescriptor-import stem.descriptor.reader-import stem.descriptor.router_status_entry-import stem.descriptor.server_descriptor-import stem.exit_policy-import stem.response-import stem.response.events-import stem.socket-import stem.util.connection-import stem.util.enum-import stem.util.str_tools-import stem.util.system-import stem.util.tor_tools-import stem.version--from stem import UNDEFINED, CircStatus, Signal, str_type-from stem.util import log--# state changes a control socket can have--State = stem.util.enum.Enum('INIT', 'RESET', 'CLOSED')--EventType = stem.util.enum.UppercaseEnum(- 'ADDRMAP',- 'AUTHDIR_NEWDESCS',- 'BUILDTIMEOUT_SET',- 'BW',- 'CELL_STATS',- 'CIRC',- 'CIRC_BW',- 'CIRC_MINOR',- 'CONF_CHANGED',- 'CONN_BW',- 'CLIENTS_SEEN',- 'DEBUG',- 'DESCCHANGED',- 'ERR',- 'GUARD',- 'HS_DESC',- 'HS_DESC_CONTENT',- 'INFO',- 'NEWCONSENSUS',- 'NEWDESC',- 'NOTICE',- 'NS',- 'ORCONN',- 'SIGNAL',- 'STATUS_CLIENT',- 'STATUS_GENERAL',- 'STATUS_SERVER',- 'STREAM',- 'STREAM_BW',- 'TB_EMPTY',- 'TRANSPORT_LAUNCHED',- 'WARN',-)--Listener = stem.util.enum.UppercaseEnum(- 'OR',- 'DIR',- 'SOCKS',- 'TRANS',- 'NATD',- 'DNS',- 'CONTROL',-)--# Configuration options that are fetched by a special key. The keys are-# lowercase to make case insensitive lookups easier.--MAPPED_CONFIG_KEYS = {- 'hiddenservicedir': 'HiddenServiceOptions',- 'hiddenserviceport': 'HiddenServiceOptions',- 'hiddenserviceversion': 'HiddenServiceOptions',- 'hiddenserviceauthorizeclient': 'HiddenServiceOptions',- 'hiddenserviceoptions': 'HiddenServiceOptions',-}--# unchangeable GETINFO parameters--CACHEABLE_GETINFO_PARAMS = (- 'version',- 'config-file',- 'exit-policy/default',- 'fingerprint',- 'config/names',- 'config/defaults',- 'info/names',- 'events/names',- 'features/names',- 'process/descriptor-limit',-)--# GETCONF parameters we shouldn't cache. This includes hidden service-# perameters due to the funky way they're set and retrieved (for instance,-# 'SETCONF HiddenServiceDir' effects 'GETCONF HiddenServiceOptions').--UNCACHEABLE_GETCONF_PARAMS = (- 'hiddenserviceoptions',- 'hiddenservicedir',- 'hiddenserviceport',- 'hiddenserviceversion',- 'hiddenserviceauthorizeclient',-)--# number of sequential attempts before we decide that the Tor geoip database-# is unavailable-GEOIP_FAILURE_THRESHOLD = 5--SERVER_DESCRIPTORS_UNSUPPORTED = "Tor is currently not configured to retrieve \-server descriptors. As of Tor version 0.2.3.25 it downloads microdescriptors \-instead unless you set 'UseMicrodescriptors 0' in your torrc."--AccountingStats = collections.namedtuple('AccountingStats', [- 'retrieved',- 'status',- 'interval_end',- 'time_until_reset',- 'read_bytes',- 'read_bytes_left',- 'read_limit',- 'written_bytes',- 'write_bytes_left',- 'write_limit',-])--CreateHiddenServiceOutput = collections.namedtuple('CreateHiddenServiceOutput', [- 'path',- 'hostname',- 'hostname_for_client',- 'config',-])---def with_default(yields = False):- """- Provides a decorator to support having a default value. This should be- treated as private.- """-- def decorator(func):- def get_default(func, args, kwargs):- arg_names = inspect.getargspec(func).args[1:] # drop 'self'- default_position = arg_names.index('default') if 'default' in arg_names else None-- if default_position is not None and default_position < len(args):- return args[default_position]- else:- return kwargs.get('default', UNDEFINED)-- if not yields:- @functools.wraps(func)- def wrapped(self, *args, **kwargs):- try:- return func(self, *args, **kwargs)- except Exception as exc:- default = get_default(func, args, kwargs)-- if default == UNDEFINED:- raise exc- else:- return default- else:- @functools.wraps(func)- def wrapped(self, *args, **kwargs):- try:- for val in func(self, *args, **kwargs):- yield val- except Exception as exc:- default = get_default(func, args, kwargs)-- if default == UNDEFINED:- raise exc- else:- if default is not None:- for val in default:- yield val-- return wrapped-- return decorator---class BaseController(object):- """- Controller for the tor process. This is a minimal base class for other- controllers, providing basic process communication and event listing. Don't- use this directly - subclasses like the :class:`~stem.control.Controller`- provide higher level functionality.-- It's highly suggested that you don't interact directly with the- :class:`~stem.socket.ControlSocket` that we're constructed from - use our- wrapper methods instead.-- If the **control_socket** is already authenticated to Tor then the caller- should provide the **is_authenticated** flag. Otherwise, we will treat the- socket as though it hasn't yet been authenticated.- """-- def __init__(self, control_socket, is_authenticated = False):- self._socket = control_socket- self._msg_lock = threading.RLock()-- self._status_listeners = [] # tuples of the form (callback, spawn_thread)- self._status_listeners_lock = threading.RLock()-- # queues where incoming messages are directed- self._reply_queue = queue.Queue()- self._event_queue = queue.Queue()-- # thread to continually pull from the control socket- self._reader_thread = None-- # thread to pull from the _event_queue and call handle_event- self._event_notice = threading.Event()- self._event_thread = None-- # saves our socket's prior _connect() and _close() methods so they can be- # called along with ours-- self._socket_connect = self._socket._connect- self._socket_close = self._socket._close-- self._socket._connect = self._connect- self._socket._close = self._close-- self._last_heartbeat = 0.0 # timestamp for when we last heard from tor- self._is_authenticated = False-- self._state_change_threads = [] # threads we've spawned to notify of state changes-- if self._socket.is_alive():- self._launch_threads()-- if is_authenticated:- self._post_authentication()-- def msg(self, message):- """- Sends a message to our control socket and provides back its reply.-- :param str message: message to be formatted and sent to tor-- :returns: :class:`~stem.response.ControlMessage` with the response-- :raises:- * :class:`stem.ProtocolError` the content from the socket is- malformed- * :class:`stem.SocketError` if a problem arises in using the- socket- * :class:`stem.SocketClosed` if the socket is shut down- """-- with self._msg_lock:- # If our _reply_queue isn't empty then one of a few things happened...- #- # - Our connection was closed and probably re-restablished. This was- # in reply to pulling for an asynchronous event and getting this is- # expected - ignore it.- #- # - Pulling for asynchronous events produced an error. If this was a- # ProtocolError then it's a tor bug, and if a non-closure SocketError- # then it was probably a socket glitch. Deserves an INFO level log- # message.- #- # - This is a leftover response for a msg() call. We can't tell who an- # exception was earmarked for, so we only know that this was the case- # if it's a ControlMessage.- #- # This is the most concerning situation since it indicates that one of- # our callers didn't get their reply. However, this is still a- # perfectly viable use case. For instance...- #- # 1. We send a request.- # 2. The reader thread encounters an exception, for instance a socket- # error. We enqueue the exception.- # 3. The reader thread receives the reply.- # 4. We raise the socket error, and have an undelivered message.- #- # Thankfully this only seems to arise in edge cases around rapidly- # closing/reconnecting the socket.-- while not self._reply_queue.empty():- try:- response = self._reply_queue.get_nowait()-- if isinstance(response, stem.SocketClosed):- pass # this is fine- elif isinstance(response, stem.ProtocolError):- log.info('Tor provided a malformed message (%s)' % response)- elif isinstance(response, stem.ControllerError):- log.info('Socket experienced a problem (%s)' % response)- elif isinstance(response, stem.response.ControlMessage):- log.info('Failed to deliver a response: %s' % response)- except queue.Empty:- # the empty() method is documented to not be fully reliable so this- # isn't entirely surprising-- break-- try:- self._socket.send(message)- response = self._reply_queue.get()-- # If the message we received back had an exception then re-raise it to the- # caller. Otherwise return the response.-- if isinstance(response, stem.ControllerError):- raise response- else:- # I really, really don't like putting hooks into this method, but- # this is the most reliable method I can think of for taking actions- # immediately after successfully authenticating to a connection.-- if message.upper().startswith('AUTHENTICATE'):- self._post_authentication()-- return response- except stem.SocketClosed as exc:- # If the recv() thread caused the SocketClosed then we could still be- # in the process of closing. Calling close() here so that we can- # provide an assurance to the caller that when we raise a SocketClosed- # exception we are shut down afterward for realz.-- self.close()- raise exc-- def is_alive(self):- """- Checks if our socket is currently connected. This is a pass-through for our- socket's :func:`~stem.socket.ControlSocket.is_alive` method.-- :returns: **bool** that's **True** if our socket is connected and **False** otherwise- """-- return self._socket.is_alive()-- def is_localhost(self):- """- Returns if the connection is for the local system or not.-- .. versionadded:: 1.3.0-- :returns: **bool** that's **True** if the connection is for the local host and **False** otherwise- """-- return self._socket.is_localhost()-- def connection_time(self):- """- Provides the unix timestamp for when our socket was either connected or- disconnected. That is to say, the time we connected if we're currently- connected and the time we disconnected if we're not connected.-- .. versionadded:: 1.3.0-- :returns: **float** for when we last connected or disconnected, zero if- we've never connected- """-- return self._socket.connection_time()-- def is_authenticated(self):- """- Checks if our socket is both connected and authenticated.-- :returns: **bool** that's **True** if our socket is authenticated to tor- and **False** otherwise- """-- if self.is_alive():- return self._is_authenticated-- return False-- def connect(self):- """- Reconnects our control socket. This is a pass-through for our socket's- :func:`~stem.socket.ControlSocket.connect` method.-- :raises: :class:`stem.SocketError` if unable to make a socket- """-- self._socket.connect()-- def close(self):- """- Closes our socket connection. This is a pass-through for our socket's- :func:`~stem.socket.ControlSocket.close` method.- """-- self._socket.close()-- # Join on any outstanding state change listeners. Closing is a state change- # of its own, so if we have any listeners it's quite likely there's some- # work in progress.- #- # It's important that we do this outside of our locks so those daemons have- # access to us. This is why we're doing this here rather than _close().-- for t in self._state_change_threads:- if t.is_alive() and threading.current_thread() != t:- t.join()-- def get_socket(self):- """- Provides the socket used to speak with the tor process. Communicating with- the socket directly isn't advised since it may confuse this controller.-- :returns: :class:`~stem.socket.ControlSocket` we're communicating with- """-- return self._socket-- def get_latest_heartbeat(self):- """- Provides the unix timestamp for when we last heard from tor. This is zero- if we've never received a message.-- :returns: float for the unix timestamp of when we last heard from tor- """-- return self._last_heartbeat-- def add_status_listener(self, callback, spawn = True):- """- Notifies a given function when the state of our socket changes. Functions- are expected to be of the form...-- ::-- my_function(controller, state, timestamp)-- The state is a value from the :data:`stem.control.State` enum. Functions- **must** allow for new values. The timestamp is a float for the unix time- when the change occurred.-- This class only provides **State.INIT** and **State.CLOSED** notifications.- Subclasses may provide others.-- If spawn is **True** then the callback is notified via a new daemon thread.- If **False** then the notice is under our locks, within the thread where- the change occurred. In general this isn't advised, especially if your- callback could block for a while. If still outstanding these threads are- joined on as part of closing this controller.-- :param function callback: function to be notified when our state changes- :param bool spawn: calls function via a new thread if **True**, otherwise- it's part of the connect/close method call- """-- with self._status_listeners_lock:- self._status_listeners.append((callback, spawn))-- def remove_status_listener(self, callback):- """- Stops listener from being notified of further events.-- :param function callback: function to be removed from our listeners-- :returns: **bool** that's **True** if we removed one or more occurrences of- the callback, **False** otherwise- """-- with self._status_listeners_lock:- new_listeners, is_changed = [], False-- for listener, spawn in self._status_listeners:- if listener != callback:- new_listeners.append((listener, spawn))- else:- is_changed = True-- self._status_listeners = new_listeners- return is_changed-- def __enter__(self):- return self-- def __exit__(self, exit_type, value, traceback):- self.close()-- def _handle_event(self, event_message):- """- Callback to be overwritten by subclasses for event listening. This is- notified whenever we receive an event from the control socket.-- :param stem.response.ControlMessage event_message: message received from- the control socket- """-- pass-- def _connect(self):- self._launch_threads()- self._notify_status_listeners(State.INIT)- self._socket_connect()- self._is_authenticated = False-- def _close(self):- # Our is_alive() state is now false. Our reader thread should already be- # awake from recv() raising a closure exception. Wake up the event thread- # too so it can end.-- self._event_notice.set()- self._is_authenticated = False-- # joins on our threads if it's safe to do so-- for t in (self._reader_thread, self._event_thread):- if t and t.is_alive() and threading.current_thread() != t:- t.join()-- self._notify_status_listeners(State.CLOSED)-- self._socket_close()-- def _post_authentication(self):- # actions to be taken after we have a newly authenticated connection-- self._is_authenticated = True-- def _notify_status_listeners(self, state):- """- Informs our status listeners that a state change occurred.-- :param stem.control.State state: state change that has occurred- """-- # Any changes to our is_alive() state happen under the send lock, so we- # need to have it to ensure it doesn't change beneath us.-- with self._socket._get_send_lock():- with self._status_listeners_lock:- # States imply that our socket is either alive or not, which may not- # hold true when multiple events occur in quick succession. For- # instance, a sighup could cause two events (State.RESET for the sighup- # and State.CLOSE if it causes tor to crash). However, there's no- # guarantee of the order in which they occur, and it would be bad if- # listeners got the State.RESET last, implying that we were alive.-- expect_alive = None-- if state in (State.INIT, State.RESET):- expect_alive = True- elif state == State.CLOSED:- expect_alive = False-- change_timestamp = time.time()-- if expect_alive is not None and expect_alive != self.is_alive():- return-- self._state_change_threads = list(filter(lambda t: t.is_alive(), self._state_change_threads))-- for listener, spawn in self._status_listeners:- if spawn:- name = '%s notification' % state- args = (self, state, change_timestamp)-- notice_thread = threading.Thread(target = listener, args = args, name = name)- notice_thread.setDaemon(True)- notice_thread.start()- self._state_change_threads.append(notice_thread)- else:- listener(self, state, change_timestamp)-- def _launch_threads(self):- """- Initializes daemon threads. Threads can't be reused so we need to recreate- them if we're restarted.- """-- # In theory concurrent calls could result in multiple start() calls on a- # single thread, which would cause an unexpected exception. Best be safe.-- with self._socket._get_send_lock():- if not self._reader_thread or not self._reader_thread.is_alive():- self._reader_thread = threading.Thread(target = self._reader_loop, name = 'Tor Listener')- self._reader_thread.setDaemon(True)- self._reader_thread.start()-- if not self._event_thread or not self._event_thread.is_alive():- self._event_thread = threading.Thread(target = self._event_loop, name = 'Event Notifier')- self._event_thread.setDaemon(True)- self._event_thread.start()-- def _reader_loop(self):- """- Continually pulls from the control socket, directing the messages into- queues based on their type. Controller messages come in two varieties...-- * Responses to messages we've sent (GETINFO, SETCONF, etc).- * Asynchronous events, identified by a status code of 650.- """-- while self.is_alive():- try:- control_message = self._socket.recv()- self._last_heartbeat = time.time()-- if control_message.content()[-1][0] == '650':- # asynchronous message, adds to the event queue and wakes up its handler- self._event_queue.put(control_message)- self._event_notice.set()- else:- # response to a msg() call- self._reply_queue.put(control_message)- except stem.ControllerError as exc:- # Assume that all exceptions belong to the reader. This isn't always- # true, but the msg() call can do a better job of sorting it out.- #- # Be aware that the msg() method relies on this to unblock callers.-- self._reply_queue.put(exc)-- def _event_loop(self):- """- Continually pulls messages from the _event_queue and sends them to our- handle_event callback. This is done via its own thread so subclasses with a- lengthy handle_event implementation don't block further reading from the- socket.- """-- while True:- try:- event_message = self._event_queue.get_nowait()- self._handle_event(event_message)- except queue.Empty:- if not self.is_alive():- break-- self._event_notice.wait()- self._event_notice.clear()---class Controller(BaseController):- """- Communicates with a control socket. This is built on top of the- BaseController and provides a more user friendly API for library users.- """-- @staticmethod- def from_port(address = '127.0.0.1', port = 9051):- """- Constructs a :class:`~stem.socket.ControlPort` based Controller.-- :param str address: ip address of the controller- :param int port: port number of the controller-- :returns: :class:`~stem.control.Controller` attached to the given port-- :raises: :class:`stem.SocketError` if we're unable to establish a connection- """-- if not stem.util.connection.is_valid_ipv4_address(address):- raise ValueError('Invalid IP address: %s' % address)- elif not stem.util.connection.is_valid_port(port):- raise ValueError('Invalid port: %s' % port)-- control_port = stem.socket.ControlPort(address, port)- return Controller(control_port)-- @staticmethod- def from_socket_file(path = '/var/run/tor/control'):- """- Constructs a :class:`~stem.socket.ControlSocketFile` based Controller.-- :param str path: path where the control socket is located-- :returns: :class:`~stem.control.Controller` attached to the given socket file-- :raises: :class:`stem.SocketError` if we're unable to establish a connection- """-- control_socket = stem.socket.ControlSocketFile(path)- return Controller(control_socket)-- def __init__(self, control_socket, is_authenticated = False):- self._is_caching_enabled = True- self._request_cache = {}- self._last_newnym = 0.0-- self._cache_lock = threading.RLock()-- # mapping of event types to their listeners-- self._event_listeners = {}- self._event_listeners_lock = threading.RLock()-- # number of sequential 'GETINFO ip-to-country/*' lookups that have failed-- self._geoip_failure_count = 0- self._enabled_features = []-- super(Controller, self).__init__(control_socket, is_authenticated)-- def _sighup_listener(event):- if event.signal == Signal.RELOAD:- self.clear_cache()- self._notify_status_listeners(State.RESET)-- self.add_event_listener(_sighup_listener, EventType.SIGNAL)-- def _confchanged_listener(event):- if self.is_caching_enabled():- self._set_cache(dict((k, None) for k in event.config), 'getconf')-- if 'exitpolicy' in event.config.keys():- self._set_cache({'exitpolicy': None})-- self.add_event_listener(_confchanged_listener, EventType.CONF_CHANGED)-- def connect(self):- super(Controller, self).connect()- self.clear_cache()-- def close(self):- # making a best-effort attempt to quit before detaching the socket- if self.is_alive():- try:- self.msg('QUIT')- except:- pass-- self.clear_cache()-- super(Controller, self).close()-- def authenticate(self, *args, **kwargs):- """- A convenience method to authenticate the controller. This is just a- pass-through to :func:`stem.connection.authenticate`.- """-- import stem.connection- stem.connection.authenticate(self, *args, **kwargs)-- @with_default()- def get_info(self, params, default = UNDEFINED, get_bytes = False):- """- get_info(params, default = UNDEFINED, get_bytes = False)-- Queries the control socket for the given GETINFO option. If provided a- default then that's returned if the GETINFO option is undefined or the- call fails for any reason (error response, control port closed, initiated,- etc).-- .. versionchanged:: 1.1.0- Added the get_bytes argument.-- :param str,list params: GETINFO option or options to be queried- :param object default: response if the query fails- :param bool get_bytes: provides **bytes** values rather than a **str** under python 3.x-- :returns:- Response depends upon how we were called as follows...-- * **str** with the response if our param was a **str**- * **dict** with the 'param => response' mapping if our param was a **list**- * default if one was provided and our call failed-- :raises:- * :class:`stem.ControllerError` if the call fails and we weren't- provided a default response- * :class:`stem.InvalidArguments` if the 'params' requested was- invalid- * :class:`stem.ProtocolError` if the geoip database is known to be- unavailable- """-- start_time = time.time()- reply = {}-- if isinstance(params, (bytes, str_type)):- is_multiple = False- params = set([params])- else:- if not params:- return {}-- is_multiple = True- params = set(params)-- # check for cached results-- from_cache = [param.lower() for param in params]- cached_results = self._get_cache_map(from_cache, 'getinfo')-- for key in cached_results:- user_expected_key = _case_insensitive_lookup(params, key)- reply[user_expected_key] = cached_results[key]- params.remove(user_expected_key)-- for param in params:- if param.startswith('ip-to-country/') and self.is_geoip_unavailable():- # the geoip database already looks to be unavailable - abort the request-- raise stem.ProtocolError('Tor geoip database is unavailable')-- # if everything was cached then short circuit making the query- if not params:- log.trace('GETINFO %s (cache fetch)' % ' '.join(reply.keys()))-- if is_multiple:- return reply- else:- return list(reply.values())[0]-- try:- response = self.msg('GETINFO %s' % ' '.join(params))- stem.response.convert('GETINFO', response)- response._assert_matches(params)-- # usually we want unicode values under python 3.x-- if stem.prereq.is_python_3() and not get_bytes:- response.entries = dict((k, stem.util.str_tools._to_unicode(v)) for (k, v) in response.entries.items())-- reply.update(response.entries)-- if self.is_caching_enabled():- to_cache = {}-- for key, value in response.entries.items():- key = key.lower() # make case insensitive-- if key in CACHEABLE_GETINFO_PARAMS:- to_cache[key] = value- elif key.startswith('ip-to-country/'):- # both cache-able and means that we should reset the geoip failure count- to_cache[key] = value- self._geoip_failure_count = -1-- self._set_cache(to_cache, 'getinfo')-- log.debug('GETINFO %s (runtime: %0.4f)' % (' '.join(params), time.time() - start_time))-- if is_multiple:- return reply- else:- return list(reply.values())[0]- except stem.ControllerError as exc:- # bump geoip failure count if...- # * we're caching results- # * this was soley a geoip lookup- # * we've never had a successful geoip lookup (failure count isn't -1)-- is_geoip_request = len(params) == 1 and list(params)[0].startswith('ip-to-country/')-- if is_geoip_request and self.is_caching_enabled() and self._geoip_failure_count != -1:- self._geoip_failure_count += 1-- if self.is_geoip_unavailable():- log.warn("Tor's geoip database is unavailable.")-- log.debug('GETINFO %s (failed: %s)' % (' '.join(params), exc))-- raise exc-- @with_default()- def get_version(self, default = UNDEFINED):- """- get_version(default = UNDEFINED)-- A convenience method to get tor version that current controller is- connected to.-- :param object default: response if the query fails-- :returns: :class:`~stem.version.Version` of the tor instance that we're- connected to-- :raises:- * :class:`stem.ControllerError` if unable to query the version- * **ValueError** if unable to parse the version-- An exception is only raised if we weren't provided a default response.- """-- version = self._get_cache('version')-- if not version:- version = stem.version.Version(self.get_info('version'))- self._set_cache({'version': version})-- return version-- @with_default()- def get_exit_policy(self, default = UNDEFINED):- """- get_exit_policy(default = UNDEFINED)-- Effective ExitPolicy for our relay. This accounts for- ExitPolicyRejectPrivate and default policies.-- :param object default: response if the query fails-- :returns: :class:`~stem.exit_policy.ExitPolicy` of the tor instance that- we're connected to-- :raises:- * :class:`stem.ControllerError` if unable to query the policy- * **ValueError** if unable to parse the policy-- An exception is only raised if we weren't provided a default response.- """-- with self._msg_lock:- config_policy = self._get_cache('exit_policy')-- if not config_policy:- policy = []-- if self.get_conf('ExitPolicyRejectPrivate') == '1':- policy.append('reject private:*')-- for policy_line in self.get_conf('ExitPolicy', multiple = True):- policy += policy_line.split(',')-- policy += self.get_info('exit-policy/default').split(',')-- config_policy = stem.exit_policy.get_config_policy(policy, self.get_info('address', None))- self._set_cache({'exit_policy': config_policy})-- return config_policy-- @with_default()- def get_ports(self, listener_type, default = UNDEFINED):- """- get_ports(listener_type, default = UNDEFINED)-- Provides the local ports where tor is listening for the given type of- connections. This is similar to- :func:`~stem.control.Controller.get_listeners`, but doesn't provide- addresses nor include non-local endpoints.-- .. versionadded:: 1.2.0-- :param stem.control.Listener listener_type: connection type being handled- by the ports we return- :param object default: response if the query fails-- :returns: **list** of **ints** for the local ports where tor handles- connections of the given type-- :raises: :class:`stem.ControllerError` if unable to determine the ports- and no default was provided- """-- return [port for (addr, port) in self.get_listeners(listener_type) if addr == '127.0.0.1']-- @with_default()- def get_listeners(self, listener_type, default = UNDEFINED):- """- get_listeners(listener_type, default = UNDEFINED)-- Provides the addresses and ports where tor is listening for connections of- the given type. This is similar to- :func:`~stem.control.Controller.get_ports` but includes listener addresses- and non-local endpoints.-- .. versionadded:: 1.2.0-- :param stem.control.Listener listener_type: connection type being handled- by the listeners we return- :param object default: response if the query fails-- :returns: **list** of **(address, port)** tuples for the available- listeners-- :raises: :class:`stem.ControllerError` if unable to determine the listeners- and no default was provided- """-- proxy_addrs = []- query = 'net/listeners/%s' % listener_type.lower()-- try:- for listener in self.get_info(query).split():- if not (listener.startswith('"') and listener.endswith('"')):- raise stem.ProtocolError("'GETINFO %s' responses are expected to be quoted: %s" % (query, listener))- elif ':' not in listener:- raise stem.ProtocolError("'GETINFO %s' had a listener without a colon: %s" % (query, listener))-- listener = listener[1:-1] # strip quotes- addr, port = listener.split(':')-- # Skip unix sockets, for instance...- #- # GETINFO net/listeners/control- # 250-net/listeners/control="unix:/tmp/tor/socket"- # 250 OK-- if addr == 'unix':- continue-- proxy_addrs.append((addr, port))- except stem.InvalidArguments:- # Tor version is old (pre-tor-0.2.2.26-beta), use get_conf() instead.- # Some options (like the ORPort) can have optional attributes after the- # actual port number.-- port_option = {- Listener.OR: 'ORPort',- Listener.DIR: 'DirPort',- Listener.SOCKS: 'SocksPort',- Listener.TRANS: 'TransPort',- Listener.NATD: 'NatdPort',- Listener.DNS: 'DNSPort',- Listener.CONTROL: 'ControlPort',- }[listener_type]-- listener_option = {- Listener.OR: 'ORListenAddress',- Listener.DIR: 'DirListenAddress',- Listener.SOCKS: 'SocksListenAddress',- Listener.TRANS: 'TransListenAddress',- Listener.NATD: 'NatdListenAddress',- Listener.DNS: 'DNSListenAddress',- Listener.CONTROL: 'ControlListenAddress',- }[listener_type]-- port_value = self.get_conf(port_option).split()[0]-- for listener in self.get_conf(listener_option, multiple = True):- if ':' in listener:- addr, port = listener.split(':')- proxy_addrs.append((addr, port))- else:- proxy_addrs.append((listener, port_value))-- # validate that address/ports are valid, and convert ports to ints-- for addr, port in proxy_addrs:- if not stem.util.connection.is_valid_ipv4_address(addr):- raise stem.ProtocolError('Invalid address for a %s listener: %s' % (listener_type, addr))- elif not stem.util.connection.is_valid_port(port):- raise stem.ProtocolError('Invalid port for a %s listener: %s' % (listener_type, port))-- return [(addr, int(port)) for (addr, port) in proxy_addrs]-- @with_default()- def get_accounting_stats(self, default = UNDEFINED):- """- get_accounting_stats(default = UNDEFINED)-- Provides stats related to our relaying limitations if AccountingMax was set- in our torrc. This provides a **namedtuple** with the following- attributes...-- * retrieved (float) - unix timestamp for when this was fetched- * status (str) - hibernation status of 'awake', 'soft', or 'hard'- * interval_end (datetime)- * time_until_reset (int) - seconds until our limits reset- * read_bytes (int)- * read_bytes_left (int)- * read_limit (int)- * written_bytes (int)- * write_bytes_left (int)- * write_limit (int)-- .. versionadded:: 1.3.0-- :param object default: response if the query fails-- :returns: **namedtuple** with our accounting stats-- :raises: :class:`stem.ControllerError` if unable to determine the listeners- and no default was provided- """-- if self.get_info('accounting/enabled') != '1':- raise stem.ControllerError("Accounting isn't enabled")-- retrieved = time.time()- status = self.get_info('accounting/hibernating')- interval_end = self.get_info('accounting/interval-end')- used = self.get_info('accounting/bytes')- left = self.get_info('accounting/bytes-left')-- interval_end = stem.util.str_tools._parse_timestamp(interval_end)- used_read, used_written = [int(val) for val in used.split(' ', 1)]- left_read, left_written = [int(val) for val in left.split(' ', 1)]-- return AccountingStats(- retrieved = retrieved,- status = status,- interval_end = interval_end,- time_until_reset = calendar.timegm(interval_end.timetuple()) - int(retrieved),- read_bytes = used_read,- read_bytes_left = left_read,- read_limit = used_read + left_read,- written_bytes = used_written,- write_bytes_left = left_written,- write_limit = used_written + left_written,- )-- def get_socks_listeners(self, default = UNDEFINED):- """- Provides the SOCKS **(address, port)** tuples that tor has open.-- .. deprecated:: 1.2.0- Use :func:`~stem.control.Controller.get_listeners` with- **Listener.SOCKS** instead.-- :param object default: response if the query fails-- :returns: list of **(address, port)** tuples for the available SOCKS- listeners-- :raises: :class:`stem.ControllerError` if unable to determine the listeners- and no default was provided- """-- return self.get_listeners(Listener.SOCKS, default)-- @with_default()- def get_protocolinfo(self, default = UNDEFINED):- """- get_protocolinfo(default = UNDEFINED)-- A convenience method to get the protocol info of the controller.-- :param object default: response if the query fails-- :returns: :class:`~stem.response.protocolinfo.ProtocolInfoResponse` provided by tor-- :raises:- * :class:`stem.ProtocolError` if the PROTOCOLINFO response is- malformed- * :class:`stem.SocketError` if problems arise in establishing or- using the socket-- An exception is only raised if we weren't provided a default response.- """-- import stem.connection- return stem.connection.get_protocolinfo(self)-- @with_default()- def get_user(self, default = UNDEFINED):- """- get_user(default = UNDEFINED)-- Provides the user tor is running as. This often only works if tor is- running locally. Also, most of its checks are platform dependent, and hence- are not entirely reliable.-- .. versionadded:: 1.1.0-- :param object default: response if the query fails-- :returns: str with the username tor is running as- """-- user = self._get_cache('user')-- if not user:- user = self.get_info('process/user', None)-- if not user and self.is_localhost():- pid = self.get_pid(None)-- if pid:- user = stem.util.system.user(pid)-- if user:- self._set_cache({'user': user})- return user- else:- raise ValueError("Unable to resolve tor's user" if self.is_localhost() else "Tor isn't running locally")-- @with_default()- def get_pid(self, default = UNDEFINED):- """- get_pid(default = UNDEFINED)-- Provides the process id of tor. This often only works if tor is running- locally. Also, most of its checks are platform dependent, and hence are not- entirely reliable.-- .. versionadded:: 1.1.0-- :param object default: response if the query fails-- :returns: **int** for tor's pid-- :raises: **ValueError** if unable to determine the pid and no default was- provided- """-- pid = self._get_cache('pid')-- if not pid:- getinfo_pid = self.get_info('process/pid', None)-- if getinfo_pid and getinfo_pid.isdigit():- pid = int(getinfo_pid)-- if not pid and self.is_localhost():- pid_file_path = self.get_conf('PidFile', None)-- if pid_file_path is not None:- with open(pid_file_path) as pid_file:- pid_file_contents = pid_file.read().strip()-- if pid_file_contents.isdigit():- pid = int(pid_file_contents)-- if not pid:- pid = stem.util.system.pid_by_name('tor')-- if not pid:- control_socket = self.get_socket()-- if isinstance(control_socket, stem.socket.ControlPort):- pid = stem.util.system.pid_by_port(control_socket.get_port())- elif isinstance(control_socket, stem.socket.ControlSocketFile):- pid = stem.util.system.pid_by_open_file(control_socket.get_socket_path())-- if pid:- self._set_cache({'pid': pid})- return pid- else:- raise ValueError("Unable to resolve tor's pid" if self.is_localhost() else "Tor isn't running locally")-- @with_default()- def get_microdescriptor(self, relay = None, default = UNDEFINED):- """- get_microdescriptor(relay = None, default = UNDEFINED)-- Provides the microdescriptor for the relay with the given fingerprint or- nickname. If the relay identifier could be either a fingerprint *or*- nickname then it's queried as a fingerprint.-- If no **relay** is provided then this defaults to ourselves. Remember that- this requires that we've retrieved our own descriptor from remote- authorities so this both won't be available for newly started relays and- may be up to around an hour out of date.-- .. versionchanged:: 1.3.0- Changed so we'd fetch our own descriptor if no 'relay' is provided.-- :param str relay: fingerprint or nickname of the relay to be queried- :param object default: response if the query fails-- :returns: :class:`~stem.descriptor.microdescriptor.Microdescriptor` for the given relay-- :raises:- * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor- for the given relay- * :class:`stem.ControllerError` if unable to query the descriptor- * **ValueError** if **relay** doesn't conform with the pattern for being- a fingerprint or nickname-- An exception is only raised if we weren't provided a default response.- """-- if relay is None:- try:- relay = self.get_info('fingerprint')- except stem.ControllerError as exc:- raise stem.ControllerError('Unable to determine our own fingerprint: %s' % exc)-- if stem.util.tor_tools.is_valid_fingerprint(relay):- query = 'md/id/%s' % relay- elif stem.util.tor_tools.is_valid_nickname(relay):- query = 'md/name/%s' % relay- else:- raise ValueError("'%s' isn't a valid fingerprint or nickname" % relay)-- try:- desc_content = self.get_info(query, get_bytes = True)- except stem.InvalidArguments as exc:- if str(exc).startswith('GETINFO request contained unrecognized keywords:'):- raise stem.DescriptorUnavailable("Tor was unable to provide the descriptor for '%s'" % relay)- else:- raise exc-- if not desc_content:- raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')-- return stem.descriptor.microdescriptor.Microdescriptor(desc_content)-- @with_default(yields = True)- def get_microdescriptors(self, default = UNDEFINED):- """- get_microdescriptors(default = UNDEFINED)-- Provides an iterator for all of the microdescriptors that tor currently- knows about.-- **Tor does not expose this information via the control protocol**- (:trac:`8323`). Until it does this reads the microdescriptors from disk,- and hence won't work remotely or if we lack read permissions.-- :param list default: items to provide if the query fails-- :returns: iterates over- :class:`~stem.descriptor.microdescriptor.Microdescriptor` for relays in- the tor network-- :raises: :class:`stem.ControllerError` if unable to query tor and no- default was provided- """-- try:- data_directory = self.get_conf('DataDirectory')- except stem.ControllerError as exc:- raise stem.OperationFailed(message = 'Unable to determine the data directory (%s)' % exc)-- cached_descriptor_path = os.path.join(data_directory, 'cached-microdescs')-- if not os.path.exists(data_directory):- raise stem.OperationFailed(message = "Data directory reported by tor doesn't exist (%s)" % data_directory)- elif not os.path.exists(cached_descriptor_path):- raise stem.OperationFailed(message = "Data directory doens't contain cached microescriptors (%s)" % cached_descriptor_path)-- with stem.descriptor.reader.DescriptorReader([cached_descriptor_path]) as reader:- for desc in reader:- # It shouldn't be possible for these to be something other than- # microdescriptors but as the saying goes: trust but verify.-- if not isinstance(desc, stem.descriptor.microdescriptor.Microdescriptor):- raise stem.OperationFailed(message = 'BUG: Descriptor reader provided non-microdescriptor content (%s)' % type(desc))-- yield desc-- @with_default()- def get_server_descriptor(self, relay = None, default = UNDEFINED):- """- get_server_descriptor(relay = None, default = UNDEFINED)-- Provides the server descriptor for the relay with the given fingerprint or- nickname. If the relay identifier could be either a fingerprint *or*- nickname then it's queried as a fingerprint.-- If no **relay** is provided then this defaults to ourselves. Remember that- this requires that we've retrieved our own descriptor from remote- authorities so this both won't be available for newly started relays and- may be up to around an hour out of date.-- **As of Tor version 0.2.3.25 relays no longer get server descriptors by- default.** It's advised that you use microdescriptors instead, but if you- really need server descriptors then you can get them by setting- 'UseMicrodescriptors 0'.-- .. versionchanged:: 1.3.0- Changed so we'd fetch our own descriptor if no 'relay' is provided.-- :param str relay: fingerprint or nickname of the relay to be queried- :param object default: response if the query fails-- :returns: :class:`~stem.descriptor.server_descriptor.RelayDescriptor` for the given relay-- :raises:- * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor- for the given relay- * :class:`stem.ControllerError` if unable to query the descriptor- * **ValueError** if **relay** doesn't conform with the pattern for being- a fingerprint or nickname-- An exception is only raised if we weren't provided a default response.- """-- try:- if relay is None:- try:- relay = self.get_info('fingerprint')- except stem.ControllerError as exc:- raise stem.ControllerError('Unable to determine our own fingerprint: %s' % exc)-- if stem.util.tor_tools.is_valid_fingerprint(relay):- query = 'desc/id/%s' % relay- elif stem.util.tor_tools.is_valid_nickname(relay):- query = 'desc/name/%s' % relay- else:- raise ValueError("'%s' isn't a valid fingerprint or nickname" % relay)-- try:- desc_content = self.get_info(query, get_bytes = True)- except stem.InvalidArguments as exc:- if str(exc).startswith('GETINFO request contained unrecognized keywords:'):- raise stem.DescriptorUnavailable("Tor was unable to provide the descriptor for '%s'" % relay)- else:- raise exc-- if not desc_content:- raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')-- return stem.descriptor.server_descriptor.RelayDescriptor(desc_content)- except Exception as exc:- if not self._is_server_descriptors_available():- raise ValueError(SERVER_DESCRIPTORS_UNSUPPORTED)-- raise exc-- @with_default(yields = True)- def get_server_descriptors(self, default = UNDEFINED):- """- get_server_descriptors(default = UNDEFINED)-- Provides an iterator for all of the server descriptors that tor currently- knows about.-- **As of Tor version 0.2.3.25 relays no longer get server descriptors by- default.** It's advised that you use microdescriptors instead, but if you- really need server descriptors then you can get them by setting- 'UseMicrodescriptors 0'.-- :param list default: items to provide if the query fails-- :returns: iterates over- :class:`~stem.descriptor.server_descriptor.RelayDescriptor` for relays in- the tor network-- :raises: :class:`stem.ControllerError` if unable to query tor and no- default was provided- """-- # TODO: We should iterate over the descriptors as they're read from the- # socket rather than reading the whole thing into memory.- #- # https://trac.torproject.org/8248-- desc_content = self.get_info('desc/all-recent', get_bytes = True)-- if not desc_content:- if not self._is_server_descriptors_available():- raise stem.ControllerError(SERVER_DESCRIPTORS_UNSUPPORTED)- else:- raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')-- for desc in stem.descriptor.server_descriptor._parse_file(io.BytesIO(desc_content)):- yield desc-- def _is_server_descriptors_available(self):- """- Checks to see if tor server descriptors should be available or not.- """-- return self.get_version() < stem.version.Requirement.MICRODESCRIPTOR_IS_DEFAULT or \- self.get_conf('UseMicrodescriptors', None) == '0'-- @with_default()- def get_network_status(self, relay = None, default = UNDEFINED):- """- get_network_status(relay = None, default = UNDEFINED)-- Provides the router status entry for the relay with the given fingerprint- or nickname. If the relay identifier could be either a fingerprint *or*- nickname then it's queried as a fingerprint.-- This provides- :class:`~stem.descriptor.router_status_entry.RouterStatusEntryMicroV3`- instances if tor is using microdescriptors...-- ::-- controller.get_conf('UseMicrodescriptors', '0') == '1'-- ... and :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3`- otherwise.-- If no **relay** is provided then this defaults to ourselves. Remember that- this requires that we've retrieved our own descriptor from remote- authorities so this both won't be available for newly started relays and- may be up to around an hour out of date.-- .. versionchanged:: 1.3.0- Changed so we'd fetch our own descriptor if no 'relay' is provided.-- :param str relay: fingerprint or nickname of the relay to be queried- :param object default: response if the query fails-- :returns: :class:`~stem.descriptor.router_status_entry.RouterStatusEntry`- for the given relay-- :raises:- * :class:`stem.DescriptorUnavailable` if unable to provide a descriptor- for the given relay- * :class:`stem.ControllerError` if unable to query the descriptor- * **ValueError** if **relay** doesn't conform with the pattern for being- a fingerprint or nickname-- An exception is only raised if we weren't provided a default response.- """-- if relay is None:- try:- relay = self.get_info('fingerprint')- except stem.ControllerError as exc:- raise stem.ControllerError('Unable to determine our own fingerprint: %s' % exc)-- if stem.util.tor_tools.is_valid_fingerprint(relay):- query = 'ns/id/%s' % relay- elif stem.util.tor_tools.is_valid_nickname(relay):- query = 'ns/name/%s' % relay- else:- raise ValueError("'%s' isn't a valid fingerprint or nickname" % relay)-- try:- desc_content = self.get_info(query, get_bytes = True)- except stem.InvalidArguments as exc:- if str(exc).startswith('GETINFO request contained unrecognized keywords:'):- raise stem.DescriptorUnavailable("Tor was unable to provide the descriptor for '%s'" % relay)- else:- raise exc-- if not desc_content:- raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')-- if self.get_conf('UseMicrodescriptors', '0') == '1':- return stem.descriptor.router_status_entry.RouterStatusEntryMicroV3(desc_content)- else:- return stem.descriptor.router_status_entry.RouterStatusEntryV3(desc_content)-- @with_default(yields = True)- def get_network_statuses(self, default = UNDEFINED):- """- get_network_statuses(default = UNDEFINED)-- Provides an iterator for all of the router status entries that tor- currently knows about.-- This provides- :class:`~stem.descriptor.router_status_entry.RouterStatusEntryMicroV3`- instances if tor is using microdescriptors...-- ::-- controller.get_conf('UseMicrodescriptors', '0') == '1'-- ... and :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3`- otherwise.-- :param list default: items to provide if the query fails-- :returns: iterates over- :class:`~stem.descriptor.router_status_entry.RouterStatusEntry` for- relays in the tor network-- :raises: :class:`stem.ControllerError` if unable to query tor and no- default was provided- """-- # TODO: We should iterate over the descriptors as they're read from the- # socket rather than reading the whole thing into memory.- #- # https://trac.torproject.org/8248-- if self.get_conf('UseMicrodescriptors', '0') == '1':- desc_class = stem.descriptor.router_status_entry.RouterStatusEntryMicroV3- else:- desc_class = stem.descriptor.router_status_entry.RouterStatusEntryV3-- desc_content = self.get_info('ns/all', get_bytes = True)-- if not desc_content:- raise stem.DescriptorUnavailable('Descriptor information is unavailable, tor might still be downloading it')-- desc_iterator = stem.descriptor.router_status_entry._parse_file(- io.BytesIO(desc_content),- True,- entry_class = desc_class,- )-- for desc in desc_iterator:- yield desc-- @with_default()- def get_hidden_service_descriptor(self, address, default = UNDEFINED, servers = None, await_result = True):- """- get_hidden_service_descriptor(address, default = UNDEFINED, servers = None, await_result = True)-- Provides the descriptor for a hidden service. The **address** is the- '.onion' address of the hidden service (for instance 3g2upl4pq6kufc4m.onion- for DuckDuckGo).-- If **await_result** is **True** then this blocks until we either receive- the descriptor or the request fails. If **False** this returns right away.-- .. versionadded:: 1.4.0-- :param str address: address of the hidden service descriptor, the '.onion' suffix is optional- :param object default: response if the query fails- :param list servers: requrest the descriptor from these specific servers-- :returns: :class:`~stem.descriptor.hidden_service_descriptor.HiddenServiceDescriptor`- for the given service if **await_result** is **True**, or **None** otherwise-- :raises:- * :class:`stem.DescriptorUnavailable` if **await_result** is **True** and- unable to provide a descriptor for the given service- * :class:`stem.ControllerError` if unable to query the descriptor- * **ValueError** if **address** doesn't conform with the pattern of a- hidden service address-- An exception is only raised if we weren't provided a default response.- """-- if address.endswith('.onion'):- address = address[:-6]-- if not stem.util.tor_tools.is_valid_hidden_service_address(address):- raise ValueError("'%s.onion' isn't a valid hidden service address" % address)-- if self.get_version() < stem.version.Requirement.HSFETCH:- raise stem.UnsatisfiableRequest(message = 'HSFETCH was added in tor version %s' % stem.version.Requirement.HSFETCH)-- hs_desc_queue, hs_desc_listener = queue.Queue(), None- hs_desc_content_queue, hs_desc_content_listener = queue.Queue(), None-- if await_result:- def hs_desc_listener(event):- hs_desc_queue.put(event)-- def hs_desc_content_listener(event):- hs_desc_content_queue.put(event)-- self.add_event_listener(hs_desc_listener, EventType.HS_DESC)- self.add_event_listener(hs_desc_content_listener, EventType.HS_DESC_CONTENT)-- try:- request = 'HSFETCH %s' % address-- if servers:- request += ' '.join(['SERVER=%s' % s for s in servers])-- response = self.msg(request)- stem.response.convert('SINGLELINE', response)-- if not response.is_ok():- raise stem.ProtocolError('HSFETCH returned unexpected response code: %s' % response.code)-- if not await_result:- return None # not waiting, so nothing to provide back- else:- while True:- event = hs_desc_content_queue.get()-- if event.address == address:- if event.descriptor:- return event.descriptor- else:- # no descriptor, looking through HS_DESC to figure out why-- while True:- event = hs_desc_queue.get()-- if event.address == address and event.action == stem.HSDescAction.FAILED:- if event.reason == stem.HSDescReason.NOT_FOUND:- raise stem.DescriptorUnavailable('No running hidden service at %s.onion' % address)- else:- raise stem.DescriptorUnavailable('Unable to retrieve the descriptor for %s.onion (retrieved from %s): %s' % (address, event.directory_fingerprint, event.reason))- finally:- if hs_desc_listener:- self.remove_event_listener(hs_desc_listener)-- if hs_desc_content_listener:- self.remove_event_listener(hs_desc_content_listener)-- def get_conf(self, param, default = UNDEFINED, multiple = False):- """- Queries the current value for a configuration option. Some configuration- options (like the ExitPolicy) can have multiple values. This provides a- **list** with all of the values if **multiple** is **True**. Otherwise this- will be a **str** with the first value.-- If provided with a **default** then that is provided if the configuration- option was unset or the query fails (invalid configuration option, error- response, control port closed, initiated, etc).-- If the configuration value is unset and no **default** was given then this- provides **None** if **multiple** was **False** and an empty list if it was- **True**.-- :param str param: configuration option to be queried- :param object default: response if the option is unset or the query fails- :param bool multiple: if **True** then provides a list with all of the- present values (this is an empty list if the config option is unset)-- :returns:- Response depends upon how we were called as follows...-- * **str** with the configuration value if **multiple** was **False**,- **None** if it was unset- * **list** with the response strings if multiple was **True**- * default if one was provided and the configuration option was either- unset or our call failed-- :raises:- * :class:`stem.ControllerError` if the call fails and we weren't- provided a default response- * :class:`stem.InvalidArguments` if the configuration option- requested was invalid- """-- # Config options are case insensitive and don't contain whitespace. Using- # strip so the following check will catch whitespace-only params.-- param = param.lower().strip()-- if not param:- return default if default != UNDEFINED else None-- entries = self.get_conf_map(param, default, multiple)- return _case_insensitive_lookup(entries, param, default)-- def get_conf_map(self, params, default = UNDEFINED, multiple = True):- """- Similar to :func:`~stem.control.Controller.get_conf` but queries multiple- configuration options, providing back a mapping of those options to their- values.-- There are three use cases for GETCONF:-- 1. a single value is provided (e.g. **ControlPort**)- 2. multiple values are provided for the option (e.g. **ExitPolicy**)- 3. a set of options that weren't necessarily requested are returned (for- instance querying **HiddenServiceOptions** gives **HiddenServiceDir**,- **HiddenServicePort**, etc)-- The vast majority of the options fall into the first two categories, in- which case calling :func:`~stem.control.Controller.get_conf` is sufficient.- However, for batch queries or the special options that give a set of values- this provides back the full response. As of tor version 0.2.1.25- **HiddenServiceOptions** was the only option that falls into the third- category.-- :param str,list params: configuration option(s) to be queried- :param object default: value for the mappings if the configuration option- is either undefined or the query fails- :param bool multiple: if **True** then the values provided are lists with- all of the present values-- :returns:- **dict** of the 'config key => value' mappings. The value is a...-- * **str** if **multiple** is **False**, **None** if the configuration- option is unset- * **list** if **multiple** is **True**- * the **default** if it was set and the value was either undefined or our- lookup failed-- :raises:- * :class:`stem.ControllerError` if the call fails and we weren't provided- a default response- * :class:`stem.InvalidArguments` if the configuration option requested- was invalid- """-- start_time = time.time()- reply = {}-- if isinstance(params, (bytes, str_type)):- params = [params]-- # remove strings which contain only whitespace- params = [entry for entry in params if entry.strip()]-- if params == []:- return {}-- # translate context sensitive options- lookup_params = set([MAPPED_CONFIG_KEYS.get(entry, entry) for entry in params])-- # check for cached results-- from_cache = [param.lower() for param in lookup_params]- cached_results = self._get_cache_map(from_cache, 'getconf')-- for key in cached_results:- user_expected_key = _case_insensitive_lookup(lookup_params, key)- reply[user_expected_key] = cached_results[key]- lookup_params.remove(user_expected_key)-- # if everything was cached then short circuit making the query- if not lookup_params:- log.trace('GETCONF %s (cache fetch)' % ' '.join(reply.keys()))- return self._get_conf_dict_to_response(reply, default, multiple)-- try:- response = self.msg('GETCONF %s' % ' '.join(lookup_params))- stem.response.convert('GETCONF', response)- reply.update(response.entries)-- if self.is_caching_enabled():- to_cache = dict((k.lower(), v) for k, v in response.entries.items())-- for key in UNCACHEABLE_GETCONF_PARAMS:- if key in to_cache:- del to_cache[key]-- self._set_cache(to_cache, 'getconf')-- # Maps the entries back to the parameters that the user requested so the- # capitalization matches (ie, if they request "exitpolicy" then that- # should be the key rather than "ExitPolicy"). When the same- # configuration key is provided multiple times this determines the case- # based on the first and ignores the rest.- #- # This retains the tor provided camel casing of MAPPED_CONFIG_KEYS- # entries since the user didn't request those by their key, so we can't- # be sure what they wanted.-- for key in reply:- if not key.lower() in MAPPED_CONFIG_KEYS.values():- user_expected_key = _case_insensitive_lookup(params, key, key)-- if key != user_expected_key:- reply[user_expected_key] = reply[key]- del reply[key]-- log.debug('GETCONF %s (runtime: %0.4f)' % (' '.join(lookup_params), time.time() - start_time))- return self._get_conf_dict_to_response(reply, default, multiple)- except stem.ControllerError as exc:- log.debug('GETCONF %s (failed: %s)' % (' '.join(lookup_params), exc))-- if default != UNDEFINED:- return dict((param, default) for param in params)- else:- raise exc-- def _get_conf_dict_to_response(self, config_dict, default, multiple):- """- Translates a dictionary of 'config key => [value1, value2...]' into the- return value of :func:`~stem.control.Controller.get_conf_map`, taking into- account what the caller requested.- """-- return_dict = {}-- for key, values in list(config_dict.items()):- if values == []:- # config option was unset- if default != UNDEFINED:- return_dict[key] = default- else:- return_dict[key] = [] if multiple else None- else:- return_dict[key] = values if multiple else values[0]-- return return_dict-- def set_conf(self, param, value):- """- Changes the value of a tor configuration option. Our value can be any of- the following...-- * a string to set a single value- * a list of strings to set a series of values (for instance the ExitPolicy)- * None to either set the value to 0/NULL-- :param str param: configuration option to be set- :param str,list value: value to set the parameter to-- :raises:- * :class:`stem.ControllerError` if the call fails- * :class:`stem.InvalidArguments` if configuration options- requested was invalid- * :class:`stem.InvalidRequest` if the configuration setting is- impossible or if there's a syntax error in the configuration values- """-- self.set_options({param: value}, False)-- def reset_conf(self, *params):- """- Reverts one or more parameters to their default values.-- :param str params: configuration option to be reset-- :raises:- * :class:`stem.ControllerError` if the call fails- * :class:`stem.InvalidArguments` if configuration options requested was invalid- * :class:`stem.InvalidRequest` if the configuration setting is- impossible or if there's a syntax error in the configuration values- """-- self.set_options(dict([(entry, None) for entry in params]), True)-- def set_options(self, params, reset = False):- """- Changes multiple tor configuration options via either a SETCONF or- RESETCONF query. Both behave identically unless our value is None, in which- case SETCONF sets the value to 0 or NULL, and RESETCONF returns it to its- default value. This accepts str, list, or None values in a similar fashion- to :func:`~stem.control.Controller.set_conf`. For example...-- ::-- my_controller.set_options({- 'Nickname': 'caerSidi',- 'ExitPolicy': ['accept *:80', 'accept *:443', 'reject *:*'],- 'ContactInfo': '[email protected]',- 'Log': None,- })-- The params can optionally be a list of key/value tuples, though the only- reason this type of argument would be useful is for hidden service- configuration (those options are order dependent).-- :param dict,list params: mapping of configuration options to the values- we're setting it to- :param bool reset: issues a RESETCONF, returning **None** values to their- defaults if **True**-- :raises:- * :class:`stem.ControllerError` if the call fails- * :class:`stem.InvalidArguments` if configuration options- requested was invalid- * :class:`stem.InvalidRequest` if the configuration setting is- impossible or if there's a syntax error in the configuration values- """-- start_time = time.time()-- # constructs the SETCONF or RESETCONF query- query_comp = ['RESETCONF' if reset else 'SETCONF']-- if isinstance(params, dict):- params = list(params.items())-- for param, value in params:- if isinstance(value, str):- query_comp.append('%s="%s"' % (param, value.strip()))- elif value:- query_comp.extend(['%s="%s"' % (param, val.strip()) for val in value])- else:- query_comp.append(param)-- query = ' '.join(query_comp)- response = self.msg(query)- stem.response.convert('SINGLELINE', response)-- if response.is_ok():- log.debug('%s (runtime: %0.4f)' % (query, time.time() - start_time))-- if self.is_caching_enabled():- to_cache = {}-- for param, value in params:- param = param.lower()-- if isinstance(value, (bytes, str_type)):- value = [value]-- to_cache[param] = value-- if param == 'exitpolicy':- self._set_cache({'exitpolicy': None})-- self._set_cache(to_cache, 'getconf')- else:- log.debug('%s (failed, code: %s, message: %s)' % (query, response.code, response.message))-- if response.code == '552':- if response.message.startswith("Unrecognized option: Unknown option '"):- key = response.message[37:response.message.find("'", 37)]- raise stem.InvalidArguments(response.code, response.message, [key])- raise stem.InvalidRequest(response.code, response.message)- elif response.code in ('513', '553'):- raise stem.InvalidRequest(response.code, response.message)- else:- raise stem.ProtocolError('Returned unexpected status code: %s' % response.code)-- @with_default()- def get_hidden_service_conf(self, default = UNDEFINED):- """- get_hidden_service_conf(default = UNDEFINED)-- This provides a mapping of hidden service directories to their- attribute's key/value pairs. All hidden services are assured to have a- 'HiddenServicePort', but other entries may or may not exist.-- ::-- {- "/var/lib/tor/hidden_service_empty/": {- "HiddenServicePort": [- ]- },- "/var/lib/tor/hidden_service_with_two_ports/": {- "HiddenServiceAuthorizeClient": "stealth a, b",- "HiddenServicePort": [- (8020, "127.0.0.1", 8020), # the ports order is kept- (8021, "127.0.0.1", 8021)- ],- "HiddenServiceVersion": "2"- },- }-- .. versionadded:: 1.3.0-- :param object default: response if the query fails-- :returns: **dict** with the hidden service configuration-- :raises: :class:`stem.ControllerError` if the call fails and we weren't- provided a default response- """-- start_time = time.time()-- try:- response = self.msg('GETCONF HiddenServiceOptions')- stem.response.convert('GETCONF', response)- log.debug('GETCONF HiddenServiceOptions (runtime: %0.4f)' %- (time.time() - start_time))- except stem.ControllerError as exc:- log.debug('GETCONF HiddenServiceOptions (failed: %s)' % exc)- raise exc-- service_dir_map = OrderedDict()- directory = None-- for status_code, divider, content in response.content():- if content == 'HiddenServiceOptions':- continue-- if '=' not in content:- continue-- k, v = content.split('=', 1)-- if k == 'HiddenServiceDir':- directory = v- service_dir_map[directory] = {'HiddenServicePort': []}- elif k == 'HiddenServicePort':- port = target_port = v- target_address = '127.0.0.1'-- if not v.isdigit():- port, target = v.split()-- if target.isdigit():- target_port = target- else:- target_address, target_port = target.split(':')-- if not stem.util.connection.is_valid_port(port):- raise stem.ProtocolError('GETCONF provided an invalid HiddenServicePort port (%s): %s' % (port, content))- elif not stem.util.connection.is_valid_ipv4_address(target_address):- raise stem.ProtocolError('GETCONF provided an invalid HiddenServicePort target address (%s): %s' % (target_address, content))- elif not stem.util.connection.is_valid_port(target_port):- raise stem.ProtocolError('GETCONF provided an invalid HiddenServicePort target port (%s): %s' % (target_port, content))-- service_dir_map[directory]['HiddenServicePort'].append((int(port), target_address, int(target_port)))- else:- service_dir_map[directory][k] = v-- return service_dir_map-- def set_hidden_service_conf(self, conf):- """- Update all the configured hidden services from a dictionary having- the same format as- :func:`~stem.control.Controller.get_hidden_service_conf`.-- For convenience the HiddenServicePort entries can be an integer, string, or- tuple. If an **int** then we treat it as just a port. If a **str** we pass- that directly as the HiddenServicePort. And finally, if a **tuple** then- it's expected to be the **(port, target_address, target_port)** as provided- by :func:`~stem.control.Controller.get_hidden_service_conf`.-- This is to say the following three are equivalent...-- ::-- "HiddenServicePort": [- 80,- '80 127.0.0.1:80',- (80, '127.0.0.1', 80),- ]-- .. versionadded:: 1.3.0-- :param dict conf: configuration dictionary-- :raises:- * :class:`stem.ControllerError` if the call fails- * :class:`stem.InvalidArguments` if configuration options- requested was invalid- * :class:`stem.InvalidRequest` if the configuration setting is- impossible or if there's a syntax error in the configuration values- """-- # If we're not adding or updating any hidden services then call RESETCONF- # so we drop existing values. Otherwise calling SETCONF is a no-op.-- if not conf:- self.reset_conf('HiddenServiceDir')- return-- # Convert conf dictionary into a list of ordered config tuples-- hidden_service_options = []-- for directory in conf:- hidden_service_options.append(('HiddenServiceDir', directory))-- for k, v in list(conf[directory].items()):- if k == 'HiddenServicePort':- for entry in v:- if isinstance(entry, int):- entry = '%s 127.0.0.1:%s' % (entry, entry)- elif isinstance(entry, str):- pass # just pass along what the user gave us- elif isinstance(entry, tuple):- port, target_address, target_port = entry- entry = '%s %s:%s' % (port, target_address, target_port)-- hidden_service_options.append(('HiddenServicePort', entry))- else:- hidden_service_options.append((k, str(v)))-- self.set_options(hidden_service_options)-- def create_hidden_service(self, path, port, target_address = None, target_port = None, auth_type = None, client_names = None):- """- Create a new hidden service. If the directory is already present, a- new port is added. This provides a **namedtuple** of the following...-- * path (str) - hidden service directory-- * hostname (str) - Content of the hostname file, if no **client_names**- are provided this is the onion address of the service. This is only- retrieved if we can read the hidden service directory.-- * hostname_for_client (dict) - mapping of client names to their onion- address, this is only set if the **client_names** was provided and we- can read the hidden service directory-- * config (dict) - tor's new hidden service configuration-- Our *.onion address is fetched by reading the hidden service directory.- However, this directory is only readable by the tor user, so if unavailable- the **hostname** will be **None**.-- **As of Tor 0.2.7.1 there's two ways for creating hidden services. This is- no longer the recommended method.** Rather, try using- :func:`~stem.control.Controller.create_ephemeral_hidden_service` instead.-- .. versionadded:: 1.3.0-- .. versionchanged:: 1.4.0- Added the auth_type and client_names arguments.-- :param str path: path for the hidden service's data directory- :param int port: hidden service port- :param str target_address: address of the service, by default 127.0.0.1- :param int target_port: port of the service, by default this is the same as- **port**- :param str auth_type: authentication type: basic, stealth or None to disable auth- :param list client_names: client names (1-16 characters "A-Za-z0-9+-_")-- :returns: **CreateHiddenServiceOutput** if we create or update a hidden service, **None** otherwise-- :raises: :class:`stem.ControllerError` if the call fails- """-- if not stem.util.connection.is_valid_port(port):- raise ValueError("%s isn't a valid port number" % port)- elif target_address and not stem.util.connection.is_valid_ipv4_address(target_address):- raise ValueError("%s isn't a valid IPv4 address" % target_address)- elif target_port is not None and not stem.util.connection.is_valid_port(target_port):- raise ValueError("%s isn't a valid port number" % target_port)- elif auth_type not in (None, 'basic', 'stealth'):- raise ValueError("%s isn't a recognized type of authentication" % auth_type)-- port = int(port)- target_address = target_address if target_address else '127.0.0.1'- target_port = port if target_port is None else int(target_port)-- conf = self.get_hidden_service_conf()-- if path in conf and (port, target_address, target_port) in conf[path]['HiddenServicePort']:- return None-- conf.setdefault(path, OrderedDict()).setdefault('HiddenServicePort', []).append((port, target_address, target_port))-- if auth_type and client_names:- hsac = "%s %s" % (auth_type, ','.join(client_names))- conf[path]['HiddenServiceAuthorizeClient'] = hsac-- self.set_hidden_service_conf(conf)-- hostname, hostname_for_client = None, {}-- if self.is_localhost():- hostname_path = os.path.join(path, 'hostname')-- if not os.path.isabs(hostname_path):- cwd = stem.util.system.cwd(self.get_pid(None))-- if cwd:- hostname_path = stem.util.system.expand_path(hostname_path, cwd)-- if os.path.isabs(hostname_path):- start_time = time.time()-- while not os.path.exists(hostname_path):- wait_time = time.time() - start_time-- if wait_time >= 3:- break- else:- time.sleep(0.05)-- try:- with open(hostname_path) as hostname_file:- hostname = hostname_file.read().strip()-- if client_names and '\n' in hostname:- # When there's multiple clients this looks like...- #- # ndisjxzkgcdhrwqf.onion sjUwjTSPznqWLdOPuwRUzg # client: c1- # ndisjxzkgcdhrwqf.onion sUu92axuL5bKnA76s2KRfw # client: c2-- for line in hostname.splitlines():- if ' # client: ' in line:- address = line.split()[0]- client = line.split(' # client: ', 1)[1]-- if len(address) == 22 and address.endswith('.onion'):- hostname_for_client[client] = address- except:- pass-- return CreateHiddenServiceOutput(- path = path,- hostname = hostname,- hostname_for_client = hostname_for_client,- config = conf,- )-- def remove_hidden_service(self, path, port = None):- """- Discontinues a given hidden service.-- .. versionadded:: 1.3.0-- :param str path: path for the hidden service's data directory- :param int port: hidden service port-- :returns: **True** if the hidden service is discontinued, **False** if it- wasn't running in the first place-- :raises: :class:`stem.ControllerError` if the call fails- """-- if port and not stem.util.connection.is_valid_port(port):- raise ValueError("%s isn't a valid port number" % port)-- port = int(port) if port else None- conf = self.get_hidden_service_conf()-- if path not in conf:- return False-- if not port:- del conf[path]- else:- to_remove = [entry for entry in conf[path]['HiddenServicePort'] if entry[0] == port]-- if not to_remove:- return False-- for entry in to_remove:- conf[path]['HiddenServicePort'].remove(entry)-- if not conf[path]['HiddenServicePort']:- del conf[path] # no ports left-- self.set_hidden_service_conf(conf)- return True-- @with_default()- def list_ephemeral_hidden_services(self, default = UNDEFINED, our_services = True, detached = False):- """- list_ephemeral_hidden_services(default = UNDEFINED, our_services = True, detached = False)-- Lists hidden service addresses created by- :func:`~stem.control.Controller.create_ephemeral_hidden_service`.-- .. versionadded:: 1.4.0-- :param object default: response if the query fails- :param bool our_services: include services created with this controller- that weren't flagged as 'detached'- :param bool detached: include services whos contiuation isn't tied to a- controller-- :returns: **list** of hidden service addresses without their '.onion'- suffix-- :raises: :class:`stem.ControllerError` if the call fails and we weren't- provided a default response- """-- if self.get_version() < stem.version.Requirement.ADD_ONION:- raise stem.UnsatisfiableRequest(message = 'Ephemeral hidden services were added in tor version %s' % stem.version.Requirement.ADD_ONION)-- result = []-- if our_services:- try:- result += self.get_info('onions/current').split('\n')- except stem.ProtocolError as exc:- if 'No onion services of the specified type.' not in str(exc):- raise exc-- if detached:- try:- result += self.get_info('onions/detached').split('\n')- except stem.ProtocolError as exc:- if 'No onion services of the specified type.' not in str(exc):- raise exc-- return result-- def create_ephemeral_hidden_service(self, ports, key_type = 'NEW', key_content = 'BEST', discard_key = False, detached = False, await_publication = False):- """- Creates a new hidden service. Unlike- :func:`~stem.control.Controller.create_hidden_service` this style of- hidden service doesn't touch disk, carrying with it a lot of advantages.- This is the suggested method for making hidden services.-- Our **ports** argument can be a single port...-- ::-- create_ephemeral_hidden_service(80)-- ... list of ports the service is available on...-- ::-- create_ephemeral_hidden_service([80, 443])-- ... or a mapping of hidden service ports to their targets...-- ::-- create_ephemeral_hidden_service({80: 80, 443: '173.194.33.133:443'})-- .. versionadded:: 1.4.0-- :param int,list,dict ports: hidden service port(s) or mapping of hidden- service ports to their targets- :param str key_type: type of key being provided, generates a new key if- 'NEW' (options are: **NEW** and **RSA1024**)- :param str key_content: key for the service to use or type of key to be- generated (options when **key_type** is **NEW** are **BEST** and- **RSA1024**)- :param bool discard_key: avoid providing the key back in our response- :param bool detached: continue this hidden service even after this control- connection is closed if **True**- :param bool await_publication: blocks until our descriptor is successfully- published if **True**-- :returns: :class:`~stem.response.add_onion.AddOnionResponse` with the response-- :raises: :class:`stem.ControllerError` if the call fails- """-- if self.get_version() < stem.version.Requirement.ADD_ONION:- raise stem.UnsatisfiableRequest(message = 'Ephemeral hidden services were added in tor version %s' % stem.version.Requirement.ADD_ONION)-- hs_desc_queue, hs_desc_listener = queue.Queue(), None-- if await_publication:- def hs_desc_listener(event):- hs_desc_queue.put(event)-- self.add_event_listener(hs_desc_listener, EventType.HS_DESC)-- request = 'ADD_ONION %s:%s' % (key_type, key_content)-- flags = []-- if discard_key:- flags.append('DiscardPK')-- if detached:- flags.append('Detach')-- if flags:- request += ' Flags=%s' % ','.join(flags)-- if isinstance(ports, int):- request += ' Port=%s' % ports- elif isinstance(ports, list):- for port in ports:- request += ' Port=%s' % port- elif isinstance(ports, dict):- for port, target in ports.items():- request += ' Port=%s,%s' % (port, target)- else:- raise ValueError("The 'ports' argument of create_ephemeral_hidden_service() needs to be an int, list, or dict")-- response = self.msg(request)- stem.response.convert('ADD_ONION', response)-- if await_publication:- # We should receive five UPLOAD events, followed by up to another five- # UPLOADED to indicate they've finished. Presently tor seems to have an- # issue where the address is provided for UPLOAD but not UPLOADED so need- # to just guess that if it's for the same hidden service authority then- # it's what we're looking for.-- directories_uploaded_to, failures = [], []-- try:- while True:- event = hs_desc_queue.get()-- if event.action == stem.HSDescAction.UPLOAD and event.address == response.service_id:- directories_uploaded_to.append(event.directory_fingerprint)- elif event.action == stem.HSDescAction.UPLOADED and event.directory_fingerprint in directories_uploaded_to:- break # successfully uploaded to a HS authority... maybe- elif event.action == stem.HSDescAction.FAILED and event.directory_fingerprint in directories_uploaded_to:- failures.append('%s (%s)' % (event.directory_fingerprint, event.reason))-- if len(directories_uploaded_to) == len(failures):- raise stem.OperationFailed(message = 'Failed to upload our hidden service descriptor to %s' % ', '.join(failures))- finally:- self.remove_event_listener(hs_desc_listener)-- return response-- def remove_ephemeral_hidden_service(self, service_id):- """- Discontinues a given hidden service that was created with- :func:`~stem.control.Controller.create_ephemeral_hidden_service`.-- .. versionadded:: 1.4.0-- :param str service_id: hidden service address without the '.onion' suffix-- :returns: **True** if the hidden service is discontinued, **False** if it- wasn't running in the first place-- :raises: :class:`stem.ControllerError` if the call fails- """-- if self.get_version() < stem.version.Requirement.ADD_ONION:- raise stem.UnsatisfiableRequest(message = 'Ephemeral hidden services were added in tor version %s' % stem.version.Requirement.ADD_ONION)-- response = self.msg('DEL_ONION %s' % service_id)- stem.response.convert('SINGLELINE', response)-- if response.is_ok():- return True- elif response.code == '552':- return False # no hidden service to discontinue- else:- raise stem.ProtocolError('DEL_ONION returned unexpected response code: %s' % response.code)-- def add_event_listener(self, listener, *events):- """- Directs further tor controller events to a given function. The function is- expected to take a single argument, which is a- :class:`~stem.response.events.Event` subclass. For instance the following- would print the bytes sent and received by tor over five seconds...-- ::-- import time- from stem.control import Controller, EventType-- def print_bw(event):- print('sent: %i, received: %i' % (event.written, event.read))-- with Controller.from_port(port = 9051) as controller:- controller.authenticate()- controller.add_event_listener(print_bw, EventType.BW)- time.sleep(5)-- If a new control connection is initialized then this listener will be- reattached.-- :param functor listener: function to be called when an event is received- :param stem.control.EventType events: event types to be listened for-- :raises: :class:`stem.ProtocolError` if unable to set the events- """-- # first checking that tor supports these event types-- with self._event_listeners_lock:- if self.is_authenticated():- for event_type in events:- event_type = stem.response.events.EVENT_TYPE_TO_CLASS.get(event_type)-- if event_type and (self.get_version() < event_type._VERSION_ADDED):- raise stem.InvalidRequest(552, '%s event requires Tor version %s or later' % (event_type, event_type._VERSION_ADDED))-- for event_type in events:- self._event_listeners.setdefault(event_type, []).append(listener)-- failed_events = self._attach_listeners()[1]-- # restricted the failures to just things we requested-- failed_events = set(failed_events).intersection(set(events))-- if failed_events:- raise stem.ProtocolError('SETEVENTS rejected %s' % ', '.join(failed_events))-- def remove_event_listener(self, listener):- """- Stops a listener from being notified of further tor events.-- :param stem.control.EventListener listener: listener to be removed-- :raises: :class:`stem.ProtocolError` if unable to set the events- """-- with self._event_listeners_lock:- event_types_changed = False-- for event_type, event_listeners in list(self._event_listeners.items()):- if listener in event_listeners:- event_listeners.remove(listener)-- if len(event_listeners) == 0:- event_types_changed = True- del self._event_listeners[event_type]-- if event_types_changed:- response = self.msg('SETEVENTS %s' % ' '.join(self._event_listeners.keys()))-- if not response.is_ok():- raise stem.ProtocolError('SETEVENTS received unexpected response\n%s' % response)-- def _get_cache(self, param, namespace = None):- """- Queries our request cache for the given key.-- :param str param: key to be queried- :param str namespace: namespace in which to check for the key-- :returns: cached value corresponding to key or **None** if the key wasn't found- """-- return self._get_cache_map([param], namespace).get(param, None)-- def _get_cache_map(self, params, namespace = None):- """- Queries our request cache for multiple entries.-- :param list params: keys to be queried- :param str namespace: namespace in which to check for the keys-- :returns: **dict** of 'param => cached value' pairs of keys present in cache- """-- with self._cache_lock:- cached_values = {}-- if self.is_caching_enabled():- for param in params:- if namespace:- cache_key = '%s.%s' % (namespace, param)- else:- cache_key = param-- if cache_key in self._request_cache:- cached_values[param] = self._request_cache[cache_key]-- return cached_values-- def _set_cache(self, params, namespace = None):- """- Sets the given request cache entries. If the new cache value is **None**- then it is removed from our cache.-- :param dict params: **dict** of 'cache_key => value' pairs to be cached- :param str namespace: namespace for the keys- """-- with self._cache_lock:- if not self.is_caching_enabled():- return-- for key, value in list(params.items()):- if namespace:- cache_key = '%s.%s' % (namespace, key)- else:- cache_key = key-- if value is None:- if cache_key in self._request_cache:- del self._request_cache[cache_key]- else:- self._request_cache[cache_key] = value-- def is_caching_enabled(self):- """- **True** if caching has been enabled, **False** otherwise.-- :returns: bool to indicate if caching is enabled- """-- return self._is_caching_enabled-- def set_caching(self, enabled):- """- Enables or disables caching of information retrieved from tor.-- :param bool enabled: **True** to enable caching, **False** to disable it- """-- self._is_caching_enabled = enabled-- if not self._is_caching_enabled:- self.clear_cache()-- def clear_cache(self):- """- Drops any cached results.- """-- with self._cache_lock:- self._request_cache = {}- self._last_newnym = 0.0- self._geoip_failure_count = 0-- def load_conf(self, configtext):- """- Sends the configuration text to Tor and loads it as if it has been read from- the torrc.-- :param str configtext: the configuration text-- :raises: :class:`stem.ControllerError` if the call fails- """-- response = self.msg('LOADCONF\n%s' % configtext)- stem.response.convert('SINGLELINE', response)-- if response.code in ('552', '553'):- if response.code == '552' and response.message.startswith('Invalid config file: Failed to parse/validate config: Unknown option'):- raise stem.InvalidArguments(response.code, response.message, [response.message[70:response.message.find('.', 70) - 1]])- raise stem.InvalidRequest(response.code, response.message)- elif not response.is_ok():- raise stem.ProtocolError('+LOADCONF Received unexpected response\n%s' % str(response))-- def save_conf(self):- """- Saves the current configuration options into the active torrc file.-- :raises:- * :class:`stem.ControllerError` if the call fails- * :class:`stem.OperationFailed` if the client is unable to save- the configuration file- """-- response = self.msg('SAVECONF')- stem.response.convert('SINGLELINE', response)-- if response.is_ok():- return True- elif response.code == '551':- raise stem.OperationFailed(response.code, response.message)- else:- raise stem.ProtocolError('SAVECONF returned unexpected response code')-- def is_feature_enabled(self, feature):- """- Checks if a control connection feature is enabled. These features can be- enabled using :func:`~stem.control.Controller.enable_feature`.-- :param str feature: feature to be checked-- :returns: **True** if feature is enabled, **False** otherwise- """-- feature = feature.upper()-- if feature in self._enabled_features:- return True- else:- # check if this feature is on by default- defaulted_version = None-- if feature == 'EXTENDED_EVENTS':- defaulted_version = stem.version.Requirement.FEATURE_EXTENDED_EVENTS- elif feature == 'VERBOSE_NAMES':- defaulted_version = stem.version.Requirement.FEATURE_VERBOSE_NAMES-- if defaulted_version:- our_version = self.get_version(None)-- if our_version and our_version >= defaulted_version:- self._enabled_features.append(feature)-- return feature in self._enabled_features-- def enable_feature(self, features):- """- Enables features that are disabled by default to maintain backward- compatibility. Once enabled, a feature cannot be disabled and a new- control connection must be opened to get a connection with the feature- disabled. Feature names are case-insensitive.-- The following features are currently accepted:-- * EXTENDED_EVENTS - Requests the extended event syntax- * VERBOSE_NAMES - Replaces ServerID with LongName in events and GETINFO results-- :param str,list features: a single feature or a list of features to be enabled-- :raises:- * :class:`stem.ControllerError` if the call fails- * :class:`stem.InvalidArguments` if features passed were invalid- """-- if isinstance(features, (bytes, str_type)):- features = [features]-- response = self.msg('USEFEATURE %s' % ' '.join(features))- stem.response.convert('SINGLELINE', response)-- if not response.is_ok():- if response.code == '552':- invalid_feature = []-- if response.message.startswith('Unrecognized feature "'):- invalid_feature = [response.message[22:response.message.find('"', 22)]]-- raise stem.InvalidArguments(response.code, response.message, invalid_feature)-- raise stem.ProtocolError('USEFEATURE provided an invalid response code: %s' % response.code)-- self._enabled_features += [entry.upper() for entry in features]-- @with_default()- def get_circuit(self, circuit_id, default = UNDEFINED):- """- get_circuit(circuit_id, default = UNDEFINED)-- Provides a circuit currently available from tor.-- :param int circuit_id: circuit to be fetched- :param object default: response if the query fails-- :returns: :class:`stem.response.events.CircuitEvent` for the given circuit-- :raises:- * :class:`stem.ControllerError` if the call fails- * **ValueError** if the circuit doesn't exist-- An exception is only raised if we weren't provided a default response.- """-- for circ in self.get_circuits():- if circ.id == circuit_id:- return circ-- raise ValueError("Tor currently does not have a circuit with the id of '%s'" % circuit_id)-- @with_default()- def get_circuits(self, default = UNDEFINED):- """- get_circuits(default = UNDEFINED)-- Provides tor's currently available circuits.-- :param object default: response if the query fails-- :returns: **list** of :class:`stem.response.events.CircuitEvent` for our circuits-- :raises: :class:`stem.ControllerError` if the call fails and no default was provided- """-- circuits = []- response = self.get_info('circuit-status')-- for circ in response.splitlines():- circ_message = stem.socket.recv_message(StringIO('650 CIRC ' + circ + '\r\n'))- stem.response.convert('EVENT', circ_message, arrived_at = 0)- circuits.append(circ_message)-- return circuits-- def new_circuit(self, path = None, purpose = 'general', await_build = False):- """- Requests a new circuit. If the path isn't provided, one is automatically- selected.-- :param list,str path: one or more relays to make a circuit through- :param str purpose: 'general' or 'controller'- :param bool await_build: blocks until the circuit is built if **True**-- :returns: str of the circuit id of the newly created circuit-- :raises: :class:`stem.ControllerError` if the call fails- """-- return self.extend_circuit('0', path, purpose, await_build)-- def extend_circuit(self, circuit_id = '0', path = None, purpose = 'general', await_build = False):- """- Either requests the creation of a new circuit or extends an existing one.-- When called with a circuit value of zero (the default) a new circuit is- created, and when non-zero the circuit with that id is extended. If the- path isn't provided, one is automatically selected.-- A python interpreter session used to create circuits could look like this...-- ::-- >>> controller.extend_circuit('0', ['718BCEA286B531757ACAFF93AE04910EA73DE617', '30BAB8EE7606CBD12F3CC269AE976E0153E7A58D', '2765D8A8C4BBA3F89585A9FFE0E8575615880BEB'])- 19- >>> controller.extend_circuit('0')- 20- >>> print(controller.get_info('circuit-status'))- 20 EXTENDED $718BCEA286B531757ACAFF93AE04910EA73DE617=KsmoinOK,$649F2D0ACF418F7CFC6539AB2257EB2D5297BAFA=Eskimo BUILD_FLAGS=NEED_CAPACITY PURPOSE=GENERAL TIME_CREATED=2012-12-06T13:51:11.433755- 19 BUILT $718BCEA286B531757ACAFF93AE04910EA73DE617=KsmoinOK,$30BAB8EE7606CBD12F3CC269AE976E0153E7A58D=Pascal1,$2765D8A8C4BBA3F89585A9FFE0E8575615880BEB=Anthracite PURPOSE=GENERAL TIME_CREATED=2012-12-06T13:50:56.969938-- :param str circuit_id: id of a circuit to be extended- :param list,str path: one or more relays to make a circuit through, this is- required if the circuit id is non-zero- :param str purpose: 'general' or 'controller'- :param bool await_build: blocks until the circuit is built if **True**-- :returns: str of the circuit id of the created or extended circuit-- :raises:- * :class:`stem.InvalidRequest` if one of the parameters were invalid- * :class:`stem.CircuitExtensionFailed` if we were waiting for the circuit- to build but it failed- * :class:`stem.ControllerError` if the call fails- """-- # Attaches a temporary listener for CIRC events if we'll be waiting for it- # to build. This is icky, but we can't reliably do this via polling since- # we then can't get the failure if it can't be created.-- circ_queue, circ_listener = queue.Queue(), None-- if await_build:- def circ_listener(event):- circ_queue.put(event)-- self.add_event_listener(circ_listener, EventType.CIRC)-- try:- # we might accidently get integer circuit ids- circuit_id = str(circuit_id)-- if path is None and circuit_id == '0':- path_opt_version = stem.version.Requirement.EXTENDCIRCUIT_PATH_OPTIONAL-- if not self.get_version() >= path_opt_version:- raise stem.InvalidRequest(512, 'EXTENDCIRCUIT requires the path prior to version %s' % path_opt_version)-- args = [circuit_id]-- if isinstance(path, (bytes, str_type)):- path = [path]-- if path:- args.append(','.join(path))-- if purpose:- args.append('purpose=%s' % purpose)-- response = self.msg('EXTENDCIRCUIT %s' % ' '.join(args))- stem.response.convert('SINGLELINE', response)-- if response.code in ('512', '552'):- raise stem.InvalidRequest(response.code, response.message)- elif not response.is_ok():- raise stem.ProtocolError('EXTENDCIRCUIT returned unexpected response code: %s' % response.code)-- if not response.message.startswith('EXTENDED '):- raise stem.ProtocolError('EXTENDCIRCUIT response invalid:\n%s', response)-- new_circuit = response.message.split(' ', 1)[1]-- if await_build:- while True:- circ = circ_queue.get()-- if circ.id == new_circuit:- if circ.status == CircStatus.BUILT:- break- elif circ.status == CircStatus.FAILED:- raise stem.CircuitExtensionFailed('Circuit failed to be created: %s' % circ.reason, circ)- elif circ.status == CircStatus.CLOSED:- raise stem.CircuitExtensionFailed('Circuit was closed prior to build', circ)-- return new_circuit- finally:- if circ_listener:- self.remove_event_listener(circ_listener)-- def repurpose_circuit(self, circuit_id, purpose):- """- Changes a circuit's purpose. Currently, two purposes are recognized...- * general- * controller-- :param str circuit_id: id of the circuit whose purpose is to be changed- :param str purpose: purpose (either 'general' or 'controller')-- :raises: :class:`stem.InvalidArguments` if the circuit doesn't exist or if the purpose was invalid- """-- response = self.msg('SETCIRCUITPURPOSE %s purpose=%s' % (circuit_id, purpose))- stem.response.convert('SINGLELINE', response)-- if not response.is_ok():- if response.code == '552':- raise stem.InvalidRequest(response.code, response.message)- else:- raise stem.ProtocolError('SETCIRCUITPURPOSE returned unexpected response code: %s' % response.code)-- def close_circuit(self, circuit_id, flag = ''):- """- Closes the specified circuit.-- :param str circuit_id: id of the circuit to be closed- :param str flag: optional value to modify closing, the only flag available- is 'IfUnused' which will not close the circuit unless it is unused-- :raises: :class:`stem.InvalidArguments` if the circuit is unknown- :raises: :class:`stem.InvalidRequest` if not enough information is provided- """-- response = self.msg('CLOSECIRCUIT %s %s' % (circuit_id, flag))- stem.response.convert('SINGLELINE', response)-- if not response.is_ok():- if response.code in ('512', '552'):- if response.message.startswith('Unknown circuit '):- raise stem.InvalidArguments(response.code, response.message, [circuit_id])- raise stem.InvalidRequest(response.code, response.message)- else:- raise stem.ProtocolError('CLOSECIRCUIT returned unexpected response code: %s' % response.code)-- @with_default()- def get_streams(self, default = UNDEFINED):- """- get_streams(default = UNDEFINED)-- Provides the list of streams tor is currently handling.-- :param object default: response if the query fails-- :returns: list of :class:`stem.response.events.StreamEvent` objects-- :raises: :class:`stem.ControllerError` if the call fails and no default was- provided- """-- streams = []- response = self.get_info('stream-status')-- for stream in response.splitlines():- message = stem.socket.recv_message(StringIO('650 STREAM ' + stream + '\r\n'))- stem.response.convert('EVENT', message, arrived_at = 0)- streams.append(message)-- return streams-- def attach_stream(self, stream_id, circuit_id, exiting_hop = None):- """- Attaches a stream to a circuit.-- Note: Tor attaches streams to circuits automatically unless the- __LeaveStreamsUnattached configuration variable is set to '1'-- :param str stream_id: id of the stream that must be attached- :param str circuit_id: id of the circuit to which it must be attached- :param int exiting_hop: hop in the circuit where traffic should exit-- :raises:- * :class:`stem.InvalidRequest` if the stream or circuit id were unrecognized- * :class:`stem.UnsatisfiableRequest` if the stream isn't in a state where it can be attached- * :class:`stem.OperationFailed` if the stream couldn't be attached for any other reason- """-- query = 'ATTACHSTREAM %s %s' % (stream_id, circuit_id)-- if exiting_hop:- query += ' HOP=%s' % exiting_hop-- response = self.msg(query)- stem.response.convert('SINGLELINE', response)-- if not response.is_ok():- if response.code == '552':- raise stem.InvalidRequest(response.code, response.message)- elif response.code == '551':- raise stem.OperationFailed(response.code, response.message)- elif response.code == '555':- raise stem.UnsatisfiableRequest(response.code, response.message)- else:- raise stem.ProtocolError('ATTACHSTREAM returned unexpected response code: %s' % response.code)-- def close_stream(self, stream_id, reason = stem.RelayEndReason.MISC, flag = ''):- """- Closes the specified stream.-- :param str stream_id: id of the stream to be closed- :param stem.RelayEndReason reason: reason the stream is closing- :param str flag: not currently used-- :raises:- * :class:`stem.InvalidArguments` if the stream or reason are not recognized- * :class:`stem.InvalidRequest` if the stream and/or reason are missing- """-- # there's a single value offset between RelayEndReason.index_of() and the- # value that tor expects since tor's value starts with the index of one-- response = self.msg('CLOSESTREAM %s %s %s' % (stream_id, stem.RelayEndReason.index_of(reason) + 1, flag))- stem.response.convert('SINGLELINE', response)-- if not response.is_ok():- if response.code in ('512', '552'):- if response.message.startswith('Unknown stream '):- raise stem.InvalidArguments(response.code, response.message, [stream_id])- elif response.message.startswith('Unrecognized reason '):- raise stem.InvalidArguments(response.code, response.message, [reason])- raise stem.InvalidRequest(response.code, response.message)- else:- raise stem.ProtocolError('CLOSESTREAM returned unexpected response code: %s' % response.code)-- def signal(self, signal):- """- Sends a signal to the Tor client.-- :param stem.Signal signal: type of signal to be sent-- :raises: :class:`stem.InvalidArguments` if signal provided wasn't recognized- """-- response = self.msg('SIGNAL %s' % signal)- stem.response.convert('SINGLELINE', response)-- if response.is_ok():- if signal == stem.Signal.NEWNYM:- self._last_newnym = time.time()- else:- if response.code == '552':- raise stem.InvalidArguments(response.code, response.message, [signal])-- raise stem.ProtocolError('SIGNAL response contained unrecognized status code: %s' % response.code)-- def is_newnym_available(self):- """- Indicates if tor would currently accept a NEWNYM signal. This can only- account for signals sent via this controller.-- .. versionadded:: 1.2.0-- :returns: **True** if tor would currently accept a NEWNYM signal, **False**- otherwise- """-- if self.is_alive():- return self.get_newnym_wait() == 0.0- else:- return False-- def get_newnym_wait(self):- """- Provides the number of seconds until a NEWNYM signal would be respected.- This can only account for signals sent via this controller.-- .. versionadded:: 1.2.0-- :returns: **float** for the number of seconds until tor would respect- another NEWNYM signal- """-- return max(0.0, self._last_newnym + 10 - time.time())-- @with_default()- def get_effective_rate(self, default = UNDEFINED, burst = False):- """- get_effective_rate(default = UNDEFINED, burst = False)-- Provides the maximum rate this relay is configured to relay in bytes per- second. This is based on multiple torrc parameters if they're set...-- * Effective Rate = min(BandwidthRate, RelayBandwidthRate, MaxAdvertisedBandwidth)- * Effective Burst = min(BandwidthBurst, RelayBandwidthBurst)-- .. versionadded:: 1.3.0-- :param object default: response if the query fails- :param bool burst: provides the burst bandwidth, otherwise this provides- the standard rate-- :returns: **int** with the effective bandwidth rate in bytes per second-- :raises: :class:`stem.ControllerError` if the call fails and no default was- provided- """-- if not burst:- attributes = ('BandwidthRate', 'RelayBandwidthRate', 'MaxAdvertisedBandwidth')- else:- attributes = ('BandwidthBurst', 'RelayBandwidthBurst')-- value = None-- for attr in attributes:- attr_value = int(self.get_conf(attr))-- if attr_value == 0 and attr.startswith('Relay'):- continue # RelayBandwidthRate and RelayBandwidthBurst default to zero-- value = min(value, attr_value) if value else attr_value-- return value-- def is_geoip_unavailable(self):- """- Provides **True** if we've concluded hat our geoip database is unavailable,- **False** otherwise. This is determined by having our 'GETINFO- ip-to-country/\*' lookups fail so this will default to **False** if we- aren't making those queries.-- Geoip failures will be untracked if caching is disabled.-- :returns: **bool** to indicate if we've concluded our geoip database to be- unavailable or not- """-- return self._geoip_failure_count >= GEOIP_FAILURE_THRESHOLD-- def map_address(self, mapping):- """- Map addresses to replacement addresses. Tor replaces subseqent connections- to the original addresses with the replacement addresses.-- If the original address is a null address, i.e., one of '0.0.0.0', '::0', or- '.' Tor picks an original address itself and returns it in the reply. If the- original address is already mapped to a different address the mapping is- removed.-- :param dict mapping: mapping of original addresses to replacement addresses-- :raises:- * :class:`stem.InvalidRequest` if the addresses are malformed- * :class:`stem.OperationFailed` if Tor couldn't fulfill the request-- :returns: **dict** with 'original -> replacement' address mappings- """-- mapaddress_arg = ' '.join(['%s=%s' % (k, v) for (k, v) in list(mapping.items())])- response = self.msg('MAPADDRESS %s' % mapaddress_arg)- stem.response.convert('MAPADDRESS', response)-- return response.entries-- def drop_guards(self):- """- Drops our present guard nodes and picks a new set.-- .. versionadded:: 1.2.0-- :raises: :class:`stem.ControllerError` if Tor couldn't fulfill the request- """-- if self.get_version() < stem.version.Requirement.DROPGUARDS:- raise stem.UnsatisfiableRequest(message = 'DROPGUARDS was added in tor version %s' % stem.version.Requirement.DROPGUARDS)-- self.msg('DROPGUARDS')-- def _post_authentication(self):- super(Controller, self)._post_authentication()-- # try to re-attach event listeners to the new instance-- with self._event_listeners_lock:- try:- failed_events = self._attach_listeners()[1]-- if failed_events:- # remove our listeners for these so we don't keep failing- for event_type in failed_events:- del self._event_listeners[event_type]-- logging_id = 'stem.controller.event_reattach-%s' % '-'.join(failed_events)- log.log_once(logging_id, log.WARN, 'We were unable to re-attach our event listeners to the new tor instance for: %s' % ', '.join(failed_events))- except stem.ProtocolError as exc:- log.warn('Unable to issue the SETEVENTS request to re-attach our listeners (%s)' % exc)-- # issue TAKEOWNERSHIP if we're the owning process for this tor instance-- owning_pid = self.get_conf('__OwningControllerProcess', None)-- if owning_pid == str(os.getpid()) and self.is_localhost():- response = self.msg('TAKEOWNERSHIP')- stem.response.convert('SINGLELINE', response)-- if response.is_ok():- # Now that tor is tracking our ownership of the process via the control- # connection, we can stop having it check for us via our pid.-- try:- self.reset_conf('__OwningControllerProcess')- except stem.ControllerError as exc:- log.warn("We were unable to reset tor's __OwningControllerProcess configuration. It will continue to periodically check if our pid exists. (%s)" % exc)- else:- log.warn('We were unable assert ownership of tor through TAKEOWNERSHIP, despite being configured to be the owning process through __OwningControllerProcess. (%s)' % response)-- def _handle_event(self, event_message):- stem.response.convert('EVENT', event_message, arrived_at = time.time())-- with self._event_listeners_lock:- for event_type, event_listeners in list(self._event_listeners.items()):- if event_type == event_message.type:- for listener in event_listeners:- listener(event_message)-- def _attach_listeners(self):- """- Attempts to subscribe to the self._event_listeners events from tor. This is- a no-op if we're not currently authenticated.-- :returns: tuple of the form (set_events, failed_events)-- :raises: :class:`stem.ControllerError` if unable to make our request to tor- """-- set_events, failed_events = [], []-- with self._event_listeners_lock:- if self.is_authenticated():- # try to set them all- response = self.msg('SETEVENTS %s' % ' '.join(self._event_listeners.keys()))-- if response.is_ok():- set_events = list(self._event_listeners.keys())- else:- # One of the following likely happened...- #- # * Our user attached listeners before having an authenticated- # connection, so we couldn't check if we met the version- # requirement.- #- # * User attached listeners to one tor instance, then connected us to- # an older tor instancce.- #- # * Some other controller hiccup (far less likely).- #- # See if we can set some subset of our events.-- for event in list(self._event_listeners.keys()):- response = self.msg('SETEVENTS %s' % ' '.join(set_events + [event]))-- if response.is_ok():- set_events.append(event)- else:- failed_events.append(event)-- return (set_events, failed_events)---def _parse_circ_path(path):- """- Parses a circuit path as a list of **(fingerprint, nickname)** tuples. Tor- circuit paths are defined as being of the form...-- ::-- Path = LongName *("," LongName)- LongName = Fingerprint [ ( "=" / "~" ) Nickname ]-- example:- $999A226EBED397F331B612FE1E4CFAE5C1F201BA=piyaz-- ... *unless* this is prior to tor version 0.2.2.1 with the VERBOSE_NAMES- feature turned off (or before version 0.1.2.2 where the feature was- introduced). In that case either the fingerprint or nickname in the tuple- will be **None**, depending on which is missing.-- ::-- Path = ServerID *("," ServerID)- ServerID = Nickname / Fingerprint-- example:- $E57A476CD4DFBD99B4EE52A100A58610AD6E80B9,hamburgerphone,PrivacyRepublic14-- :param str path: circuit path to be parsed-- :returns: list of **(fingerprint, nickname)** tuples, fingerprints do not have a proceeding '$'-- :raises: :class:`stem.ProtocolError` if the path is malformed- """-- if path:- try:- return [_parse_circ_entry(entry) for entry in path.split(',')]- except stem.ProtocolError as exc:- # include the path with the exception- raise stem.ProtocolError('%s: %s' % (exc, path))- else:- return []---def _parse_circ_entry(entry):- """- Parses a single relay's 'LongName' or 'ServerID'. See the- :func:`~stem.control._parse_circ_path` function for more information.-- :param str entry: relay information to be parsed-- :returns: **(fingerprint, nickname)** tuple-- :raises: :class:`stem.ProtocolError` if the entry is malformed- """-- if '=' in entry:- # common case- fingerprint, nickname = entry.split('=')- elif '~' in entry:- # this is allowed for by the spec, but I've never seen it used- fingerprint, nickname = entry.split('~')- elif entry[0] == '$':- # old style, fingerprint only- fingerprint, nickname = entry, None- else:- # old style, nickname only- fingerprint, nickname = None, entry-- if fingerprint is not None:- if not stem.util.tor_tools.is_valid_fingerprint(fingerprint, True):- raise stem.ProtocolError('Fingerprint in the circuit path is malformed (%s)' % fingerprint)-- fingerprint = fingerprint[1:] # strip off the leading '$'-- if nickname is not None and not stem.util.tor_tools.is_valid_nickname(nickname):- raise stem.ProtocolError('Nickname in the circuit path is malformed (%s)' % nickname)-- return (fingerprint, nickname)---@with_default()-def _case_insensitive_lookup(entries, key, default = UNDEFINED):- """- Makes a case insensitive lookup within a list or dictionary, providing the- first matching entry that we come across.-- :param list,dict entries: list or dictionary to be searched- :param str key: entry or key value to look up- :param object default: value to be returned if the key doesn't exist-- :returns: case insensitive match or default if one was provided and key wasn't found-- :raises: **ValueError** if no such value exists- """-- if entries is not None:- if isinstance(entries, dict):- for k, v in list(entries.items()):- if k.lower() == key.lower():- return v- else:- for entry in entries:- if entry.lower() == key.lower():- return entry-- raise ValueError("key '%s' doesn't exist in dict: %s" % (key, entries))diff --git a/ext/stem/descriptor/__init__.py b/ext/stem/descriptor/__init__.pydeleted file mode 100644index e8b581ed..00000000--- a/ext/stem/descriptor/__init__.py+++ /dev/null@@ -1,847 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Package for parsing and processing descriptor data.--**Module Overview:**--::-- parse_file - Parses the descriptors in a file.-- Descriptor - Common parent for all descriptor file types.- |- get_path - location of the descriptor on disk if it came from a file- |- get_archive_path - location of the descriptor within the archive it came from- |- get_bytes - similar to str(), but provides our original bytes content- |- get_unrecognized_lines - unparsed descriptor content- +- __str__ - string that the descriptor was made from--.. data:: DocumentHandler (enum)-- Ways in which we can parse a- :class:`~stem.descriptor.networkstatus.NetworkStatusDocument`.-- Both **ENTRIES** and **BARE_DOCUMENT** have a 'thin' document, which doesn't- have a populated **routers** attribute. This allows for lower memory usage- and upfront runtime. However, if read time and memory aren't a concern then- **DOCUMENT** can provide you with a fully populated document.-- =================== ===========- DocumentHandler Description- =================== ===========- **ENTRIES** Iterates over the contained :class:`~stem.descriptor.router_status_entry.RouterStatusEntry`. Each has a reference to the bare document it came from (through its **document** attribute).- **DOCUMENT** :class:`~stem.descriptor.networkstatus.NetworkStatusDocument` with the :class:`~stem.descriptor.router_status_entry.RouterStatusEntry` it contains (through its **routers** attribute).- **BARE_DOCUMENT** :class:`~stem.descriptor.networkstatus.NetworkStatusDocument` **without** a reference to its contents (the :class:`~stem.descriptor.router_status_entry.RouterStatusEntry` are unread).- =================== ===========-"""--__all__ = [- 'export',- 'reader',- 'remote',- 'extrainfo_descriptor',- 'server_descriptor',- 'microdescriptor',- 'networkstatus',- 'router_status_entry',- 'tordnsel',- 'parse_file',- 'Descriptor',-]--import base64-import codecs-import copy-import hashlib-import os-import re-import tarfile--import stem.prereq-import stem.util.enum-import stem.util.str_tools-import stem.util.system--from stem import str_type--try:- # added in python 2.7- from collections import OrderedDict-except ImportError:- from stem.util.ordereddict import OrderedDict--KEYWORD_CHAR = 'a-zA-Z0-9-'-WHITESPACE = ' \t'-KEYWORD_LINE = re.compile('^([%s]+)(?:[%s]+(.*))?$' % (KEYWORD_CHAR, WHITESPACE))-SPECIFIC_KEYWORD_LINE = '^(%%s)(?:[%s]+(.*))?$' % WHITESPACE-PGP_BLOCK_START = re.compile('^-----BEGIN ([%s%s]+)-----$' % (KEYWORD_CHAR, WHITESPACE))-PGP_BLOCK_END = '-----END %s-----'--DocumentHandler = stem.util.enum.UppercaseEnum(- 'ENTRIES',- 'DOCUMENT',- 'BARE_DOCUMENT',-)---def parse_file(descriptor_file, descriptor_type = None, validate = False, document_handler = DocumentHandler.ENTRIES, **kwargs):- """- Simple function to read the descriptor contents from a file, providing an- iterator for its :class:`~stem.descriptor.__init__.Descriptor` contents.-- If you don't provide a **descriptor_type** argument then this automatically- tries to determine the descriptor type based on the following...-- * The @type annotation on the first line. These are generally only found in- the `CollecTor archives <https://collector.torproject.org/formats.html#relay-descriptors>`_.-- * The filename if it matches something from tor's data directory. For- instance, tor's 'cached-descriptors' contains server descriptors.-- This is a handy function for simple usage, but if you're reading multiple- descriptor files you might want to consider the- :class:`~stem.descriptor.reader.DescriptorReader`.-- Descriptor types include the following, including further minor versions (ie.- if we support 1.1 then we also support everything from 1.0 and most things- from 1.2, but not 2.0)...-- ========================================= =====- Descriptor Type Class- ========================================= =====- server-descriptor 1.0 :class:`~stem.descriptor.server_descriptor.RelayDescriptor`- extra-info 1.0 :class:`~stem.descriptor.extrainfo_descriptor.RelayExtraInfoDescriptor`- microdescriptor 1.0 :class:`~stem.descriptor.microdescriptor.Microdescriptor`- directory 1.0 **unsupported**- network-status-2 1.0 :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV2` (with a :class:`~stem.descriptor.networkstatus.NetworkStatusDocumentV2`)- dir-key-certificate-3 1.0 :class:`~stem.descriptor.networkstatus.KeyCertificate`- network-status-consensus-3 1.0 :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` (with a :class:`~stem.descriptor.networkstatus.NetworkStatusDocumentV3`)- network-status-vote-3 1.0 :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` (with a :class:`~stem.descriptor.networkstatus.NetworkStatusDocumentV3`)- network-status-microdesc-consensus-3 1.0 :class:`~stem.descriptor.router_status_entry.RouterStatusEntryMicroV3` (with a :class:`~stem.descriptor.networkstatus.NetworkStatusDocumentV3`)- bridge-network-status 1.0 :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` (with a :class:`~stem.descriptor.networkstatus.BridgeNetworkStatusDocument`)- bridge-server-descriptor 1.0 :class:`~stem.descriptor.server_descriptor.BridgeDescriptor`- bridge-extra-info 1.1 or 1.2 :class:`~stem.descriptor.extrainfo_descriptor.BridgeExtraInfoDescriptor`- torperf 1.0 **unsupported**- bridge-pool-assignment 1.0 **unsupported**- tordnsel 1.0 :class:`~stem.descriptor.tordnsel.TorDNSEL`- hidden-service-descriptor 1.0 :class:`~stem.descriptor.hidden_service_descriptor.HiddenServiceDescriptor`- ========================================= =====-- If you're using **python 3** then beware that the open() function defaults to- using text mode. **Binary mode** is strongly suggested because it's both- faster (by my testing by about 33x) and doesn't do universal newline- translation which can make us misparse the document.-- ::-- my_descriptor_file = open(descriptor_path, 'rb')-- :param str,file,tarfile descriptor_file: path or opened file with the descriptor contents- :param str descriptor_type: `descriptor type <https://collector.torproject.org/formats.html>`_, this is guessed if not provided- :param bool validate: checks the validity of the descriptor's content if- **True**, skips these checks otherwise- :param stem.descriptor.__init__.DocumentHandler document_handler: method in- which to parse the :class:`~stem.descriptor.networkstatus.NetworkStatusDocument`- :param dict kwargs: additional arguments for the descriptor constructor-- :returns: iterator for :class:`~stem.descriptor.__init__.Descriptor` instances in the file-- :raises:- * **ValueError** if the contents is malformed and validate is True- * **TypeError** if we can't match the contents of the file to a descriptor type- * **IOError** if unable to read from the descriptor_file- """-- # Delegate to a helper if this is a path or tarfile.-- handler = None-- if isinstance(descriptor_file, (bytes, str_type)):- if stem.util.system.is_tarfile(descriptor_file):- handler = _parse_file_for_tar_path- else:- handler = _parse_file_for_path- elif isinstance(descriptor_file, tarfile.TarFile):- handler = _parse_file_for_tarfile-- if handler:- for desc in handler(descriptor_file, descriptor_type, validate, document_handler, **kwargs):- yield desc-- return-- # The tor descriptor specifications do not provide a reliable method for- # identifying a descriptor file's type and version so we need to guess- # based on its filename. Metrics descriptors, however, can be identified- # by an annotation on their first line...- # https://trac.torproject.org/5651-- initial_position = descriptor_file.tell()- first_line = stem.util.str_tools._to_unicode(descriptor_file.readline().strip())- metrics_header_match = re.match('^@type (\S+) (\d+).(\d+)$', first_line)-- if not metrics_header_match:- descriptor_file.seek(initial_position)-- descriptor_path = getattr(descriptor_file, 'name', None)- filename = '<undefined>' if descriptor_path is None else os.path.basename(descriptor_file.name)- file_parser = None-- if descriptor_type is not None:- descriptor_type_match = re.match('^(\S+) (\d+).(\d+)$', descriptor_type)-- if descriptor_type_match:- desc_type, major_version, minor_version = descriptor_type_match.groups()- file_parser = lambda f: _parse_metrics_file(desc_type, int(major_version), int(minor_version), f, validate, document_handler, **kwargs)- else:- raise ValueError("The descriptor_type must be of the form '<type> <major_version>.<minor_version>'")- elif metrics_header_match:- # Metrics descriptor handling-- desc_type, major_version, minor_version = metrics_header_match.groups()- file_parser = lambda f: _parse_metrics_file(desc_type, int(major_version), int(minor_version), f, validate, document_handler, **kwargs)- else:- # Cached descriptor handling. These contain multiple descriptors per file.-- if filename == 'cached-descriptors' or filename == 'cached-descriptors.new':- file_parser = lambda f: stem.descriptor.server_descriptor._parse_file(f, validate = validate, **kwargs)- elif filename == 'cached-extrainfo' or filename == 'cached-extrainfo.new':- file_parser = lambda f: stem.descriptor.extrainfo_descriptor._parse_file(f, validate = validate, **kwargs)- elif filename == 'cached-microdescs' or filename == 'cached-microdescs.new':- file_parser = lambda f: stem.descriptor.microdescriptor._parse_file(f, validate = validate, **kwargs)- elif filename == 'cached-consensus':- file_parser = lambda f: stem.descriptor.networkstatus._parse_file(f, validate = validate, document_handler = document_handler, **kwargs)- elif filename == 'cached-microdesc-consensus':- file_parser = lambda f: stem.descriptor.networkstatus._parse_file(f, is_microdescriptor = True, validate = validate, document_handler = document_handler, **kwargs)-- if file_parser:- for desc in file_parser(descriptor_file):- if descriptor_path is not None:- desc._set_path(os.path.abspath(descriptor_path))-- yield desc-- return-- # Not recognized as a descriptor file.-- raise TypeError("Unable to determine the descriptor's type. filename: '%s', first line: '%s'" % (filename, first_line))---def _parse_file_for_path(descriptor_file, *args, **kwargs):- with open(descriptor_file, 'rb') as desc_file:- for desc in parse_file(desc_file, *args, **kwargs):- yield desc---def _parse_file_for_tar_path(descriptor_file, *args, **kwargs):- # TODO: use 'with' for tarfile after dropping python 2.6 support- tar_file = tarfile.open(descriptor_file)-- try:- for desc in parse_file(tar_file, *args, **kwargs):- desc._set_path(os.path.abspath(descriptor_file))- yield desc- finally:- if tar_file:- tar_file.close()---def _parse_file_for_tarfile(descriptor_file, *args, **kwargs):- for tar_entry in descriptor_file:- if tar_entry.isfile():- entry = descriptor_file.extractfile(tar_entry)-- try:- for desc in parse_file(entry, *args, **kwargs):- desc._set_archive_path(entry.name)- yield desc- finally:- entry.close()---def _parse_metrics_file(descriptor_type, major_version, minor_version, descriptor_file, validate, document_handler, **kwargs):- # Parses descriptor files from metrics, yielding individual descriptors. This- # throws a TypeError if the descriptor_type or version isn't recognized.-- if descriptor_type == 'server-descriptor' and major_version == 1:- for desc in stem.descriptor.server_descriptor._parse_file(descriptor_file, is_bridge = False, validate = validate, **kwargs):- yield desc- elif descriptor_type == 'bridge-server-descriptor' and major_version == 1:- for desc in stem.descriptor.server_descriptor._parse_file(descriptor_file, is_bridge = True, validate = validate, **kwargs):- yield desc- elif descriptor_type == 'extra-info' and major_version == 1:- for desc in stem.descriptor.extrainfo_descriptor._parse_file(descriptor_file, is_bridge = False, validate = validate, **kwargs):- yield desc- elif descriptor_type == 'microdescriptor' and major_version == 1:- for desc in stem.descriptor.microdescriptor._parse_file(descriptor_file, validate = validate, **kwargs):- yield desc- elif descriptor_type == 'bridge-extra-info' and major_version == 1:- # version 1.1 introduced a 'transport' field...- # https://trac.torproject.org/6257-- for desc in stem.descriptor.extrainfo_descriptor._parse_file(descriptor_file, is_bridge = True, validate = validate, **kwargs):- yield desc- elif descriptor_type == 'network-status-2' and major_version == 1:- document_type = stem.descriptor.networkstatus.NetworkStatusDocumentV2-- for desc in stem.descriptor.networkstatus._parse_file(descriptor_file, document_type, validate = validate, document_handler = document_handler, **kwargs):- yield desc- elif descriptor_type == 'dir-key-certificate-3' and major_version == 1:- for desc in stem.descriptor.networkstatus._parse_file_key_certs(descriptor_file, validate = validate, **kwargs):- yield desc- elif descriptor_type in ('network-status-consensus-3', 'network-status-vote-3') and major_version == 1:- document_type = stem.descriptor.networkstatus.NetworkStatusDocumentV3-- for desc in stem.descriptor.networkstatus._parse_file(descriptor_file, document_type, validate = validate, document_handler = document_handler, **kwargs):- yield desc- elif descriptor_type == 'network-status-microdesc-consensus-3' and major_version == 1:- document_type = stem.descriptor.networkstatus.NetworkStatusDocumentV3-- for desc in stem.descriptor.networkstatus._parse_file(descriptor_file, document_type, is_microdescriptor = True, validate = validate, document_handler = document_handler, **kwargs):- yield desc- elif descriptor_type == 'bridge-network-status' and major_version == 1:- document_type = stem.descriptor.networkstatus.BridgeNetworkStatusDocument-- for desc in stem.descriptor.networkstatus._parse_file(descriptor_file, document_type, validate = validate, document_handler = document_handler, **kwargs):- yield desc- elif descriptor_type == 'tordnsel' and major_version == 1:- document_type = stem.descriptor.tordnsel.TorDNSEL-- for desc in stem.descriptor.tordnsel._parse_file(descriptor_file, validate = validate, **kwargs):- yield desc- elif descriptor_type == 'hidden-service-descriptor' and major_version == 1:- document_type = stem.descriptor.hidden_service_descriptor.HiddenServiceDescriptor-- for desc in stem.descriptor.hidden_service_descriptor._parse_file(descriptor_file, validate = validate, **kwargs):- yield desc- else:- raise TypeError("Unrecognized metrics descriptor format. type: '%s', version: '%i.%i'" % (descriptor_type, major_version, minor_version))---def _value(line, entries):- return entries[line][0][0]---def _values(line, entries):- return [entry[0] for entry in entries[line]]---def _parse_simple_line(keyword, attribute):- def _parse(descriptor, entries):- setattr(descriptor, attribute, _value(keyword, entries))-- return _parse---def _parse_bytes_line(keyword, attribute):- def _parse(descriptor, entries):- line_match = re.search(stem.util.str_tools._to_bytes('^(opt )?%s(?:[%s]+(.*))?$' % (keyword, WHITESPACE)), descriptor.get_bytes(), re.MULTILINE)- result = None-- if line_match:- value = line_match.groups()[1]- result = b'' if value is None else value-- setattr(descriptor, attribute, result)-- return _parse---def _parse_timestamp_line(keyword, attribute):- # "<keyword>" YYYY-MM-DD HH:MM:SS-- def _parse(descriptor, entries):- value = _value(keyword, entries)-- try:- setattr(descriptor, attribute, stem.util.str_tools._parse_timestamp(value))- except ValueError:- raise ValueError("Timestamp on %s line wasn't parsable: %s %s" % (keyword, keyword, value))-- return _parse---def _parse_forty_character_hex(keyword, attribute):- # format of fingerprints, sha1 digests, etc-- def _parse(descriptor, entries):- value = _value(keyword, entries)-- if not stem.util.tor_tools.is_hex_digits(value, 40):- raise ValueError('%s line had an invalid value (should be 40 hex characters): %s %s' % (keyword, keyword, value))-- setattr(descriptor, attribute, value)-- return _parse---def _parse_key_block(keyword, attribute, expected_block_type, value_attribute = None):- def _parse(descriptor, entries):- value, block_type, block_contents = entries[keyword][0]-- if not block_contents or block_type != expected_block_type:- raise ValueError("'%s' should be followed by a %s block, but was a %s" % (keyword, expected_block_type, block_type))-- setattr(descriptor, attribute, block_contents)-- if value_attribute:- setattr(descriptor, value_attribute, value)-- return _parse---class Descriptor(object):- """- Common parent for all types of descriptors.- """-- ATTRIBUTES = {} # mapping of 'attribute' => (default_value, parsing_function)- PARSER_FOR_LINE = {} # line keyword to its associated parsing function-- def __init__(self, contents, lazy_load = False):- self._path = None- self._archive_path = None- self._raw_contents = contents- self._lazy_loading = lazy_load- self._entries = {}- self._unrecognized_lines = []-- def get_path(self):- """- Provides the absolute path that we loaded this descriptor from.-- :returns: **str** with the absolute path of the descriptor source- """-- return self._path-- def get_archive_path(self):- """- If this descriptor came from an archive then provides its path within the- archive. This is only set if the descriptor came from a- :class:`~stem.descriptor.reader.DescriptorReader`, and is **None** if this- descriptor didn't come from an archive.-- :returns: **str** with the descriptor's path within the archive- """-- return self._archive_path-- def get_bytes(self):- """- Provides the ASCII **bytes** of the descriptor. This only differs from- **str()** if you're running python 3.x, in which case **str()** provides a- **unicode** string.-- :returns: **bytes** for the descriptor's contents- """-- return self._raw_contents-- def get_unrecognized_lines(self):- """- Provides a list of lines that were either ignored or had data that we did- not know how to process. This is most common due to new descriptor fields- that this library does not yet know how to process. Patches welcome!-- :returns: **list** of lines of unrecognized content- """-- if self._lazy_loading:- # we need to go ahead and parse the whole document to figure this out- self._parse(self._entries, False)- self._lazy_loading = False-- return list(self._unrecognized_lines)-- def _parse(self, entries, validate, parser_for_line = None):- """- Parses a series of 'keyword => (value, pgp block)' mappings and applies- them as attributes.-- :param dict entries: descriptor contents to be applied- :param bool validate: checks the validity of descriptor content if True- :param dict parsers: mapping of lines to the function for parsing it-- :raises: **ValueError** if an error occurs in validation- """-- if parser_for_line is None:- parser_for_line = self.PARSER_FOR_LINE-- # set defaults-- for attr in self.ATTRIBUTES:- if not hasattr(self, attr):- setattr(self, attr, copy.copy(self.ATTRIBUTES[attr][0]))-- for keyword, values in list(entries.items()):- try:- if keyword in parser_for_line:- parser_for_line[keyword](self, entries)- else:- for value, block_type, block_contents in values:- line = '%s %s' % (keyword, value)-- if block_contents:- line += '\n%s' % block_contents-- self._unrecognized_lines.append(line)- except ValueError as exc:- if validate:- raise exc-- def _set_path(self, path):- self._path = path-- def _set_archive_path(self, path):- self._archive_path = path-- def _name(self, is_plural = False):- return str(type(self))-- def _digest_for_signature(self, signing_key, signature):- """- Provides the signed digest we should have given this key and signature.-- :param str signing_key: key block used to make this signature- :param str signature: signed digest for this descriptor content-- :returns: the digest string encoded in uppercase hex-- :raises: ValueError if unable to provide a validly signed digest- """-- if not stem.prereq.is_crypto_available():- raise ValueError('Generating the signed digest requires pycrypto')-- from Crypto.Util import asn1- from Crypto.Util.number import bytes_to_long, long_to_bytes-- # get the ASN.1 sequence-- seq = asn1.DerSequence()- seq.decode(_bytes_for_block(signing_key))- modulus, public_exponent = seq[0], seq[1]-- sig_as_bytes = _bytes_for_block(signature)- sig_as_long = bytes_to_long(sig_as_bytes) # convert signature to an int- blocksize = 128 # block size will always be 128 for a 1024 bit key-- # use the public exponent[e] & the modulus[n] to decrypt the int-- decrypted_int = pow(sig_as_long, public_exponent, modulus)-- # convert the int to a byte array-- decrypted_bytes = long_to_bytes(decrypted_int, blocksize)-- ############################################################################- # The decrypted bytes should have a structure exactly along these lines.- # 1 byte - [null '\x00']- # 1 byte - [block type identifier '\x01'] - Should always be 1- # N bytes - [padding '\xFF' ]- # 1 byte - [separator '\x00' ]- # M bytes - [message]- # Total - 128 bytes- # More info here http://www.ietf.org/rfc/rfc2313.txt- # esp the Notes in section 8.1- ############################################################################-- try:- if decrypted_bytes.index(b'\x00\x01') != 0:- raise ValueError('Verification failed, identifier missing')- except ValueError:- raise ValueError('Verification failed, malformed data')-- try:- identifier_offset = 2-- # find the separator- seperator_index = decrypted_bytes.index(b'\x00', identifier_offset)- except ValueError:- raise ValueError('Verification failed, seperator not found')-- digest_hex = codecs.encode(decrypted_bytes[seperator_index + 1:], 'hex_codec')- return stem.util.str_tools._to_unicode(digest_hex.upper())-- def _digest_for_content(self, start, end):- """- Provides the digest of our descriptor's content in a given range.-- :param bytes start: start of the range to generate a digest for- :param bytes end: end of the range to generate a digest for-- :returns: the digest string encoded in uppercase hex-- :raises: ValueError if the digest canot be calculated- """-- raw_descriptor = self.get_bytes()-- start_index = raw_descriptor.find(start)- end_index = raw_descriptor.find(end, start_index)-- if start_index == -1:- raise ValueError("Digest is for the range starting with '%s' but that isn't in our descriptor" % start)- elif end_index == -1:- raise ValueError("Digest is for the range ending with '%s' but that isn't in our descriptor" % end)-- digest_content = raw_descriptor[start_index:end_index + len(end)]- digest_hash = hashlib.sha1(stem.util.str_tools._to_bytes(digest_content))- return stem.util.str_tools._to_unicode(digest_hash.hexdigest().upper())-- def __getattr__(self, name):- # Our constructor sets these, but when unpickling we might lack them. This- # check is needed to avoid an infinite loop in that case.-- if name in ('_lazy_loading', 'ATTRIBUTES'):- return super(Descriptor, self).__getattribute__(name)-- # If attribute isn't already present we might be lazy loading it...-- if self._lazy_loading and name in self.ATTRIBUTES:- default, parsing_function = self.ATTRIBUTES[name]-- try:- parsing_function(self, self._entries)- except (ValueError, KeyError):- try:- # despite having a validation failure check to see if we set something- return super(Descriptor, self).__getattribute__(name)- except AttributeError:- setattr(self, name, copy.copy(default))-- return super(Descriptor, self).__getattribute__(name)-- def __str__(self):- if stem.prereq.is_python_3():- return stem.util.str_tools._to_unicode(self._raw_contents)- else:- return self._raw_contents---def _read_until_keywords(keywords, descriptor_file, inclusive = False, ignore_first = False, skip = False, end_position = None, include_ending_keyword = False):- """- Reads from the descriptor file until we get to one of the given keywords or reach the- end of the file.-- :param str,list keywords: keyword(s) we want to read until- :param file descriptor_file: file with the descriptor content- :param bool inclusive: includes the line with the keyword if True- :param bool ignore_first: doesn't check if the first line read has one of the- given keywords- :param bool skip: skips buffering content, returning None- :param int end_position: end if we reach this point in the file- :param bool include_ending_keyword: provides the keyword we broke on if **True**-- :returns: **list** with the lines until we find one of the keywords, this is- a two value tuple with the ending keyword if include_ending_keyword is- **True**- """-- if skip:- content = None- content_append = lambda x: None- else:- content = []- content_append = content.append-- ending_keyword = None-- if isinstance(keywords, (bytes, str_type)):- keywords = (keywords,)-- if ignore_first:- first_line = descriptor_file.readline()-- if first_line:- content_append(first_line)-- keyword_match = re.compile(SPECIFIC_KEYWORD_LINE % '|'.join(keywords))-- while True:- last_position = descriptor_file.tell()-- if end_position and last_position >= end_position:- break-- line = descriptor_file.readline()-- if not line:- break # EOF-- line_match = keyword_match.match(stem.util.str_tools._to_unicode(line))-- if line_match:- ending_keyword = line_match.groups()[0]-- if not inclusive:- descriptor_file.seek(last_position)- else:- content_append(line)-- break- else:- content_append(line)-- if include_ending_keyword:- return (content, ending_keyword)- else:- return content---def _bytes_for_block(content):- """- Provides the base64 decoded content of a pgp-style block.-- :param str content: block to be decoded-- :returns: decoded block content-- :raises: **TypeError** if this isn't base64 encoded content- """-- # strip the '-----BEGIN RSA PUBLIC KEY-----' header and footer-- content = ''.join(content.split('\n')[1:-1])-- return base64.b64decode(stem.util.str_tools._to_bytes(content))---def _get_pseudo_pgp_block(remaining_contents):- """- Checks if given contents begins with a pseudo-Open-PGP-style block and, if- so, pops it off and provides it back to the caller.-- :param list remaining_contents: lines to be checked for a public key block-- :returns: **tuple** of the (block_type, content) or None if it doesn't exist-- :raises: **ValueError** if the contents starts with a key block but it's- malformed (for instance, if it lacks an ending line)- """-- if not remaining_contents:- return None # nothing left-- block_match = PGP_BLOCK_START.match(remaining_contents[0])-- if block_match:- block_type = block_match.groups()[0]- block_lines = []- end_line = PGP_BLOCK_END % block_type-- while True:- if not remaining_contents:- raise ValueError("Unterminated pgp style block (looking for '%s'):\n%s" % (end_line, '\n'.join(block_lines)))-- line = remaining_contents.pop(0)- block_lines.append(line)-- if line == end_line:- return (block_type, '\n'.join(block_lines))- else:- return None---def _get_descriptor_components(raw_contents, validate, extra_keywords = ()):- """- Initial breakup of the server descriptor contents to make parsing easier.-- A descriptor contains a series of 'keyword lines' which are simply a keyword- followed by an optional value. Lines can also be followed by a signature- block.-- To get a sub-listing with just certain keywords use extra_keywords. This can- be useful if we care about their relative ordering with respect to each- other. For instance, we care about the ordering of 'accept' and 'reject'- entries because this influences the resulting exit policy, but for everything- else in server descriptors the order does not matter.-- :param str raw_contents: descriptor content provided by the relay- :param bool validate: checks the validity of the descriptor's content if- True, skips these checks otherwise- :param list extra_keywords: entity keywords to put into a separate listing- with ordering intact-- :returns:- **collections.OrderedDict** with the 'keyword => (value, pgp key) entries'- mappings. If a extra_keywords was provided then this instead provides a two- value tuple, the second being a list of those entries.- """-- if isinstance(raw_contents, bytes):- raw_contents = stem.util.str_tools._to_unicode(raw_contents)-- entries = OrderedDict()- extra_entries = [] # entries with a keyword in extra_keywords- remaining_lines = raw_contents.split('\n')-- while remaining_lines:- line = remaining_lines.pop(0)-- # V2 network status documents explicitly can contain blank lines...- #- # "Implementations MAY insert blank lines for clarity between sections;- # these blank lines are ignored."- #- # ... and server descriptors end with an extra newline. But other documents- # don't say how blank lines should be handled so globally ignoring them.-- if not line:- continue-- # Some lines have an 'opt ' for backward compatibility. They should be- # ignored. This prefix is being removed in...- # https://trac.torproject.org/projects/tor/ticket/5124-- if line.startswith('opt '):- line = line[4:]-- line_match = KEYWORD_LINE.match(line)-- if not line_match:- if not validate:- continue-- raise ValueError('Line contains invalid characters: %s' % line)-- keyword, value = line_match.groups()-- if value is None:- value = ''-- try:- block_attr = _get_pseudo_pgp_block(remaining_lines)-- if block_attr:- block_type, block_contents = block_attr- else:- block_type, block_contents = None, None- except ValueError as exc:- if not validate:- continue-- raise exc-- if keyword in extra_keywords:- extra_entries.append('%s %s' % (keyword, value))- else:- entries.setdefault(keyword, []).append((value, block_type, block_contents))-- if extra_keywords:- return entries, extra_entries- else:- return entries--# importing at the end to avoid circular dependencies on our Descriptor class--import stem.descriptor.server_descriptor-import stem.descriptor.extrainfo_descriptor-import stem.descriptor.networkstatus-import stem.descriptor.microdescriptor-import stem.descriptor.tordnsel-import stem.descriptor.hidden_service_descriptordiff --git a/ext/stem/descriptor/export.py b/ext/stem/descriptor/export.pydeleted file mode 100644index f90a607c..00000000--- a/ext/stem/descriptor/export.py+++ /dev/null@@ -1,110 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Toolkit for exporting descriptors to other formats.--**Module Overview:**--::-- export_csv - Exports descriptors to a CSV- export_csv_file - Writes exported CSV output to a file-"""--import csv--try:- from cStringIO import StringIO-except ImportError:- from io import StringIO--import stem.descriptor-import stem.prereq---class _ExportDialect(csv.excel):- lineterminator = '\n'---def export_csv(descriptors, included_fields = (), excluded_fields = (), header = True):- """- Provides a newline separated CSV for one or more descriptors. If simply- provided with descriptors then the CSV contains all of its attributes,- labeled with a header row. Either 'included_fields' or 'excluded_fields' can- be used for more granular control over its attributes and the order.-- :param Descriptor,list descriptors: either a- :class:`~stem.descriptor.Descriptor` or list of descriptors to be exported- :param list included_fields: attributes to include in the csv- :param list excluded_fields: attributes to exclude from the csv- :param bool header: if **True** then the first line will be a comma separated- list of the attribute names (**only supported in python 2.7 and higher**)-- :returns: **str** of the CSV for the descriptors, one per line- :raises: **ValueError** if descriptors contain more than one descriptor type- """-- output_buffer = StringIO()- export_csv_file(output_buffer, descriptors, included_fields, excluded_fields, header)- return output_buffer.getvalue()---def export_csv_file(output_file, descriptors, included_fields = (), excluded_fields = (), header = True):- """- Similar to :func:`stem.descriptor.export.export_csv`, except that the CSV is- written directly to a file.-- :param file output_file: file to be written to- :param Descriptor,list descriptors: either a- :class:`~stem.descriptor.Descriptor` or list of descriptors to be exported- :param list included_fields: attributes to include in the csv- :param list excluded_fields: attributes to exclude from the csv- :param bool header: if **True** then the first line will be a comma separated- list of the attribute names (**only supported in python 2.7 and higher**)-- :returns: **str** of the CSV for the descriptors, one per line- :raises: **ValueError** if descriptors contain more than one descriptor type- """-- if isinstance(descriptors, stem.descriptor.Descriptor):- descriptors = (descriptors,)-- if not descriptors:- return-- descriptor_type = type(descriptors[0])- descriptor_type_label = descriptor_type.__name__- included_fields = list(included_fields)-- # If the user didn't specify the fields to include then export everything,- # ordered alphabetically. If they did specify fields then make sure that- # they exist.-- desc_attr = sorted(vars(descriptors[0]).keys())-- if included_fields:- for field in included_fields:- if field not in desc_attr:- raise ValueError("%s does not have a '%s' attribute, valid fields are: %s" % (descriptor_type_label, field, ', '.join(desc_attr)))- else:- included_fields = [attr for attr in desc_attr if not attr.startswith('_')]-- for field in excluded_fields:- try:- included_fields.remove(field)- except ValueError:- pass-- writer = csv.DictWriter(output_file, included_fields, dialect = _ExportDialect(), extrasaction='ignore')-- if header and stem.prereq.is_python_27():- writer.writeheader()-- for desc in descriptors:- if not isinstance(desc, stem.descriptor.Descriptor):- raise ValueError('Unable to export a descriptor CSV since %s is not a descriptor.' % type(desc).__name__)- elif descriptor_type != type(desc):- raise ValueError('To export a descriptor CSV all of the descriptors must be of the same type. First descriptor was a %s but we later got a %s.' % (descriptor_type_label, type(desc)))-- writer.writerow(vars(desc))diff --git a/ext/stem/descriptor/extrainfo_descriptor.py b/ext/stem/descriptor/extrainfo_descriptor.pydeleted file mode 100644index 607bbbec..00000000--- a/ext/stem/descriptor/extrainfo_descriptor.py+++ /dev/null@@ -1,939 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Parsing for Tor extra-info descriptors. These are published by relays whenever-their server descriptor is published and have a similar format. However, unlike-server descriptors these don't contain information that Tor clients require to-function and as such aren't fetched by default.--Defined in section 2.2 of the `dir-spec-<https://gitweb.torproject.org/torspec.git/tree/dir-spec.txt>`_,-extra-info descriptors contain interesting but non-vital information such as-usage statistics. Tor clients cannot request these documents for bridges.--Extra-info descriptors are available from a few sources...--* If you have 'DownloadExtraInfo 1' in your torrc...-- * control port via 'GETINFO extra-info/digest/\*' queries- * the 'cached-extrainfo' file in tor's data directory--* Archived descriptors provided by CollecTor- (https://collector.torproject.org/).--* Directory authorities and mirrors via their DirPort.--**Module Overview:**--::-- ExtraInfoDescriptor - Tor extra-info descriptor.- |- RelayExtraInfoDescriptor - Extra-info descriptor for a relay.- |- BridgeExtraInfoDescriptor - Extra-info descriptor for a bridge.- |- +- digest - calculates the upper-case hex digest value for our content--.. data:: DirResponse (enum)-- Enumeration for known statuses for ExtraInfoDescriptor's dir_*_responses.-- =================== ===========- DirResponse Description- =================== ===========- **OK** network status requests that were answered- **NOT_ENOUGH_SIGS** network status wasn't signed by enough authorities- **UNAVAILABLE** requested network status was unavailable- **NOT_FOUND** requested network status was not found- **NOT_MODIFIED** network status unmodified since If-Modified-Since time- **BUSY** directory was busy- =================== ===========--.. data:: DirStat (enum)-- Enumeration for known stats for ExtraInfoDescriptor's dir_*_direct_dl and- dir_*_tunneled_dl.-- ===================== ===========- DirStat Description- ===================== ===========- **COMPLETE** requests that completed successfully- **TIMEOUT** requests that didn't complete within a ten minute timeout- **RUNNING** requests still in process when measurement's taken- **MIN** smallest rate at which a descriptor was downloaded in B/s- **MAX** largest rate at which a descriptor was downloaded in B/s- **D1-4** and **D6-9** rate of the slowest x/10 download rates in B/s- **Q1** and **Q3** rate of the slowest and fastest quarter download rates in B/s- **MD** median download rate in B/s- ===================== ===========-"""--import functools-import hashlib-import re--import stem.util.connection-import stem.util.enum-import stem.util.str_tools--from stem.descriptor import (- PGP_BLOCK_END,- Descriptor,- _read_until_keywords,- _get_descriptor_components,- _value,- _values,- _parse_timestamp_line,- _parse_forty_character_hex,- _parse_key_block,-)--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache--# known statuses for dirreq-v2-resp and dirreq-v3-resp...-DirResponse = stem.util.enum.Enum(- ('OK', 'ok'),- ('NOT_ENOUGH_SIGS', 'not-enough-sigs'),- ('UNAVAILABLE', 'unavailable'),- ('NOT_FOUND', 'not-found'),- ('NOT_MODIFIED', 'not-modified'),- ('BUSY', 'busy'),-)--# known stats for dirreq-v2/3-direct-dl and dirreq-v2/3-tunneled-dl...-dir_stats = ['complete', 'timeout', 'running', 'min', 'max', 'q1', 'q3', 'md']-dir_stats += ['d%i' % i for i in range(1, 5)]-dir_stats += ['d%i' % i for i in range(6, 10)]-DirStat = stem.util.enum.Enum(*[(stat.upper(), stat) for stat in dir_stats])--# relay descriptors must have exactly one of the following-REQUIRED_FIELDS = (- 'extra-info',- 'published',- 'router-signature',-)--# optional entries that can appear at most once-SINGLE_FIELDS = (- 'read-history',- 'write-history',- 'geoip-db-digest',- 'geoip6-db-digest',- 'bridge-stats-end',- 'bridge-ips',- 'dirreq-stats-end',- 'dirreq-v2-ips',- 'dirreq-v3-ips',- 'dirreq-v2-reqs',- 'dirreq-v3-reqs',- 'dirreq-v2-share',- 'dirreq-v3-share',- 'dirreq-v2-resp',- 'dirreq-v3-resp',- 'dirreq-v2-direct-dl',- 'dirreq-v3-direct-dl',- 'dirreq-v2-tunneled-dl',- 'dirreq-v3-tunneled-dl',- 'dirreq-read-history',- 'dirreq-write-history',- 'entry-stats-end',- 'entry-ips',- 'cell-stats-end',- 'cell-processed-cells',- 'cell-queued-cells',- 'cell-time-in-queue',- 'cell-circuits-per-decile',- 'conn-bi-direct',- 'exit-stats-end',- 'exit-kibibytes-written',- 'exit-kibibytes-read',- 'exit-streams-opened',-)---_timestamp_re = re.compile('^(.*) \(([0-9]+) s\)( .*)?$')-_locale_re = re.compile('^[a-zA-Z0-9\?]{2}$')---def _parse_file(descriptor_file, is_bridge = False, validate = False, **kwargs):- """- Iterates over the extra-info descriptors in a file.-- :param file descriptor_file: file with descriptor content- :param bool is_bridge: parses the file as being a bridge descriptor- :param bool validate: checks the validity of the descriptor's content if- **True**, skips these checks otherwise- :param dict kwargs: additional arguments for the descriptor constructor-- :returns: iterator for :class:`~stem.descriptor.extrainfo_descriptor.ExtraInfoDescriptor`- instances in the file-- :raises:- * **ValueError** if the contents is malformed and validate is **True**- * **IOError** if the file can't be read- """-- while True:- if not is_bridge:- extrainfo_content = _read_until_keywords('router-signature', descriptor_file)-- # we've reached the 'router-signature', now include the pgp style block-- block_end_prefix = PGP_BLOCK_END.split(' ', 1)[0]- extrainfo_content += _read_until_keywords(block_end_prefix, descriptor_file, True)- else:- extrainfo_content = _read_until_keywords('router-digest', descriptor_file, True)-- if extrainfo_content:- if extrainfo_content[0].startswith(b'@type'):- extrainfo_content = extrainfo_content[1:]-- if is_bridge:- yield BridgeExtraInfoDescriptor(bytes.join(b'', extrainfo_content), validate, **kwargs)- else:- yield RelayExtraInfoDescriptor(bytes.join(b'', extrainfo_content), validate, **kwargs)- else:- break # done parsing file---def _parse_timestamp_and_interval(keyword, content):- """- Parses a 'YYYY-MM-DD HH:MM:SS (NSEC s) *' entry.-- :param str keyword: line's keyword- :param str content: line content to be parsed-- :returns: **tuple** of the form (timestamp (**datetime**), interval- (**int**), remaining content (**str**))-- :raises: **ValueError** if the content is malformed- """-- line = '%s %s' % (keyword, content)- content_match = _timestamp_re.match(content)-- if not content_match:- raise ValueError('Malformed %s line: %s' % (keyword, line))-- timestamp_str, interval, remainder = content_match.groups()-- if remainder:- remainder = remainder[1:] # remove leading space-- if not interval.isdigit():- raise ValueError("%s line's interval wasn't a number: %s" % (keyword, line))-- try:- timestamp = stem.util.str_tools._parse_timestamp(timestamp_str)- return timestamp, int(interval), remainder- except ValueError:- raise ValueError("%s line's timestamp wasn't parsable: %s" % (keyword, line))---def _parse_extra_info_line(descriptor, entries):- # "extra-info" Nickname Fingerprint-- value = _value('extra-info', entries)- extra_info_comp = value.split()-- if len(extra_info_comp) < 2:- raise ValueError('Extra-info line must have two values: extra-info %s' % value)- elif not stem.util.tor_tools.is_valid_nickname(extra_info_comp[0]):- raise ValueError("Extra-info line entry isn't a valid nickname: %s" % extra_info_comp[0])- elif not stem.util.tor_tools.is_valid_fingerprint(extra_info_comp[1]):- raise ValueError('Tor relay fingerprints consist of forty hex digits: %s' % extra_info_comp[1])-- descriptor.nickname = extra_info_comp[0]- descriptor.fingerprint = extra_info_comp[1]---def _parse_transport_line(descriptor, entries):- # "transport" transportname address:port [arglist]- # Everything after the transportname is scrubbed in published bridge- # descriptors, so we'll never see it in practice.- #- # These entries really only make sense for bridges, but have been seen- # on non-bridges in the wild when the relay operator configured it this- # way.-- transports = {}-- for value in _values('transport', entries):- name, address, port, args = None, None, None, None-- if ' ' not in value:- # scrubbed- name = value- else:- # not scrubbed- value_comp = value.split()-- if len(value_comp) < 1:- raise ValueError('Transport line is missing its transport name: transport %s' % value)- elif len(value_comp) < 2:- raise ValueError('Transport line is missing its address:port value: transport %s' % value)- elif ':' not in value_comp[1]:- raise ValueError("Transport line's address:port entry is missing a colon: transport %s" % value)-- name = value_comp[0]- address, port_str = value_comp[1].split(':', 1)-- if not stem.util.connection.is_valid_ipv4_address(address) or \- stem.util.connection.is_valid_ipv6_address(address):- raise ValueError('Transport line has a malformed address: transport %s' % value)- elif not stem.util.connection.is_valid_port(port_str):- raise ValueError('Transport line has a malformed port: transport %s' % value)-- port = int(port_str)- args = value_comp[2:] if len(value_comp) >= 3 else []-- transports[name] = (address, port, args)-- descriptor.transport = transports---def _parse_cell_circuits_per_decline_line(descriptor, entries):- # "cell-circuits-per-decile" num-- value = _value('cell-circuits-per-decile', entries)-- if not value.isdigit():- raise ValueError('Non-numeric cell-circuits-per-decile value: %s' % value)- elif int(value) < 0:- raise ValueError('Negative cell-circuits-per-decile value: %s' % value)-- descriptor.cell_circuits_per_decile = int(value)---def _parse_dirreq_line(keyword, recognized_counts_attr, unrecognized_counts_attr, descriptor, entries):- value = _value(keyword, entries)-- recognized_counts = {}- unrecognized_counts = {}-- is_response_stats = keyword in ('dirreq-v2-resp', 'dirreq-v3-resp')- key_set = DirResponse if is_response_stats else DirStat-- key_type = 'STATUS' if is_response_stats else 'STAT'- error_msg = '%s lines should contain %s=COUNT mappings: %s %s' % (keyword, key_type, keyword, value)-- if value:- for entry in value.split(','):- if '=' not in entry:- raise ValueError(error_msg)-- status, count = entry.split('=', 1)-- if count.isdigit():- if status in key_set:- recognized_counts[status] = int(count)- else:- unrecognized_counts[status] = int(count)- else:- raise ValueError(error_msg)-- setattr(descriptor, recognized_counts_attr, recognized_counts)- setattr(descriptor, unrecognized_counts_attr, unrecognized_counts)---def _parse_dirreq_share_line(keyword, attribute, descriptor, entries):- value = _value(keyword, entries)-- if not value.endswith('%'):- raise ValueError('%s lines should be a percentage: %s %s' % (keyword, keyword, value))- elif float(value[:-1]) < 0:- raise ValueError('Negative percentage value: %s %s' % (keyword, value))-- # bug means it might be above 100%: https://lists.torproject.org/pipermail/tor-dev/2012-June/003679.html-- setattr(descriptor, attribute, float(value[:-1]) / 100)---def _parse_cell_line(keyword, attribute, descriptor, entries):- # "<keyword>" num,...,num-- value = _value(keyword, entries)- entries, exc = [], None-- if value:- for entry in value.split(','):- try:- # Values should be positive but as discussed in ticket #5849- # there was a bug around this. It was fixed in tor 0.2.2.1.-- entries.append(float(entry))- except ValueError:- exc = ValueError('Non-numeric entry in %s listing: %s %s' % (keyword, keyword, value))-- setattr(descriptor, attribute, entries)-- if exc:- raise exc---def _parse_timestamp_and_interval_line(keyword, end_attribute, interval_attribute, descriptor, entries):- # "<keyword>" YYYY-MM-DD HH:MM:SS (NSEC s)-- timestamp, interval, _ = _parse_timestamp_and_interval(keyword, _value(keyword, entries))- setattr(descriptor, end_attribute, timestamp)- setattr(descriptor, interval_attribute, interval)---def _parse_conn_bi_direct_line(descriptor, entries):- # "conn-bi-direct" YYYY-MM-DD HH:MM:SS (NSEC s) BELOW,READ,WRITE,BOTH-- value = _value('conn-bi-direct', entries)- timestamp, interval, remainder = _parse_timestamp_and_interval('conn-bi-direct', value)- stats = remainder.split(',')-- if len(stats) != 4 or not (stats[0].isdigit() and stats[1].isdigit() and stats[2].isdigit() and stats[3].isdigit()):- raise ValueError('conn-bi-direct line should end with four numeric values: conn-bi-direct %s' % value)-- descriptor.conn_bi_direct_end = timestamp- descriptor.conn_bi_direct_interval = interval- descriptor.conn_bi_direct_below = int(stats[0])- descriptor.conn_bi_direct_read = int(stats[1])- descriptor.conn_bi_direct_write = int(stats[2])- descriptor.conn_bi_direct_both = int(stats[3])---def _parse_history_line(keyword, end_attribute, interval_attribute, values_attribute, descriptor, entries):- # "<keyword>" YYYY-MM-DD HH:MM:SS (NSEC s) NUM,NUM,NUM,NUM,NUM...-- value = _value(keyword, entries)- timestamp, interval, remainder = _parse_timestamp_and_interval(keyword, value)- history_values = []-- if remainder:- try:- history_values = [int(entry) for entry in remainder.split(',')]- except ValueError:- raise ValueError('%s line has non-numeric values: %s %s' % (keyword, keyword, value))-- setattr(descriptor, end_attribute, timestamp)- setattr(descriptor, interval_attribute, interval)- setattr(descriptor, values_attribute, history_values)---def _parse_port_count_line(keyword, attribute, descriptor, entries):- # "<keyword>" port=N,port=N,...-- value, port_mappings = _value(keyword, entries), {}- error_msg = 'Entries in %s line should only be PORT=N entries: %s %s' % (keyword, keyword, value)-- if value:- for entry in value.split(','):- if '=' not in entry:- raise ValueError(error_msg)-- port, stat = entry.split('=', 1)-- if (port == 'other' or stem.util.connection.is_valid_port(port)) and stat.isdigit():- if port != 'other':- port = int(port)-- port_mappings[port] = int(stat)- else:- raise ValueError(error_msg)-- setattr(descriptor, attribute, port_mappings)---def _parse_geoip_to_count_line(keyword, attribute, descriptor, entries):- # "<keyword>" CC=N,CC=N,...- #- # The maxmind geoip (https://www.maxmind.com/app/iso3166) has numeric- # locale codes for some special values, for instance...- # A1,"Anonymous Proxy"- # A2,"Satellite Provider"- # ??,"Unknown"-- value, locale_usage = _value(keyword, entries), {}- error_msg = 'Entries in %s line should only be CC=N entries: %s %s' % (keyword, keyword, value)-- if value:- for entry in value.split(','):- if '=' not in entry:- raise ValueError(error_msg)-- locale, count = entry.split('=', 1)-- if _locale_re.match(locale) and count.isdigit():- locale_usage[locale] = int(count)- else:- raise ValueError(error_msg)-- setattr(descriptor, attribute, locale_usage)---def _parse_bridge_ip_versions_line(descriptor, entries):- value, ip_versions = _value('bridge-ip-versions', entries), {}-- if value:- for entry in value.split(','):- if '=' not in entry:- raise stem.ProtocolError("The bridge-ip-versions should be a comma separated listing of '<protocol>=<count>' mappings: bridge-ip-versions %s" % value)-- protocol, count = entry.split('=', 1)-- if not count.isdigit():- raise stem.ProtocolError('IP protocol count was non-numeric (%s): bridge-ip-versions %s' % (count, value))-- ip_versions[protocol] = int(count)-- descriptor.ip_versions = ip_versions---def _parse_bridge_ip_transports_line(descriptor, entries):- value, ip_transports = _value('bridge-ip-transports', entries), {}-- if value:- for entry in value.split(','):- if '=' not in entry:- raise stem.ProtocolError("The bridge-ip-transports should be a comma separated listing of '<protocol>=<count>' mappings: bridge-ip-transports %s" % value)-- protocol, count = entry.split('=', 1)-- if not count.isdigit():- raise stem.ProtocolError('Transport count was non-numeric (%s): bridge-ip-transports %s' % (count, value))-- ip_transports[protocol] = int(count)-- descriptor.ip_transports = ip_transports---def _parse_hs_stats(keyword, stat_attribute, extra_attribute, descriptor, entries):- # "<keyword>" num key=val key=val...-- value, stat, extra = _value(keyword, entries), None, {}-- if value is not None:- value_comp = value.split()-- if not value_comp:- raise ValueError("'%s' line was blank" % keyword)-- try:- stat = int(value_comp[0])- except ValueError:- raise ValueError("'%s' stat was non-numeric (%s): %s %s" % (keyword, value_comp[0], keyword, value))-- for entry in value_comp[1:]:- if '=' not in entry:- raise ValueError('Entries after the stat in %s lines should only be key=val entries: %s %s' % (keyword, keyword, value))-- key, val = entry.split('=', 1)- extra[key] = val-- setattr(descriptor, stat_attribute, stat)- setattr(descriptor, extra_attribute, extra)---_parse_geoip_db_digest_line = _parse_forty_character_hex('geoip-db-digest', 'geoip_db_digest')-_parse_geoip6_db_digest_line = _parse_forty_character_hex('geoip6-db-digest', 'geoip6_db_digest')-_parse_dirreq_v2_resp_line = functools.partial(_parse_dirreq_line, 'dirreq-v2-resp', 'dir_v2_responses', 'dir_v2_responses_unknown')-_parse_dirreq_v3_resp_line = functools.partial(_parse_dirreq_line, 'dirreq-v3-resp', 'dir_v3_responses', 'dir_v3_responses_unknown')-_parse_dirreq_v2_direct_dl_line = functools.partial(_parse_dirreq_line, 'dirreq-v2-direct-dl', 'dir_v2_direct_dl', 'dir_v2_direct_dl_unknown')-_parse_dirreq_v3_direct_dl_line = functools.partial(_parse_dirreq_line, 'dirreq-v3-direct-dl', 'dir_v3_direct_dl', 'dir_v3_direct_dl_unknown')-_parse_dirreq_v2_tunneled_dl_line = functools.partial(_parse_dirreq_line, 'dirreq-v2-tunneled-dl', 'dir_v2_tunneled_dl', 'dir_v2_tunneled_dl_unknown')-_parse_dirreq_v3_tunneled_dl_line = functools.partial(_parse_dirreq_line, 'dirreq-v3-tunneled-dl', 'dir_v3_tunneled_dl', 'dir_v3_tunneled_dl_unknown')-_parse_dirreq_v2_share_line = functools.partial(_parse_dirreq_share_line, 'dirreq-v2-share', 'dir_v2_share')-_parse_dirreq_v3_share_line = functools.partial(_parse_dirreq_share_line, 'dirreq-v3-share', 'dir_v3_share')-_parse_cell_processed_cells_line = functools.partial(_parse_cell_line, 'cell-processed-cells', 'cell_processed_cells')-_parse_cell_queued_cells_line = functools.partial(_parse_cell_line, 'cell-queued-cells', 'cell_queued_cells')-_parse_cell_time_in_queue_line = functools.partial(_parse_cell_line, 'cell-time-in-queue', 'cell_time_in_queue')-_parse_published_line = _parse_timestamp_line('published', 'published')-_parse_geoip_start_time_line = _parse_timestamp_line('geoip-start-time', 'geoip_start_time')-_parse_cell_stats_end_line = functools.partial(_parse_timestamp_and_interval_line, 'cell-stats-end', 'cell_stats_end', 'cell_stats_interval')-_parse_entry_stats_end_line = functools.partial(_parse_timestamp_and_interval_line, 'entry-stats-end', 'entry_stats_end', 'entry_stats_interval')-_parse_exit_stats_end_line = functools.partial(_parse_timestamp_and_interval_line, 'exit-stats-end', 'exit_stats_end', 'exit_stats_interval')-_parse_bridge_stats_end_line = functools.partial(_parse_timestamp_and_interval_line, 'bridge-stats-end', 'bridge_stats_end', 'bridge_stats_interval')-_parse_dirreq_stats_end_line = functools.partial(_parse_timestamp_and_interval_line, 'dirreq-stats-end', 'dir_stats_end', 'dir_stats_interval')-_parse_read_history_line = functools.partial(_parse_history_line, 'read-history', 'read_history_end', 'read_history_interval', 'read_history_values')-_parse_write_history_line = functools.partial(_parse_history_line, 'write-history', 'write_history_end', 'write_history_interval', 'write_history_values')-_parse_dirreq_read_history_line = functools.partial(_parse_history_line, 'dirreq-read-history', 'dir_read_history_end', 'dir_read_history_interval', 'dir_read_history_values')-_parse_dirreq_write_history_line = functools.partial(_parse_history_line, 'dirreq-write-history', 'dir_write_history_end', 'dir_write_history_interval', 'dir_write_history_values')-_parse_exit_kibibytes_written_line = functools.partial(_parse_port_count_line, 'exit-kibibytes-written', 'exit_kibibytes_written')-_parse_exit_kibibytes_read_line = functools.partial(_parse_port_count_line, 'exit-kibibytes-read', 'exit_kibibytes_read')-_parse_exit_streams_opened_line = functools.partial(_parse_port_count_line, 'exit-streams-opened', 'exit_streams_opened')-_parse_hidden_service_stats_end_line = _parse_timestamp_line('hidserv-stats-end', 'hs_stats_end')-_parse_hidden_service_rend_relayed_cells_line = functools.partial(_parse_hs_stats, 'hidserv-rend-relayed-cells', 'hs_rend_cells', 'hs_rend_cells_attr')-_parse_hidden_service_dir_onions_seen_line = functools.partial(_parse_hs_stats, 'hidserv-dir-onions-seen', 'hs_dir_onions_seen', 'hs_dir_onions_seen_attr')-_parse_dirreq_v2_ips_line = functools.partial(_parse_geoip_to_count_line, 'dirreq-v2-ips', 'dir_v2_ips')-_parse_dirreq_v3_ips_line = functools.partial(_parse_geoip_to_count_line, 'dirreq-v3-ips', 'dir_v3_ips')-_parse_dirreq_v2_reqs_line = functools.partial(_parse_geoip_to_count_line, 'dirreq-v2-reqs', 'dir_v2_requests')-_parse_dirreq_v3_reqs_line = functools.partial(_parse_geoip_to_count_line, 'dirreq-v3-reqs', 'dir_v3_requests')-_parse_geoip_client_origins_line = functools.partial(_parse_geoip_to_count_line, 'geoip-client-origins', 'geoip_client_origins')-_parse_entry_ips_line = functools.partial(_parse_geoip_to_count_line, 'entry-ips', 'entry_ips')-_parse_bridge_ips_line = functools.partial(_parse_geoip_to_count_line, 'bridge-ips', 'bridge_ips')-_parse_router_digest_line = _parse_forty_character_hex('router-digest', '_digest')-_parse_router_signature_line = _parse_key_block('router-signature', 'signature', 'SIGNATURE')---class ExtraInfoDescriptor(Descriptor):- """- Extra-info descriptor document.-- :var str nickname: **\*** relay's nickname- :var str fingerprint: **\*** identity key fingerprint- :var datetime published: **\*** time in UTC when this descriptor was made- :var str geoip_db_digest: sha1 of the geoIP database file for IPv4 addresses- :var str geoip6_db_digest: sha1 of the geoIP database file for IPv6 addresses- :var dict transport: **\*** mapping of transport methods to their (address,- port, args) tuple, these usually appear on bridges in which case all of- those are **None**-- **Bi-directional connection usage:**-- :var datetime conn_bi_direct_end: end of the sampling interval- :var int conn_bi_direct_interval: seconds per interval- :var int conn_bi_direct_below: connections that read/wrote less than 20 KiB- :var int conn_bi_direct_read: connections that read at least 10x more than wrote- :var int conn_bi_direct_write: connections that wrote at least 10x more than read- :var int conn_bi_direct_both: remaining connections-- **Bytes read/written for relayed traffic:**-- :var datetime read_history_end: end of the sampling interval- :var int read_history_interval: seconds per interval- :var list read_history_values: bytes read during each interval-- :var datetime write_history_end: end of the sampling interval- :var int write_history_interval: seconds per interval- :var list write_history_values: bytes written during each interval-- **Cell relaying statistics:**-- :var datetime cell_stats_end: end of the period when stats were gathered- :var int cell_stats_interval: length in seconds of the interval- :var list cell_processed_cells: measurement of processed cells per circuit- :var list cell_queued_cells: measurement of queued cells per circuit- :var list cell_time_in_queue: mean enqueued time in milliseconds for cells- :var int cell_circuits_per_decile: mean number of circuits in a decile-- **Directory Mirror Attributes:**-- :var datetime dir_stats_end: end of the period when stats were gathered- :var int dir_stats_interval: length in seconds of the interval- :var dict dir_v2_ips: mapping of locales to rounded count of requester ips- :var dict dir_v3_ips: mapping of locales to rounded count of requester ips- :var float dir_v2_share: percent of total directory traffic it expects to serve- :var float dir_v3_share: percent of total directory traffic it expects to serve- :var dict dir_v2_requests: mapping of locales to rounded count of requests- :var dict dir_v3_requests: mapping of locales to rounded count of requests-- :var dict dir_v2_responses: mapping of :data:`~stem.descriptor.extrainfo_descriptor.DirResponse` to their rounded count- :var dict dir_v3_responses: mapping of :data:`~stem.descriptor.extrainfo_descriptor.DirResponse` to their rounded count- :var dict dir_v2_responses_unknown: mapping of unrecognized statuses to their count- :var dict dir_v3_responses_unknown: mapping of unrecognized statuses to their count-- :var dict dir_v2_direct_dl: mapping of :data:`~stem.descriptor.extrainfo_descriptor.DirStat` to measurement over DirPort- :var dict dir_v3_direct_dl: mapping of :data:`~stem.descriptor.extrainfo_descriptor.DirStat` to measurement over DirPort- :var dict dir_v2_direct_dl_unknown: mapping of unrecognized stats to their measurement- :var dict dir_v3_direct_dl_unknown: mapping of unrecognized stats to their measurement-- :var dict dir_v2_tunneled_dl: mapping of :data:`~stem.descriptor.extrainfo_descriptor.DirStat` to measurement over ORPort- :var dict dir_v3_tunneled_dl: mapping of :data:`~stem.descriptor.extrainfo_descriptor.DirStat` to measurement over ORPort- :var dict dir_v2_tunneled_dl_unknown: mapping of unrecognized stats to their measurement- :var dict dir_v3_tunneled_dl_unknown: mapping of unrecognized stats to their measurement-- **Bytes read/written for directory mirroring:**-- :var datetime dir_read_history_end: end of the sampling interval- :var int dir_read_history_interval: seconds per interval- :var list dir_read_history_values: bytes read during each interval-- :var datetime dir_write_history_end: end of the sampling interval- :var int dir_write_history_interval: seconds per interval- :var list dir_write_history_values: bytes read during each interval-- **Guard Attributes:**-- :var datetime entry_stats_end: end of the period when stats were gathered- :var int entry_stats_interval: length in seconds of the interval- :var dict entry_ips: mapping of locales to rounded count of unique user ips-- **Exit Attributes:**-- :var datetime exit_stats_end: end of the period when stats were gathered- :var int exit_stats_interval: length in seconds of the interval- :var dict exit_kibibytes_written: traffic per port (keys are ints or 'other')- :var dict exit_kibibytes_read: traffic per port (keys are ints or 'other')- :var dict exit_streams_opened: streams per port (keys are ints or 'other')-- **Hidden Service Attributes:**-- :var datetime hs_stats_end: end of the sampling interval- :var int hs_rend_cells: rounded count of the RENDEZVOUS1 cells seen- :var int hs_rend_cells_attr: **\*** attributes provided for the hs_rend_cells- :var int hs_dir_onions_seen: rounded count of the identities seen- :var int hs_dir_onions_seen_attr: **\*** attributes provided for the hs_dir_onions_seen-- **Bridge Attributes:**-- :var datetime bridge_stats_end: end of the period when stats were gathered- :var int bridge_stats_interval: length in seconds of the interval- :var dict bridge_ips: mapping of locales to rounded count of unique user ips- :var datetime geoip_start_time: replaced by bridge_stats_end (deprecated)- :var dict geoip_client_origins: replaced by bridge_ips (deprecated)- :var dict ip_versions: mapping of ip protocols to a rounded count for the number of users- :var dict ip_versions: mapping of ip transports to a count for the number of users-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as **None** if undefined-- .. versionchanged:: 1.4.0- Added the hs_stats_end, hs_rend_cells, hs_rend_cells_attr,- hs_dir_onions_seen, and hs_dir_onions_seen_attr attributes.- """-- ATTRIBUTES = {- 'nickname': (None, _parse_extra_info_line),- 'fingerprint': (None, _parse_extra_info_line),- 'published': (None, _parse_published_line),- 'geoip_db_digest': (None, _parse_geoip_db_digest_line),- 'geoip6_db_digest': (None, _parse_geoip6_db_digest_line),- 'transport': ({}, _parse_transport_line),-- 'conn_bi_direct_end': (None, _parse_conn_bi_direct_line),- 'conn_bi_direct_interval': (None, _parse_conn_bi_direct_line),- 'conn_bi_direct_below': (None, _parse_conn_bi_direct_line),- 'conn_bi_direct_read': (None, _parse_conn_bi_direct_line),- 'conn_bi_direct_write': (None, _parse_conn_bi_direct_line),- 'conn_bi_direct_both': (None, _parse_conn_bi_direct_line),-- 'read_history_end': (None, _parse_read_history_line),- 'read_history_interval': (None, _parse_read_history_line),- 'read_history_values': (None, _parse_read_history_line),-- 'write_history_end': (None, _parse_write_history_line),- 'write_history_interval': (None, _parse_write_history_line),- 'write_history_values': (None, _parse_write_history_line),-- 'cell_stats_end': (None, _parse_cell_stats_end_line),- 'cell_stats_interval': (None, _parse_cell_stats_end_line),- 'cell_processed_cells': (None, _parse_cell_processed_cells_line),- 'cell_queued_cells': (None, _parse_cell_queued_cells_line),- 'cell_time_in_queue': (None, _parse_cell_time_in_queue_line),- 'cell_circuits_per_decile': (None, _parse_cell_circuits_per_decline_line),-- 'dir_stats_end': (None, _parse_dirreq_stats_end_line),- 'dir_stats_interval': (None, _parse_dirreq_stats_end_line),- 'dir_v2_ips': (None, _parse_dirreq_v2_ips_line),- 'dir_v3_ips': (None, _parse_dirreq_v3_ips_line),- 'dir_v2_share': (None, _parse_dirreq_v2_share_line),- 'dir_v3_share': (None, _parse_dirreq_v3_share_line),- 'dir_v2_requests': (None, _parse_dirreq_v2_reqs_line),- 'dir_v3_requests': (None, _parse_dirreq_v3_reqs_line),- 'dir_v2_responses': (None, _parse_dirreq_v2_resp_line),- 'dir_v3_responses': (None, _parse_dirreq_v3_resp_line),- 'dir_v2_responses_unknown': (None, _parse_dirreq_v2_resp_line),- 'dir_v3_responses_unknown': (None, _parse_dirreq_v3_resp_line),- 'dir_v2_direct_dl': (None, _parse_dirreq_v2_direct_dl_line),- 'dir_v3_direct_dl': (None, _parse_dirreq_v3_direct_dl_line),- 'dir_v2_direct_dl_unknown': (None, _parse_dirreq_v2_direct_dl_line),- 'dir_v3_direct_dl_unknown': (None, _parse_dirreq_v3_direct_dl_line),- 'dir_v2_tunneled_dl': (None, _parse_dirreq_v2_tunneled_dl_line),- 'dir_v3_tunneled_dl': (None, _parse_dirreq_v3_tunneled_dl_line),- 'dir_v2_tunneled_dl_unknown': (None, _parse_dirreq_v2_tunneled_dl_line),- 'dir_v3_tunneled_dl_unknown': (None, _parse_dirreq_v3_tunneled_dl_line),-- 'dir_read_history_end': (None, _parse_dirreq_read_history_line),- 'dir_read_history_interval': (None, _parse_dirreq_read_history_line),- 'dir_read_history_values': (None, _parse_dirreq_read_history_line),-- 'dir_write_history_end': (None, _parse_dirreq_write_history_line),- 'dir_write_history_interval': (None, _parse_dirreq_write_history_line),- 'dir_write_history_values': (None, _parse_dirreq_write_history_line),-- 'entry_stats_end': (None, _parse_entry_stats_end_line),- 'entry_stats_interval': (None, _parse_entry_stats_end_line),- 'entry_ips': (None, _parse_entry_ips_line),-- 'exit_stats_end': (None, _parse_exit_stats_end_line),- 'exit_stats_interval': (None, _parse_exit_stats_end_line),- 'exit_kibibytes_written': (None, _parse_exit_kibibytes_written_line),- 'exit_kibibytes_read': (None, _parse_exit_kibibytes_read_line),- 'exit_streams_opened': (None, _parse_exit_streams_opened_line),-- 'hs_stats_end': (None, _parse_hidden_service_stats_end_line),- 'hs_rend_cells': (None, _parse_hidden_service_rend_relayed_cells_line),- 'hs_rend_cells_attr': ({}, _parse_hidden_service_rend_relayed_cells_line),- 'hs_dir_onions_seen': (None, _parse_hidden_service_dir_onions_seen_line),- 'hs_dir_onions_seen_attr': ({}, _parse_hidden_service_dir_onions_seen_line),-- 'bridge_stats_end': (None, _parse_bridge_stats_end_line),- 'bridge_stats_interval': (None, _parse_bridge_stats_end_line),- 'bridge_ips': (None, _parse_bridge_ips_line),- 'geoip_start_time': (None, _parse_geoip_start_time_line),- 'geoip_client_origins': (None, _parse_geoip_client_origins_line),-- 'ip_versions': (None, _parse_bridge_ip_versions_line),- 'ip_transports': (None, _parse_bridge_ip_transports_line),- }-- PARSER_FOR_LINE = {- 'extra-info': _parse_extra_info_line,- 'geoip-db-digest': _parse_geoip_db_digest_line,- 'geoip6-db-digest': _parse_geoip6_db_digest_line,- 'transport': _parse_transport_line,- 'cell-circuits-per-decile': _parse_cell_circuits_per_decline_line,- 'dirreq-v2-resp': _parse_dirreq_v2_resp_line,- 'dirreq-v3-resp': _parse_dirreq_v3_resp_line,- 'dirreq-v2-direct-dl': _parse_dirreq_v2_direct_dl_line,- 'dirreq-v3-direct-dl': _parse_dirreq_v3_direct_dl_line,- 'dirreq-v2-tunneled-dl': _parse_dirreq_v2_tunneled_dl_line,- 'dirreq-v3-tunneled-dl': _parse_dirreq_v3_tunneled_dl_line,- 'dirreq-v2-share': _parse_dirreq_v2_share_line,- 'dirreq-v3-share': _parse_dirreq_v3_share_line,- 'cell-processed-cells': _parse_cell_processed_cells_line,- 'cell-queued-cells': _parse_cell_queued_cells_line,- 'cell-time-in-queue': _parse_cell_time_in_queue_line,- 'published': _parse_published_line,- 'geoip-start-time': _parse_geoip_start_time_line,- 'cell-stats-end': _parse_cell_stats_end_line,- 'entry-stats-end': _parse_entry_stats_end_line,- 'exit-stats-end': _parse_exit_stats_end_line,- 'bridge-stats-end': _parse_bridge_stats_end_line,- 'dirreq-stats-end': _parse_dirreq_stats_end_line,- 'conn-bi-direct': _parse_conn_bi_direct_line,- 'read-history': _parse_read_history_line,- 'write-history': _parse_write_history_line,- 'dirreq-read-history': _parse_dirreq_read_history_line,- 'dirreq-write-history': _parse_dirreq_write_history_line,- 'exit-kibibytes-written': _parse_exit_kibibytes_written_line,- 'exit-kibibytes-read': _parse_exit_kibibytes_read_line,- 'exit-streams-opened': _parse_exit_streams_opened_line,- 'hidserv-stats-end': _parse_hidden_service_stats_end_line,- 'hidserv-rend-relayed-cells': _parse_hidden_service_rend_relayed_cells_line,- 'hidserv-dir-onions-seen': _parse_hidden_service_dir_onions_seen_line,- 'dirreq-v2-ips': _parse_dirreq_v2_ips_line,- 'dirreq-v3-ips': _parse_dirreq_v3_ips_line,- 'dirreq-v2-reqs': _parse_dirreq_v2_reqs_line,- 'dirreq-v3-reqs': _parse_dirreq_v3_reqs_line,- 'geoip-client-origins': _parse_geoip_client_origins_line,- 'entry-ips': _parse_entry_ips_line,- 'bridge-ips': _parse_bridge_ips_line,- 'bridge-ip-versions': _parse_bridge_ip_versions_line,- 'bridge-ip-transports': _parse_bridge_ip_transports_line,- }-- def __init__(self, raw_contents, validate = False):- """- Extra-info descriptor constructor. By default this validates the- descriptor's content as it's parsed. This validation can be disabled to- either improve performance or be accepting of malformed data.-- :param str raw_contents: extra-info content provided by the relay- :param bool validate: checks the validity of the extra-info descriptor if- **True**, skips these checks otherwise-- :raises: **ValueError** if the contents is malformed and validate is True- """-- super(ExtraInfoDescriptor, self).__init__(raw_contents, lazy_load = not validate)- entries = _get_descriptor_components(raw_contents, validate)-- if validate:- for keyword in self._required_fields():- if keyword not in entries:- raise ValueError("Extra-info descriptor must have a '%s' entry" % keyword)-- for keyword in self._required_fields() + SINGLE_FIELDS:- if keyword in entries and len(entries[keyword]) > 1:- raise ValueError("The '%s' entry can only appear once in an extra-info descriptor" % keyword)-- expected_first_keyword = self._first_keyword()- if expected_first_keyword and expected_first_keyword != list(entries.keys())[0]:- raise ValueError("Extra-info descriptor must start with a '%s' entry" % expected_first_keyword)-- expected_last_keyword = self._last_keyword()- if expected_last_keyword and expected_last_keyword != list(entries.keys())[-1]:- raise ValueError("Descriptor must end with a '%s' entry" % expected_last_keyword)-- self._parse(entries, validate)- else:- self._entries = entries-- def digest(self):- """- Provides the upper-case hex encoded sha1 of our content. This value is part- of the server descriptor entry for this relay.-- :returns: **str** with the upper-case hex digest value for this server- descriptor- """-- raise NotImplementedError('Unsupported Operation: this should be implemented by the ExtraInfoDescriptor subclass')-- def _required_fields(self):- return REQUIRED_FIELDS-- def _first_keyword(self):- return 'extra-info'-- def _last_keyword(self):- return 'router-signature'---class RelayExtraInfoDescriptor(ExtraInfoDescriptor):- """- Relay extra-info descriptor, constructed from data such as that provided by- 'GETINFO extra-info/digest/\*', cached descriptors, and metrics- (`specification <https://gitweb.torproject.org/torspec.git/tree/dir-spec.txt>`_).-- :var str signature: **\*** signature for this extrainfo descriptor-- **\*** attribute is required when we're parsed with validation- """-- ATTRIBUTES = dict(ExtraInfoDescriptor.ATTRIBUTES, **{- 'signature': (None, _parse_router_signature_line),- })-- PARSER_FOR_LINE = dict(ExtraInfoDescriptor.PARSER_FOR_LINE, **{- 'router-signature': _parse_router_signature_line,- })-- @lru_cache()- def digest(self):- # our digest is calculated from everything except our signature- raw_content, ending = str(self), '\nrouter-signature\n'- raw_content = raw_content[:raw_content.find(ending) + len(ending)]- return hashlib.sha1(stem.util.str_tools._to_bytes(raw_content)).hexdigest().upper()---class BridgeExtraInfoDescriptor(ExtraInfoDescriptor):- """- Bridge extra-info descriptor (`bridge descriptor specification- <https://collector.torproject.org/formats.html#bridge-descriptors>`_)- """-- ATTRIBUTES = dict(ExtraInfoDescriptor.ATTRIBUTES, **{- '_digest': (None, _parse_router_digest_line),- })-- PARSER_FOR_LINE = dict(ExtraInfoDescriptor.PARSER_FOR_LINE, **{- 'router-digest': _parse_router_digest_line,- })-- def digest(self):- return self._digest-- def _required_fields(self):- excluded_fields = [- 'router-signature',- ]-- included_fields = [- 'router-digest',- ]-- return tuple(included_fields + [f for f in REQUIRED_FIELDS if f not in excluded_fields])-- def _last_keyword(self):- return Nonediff --git a/ext/stem/descriptor/hidden_service_descriptor.py b/ext/stem/descriptor/hidden_service_descriptor.pydeleted file mode 100644index 31a99cc4..00000000--- a/ext/stem/descriptor/hidden_service_descriptor.py+++ /dev/null@@ -1,422 +0,0 @@-# Copyright 2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Parsing for Tor hidden service descriptors as described in Tor's `rend-spec-<https://gitweb.torproject.org/torspec.git/tree/rend-spec.txt>`_.--Unlike other descriptor types these describe a hidden service rather than a-relay. They're created by the service, and can only be fetched via relays with-the HSDir flag.--**Module Overview:**--::-- HiddenServiceDescriptor - Tor hidden service descriptor.--.. versionadded:: 1.4.0-"""--# TODO: Add a description for how to retrieve them when tor supports that-# (#14847) and then update #15009.--import base64-import binascii-import collections-import hashlib-import io--import stem.util.connection-import stem.util.str_tools--from stem.descriptor import (- PGP_BLOCK_END,- Descriptor,- _get_descriptor_components,- _read_until_keywords,- _bytes_for_block,- _value,- _parse_simple_line,- _parse_timestamp_line,- _parse_key_block,-)--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache--REQUIRED_FIELDS = (- 'rendezvous-service-descriptor',- 'version',- 'permanent-key',- 'secret-id-part',- 'publication-time',- 'protocol-versions',- 'signature',-)--INTRODUCTION_POINTS_ATTR = {- 'identifier': None,- 'address': None,- 'port': None,- 'onion_key': None,- 'service_key': None,- 'intro_authentication': [],-}--# introduction-point fields that can only appear once--SINGLE_INTRODUCTION_POINT_FIELDS = [- 'introduction-point',- 'ip-address',- 'onion-port',- 'onion-key',- 'service-key',-]--BASIC_AUTH = 1-STEALTH_AUTH = 2--IntroductionPoint = collections.namedtuple('IntroductionPoints', INTRODUCTION_POINTS_ATTR.keys())---class DecryptionFailure(Exception):- """- Failure to decrypt the hidden service descriptor's introduction-points.- """---def _parse_file(descriptor_file, validate = False, **kwargs):- """- Iterates over the hidden service descriptors in a file.-- :param file descriptor_file: file with descriptor content- :param bool validate: checks the validity of the descriptor's content if- **True**, skips these checks otherwise- :param dict kwargs: additional arguments for the descriptor constructor-- :returns: iterator for :class:`~stem.descriptor.hidden_service_descriptor.HiddenServiceDescriptor`- instances in the file-- :raises:- * **ValueError** if the contents is malformed and validate is **True**- * **IOError** if the file can't be read- """-- while True:- descriptor_content = _read_until_keywords('signature', descriptor_file)-- # we've reached the 'signature', now include the pgp style block- block_end_prefix = PGP_BLOCK_END.split(' ', 1)[0]- descriptor_content += _read_until_keywords(block_end_prefix, descriptor_file, True)-- if descriptor_content:- if descriptor_content[0].startswith(b'@type'):- descriptor_content = descriptor_content[1:]-- yield HiddenServiceDescriptor(bytes.join(b'', descriptor_content), validate, **kwargs)- else:- break # done parsing file---def _parse_version_line(descriptor, entries):- value = _value('version', entries)-- if value.isdigit():- descriptor.version = int(value)- else:- raise ValueError('version line must have a positive integer value: %s' % value)---def _parse_protocol_versions_line(descriptor, entries):- value = _value('protocol-versions', entries)-- try:- versions = [int(entry) for entry in value.split(',')]- except ValueError:- raise ValueError('protocol-versions line has non-numeric versoins: protocol-versions %s' % value)-- for v in versions:- if v <= 0:- raise ValueError('protocol-versions must be positive integers: %s' % value)-- descriptor.protocol_versions = versions---def _parse_introduction_points_line(descriptor, entries):- _, block_type, block_contents = entries['introduction-points'][0]-- if not block_contents or block_type != 'MESSAGE':- raise ValueError("'introduction-points' should be followed by a MESSAGE block, but was a %s" % block_type)-- descriptor.introduction_points_encoded = block_contents-- try:- decoded_field = _bytes_for_block(block_contents)- except TypeError:- raise ValueError("'introduction-points' isn't base64 encoded content:\n%s" % block_contents)-- auth_types = []-- while decoded_field.startswith(b'service-authentication ') and b'\n' in decoded_field:- auth_line, decoded_field = decoded_field.split(b'\n', 1)- auth_line_comp = auth_line.split(b' ')-- if len(auth_line_comp) < 3:- raise ValueError("Within introduction-points we expected 'service-authentication [auth_type] [auth_data]', but had '%s'" % auth_line)-- auth_types.append((auth_line_comp[1], auth_line_comp[2]))-- descriptor.introduction_points_auth = auth_types- descriptor.introduction_points_content = decoded_field--_parse_rendezvous_service_descriptor_line = _parse_simple_line('rendezvous-service-descriptor', 'descriptor_id')-_parse_permanent_key_line = _parse_key_block('permanent-key', 'permanent_key', 'RSA PUBLIC KEY')-_parse_secret_id_part_line = _parse_simple_line('secret-id-part', 'secret_id_part')-_parse_publication_time_line = _parse_timestamp_line('publication-time', 'published')-_parse_signature_line = _parse_key_block('signature', 'signature', 'SIGNATURE')---class HiddenServiceDescriptor(Descriptor):- """- Hidden service descriptor.-- :var str descriptor_id: **\*** identifier for this descriptor, this is a base32 hash of several fields- :var int version: **\*** hidden service descriptor version- :var str permanent_key: **\*** long term key of the hidden service- :var str secret_id_part: **\*** hash of the time period, cookie, and replica- values so our descriptor_id can be validated- :var datetime published: **\*** time in UTC when this descriptor was made- :var list protocol_versions: **\*** list of **int** versions that are supported when establishing a connection- :var str introduction_points_encoded: raw introduction points blob- :var list introduction_points_auth: **\*** tuples of the form- (auth_method, auth_data) for our introduction_points_content- :var bytes introduction_points_content: decoded introduction-points content- without authentication data, if using cookie authentication this is- encrypted- :var str signature: signature of the descriptor content-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as **None** if undefined- """-- ATTRIBUTES = {- 'descriptor_id': (None, _parse_rendezvous_service_descriptor_line),- 'version': (None, _parse_version_line),- 'permanent_key': (None, _parse_permanent_key_line),- 'secret_id_part': (None, _parse_secret_id_part_line),- 'published': (None, _parse_publication_time_line),- 'protocol_versions': ([], _parse_protocol_versions_line),- 'introduction_points_encoded': (None, _parse_introduction_points_line),- 'introduction_points_auth': ([], _parse_introduction_points_line),- 'introduction_points_content': (None, _parse_introduction_points_line),- 'signature': (None, _parse_signature_line),- }-- PARSER_FOR_LINE = {- 'rendezvous-service-descriptor': _parse_rendezvous_service_descriptor_line,- 'version': _parse_version_line,- 'permanent-key': _parse_permanent_key_line,- 'secret-id-part': _parse_secret_id_part_line,- 'publication-time': _parse_publication_time_line,- 'protocol-versions': _parse_protocol_versions_line,- 'introduction-points': _parse_introduction_points_line,- 'signature': _parse_signature_line,- }-- def __init__(self, raw_contents, validate = False):- super(HiddenServiceDescriptor, self).__init__(raw_contents, lazy_load = not validate)- entries = _get_descriptor_components(raw_contents, validate)-- if validate:- for keyword in REQUIRED_FIELDS:- if keyword not in entries:- raise ValueError("Hidden service descriptor must have a '%s' entry" % keyword)- elif keyword in entries and len(entries[keyword]) > 1:- raise ValueError("The '%s' entry can only appear once in a hidden service descriptor" % keyword)-- if 'rendezvous-service-descriptor' != list(entries.keys())[0]:- raise ValueError("Hidden service descriptor must start with a 'rendezvous-service-descriptor' entry")- elif 'signature' != list(entries.keys())[-1]:- raise ValueError("Hidden service descriptor must end with a 'signature' entry")-- self._parse(entries, validate)-- if stem.prereq.is_crypto_available():- signed_digest = self._digest_for_signature(self.permanent_key, self.signature)- content_digest = self._digest_for_content(b'rendezvous-service-descriptor ', b'\nsignature\n')-- if signed_digest != content_digest:- raise ValueError('Decrypted digest does not match local digest (calculated: %s, local: %s)' % (signed_digest, content_digest))- else:- self._entries = entries-- @lru_cache()- def introduction_points(self, authentication_cookie = None):- """- Provided this service's introduction points. This provides a list of- IntroductionPoint instances, which have the following attributes...-- * **identifier** (str): hash of this introduction point's identity key- * **address** (str): address of this introduction point- * **port** (int): port where this introduction point is listening- * **onion_key** (str): public key for communicating with this introduction point- * **service_key** (str): public key for communicating with this hidden service- * **intro_authentication** (list): tuples of the form (auth_type, auth_data)- for establishing a connection-- :param str authentication_cookie: cookie to decrypt the introduction-points- if it's encrypted-- :returns: **list** of IntroductionPoints instances-- :raises:- * **ValueError** if the our introduction-points is malformed- * **DecryptionFailure** if unable to decrypt this field- """-- content = self.introduction_points_content-- if not content:- return []- elif authentication_cookie:- if not stem.prereq.is_crypto_available():- raise DecryptionFailure('Decrypting introduction-points requires pycrypto')-- try:- missing_padding = len(authentication_cookie) % 4- authentication_cookie = base64.b64decode(stem.util.str_tools._to_bytes(authentication_cookie) + b'=' * missing_padding)- except TypeError as exc:- raise DecryptionFailure('authentication_cookie must be a base64 encoded string (%s)' % exc)-- authentication_type = int(binascii.hexlify(content[0:1]), 16)-- if authentication_type == BASIC_AUTH:- content = HiddenServiceDescriptor._decrypt_basic_auth(content, authentication_cookie)- elif authentication_type == STEALTH_AUTH:- content = HiddenServiceDescriptor._decrypt_stealth_auth(content, authentication_cookie)- else:- raise DecryptionFailure("Unrecognized authentication type '%s', currently we only support basic auth (%s) and stealth auth (%s)" % (authentication_type, BASIC_AUTH, STEALTH_AUTH))-- if not content.startswith(b'introduction-point '):- raise DecryptionFailure('Unable to decrypt the introduction-points, maybe this is the wrong key?')- elif not content.startswith(b'introduction-point '):- raise DecryptionFailure('introduction-points content is encrypted, you need to provide its authentication_cookie')-- return HiddenServiceDescriptor._parse_introduction_points(content)-- @staticmethod- def _decrypt_basic_auth(content, authentication_cookie):- from Crypto.Cipher import AES- from Crypto.Util import Counter- from Crypto.Util.number import bytes_to_long-- try:- client_blocks = int(binascii.hexlify(content[1:2]), 16)- except ValueError:- raise DecryptionFailure("When using basic auth the content should start with a number of blocks but wasn't a hex digit: %s" % binascii.hexlify(content[1:2]))-- # parse the client id and encrypted session keys-- client_entries_length = client_blocks * 16 * 20- client_entries = content[2:2 + client_entries_length]- client_keys = [(client_entries[i:i + 4], client_entries[i + 4:i + 20]) for i in range(0, client_entries_length, 4 + 16)]-- iv = content[2 + client_entries_length:2 + client_entries_length + 16]- encrypted = content[2 + client_entries_length + 16:]-- client_id = hashlib.sha1(authentication_cookie + iv).digest()[:4]-- for entry_id, encrypted_session_key in client_keys:- if entry_id != client_id:- continue # not the session key for this client-- # try decrypting the session key-- counter = Counter.new(128, initial_value = 0)- cipher = AES.new(authentication_cookie, AES.MODE_CTR, counter = counter)- session_key = cipher.decrypt(encrypted_session_key)-- # attempt to decrypt the intro points with the session key-- counter = Counter.new(128, initial_value = bytes_to_long(iv))- cipher = AES.new(session_key, AES.MODE_CTR, counter = counter)- decrypted = cipher.decrypt(encrypted)-- # check if the decryption looks correct-- if decrypted.startswith(b'introduction-point '):- return decrypted-- return content # nope, unable to decrypt the content-- @staticmethod- def _decrypt_stealth_auth(content, authentication_cookie):- from Crypto.Cipher import AES- from Crypto.Util import Counter- from Crypto.Util.number import bytes_to_long-- # byte 1 = authentication type, 2-17 = input vector, 18 on = encrypted content-- iv, encrypted = content[1:17], content[17:]- counter = Counter.new(128, initial_value = bytes_to_long(iv))- cipher = AES.new(authentication_cookie, AES.MODE_CTR, counter = counter)-- return cipher.decrypt(encrypted)-- @staticmethod- def _parse_introduction_points(content):- """- Provides the parsed list of IntroductionPoint for the unencrypted content.- """-- introduction_points = []- content_io = io.BytesIO(content)-- while True:- content = b''.join(_read_until_keywords('introduction-point', content_io, ignore_first = True))-- if not content:- break # reached the end-- attr = dict(INTRODUCTION_POINTS_ATTR)- entries = _get_descriptor_components(content, False)-- for keyword, values in list(entries.items()):- value, block_type, block_contents = values[0]-- if keyword in SINGLE_INTRODUCTION_POINT_FIELDS and len(values) > 1:- raise ValueError("'%s' can only appear once in an introduction-point block, but appeared %i times" % (keyword, len(values)))-- if keyword == 'introduction-point':- attr['identifier'] = value- elif keyword == 'ip-address':- if not stem.util.connection.is_valid_ipv4_address(value):- raise ValueError("'%s' is an invalid IPv4 address" % value)-- attr['address'] = value- elif keyword == 'onion-port':- if not stem.util.connection.is_valid_port(value):- raise ValueError("'%s' is an invalid port" % value)-- attr['port'] = int(value)- elif keyword == 'onion-key':- attr['onion_key'] = block_contents- elif keyword == 'service-key':- attr['service_key'] = block_contents- elif keyword == 'intro-authentication':- auth_entries = []-- for auth_value, _, _ in values:- if ' ' not in auth_value:- raise ValueError("We expected 'intro-authentication [auth_type] [auth_data]', but had '%s'" % auth_value)-- auth_type, auth_data = auth_value.split(' ')[:2]- auth_entries.append((auth_type, auth_data))-- introduction_points.append(IntroductionPoint(**attr))-- return introduction_pointsdiff --git a/ext/stem/descriptor/microdescriptor.py b/ext/stem/descriptor/microdescriptor.pydeleted file mode 100644index ffbec438..00000000--- a/ext/stem/descriptor/microdescriptor.py+++ /dev/null@@ -1,314 +0,0 @@-# Copyright 2013-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Parsing for Tor microdescriptors, which contain a distilled version of a-relay's server descriptor. As of Tor version 0.2.3.3-alpha Tor no longer-downloads server descriptors by default, opting for microdescriptors instead.--Unlike most descriptor documents these aren't available on the metrics site-(since they don't contain any information that the server descriptors don't).--The limited information in microdescriptors make them rather clunky to use-compared with server descriptors. For instance microdescriptors lack the-relay's fingerprint, making it difficut to use them to look up the relay's-other descriptors.--To do so you need to match the microdescriptor's digest against its-corresponding router status entry. For added fun as of this writing the-controller doesn't even surface those router status entries-(:trac:`7953`).--For instance, here's an example that prints the nickname and fignerprints of-the exit relays.--::-- import os-- from stem.control import Controller- from stem.descriptor import parse_file-- with Controller.from_port(port = 9051) as controller:- controller.authenticate()-- exit_digests = set()- data_dir = controller.get_conf('DataDirectory')-- for desc in controller.get_microdescriptors():- if desc.exit_policy.is_exiting_allowed():- exit_digests.add(desc.digest)-- print 'Exit Relays:'-- for desc in parse_file(os.path.join(data_dir, 'cached-microdesc-consensus')):- if desc.digest in exit_digests:- print ' %s (%s)' % (desc.nickname, desc.fingerprint)--Doing the same is trivial with server descriptors...--::-- from stem.descriptor import parse_file-- print 'Exit Relays:'-- for desc in parse_file('/home/atagar/.tor/cached-descriptors'):- if desc.exit_policy.is_exiting_allowed():- print ' %s (%s)' % (desc.nickname, desc.fingerprint)--**Module Overview:**--::-- Microdescriptor - Tor microdescriptor.-"""--import hashlib--import stem.exit_policy--from stem.descriptor import (- Descriptor,- _get_descriptor_components,- _read_until_keywords,- _value,- _parse_simple_line,- _parse_key_block,-)--from stem.descriptor.router_status_entry import (- _parse_a_line,- _parse_p_line,-)--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache--REQUIRED_FIELDS = (- 'onion-key',-)--SINGLE_FIELDS = (- 'onion-key',- 'ntor-onion-key',- 'family',- 'p',- 'p6',-)---def _parse_file(descriptor_file, validate = False, **kwargs):- """- Iterates over the microdescriptors in a file.-- :param file descriptor_file: file with descriptor content- :param bool validate: checks the validity of the descriptor's content if- **True**, skips these checks otherwise- :param dict kwargs: additional arguments for the descriptor constructor-- :returns: iterator for Microdescriptor instances in the file-- :raises:- * **ValueError** if the contents is malformed and validate is True- * **IOError** if the file can't be read- """-- while True:- annotations = _read_until_keywords('onion-key', descriptor_file)-- # read until we reach an annotation or onion-key line- descriptor_lines = []-- # read the onion-key line, done if we're at the end of the document-- onion_key_line = descriptor_file.readline()-- if onion_key_line:- descriptor_lines.append(onion_key_line)- else:- break-- while True:- last_position = descriptor_file.tell()- line = descriptor_file.readline()-- if not line:- break # EOF- elif line.startswith(b'@') or line.startswith(b'onion-key'):- descriptor_file.seek(last_position)- break- else:- descriptor_lines.append(line)-- if descriptor_lines:- if descriptor_lines[0].startswith(b'@type'):- descriptor_lines = descriptor_lines[1:]-- # strip newlines from annotations- annotations = list(map(bytes.strip, annotations))-- descriptor_text = bytes.join(b'', descriptor_lines)-- yield Microdescriptor(descriptor_text, validate, annotations, **kwargs)- else:- break # done parsing descriptors---def _parse_id_line(descriptor, entries):- value = _value('id', entries)- value_comp = value.split()-- if len(value_comp) >= 2:- descriptor.identifier_type = value_comp[0]- descriptor.identifier = value_comp[1]- else:- raise ValueError("'id' lines should contain both the key type and digest: id %s" % value)---_parse_digest = lambda descriptor, entries: setattr(descriptor, 'digest', hashlib.sha256(descriptor.get_bytes()).hexdigest().upper())-_parse_onion_key_line = _parse_key_block('onion-key', 'onion_key', 'RSA PUBLIC KEY')-_parse_ntor_onion_key_line = _parse_simple_line('ntor-onion-key', 'ntor_onion_key')-_parse_family_line = lambda descriptor, entries: setattr(descriptor, 'family', _value('family', entries).split(' '))-_parse_p6_line = lambda descriptor, entries: setattr(descriptor, 'exit_policy_v6', stem.exit_policy.MicroExitPolicy(_value('p6', entries)))---class Microdescriptor(Descriptor):- """- Microdescriptor (`descriptor specification- <https://gitweb.torproject.org/torspec.git/tree/dir-spec.txt>`_)-- :var str digest: **\*** hex digest for this microdescriptor, this can be used- to match against the corresponding digest attribute of a- :class:`~stem.descriptor.router_status_entry.RouterStatusEntryMicroV3`- :var str onion_key: **\*** key used to encrypt EXTEND cells- :var str ntor_onion_key: base64 key used to encrypt EXTEND in the ntor protocol- :var list or_addresses: **\*** alternative for our address/or_port attributes, each- entry is a tuple of the form (address (**str**), port (**int**), is_ipv6- (**bool**))- :var list family: **\*** nicknames or fingerprints of declared family- :var stem.exit_policy.MicroExitPolicy exit_policy: **\*** relay's exit policy- :var stem.exit_policy.MicroExitPolicy exit_policy_v6: **\*** exit policy for IPv6- :var str identifier_type: identity digest key type- :var str identifier: base64 encoded identity digest, this is only used for collision prevention (:trac:`11743`)-- **\*** attribute is required when we're parsed with validation-- .. versionchanged:: 1.1.0- Added the identifier and identifier_type attributes.- """-- ATTRIBUTES = {- 'onion_key': (None, _parse_onion_key_line),- 'ntor_onion_key': (None, _parse_ntor_onion_key_line),- 'or_addresses': ([], _parse_a_line),- 'family': ([], _parse_family_line),- 'exit_policy': (stem.exit_policy.MicroExitPolicy('reject 1-65535'), _parse_p_line),- 'exit_policy_v6': (None, _parse_p6_line),- 'identifier_type': (None, _parse_id_line),- 'identifier': (None, _parse_id_line),- 'digest': (None, _parse_digest),- }-- PARSER_FOR_LINE = {- 'onion-key': _parse_onion_key_line,- 'ntor-onion-key': _parse_ntor_onion_key_line,- 'a': _parse_a_line,- 'family': _parse_family_line,- 'p': _parse_p_line,- 'p6': _parse_p6_line,- 'id': _parse_id_line,- }-- def __init__(self, raw_contents, validate = False, annotations = None):- super(Microdescriptor, self).__init__(raw_contents, lazy_load = not validate)- self._annotation_lines = annotations if annotations else []- entries = _get_descriptor_components(raw_contents, validate)-- if validate:- self.digest = hashlib.sha256(self.get_bytes()).hexdigest().upper()- self._parse(entries, validate)- self._check_constraints(entries)- else:- self._entries = entries-- @lru_cache()- def get_annotations(self):- """- Provides content that appeared prior to the descriptor. If this comes from- the cached-microdescs then this commonly contains content like...-- ::-- @last-listed 2013-02-24 00:18:30-- :returns: **dict** with the key/value pairs in our annotations- """-- annotation_dict = {}-- for line in self._annotation_lines:- if b' ' in line:- key, value = line.split(b' ', 1)- annotation_dict[key] = value- else:- annotation_dict[line] = None-- return annotation_dict-- def get_annotation_lines(self):- """- Provides the lines of content that appeared prior to the descriptor. This- is the same as the- :func:`~stem.descriptor.microdescriptor.Microdescriptor.get_annotations`- results, but with the unparsed lines and ordering retained.-- :returns: **list** with the lines of annotation that came before this descriptor- """-- return self._annotation_lines-- def _check_constraints(self, entries):- """- Does a basic check that the entries conform to this descriptor type's- constraints.-- :param dict entries: keyword => (value, pgp key) entries-- :raises: **ValueError** if an issue arises in validation- """-- for keyword in REQUIRED_FIELDS:- if keyword not in entries:- raise ValueError("Microdescriptor must have a '%s' entry" % keyword)-- for keyword in SINGLE_FIELDS:- if keyword in entries and len(entries[keyword]) > 1:- raise ValueError("The '%s' entry can only appear once in a microdescriptor" % keyword)-- if 'onion-key' != list(entries.keys())[0]:- raise ValueError("Microdescriptor must start with a 'onion-key' entry")-- def _name(self, is_plural = False):- return 'microdescriptors' if is_plural else 'microdescriptor'-- def _compare(self, other, method):- if not isinstance(other, Microdescriptor):- return False-- return method(str(self).strip(), str(other).strip())-- def __hash__(self):- return hash(str(self).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)diff --git a/ext/stem/descriptor/networkstatus.py b/ext/stem/descriptor/networkstatus.pydeleted file mode 100644index a162e2ec..00000000--- a/ext/stem/descriptor/networkstatus.py+++ /dev/null@@ -1,1444 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Parsing for Tor network status documents. This supports both the v2 and v3-dir-spec. Documents can be obtained from a few sources...--* The 'cached-consensus' file in Tor's data directory.--* Archived descriptors provided by CollecTor- (https://collector.torproject.org/).--* Directory authorities and mirrors via their DirPort.--... and contain the following sections...--* document header-* list of :class:`stem.descriptor.networkstatus.DirectoryAuthority`-* list of :class:`stem.descriptor.router_status_entry.RouterStatusEntry`-* document footer--Of these, the router status entry section can be quite large (on the order of-hundreds of kilobytes). As such we provide a couple of methods for reading-network status documents through :func:`~stem.descriptor.__init__.parse_file`.-For more information see :func:`~stem.descriptor.__init__.DocumentHandler`...--::-- from stem.descriptor import parse_file, DocumentHandler-- with open('.tor/cached-consensus', 'rb') as consensus_file:- # Processes the routers as we read them in. The routers refer to a document- # with an unset 'routers' attribute.-- for router in parse_file(consensus_file, 'network-status-consensus-3 1.0', document_handler = DocumentHandler.ENTRIES):- print router.nickname--**Module Overview:**--::-- NetworkStatusDocument - Network status document- |- NetworkStatusDocumentV2 - Version 2 network status document- |- NetworkStatusDocumentV3 - Version 3 network status document- +- BridgeNetworkStatusDocument - Version 3 network status document for bridges-- KeyCertificate - Certificate used to authenticate an authority- DocumentSignature - Signature of a document by a directory authority- DirectoryAuthority - Directory authority as defined in a v3 network status document---.. data:: PackageVersion-- Latest recommended version of a package that's available.-- :var str name: name of the package- :var str version: latest recommended version- :var str url: package's url- :var dict digests: mapping of digest types to their value-"""--import collections-import io--import stem.descriptor.router_status_entry-import stem.util.str_tools-import stem.util.tor_tools-import stem.version--from stem.descriptor import (- PGP_BLOCK_END,- Descriptor,- DocumentHandler,- _get_descriptor_components,- _read_until_keywords,- _value,- _parse_simple_line,- _parse_timestamp_line,- _parse_forty_character_hex,- _parse_key_block,-)--from stem.descriptor.router_status_entry import (- RouterStatusEntryV2,- RouterStatusEntryV3,- RouterStatusEntryMicroV3,-)--PackageVersion = collections.namedtuple('PackageVersion', [- 'name',- 'version',- 'url',- 'digests',-])--# Version 2 network status document fields, tuples of the form...-# (keyword, is_mandatory)--NETWORK_STATUS_V2_FIELDS = (- ('network-status-version', True),- ('dir-source', True),- ('fingerprint', True),- ('contact', True),- ('dir-signing-key', True),- ('client-versions', False),- ('server-versions', False),- ('published', True),- ('dir-options', False),- ('directory-signature', True),-)--# Network status document are either a 'vote' or 'consensus', with different-# mandatory fields for each. Both though require that their fields appear in a-# specific order. This is an ordered listing of the following...-#-# (field, in_votes, in_consensus, is_mandatory)--HEADER_STATUS_DOCUMENT_FIELDS = (- ('network-status-version', True, True, True),- ('vote-status', True, True, True),- ('consensus-methods', True, False, False),- ('consensus-method', False, True, False),- ('published', True, False, True),- ('valid-after', True, True, True),- ('fresh-until', True, True, True),- ('valid-until', True, True, True),- ('voting-delay', True, True, True),- ('client-versions', True, True, False),- ('server-versions', True, True, False),- ('package', True, True, False),- ('known-flags', True, True, True),- ('flag-thresholds', True, False, False),- ('params', True, True, False),-)--FOOTER_STATUS_DOCUMENT_FIELDS = (- ('directory-footer', True, True, False),- ('bandwidth-weights', False, True, False),- ('directory-signature', True, True, True),-)--HEADER_FIELDS = [attr[0] for attr in HEADER_STATUS_DOCUMENT_FIELDS]-FOOTER_FIELDS = [attr[0] for attr in FOOTER_STATUS_DOCUMENT_FIELDS]--AUTH_START = 'dir-source'-ROUTERS_START = 'r'-FOOTER_START = 'directory-footer'-V2_FOOTER_START = 'directory-signature'--DEFAULT_PARAMS = {- 'bwweightscale': 10000,- 'cbtdisabled': 0,- 'cbtnummodes': 3,- 'cbtrecentcount': 20,- 'cbtmaxtimeouts': 18,- 'cbtmincircs': 100,- 'cbtquantile': 80,- 'cbtclosequantile': 95,- 'cbttestfreq': 60,- 'cbtmintimeout': 2000,- 'cbtinitialtimeout': 60000,- 'Support022HiddenServices': 1,- 'usecreatefast': 1,-}--# KeyCertificate fields, tuple is of the form...-# (keyword, is_mandatory)--KEY_CERTIFICATE_PARAMS = (- ('dir-key-certificate-version', True),- ('dir-address', False),- ('fingerprint', True),- ('dir-identity-key', True),- ('dir-key-published', True),- ('dir-key-expires', True),- ('dir-signing-key', True),- ('dir-key-crosscert', False),- ('dir-key-certification', True),-)--# all parameters are constrained to int32 range-MIN_PARAM, MAX_PARAM = -2147483648, 2147483647--PARAM_RANGE = {- 'circwindow': (100, 1000),- 'CircuitPriorityHalflifeMsec': (-1, MAX_PARAM),- 'perconnbwrate': (-1, MAX_PARAM),- 'perconnbwburst': (-1, MAX_PARAM),- 'refuseunknownexits': (0, 1),- 'bwweightscale': (1, MAX_PARAM),- 'cbtdisabled': (0, 1),- 'cbtnummodes': (1, 20),- 'cbtrecentcount': (3, 1000),- 'cbtmaxtimeouts': (3, 10000),- 'cbtmincircs': (1, 10000),- 'cbtquantile': (10, 99),- 'cbtclosequantile': (MIN_PARAM, 99),- 'cbttestfreq': (1, MAX_PARAM),- 'cbtmintimeout': (500, MAX_PARAM),- 'UseOptimisticData': (0, 1),- 'Support022HiddenServices': (0, 1),- 'usecreatefast': (0, 1),- 'UseNTorHandshake': (0, 1),- 'FastFlagMinThreshold': (4, MAX_PARAM),- 'NumDirectoryGuards': (0, 10),- 'NumEntryGuards': (1, 10),- 'GuardLifetime': (2592000, 157766400), # min: 30 days, max: 1826 days- 'NumNTorsPerTAP': (1, 100000),- 'AllowNonearlyExtend': (0, 1),-}---def _parse_file(document_file, document_type = None, validate = False, is_microdescriptor = False, document_handler = DocumentHandler.ENTRIES, **kwargs):- """- Parses a network status and iterates over the RouterStatusEntry in it. The- document that these instances reference have an empty 'routers' attribute to- allow for limited memory usage.-- :param file document_file: file with network status document content- :param class document_type: NetworkStatusDocument subclass- :param bool validate: checks the validity of the document's contents if- **True**, skips these checks otherwise- :param bool is_microdescriptor: **True** if this is for a microdescriptor- consensus, **False** otherwise- :param stem.descriptor.__init__.DocumentHandler document_handler: method in- which to parse :class:`~stem.descriptor.networkstatus.NetworkStatusDocument`- :param dict kwargs: additional arguments for the descriptor constructor-- :returns: :class:`stem.descriptor.networkstatus.NetworkStatusDocument` object-- :raises:- * **ValueError** if the document_version is unrecognized or the contents is- malformed and validate is **True**- * **IOError** if the file can't be read- """-- # we can't properly default this since NetworkStatusDocumentV3 isn't defined yet-- if document_type is None:- document_type = NetworkStatusDocumentV3-- if document_type == NetworkStatusDocumentV2:- document_type, router_type = NetworkStatusDocumentV2, RouterStatusEntryV2- elif document_type == NetworkStatusDocumentV3:- router_type = RouterStatusEntryMicroV3 if is_microdescriptor else RouterStatusEntryV3- elif document_type == BridgeNetworkStatusDocument:- document_type, router_type = BridgeNetworkStatusDocument, RouterStatusEntryV2- else:- raise ValueError("Document type %i isn't recognized (only able to parse v2, v3, and bridge)" % document_type)-- if document_handler == DocumentHandler.DOCUMENT:- yield document_type(document_file.read(), validate, **kwargs)- return-- # getting the document without the routers section-- header = _read_until_keywords((ROUTERS_START, FOOTER_START, V2_FOOTER_START), document_file)-- if header and header[0].startswith(b'@type'):- header = header[1:]-- routers_start = document_file.tell()- _read_until_keywords((FOOTER_START, V2_FOOTER_START), document_file, skip = True)- routers_end = document_file.tell()-- footer = document_file.readlines()- document_content = bytes.join(b'', header + footer)-- if document_handler == DocumentHandler.BARE_DOCUMENT:- yield document_type(document_content, validate, **kwargs)- elif document_handler == DocumentHandler.ENTRIES:- desc_iterator = stem.descriptor.router_status_entry._parse_file(- document_file,- validate,- entry_class = router_type,- entry_keyword = ROUTERS_START,- start_position = routers_start,- end_position = routers_end,- extra_args = (document_type(document_content, validate),),- **kwargs- )-- for desc in desc_iterator:- yield desc- else:- raise ValueError('Unrecognized document_handler: %s' % document_handler)---def _parse_file_key_certs(certificate_file, validate = False):- """- Parses a file containing one or more authority key certificates.-- :param file certificate_file: file with key certificates- :param bool validate: checks the validity of the certificate's contents if- **True**, skips these checks otherwise-- :returns: iterator for :class:`stem.descriptor.networkstatus.KeyCertificate`- instance in the file-- :raises:- * **ValueError** if the key certificate content is invalid and validate is- **True**- * **IOError** if the file can't be read- """-- while True:- keycert_content = _read_until_keywords('dir-key-certification', certificate_file)-- # we've reached the 'router-signature', now include the pgp style block- block_end_prefix = PGP_BLOCK_END.split(' ', 1)[0]- keycert_content += _read_until_keywords(block_end_prefix, certificate_file, True)-- if keycert_content:- yield stem.descriptor.networkstatus.KeyCertificate(bytes.join(b'', keycert_content), validate = validate)- else:- break # done parsing file---class NetworkStatusDocument(Descriptor):- """- Common parent for network status documents.- """---def _parse_version_line(keyword, attribute, expected_version):- def _parse(descriptor, entries):- value = _value(keyword, entries)-- if not value.isdigit():- raise ValueError('Document has a non-numeric version: %s %s' % (keyword, value))-- setattr(descriptor, attribute, int(value))-- if int(value) != expected_version:- raise ValueError("Expected a version %i document, but got version '%s' instead" % (expected_version, value))-- return _parse---def _parse_dir_source_line(descriptor, entries):- value = _value('dir-source', entries)- dir_source_comp = value.split()-- if len(dir_source_comp) < 3:- raise ValueError("The 'dir-source' line of a v2 network status document must have three values: dir-source %s" % value)-- if not dir_source_comp[0]:- # https://trac.torproject.org/7055- raise ValueError("Authority's hostname can't be blank: dir-source %s" % value)- elif not stem.util.connection.is_valid_ipv4_address(dir_source_comp[1]):- raise ValueError("Authority's address isn't a valid IPv4 address: %s" % dir_source_comp[1])- elif not stem.util.connection.is_valid_port(dir_source_comp[2], allow_zero = True):- raise ValueError("Authority's DirPort is invalid: %s" % dir_source_comp[2])-- descriptor.hostname = dir_source_comp[0]- descriptor.address = dir_source_comp[1]- descriptor.dir_port = None if dir_source_comp[2] == '0' else int(dir_source_comp[2])---_parse_network_status_version_line = _parse_version_line('network-status-version', 'version', 2)-_parse_fingerprint_line = _parse_forty_character_hex('fingerprint', 'fingerprint')-_parse_contact_line = _parse_simple_line('contact', 'contact')-_parse_dir_signing_key_line = _parse_key_block('dir-signing-key', 'signing_key', 'RSA PUBLIC KEY')-_parse_client_versions_line = lambda descriptor, entries: setattr(descriptor, 'client_versions', _value('client-versions', entries).split(','))-_parse_server_versions_line = lambda descriptor, entries: setattr(descriptor, 'server_versions', _value('server-versions', entries).split(','))-_parse_published_line = _parse_timestamp_line('published', 'published')-_parse_dir_options_line = lambda descriptor, entries: setattr(descriptor, 'options', _value('dir-options', entries).split())-_parse_directory_signature_line = _parse_key_block('directory-signature', 'signature', 'SIGNATURE', value_attribute = 'signing_authority')---class NetworkStatusDocumentV2(NetworkStatusDocument):- """- Version 2 network status document. These have been deprecated and are no- longer generated by Tor.-- :var dict routers: fingerprints to :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV2`- contained in the document-- :var int version: **\*** document version-- :var str hostname: **\*** hostname of the authority- :var str address: **\*** authority's IP address- :var int dir_port: **\*** authority's DirPort- :var str fingerprint: **\*** authority's fingerprint- :var str contact: **\*** authority's contact information- :var str signing_key: **\*** authority's public signing key-- :var list client_versions: list of recommended client tor version strings- :var list server_versions: list of recommended server tor version strings- :var datetime published: **\*** time when the document was published- :var list options: **\*** list of things that this authority decides-- :var str signing_authority: **\*** name of the authority signing the document- :var str signature: **\*** authority's signature for the document-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as **None** if undefined- """-- ATTRIBUTES = {- 'version': (None, _parse_network_status_version_line),- 'hostname': (None, _parse_dir_source_line),- 'address': (None, _parse_dir_source_line),- 'dir_port': (None, _parse_dir_source_line),- 'fingerprint': (None, _parse_fingerprint_line),- 'contact': (None, _parse_contact_line),- 'signing_key': (None, _parse_dir_signing_key_line),-- 'client_versions': ([], _parse_client_versions_line),- 'server_versions': ([], _parse_server_versions_line),- 'published': (None, _parse_published_line),- 'options': ([], _parse_dir_options_line),-- 'signing_authority': (None, _parse_directory_signature_line),- 'signatures': (None, _parse_directory_signature_line),- }-- PARSER_FOR_LINE = {- 'network-status-version': _parse_network_status_version_line,- 'dir-source': _parse_dir_source_line,- 'fingerprint': _parse_fingerprint_line,- 'contact': _parse_contact_line,- 'dir-signing-key': _parse_dir_signing_key_line,- 'client-versions': _parse_client_versions_line,- 'server-versions': _parse_server_versions_line,- 'published': _parse_published_line,- 'dir-options': _parse_dir_options_line,- 'directory-signature': _parse_directory_signature_line,- }-- def __init__(self, raw_content, validate = False):- super(NetworkStatusDocumentV2, self).__init__(raw_content, lazy_load = not validate)-- # Splitting the document from the routers. Unlike v3 documents we're not- # bending over backwards on the validation by checking the field order or- # that header/footer attributes aren't in the wrong section. This is a- # deprecated descriptor type - patches welcome if you want those checks.-- document_file = io.BytesIO(raw_content)- document_content = bytes.join(b'', _read_until_keywords((ROUTERS_START, V2_FOOTER_START), document_file))-- router_iter = stem.descriptor.router_status_entry._parse_file(- document_file,- validate,- entry_class = RouterStatusEntryV2,- entry_keyword = ROUTERS_START,- section_end_keywords = (V2_FOOTER_START,),- extra_args = (self,),- )-- self.routers = dict((desc.fingerprint, desc) for desc in router_iter)-- entries = _get_descriptor_components(document_content + b'\n' + document_file.read(), validate)-- if validate:- self._check_constraints(entries)- self._parse(entries, validate)-- # 'client-versions' and 'server-versions' are only required if 'Versions'- # is among the options-- if 'Versions' in self.options and not ('client-versions' in entries and 'server-versions' in entries):- raise ValueError("Version 2 network status documents must have a 'client-versions' and 'server-versions' when 'Versions' is listed among its dir-options:\n%s" % str(self))- else:- self._entries = entries-- def _check_constraints(self, entries):- required_fields = [field for (field, is_mandatory) in NETWORK_STATUS_V2_FIELDS if is_mandatory]- for keyword in required_fields:- if keyword not in entries:- raise ValueError("Network status document (v2) must have a '%s' line:\n%s" % (keyword, str(self)))-- # all recognized fields can only appear once- single_fields = [field for (field, _) in NETWORK_STATUS_V2_FIELDS]- for keyword in single_fields:- if keyword in entries and len(entries[keyword]) > 1:- raise ValueError("Network status document (v2) can only have a single '%s' line, got %i:\n%s" % (keyword, len(entries[keyword]), str(self)))-- if 'network-status-version' != list(entries.keys())[0]:- raise ValueError("Network status document (v2) are expected to start with a 'network-status-version' line:\n%s" % str(self))---def _parse_header_network_status_version_line(descriptor, entries):- # "network-status-version" version-- value = _value('network-status-version', entries)-- if ' ' in value:- version, flavor = value.split(' ', 1)- else:- version, flavor = value, None-- if not version.isdigit():- raise ValueError('Network status document has a non-numeric version: network-status-version %s' % value)-- descriptor.version = int(version)- descriptor.version_flavor = flavor- descriptor.is_microdescriptor = flavor == 'microdesc'-- if descriptor.version != 3:- raise ValueError("Expected a version 3 network status document, got version '%s' instead" % descriptor.version)---def _parse_header_vote_status_line(descriptor, entries):- # "vote-status" type- #- # The consensus-method and consensus-methods fields are optional since- # they weren't included in version 1. Setting a default now that we- # know if we're a vote or not.-- value = _value('vote-status', entries)-- if value == 'consensus':- descriptor.is_consensus, descriptor.is_vote = True, False- elif value == 'vote':- descriptor.is_consensus, descriptor.is_vote = False, True- else:- raise ValueError("A network status document's vote-status line can only be 'consensus' or 'vote', got '%s' instead" % value)---def _parse_header_consensus_methods_line(descriptor, entries):- # "consensus-methods" IntegerList-- if descriptor._lazy_loading and descriptor.is_vote:- descriptor.consensus_methods = [1]-- value, consensus_methods = _value('consensus-methods', entries), []-- for entry in value.split(' '):- if not entry.isdigit():- raise ValueError("A network status document's consensus-methods must be a list of integer values, but was '%s'" % value)-- consensus_methods.append(int(entry))-- descriptor.consensus_methods = consensus_methods---def _parse_header_consensus_method_line(descriptor, entries):- # "consensus-method" Integer-- if descriptor._lazy_loading and descriptor.is_consensus:- descriptor.consensus_method = 1-- value = _value('consensus-method', entries)-- if not value.isdigit():- raise ValueError("A network status document's consensus-method must be an integer, but was '%s'" % value)-- descriptor.consensus_method = int(value)---def _parse_header_voting_delay_line(descriptor, entries):- # "voting-delay" VoteSeconds DistSeconds-- value = _value('voting-delay', entries)- value_comp = value.split(' ')-- if len(value_comp) == 2 and value_comp[0].isdigit() and value_comp[1].isdigit():- descriptor.vote_delay = int(value_comp[0])- descriptor.dist_delay = int(value_comp[1])- else:- raise ValueError("A network status document's 'voting-delay' line must be a pair of integer values, but was '%s'" % value)---def _parse_versions_line(keyword, attribute):- def _parse(descriptor, entries):- value, entries = _value(keyword, entries), []-- for entry in value.split(','):- try:- entries.append(stem.version._get_version(entry))- except ValueError:- raise ValueError("Network status document's '%s' line had '%s', which isn't a parsable tor version: %s %s" % (keyword, entry, keyword, value))-- setattr(descriptor, attribute, entries)-- return _parse---def _parse_header_flag_thresholds_line(descriptor, entries):- # "flag-thresholds" SP THRESHOLDS-- value, thresholds = _value('flag-thresholds', entries).strip(), {}-- if value:- for entry in value.split(' '):- if '=' not in entry:- raise ValueError("Network status document's 'flag-thresholds' line is expected to be space separated key=value mappings, got: flag-thresholds %s" % value)-- entry_key, entry_value = entry.split('=', 1)-- try:- if entry_value.endswith('%'):- # opting for string manipulation rather than just- # 'float(entry_value) / 100' because floating point arithmetic- # will lose precision-- thresholds[entry_key] = float('0.' + entry_value[:-1].replace('.', '', 1))- elif '.' in entry_value:- thresholds[entry_key] = float(entry_value)- else:- thresholds[entry_key] = int(entry_value)- except ValueError:- raise ValueError("Network status document's 'flag-thresholds' line is expected to have float values, got: flag-thresholds %s" % value)-- descriptor.flag_thresholds = thresholds---def _parse_header_parameters_line(descriptor, entries):- # "params" [Parameters]- # Parameter ::= Keyword '=' Int32- # Int32 ::= A decimal integer between -2147483648 and 2147483647.- # Parameters ::= Parameter | Parameters SP Parameter-- if descriptor._lazy_loading:- descriptor.params = dict(DEFAULT_PARAMS) if descriptor._default_params else {}-- value = _value('params', entries)-- # should only appear in consensus-method 7 or later-- if not descriptor.meets_consensus_method(7):- raise ValueError("A network status document's 'params' line should only appear in consensus-method 7 or later")-- if value != '':- descriptor.params = _parse_int_mappings('params', value, True)- descriptor._check_params_constraints()---def _parse_directory_footer_line(descriptor, entries):- # nothing to parse, simply checking that we don't have a value-- value = _value('directory-footer', entries)-- if value:- raise ValueError("A network status document's 'directory-footer' line shouldn't have any content, got 'directory-footer %s'" % value)---def _parse_footer_directory_signature_line(descriptor, entries):- signatures = []-- for sig_value, block_type, block_contents in entries['directory-signature']:- if sig_value.count(' ') not in (1, 2):- raise ValueError("Authority signatures in a network status document are expected to be of the form 'directory-signature [METHOD] FINGERPRINT KEY_DIGEST', received: %s" % sig_value)-- if not block_contents or block_type != 'SIGNATURE':- raise ValueError("'directory-signature' should be followed by a SIGNATURE block, but was a %s" % block_type)-- if sig_value.count(' ') == 1:- method = 'sha1' # default if none was provided- fingerprint, key_digest = sig_value.split(' ', 1)- else:- method, fingerprint, key_digest = sig_value.split(' ', 2)-- signatures.append(DocumentSignature(method, fingerprint, key_digest, block_contents, True))-- descriptor.signatures = signatures---def _parse_package_line(descriptor, entries):- package_versions = []-- for value, _, _ in entries['package']:- value_comp = value.split()-- if len(value_comp) < 3:- raise ValueError("'package' must at least have a 'PackageName Version URL': %s" % value)-- name, version, url = value_comp[:3]- digests = {}-- for digest_entry in value_comp[3:]:- if '=' not in digest_entry:- raise ValueError("'package' digest entries should be 'key=value' pairs: %s" % value)-- key, value = digest_entry.split('=', 1)- digests[key] = value-- package_versions.append(PackageVersion(name, version, url, digests))-- descriptor.packages = package_versions---_parse_header_valid_after_line = _parse_timestamp_line('valid-after', 'valid_after')-_parse_header_fresh_until_line = _parse_timestamp_line('fresh-until', 'fresh_until')-_parse_header_valid_until_line = _parse_timestamp_line('valid-until', 'valid_until')-_parse_header_client_versions_line = _parse_versions_line('client-versions', 'client_versions')-_parse_header_server_versions_line = _parse_versions_line('server-versions', 'server_versions')-_parse_header_known_flags_line = lambda descriptor, entries: setattr(descriptor, 'known_flags', [entry for entry in _value('known-flags', entries).split(' ') if entry])-_parse_footer_bandwidth_weights_line = lambda descriptor, entries: setattr(descriptor, 'bandwidth_weights', _parse_int_mappings('bandwidth-weights', _value('bandwidth-weights', entries), True))---class NetworkStatusDocumentV3(NetworkStatusDocument):- """- Version 3 network status document. This could be either a vote or consensus.-- :var tuple routers: :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3`- contained in the document-- :var int version: **\*** document version- :var str version_flavor: **\*** flavor associated with the document (such as 'microdesc')- :var bool is_consensus: **\*** **True** if the document is a consensus- :var bool is_vote: **\*** **True** if the document is a vote- :var bool is_microdescriptor: **\*** **True** if this is a microdescriptor- flavored document, **False** otherwise- :var datetime valid_after: **\*** time when the consensus became valid- :var datetime fresh_until: **\*** time when the next consensus should be produced- :var datetime valid_until: **\*** time when this consensus becomes obsolete- :var int vote_delay: **\*** number of seconds allowed for collecting votes- from all authorities- :var int dist_delay: **\*** number of seconds allowed for collecting- signatures from all authorities- :var list client_versions: list of recommended client tor versions- :var list server_versions: list of recommended server tor versions- :var list packages: **\*** list of :data:`~stem.descriptor.networkstatus.PackageVersion` entries- :var list known_flags: **\*** list of :data:`~stem.Flag` for the router's flags- :var dict params: **\*** dict of parameter(**str**) => value(**int**) mappings- :var list directory_authorities: **\*** list of :class:`~stem.descriptor.networkstatus.DirectoryAuthority`- objects that have generated this document- :var list signatures: **\*** :class:`~stem.descriptor.networkstatus.DocumentSignature`- of the authorities that have signed the document-- **Consensus Attributes:**-- :var int consensus_method: method version used to generate this consensus- :var dict bandwidth_weights: dict of weight(str) => value(int) mappings-- **Vote Attributes:**-- :var list consensus_methods: list of ints for the supported method versions- :var datetime published: time when the document was published- :var dict flag_thresholds: **\*** mapping of internal performance thresholds used while making the vote, values are **ints** or **floats**-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as None if undefined-- .. versionchanged:: 1.4.0- Added the packages attribute.- """-- ATTRIBUTES = {- 'version': (None, _parse_header_network_status_version_line),- 'version_flavor': (None, _parse_header_network_status_version_line),- 'is_consensus': (True, _parse_header_vote_status_line),- 'is_vote': (False, _parse_header_vote_status_line),- 'is_microdescriptor': (False, _parse_header_network_status_version_line),- 'consensus_methods': ([], _parse_header_consensus_methods_line),- 'published': (None, _parse_published_line),- 'consensus_method': (None, _parse_header_consensus_method_line),- 'valid_after': (None, _parse_header_valid_after_line),- 'fresh_until': (None, _parse_header_fresh_until_line),- 'valid_until': (None, _parse_header_valid_until_line),- 'vote_delay': (None, _parse_header_voting_delay_line),- 'dist_delay': (None, _parse_header_voting_delay_line),- 'client_versions': ([], _parse_header_client_versions_line),- 'server_versions': ([], _parse_header_server_versions_line),- 'packages': ([], _parse_package_line),- 'known_flags': ([], _parse_header_known_flags_line),- 'flag_thresholds': ({}, _parse_header_flag_thresholds_line),- 'params': ({}, _parse_header_parameters_line),-- 'signatures': ([], _parse_footer_directory_signature_line),- 'bandwidth_weights': ({}, _parse_footer_bandwidth_weights_line),- }-- HEADER_PARSER_FOR_LINE = {- 'network-status-version': _parse_header_network_status_version_line,- 'vote-status': _parse_header_vote_status_line,- 'consensus-methods': _parse_header_consensus_methods_line,- 'consensus-method': _parse_header_consensus_method_line,- 'published': _parse_published_line,- 'valid-after': _parse_header_valid_after_line,- 'fresh-until': _parse_header_fresh_until_line,- 'valid-until': _parse_header_valid_until_line,- 'voting-delay': _parse_header_voting_delay_line,- 'client-versions': _parse_header_client_versions_line,- 'server-versions': _parse_header_server_versions_line,- 'package': _parse_package_line,- 'known-flags': _parse_header_known_flags_line,- 'flag-thresholds': _parse_header_flag_thresholds_line,- 'params': _parse_header_parameters_line,- }-- FOOTER_PARSER_FOR_LINE = {- 'directory-footer': _parse_directory_footer_line,- 'bandwidth-weights': _parse_footer_bandwidth_weights_line,- 'directory-signature': _parse_footer_directory_signature_line,- }-- def __init__(self, raw_content, validate = False, default_params = True):- """- Parse a v3 network status document.-- :param str raw_content: raw network status document data- :param bool validate: **True** if the document is to be validated, **False** otherwise- :param bool default_params: includes defaults in our params dict, otherwise- it just contains values from the document-- :raises: **ValueError** if the document is invalid- """-- super(NetworkStatusDocumentV3, self).__init__(raw_content, lazy_load = not validate)- document_file = io.BytesIO(raw_content)-- self._default_params = default_params- self._header(document_file, validate)-- self.directory_authorities = tuple(stem.descriptor.router_status_entry._parse_file(- document_file,- validate,- entry_class = DirectoryAuthority,- entry_keyword = AUTH_START,- section_end_keywords = (ROUTERS_START, FOOTER_START, V2_FOOTER_START),- extra_args = (self.is_vote,),- ))-- if validate and self.is_vote and len(self.directory_authorities) != 1:- raise ValueError('Votes should only have an authority entry for the one that issued it, got %i: %s' % (len(self.directory_authorities), self.directory_authorities))-- router_iter = stem.descriptor.router_status_entry._parse_file(- document_file,- validate,- entry_class = RouterStatusEntryMicroV3 if self.is_microdescriptor else RouterStatusEntryV3,- entry_keyword = ROUTERS_START,- section_end_keywords = (FOOTER_START, V2_FOOTER_START),- extra_args = (self,),- )-- self.routers = dict((desc.fingerprint, desc) for desc in router_iter)- self._footer(document_file, validate)-- def get_unrecognized_lines(self):- if self._lazy_loading:- self._parse(self._header_entries, False, parser_for_line = self.HEADER_PARSER_FOR_LINE)- self._parse(self._footer_entries, False, parser_for_line = self.FOOTER_PARSER_FOR_LINE)- self._lazy_loading = False-- return super(NetworkStatusDocumentV3, self).get_unrecognized_lines()-- def meets_consensus_method(self, method):- """- Checks if we meet the given consensus-method. This works for both votes and- consensuses, checking our 'consensus-method' and 'consensus-methods'- entries.-- :param int method: consensus-method to check for-- :returns: **True** if we meet the given consensus-method, and **False** otherwise- """-- if self.consensus_method is not None:- return self.consensus_method >= method- elif self.consensus_methods is not None:- return bool([x for x in self.consensus_methods if x >= method])- else:- return False # malformed document-- def _compare(self, other, method):- if not isinstance(other, NetworkStatusDocumentV3):- return False-- return method(str(self).strip(), str(other).strip())-- def _header(self, document_file, validate):- content = bytes.join(b'', _read_until_keywords((AUTH_START, ROUTERS_START, FOOTER_START), document_file))- entries = _get_descriptor_components(content, validate)-- if validate:- # all known header fields can only appear once except-- for keyword, values in list(entries.items()):- if len(values) > 1 and keyword in HEADER_FIELDS and keyword != 'package':- raise ValueError("Network status documents can only have a single '%s' line, got %i" % (keyword, len(values)))-- if self._default_params:- self.params = dict(DEFAULT_PARAMS)-- self._parse(entries, validate, parser_for_line = self.HEADER_PARSER_FOR_LINE)-- _check_for_missing_and_disallowed_fields(self, entries, HEADER_STATUS_DOCUMENT_FIELDS)- _check_for_misordered_fields(entries, HEADER_FIELDS)-- # default consensus_method and consensus_methods based on if we're a consensus or vote-- if self.is_consensus and not self.consensus_method:- self.consensus_method = 1- elif self.is_vote and not self.consensus_methods:- self.consensus_methods = [1]- else:- self._header_entries = entries- self._entries.update(entries)-- def _footer(self, document_file, validate):- entries = _get_descriptor_components(document_file.read(), validate)-- if validate:- for keyword, values in list(entries.items()):- # all known footer fields can only appear once except...- # * 'directory-signature' in a consensus-- if len(values) > 1 and keyword in FOOTER_FIELDS:- if not (keyword == 'directory-signature' and self.is_consensus):- raise ValueError("Network status documents can only have a single '%s' line, got %i" % (keyword, len(values)))-- self._parse(entries, validate, parser_for_line = self.FOOTER_PARSER_FOR_LINE)-- # Check that the footer has the right initial line. Prior to consensus- # method 9 it's a 'directory-signature' and after that footers start with- # 'directory-footer'.-- if entries:- if self.meets_consensus_method(9):- if list(entries.keys())[0] != 'directory-footer':- raise ValueError("Network status document's footer should start with a 'directory-footer' line in consensus-method 9 or later")- else:- if list(entries.keys())[0] != 'directory-signature':- raise ValueError("Network status document's footer should start with a 'directory-signature' line prior to consensus-method 9")-- _check_for_missing_and_disallowed_fields(self, entries, FOOTER_STATUS_DOCUMENT_FIELDS)- _check_for_misordered_fields(entries, FOOTER_FIELDS)- else:- self._footer_entries = entries- self._entries.update(entries)-- def _check_params_constraints(self):- """- Checks that the params we know about are within their documented ranges.- """-- for key, value in self.params.items():- minimum, maximum = PARAM_RANGE.get(key, (MIN_PARAM, MAX_PARAM))-- # there's a few dynamic parameter ranges-- if key == 'cbtclosequantile':- minimum = self.params.get('cbtquantile', minimum)- elif key == 'cbtinitialtimeout':- minimum = self.params.get('cbtmintimeout', minimum)-- if value < minimum or value > maximum:- raise ValueError("'%s' value on the params line must be in the range of %i - %i, was %i" % (key, minimum, maximum, value))-- def __hash__(self):- return hash(str(self).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)---def _check_for_missing_and_disallowed_fields(document, entries, fields):- """- Checks that we have mandatory fields for our type, and that we don't have- any fields exclusive to the other (ie, no vote-only fields appear in a- consensus or vice versa).-- :param NetworkStatusDocumentV3 document: network status document- :param dict entries: ordered keyword/value mappings of the header or footer- :param list fields: expected field attributes (either- **HEADER_STATUS_DOCUMENT_FIELDS** or **FOOTER_STATUS_DOCUMENT_FIELDS**)-- :raises: **ValueError** if we're missing mandatory fields or have fields we shouldn't- """-- missing_fields, disallowed_fields = [], []-- for field, in_votes, in_consensus, mandatory in fields:- if mandatory and ((document.is_consensus and in_consensus) or (document.is_vote and in_votes)):- # mandatory field, check that we have it- if field not in entries.keys():- missing_fields.append(field)- elif (document.is_consensus and not in_consensus) or (document.is_vote and not in_votes):- # field we shouldn't have, check that we don't- if field in entries.keys():- disallowed_fields.append(field)-- if missing_fields:- raise ValueError('Network status document is missing mandatory field: %s' % ', '.join(missing_fields))-- if disallowed_fields:- raise ValueError("Network status document has fields that shouldn't appear in this document type or version: %s" % ', '.join(disallowed_fields))---def _check_for_misordered_fields(entries, expected):- """- To be valid a network status document's fiends need to appear in a specific- order. Checks that known fields appear in that order (unrecognized fields- are ignored).-- :param dict entries: ordered keyword/value mappings of the header or footer- :param list expected: ordered list of expected fields (either- **HEADER_FIELDS** or **FOOTER_FIELDS**)-- :raises: **ValueError** if entries aren't properly ordered- """-- # Earlier validation has ensured that our fields either belong to our- # document type or are unknown. Remove the unknown fields since they- # reflect a spec change and can appear anywhere in the document.-- actual = [field for field in entries.keys() if field in expected]-- # Narrow the expected to just what we have. If the lists then match then the- # order's valid.-- expected = [field for field in expected if field in actual]-- if actual != expected:- actual_label = ', '.join(actual)- expected_label = ', '.join(expected)- raise ValueError("The fields in a section of the document are misordered. It should be '%s' but was '%s'" % (actual_label, expected_label))---def _parse_int_mappings(keyword, value, validate):- # Parse a series of 'key=value' entries, checking the following:- # - values are integers- # - keys are sorted in lexical order-- results, seen_keys = {}, []- for entry in value.split(' '):- try:- if '=' not in entry:- raise ValueError("must only have 'key=value' entries")-- entry_key, entry_value = entry.split('=', 1)-- try:- # the int() function accepts things like '+123', but we don't want to- if entry_value.startswith('+'):- raise ValueError()-- entry_value = int(entry_value)- except ValueError:- raise ValueError("'%s' is a non-numeric value" % entry_value)-- if validate:- # parameters should be in ascending order by their key- for prior_key in seen_keys:- if prior_key > entry_key:- raise ValueError('parameters must be sorted by their key')-- results[entry_key] = entry_value- seen_keys.append(entry_key)- except ValueError as exc:- if not validate:- continue-- raise ValueError("Unable to parse network status document's '%s' line (%s): %s'" % (keyword, exc, value))-- return results---def _parse_dirauth_source_line(descriptor, entries):- # "dir-source" nickname identity address IP dirport orport-- value = _value('dir-source', entries)- dir_source_comp = value.split(' ')-- if len(dir_source_comp) < 6:- raise ValueError("Authority entry's 'dir-source' line must have six values: dir-source %s" % value)-- if not stem.util.tor_tools.is_valid_nickname(dir_source_comp[0].rstrip('-legacy')):- raise ValueError("Authority's nickname is invalid: %s" % dir_source_comp[0])- elif not stem.util.tor_tools.is_valid_fingerprint(dir_source_comp[1]):- raise ValueError("Authority's v3ident is invalid: %s" % dir_source_comp[1])- elif not dir_source_comp[2]:- # https://trac.torproject.org/7055- raise ValueError("Authority's hostname can't be blank: dir-source %s" % value)- elif not stem.util.connection.is_valid_ipv4_address(dir_source_comp[3]):- raise ValueError("Authority's address isn't a valid IPv4 address: %s" % dir_source_comp[3])- elif not stem.util.connection.is_valid_port(dir_source_comp[4], allow_zero = True):- raise ValueError("Authority's DirPort is invalid: %s" % dir_source_comp[4])- elif not stem.util.connection.is_valid_port(dir_source_comp[5]):- raise ValueError("Authority's ORPort is invalid: %s" % dir_source_comp[5])-- descriptor.nickname = dir_source_comp[0]- descriptor.v3ident = dir_source_comp[1]- descriptor.hostname = dir_source_comp[2]- descriptor.address = dir_source_comp[3]- descriptor.dir_port = None if dir_source_comp[4] == '0' else int(dir_source_comp[4])- descriptor.or_port = int(dir_source_comp[5])- descriptor.is_legacy = descriptor.nickname.endswith('-legacy')---_parse_legacy_dir_key_line = _parse_forty_character_hex('legacy-dir-key', 'legacy_dir_key')-_parse_vote_digest_line = _parse_forty_character_hex('vote-digest', 'vote_digest')---class DirectoryAuthority(Descriptor):- """- Directory authority information obtained from a v3 network status document.-- Authorities can optionally use a legacy format. These are no longer found in- practice, but have the following differences...-- * The authority's nickname ends with '-legacy'.- * There's no **contact** or **vote_digest** attribute.-- :var str nickname: **\*** authority's nickname- :var str v3ident: **\*** identity key fingerprint used to sign votes and consensus- :var str hostname: **\*** hostname of the authority- :var str address: **\*** authority's IP address- :var int dir_port: **\*** authority's DirPort- :var int or_port: **\*** authority's ORPort- :var bool is_legacy: **\*** if the authority's using the legacy format- :var str contact: contact information, this is included if is_legacy is **False**-- **Consensus Attributes:**-- :var str vote_digest: digest of the authority that contributed to the consensus, this is included if is_legacy is **False**-- **Vote Attributes:**-- :var str legacy_dir_key: fingerprint of and obsolete identity key- :var stem.descriptor.networkstatus.KeyCertificate key_certificate: **\***- authority's key certificate-- **\*** mandatory attribute-- .. versionchanged:: 1.4.0- Renamed our 'fingerprint' attribute to 'v3ident' (prior attribute exists- for backward compatability, but is deprecated).- """-- ATTRIBUTES = {- 'nickname': (None, _parse_dirauth_source_line),- 'v3ident': (None, _parse_dirauth_source_line),- 'hostname': (None, _parse_dirauth_source_line),- 'address': (None, _parse_dirauth_source_line),- 'dir_port': (None, _parse_dirauth_source_line),- 'or_port': (None, _parse_dirauth_source_line),- 'is_legacy': (False, _parse_dirauth_source_line),- 'contact': (None, _parse_contact_line),- 'vote_digest': (None, _parse_vote_digest_line),- 'legacy_dir_key': (None, _parse_legacy_dir_key_line),- }-- PARSER_FOR_LINE = {- 'dir-source': _parse_dirauth_source_line,- 'contact': _parse_contact_line,- 'legacy-dir-key': _parse_legacy_dir_key_line,- 'vote-digest': _parse_vote_digest_line,- }-- def __init__(self, raw_content, validate = False, is_vote = False):- """- Parse a directory authority entry in a v3 network status document.-- :param str raw_content: raw directory authority entry information- :param bool validate: checks the validity of the content if True, skips- these checks otherwise- :param bool is_vote: True if this is for a vote, False if it's for a consensus-- :raises: ValueError if the descriptor data is invalid- """-- super(DirectoryAuthority, self).__init__(raw_content, lazy_load = not validate)- content = stem.util.str_tools._to_unicode(raw_content)-- # separate the directory authority entry from its key certificate- key_div = content.find('\ndir-key-certificate-version')-- if key_div != -1:- self.key_certificate = KeyCertificate(content[key_div + 1:], validate)- content = content[:key_div + 1]- else:- self.key_certificate = None-- entries = _get_descriptor_components(content, validate)-- if validate and 'dir-source' != list(entries.keys())[0]:- raise ValueError("Authority entries are expected to start with a 'dir-source' line:\n%s" % (content))-- # check that we have mandatory fields-- if validate:- is_legacy, dir_source_entry = False, entries.get('dir-source')-- if dir_source_entry:- is_legacy = dir_source_entry[0][0].split()[0].endswith('-legacy')-- required_fields, excluded_fields = ['dir-source'], []-- if not is_legacy:- required_fields += ['contact']-- if is_vote:- if not self.key_certificate:- raise ValueError('Authority votes must have a key certificate:\n%s' % content)-- excluded_fields += ['vote-digest']- elif not is_vote:- if self.key_certificate:- raise ValueError("Authority consensus entries shouldn't have a key certificate:\n%s" % content)-- if not is_legacy:- required_fields += ['vote-digest']-- excluded_fields += ['legacy-dir-key']-- for keyword in required_fields:- if keyword not in entries:- raise ValueError("Authority entries must have a '%s' line:\n%s" % (keyword, content))-- for keyword in entries:- if keyword in excluded_fields:- type_label = 'votes' if is_vote else 'consensus entries'- raise ValueError("Authority %s shouldn't have a '%s' line:\n%s" % (type_label, keyword, content))-- # all known attributes can only appear at most once- for keyword, values in list(entries.items()):- if len(values) > 1 and keyword in ('dir-source', 'contact', 'legacy-dir-key', 'vote-digest'):- raise ValueError("Authority entries can only have a single '%s' line, got %i:\n%s" % (keyword, len(values), content))-- self._parse(entries, validate)- else:- self._entries = entries-- # TODO: Due to a bug we had a 'fingerprint' rather than 'v3ident' attribute- # for a long while. Keeping this around for backward compatability, but- # this will be dropped in stem's 2.0 release.-- self.fingerprint = self.v3ident-- def _compare(self, other, method):- if not isinstance(other, DirectoryAuthority):- return False-- return method(str(self).strip(), str(other).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)---def _parse_dir_address_line(descriptor, entries):- # "dir-address" IPPort-- value = _value('dir-address', entries)-- if ':' not in value:- raise ValueError("Key certificate's 'dir-address' is expected to be of the form ADDRESS:PORT: dir-address %s" % value)-- address, dirport = value.split(':', 1)-- if not stem.util.connection.is_valid_ipv4_address(address):- raise ValueError("Key certificate's address isn't a valid IPv4 address: dir-address %s" % value)- elif not stem.util.connection.is_valid_port(dirport):- raise ValueError("Key certificate's dirport is invalid: dir-address %s" % value)-- descriptor.address = address- descriptor.dir_port = int(dirport)---_parse_dir_key_certificate_version_line = _parse_version_line('dir-key-certificate-version', 'version', 3)-_parse_dir_key_published_line = _parse_timestamp_line('dir-key-published', 'published')-_parse_dir_key_expires_line = _parse_timestamp_line('dir-key-expires', 'expires')-_parse_identity_key_line = _parse_key_block('dir-identity-key', 'identity_key', 'RSA PUBLIC KEY')-_parse_signing_key_line = _parse_key_block('dir-signing-key', 'signing_key', 'RSA PUBLIC KEY')-_parse_dir_key_crosscert_line = _parse_key_block('dir-key-crosscert', 'crosscert', 'ID SIGNATURE')-_parse_dir_key_certification_line = _parse_key_block('dir-key-certification', 'certification', 'SIGNATURE')---class KeyCertificate(Descriptor):- """- Directory key certificate for a v3 network status document.-- :var int version: **\*** version of the key certificate- :var str address: authority's IP address- :var int dir_port: authority's DirPort- :var str fingerprint: **\*** authority's fingerprint- :var str identity_key: **\*** long term authority identity key- :var datetime published: **\*** time when this key was generated- :var datetime expires: **\*** time after which this key becomes invalid- :var str signing_key: **\*** directory server's public signing key- :var str crosscert: signature made using certificate's signing key- :var str certification: **\*** signature of this key certificate signed with- the identity key-- **\*** mandatory attribute- """-- ATTRIBUTES = {- 'version': (None, _parse_dir_key_certificate_version_line),- 'address': (None, _parse_dir_address_line),- 'dir_port': (None, _parse_dir_address_line),- 'fingerprint': (None, _parse_fingerprint_line),- 'identity_key': (None, _parse_identity_key_line),- 'published': (None, _parse_dir_key_published_line),- 'expires': (None, _parse_dir_key_expires_line),- 'signing_key': (None, _parse_signing_key_line),- 'crosscert': (None, _parse_dir_key_crosscert_line),- 'certification': (None, _parse_dir_key_certification_line),- }-- PARSER_FOR_LINE = {- 'dir-key-certificate-version': _parse_dir_key_certificate_version_line,- 'dir-address': _parse_dir_address_line,- 'fingerprint': _parse_fingerprint_line,- 'dir-key-published': _parse_dir_key_published_line,- 'dir-key-expires': _parse_dir_key_expires_line,- 'dir-identity-key': _parse_identity_key_line,- 'dir-signing-key': _parse_signing_key_line,- 'dir-key-crosscert': _parse_dir_key_crosscert_line,- 'dir-key-certification': _parse_dir_key_certification_line,- }-- def __init__(self, raw_content, validate = False):- super(KeyCertificate, self).__init__(raw_content, lazy_load = not validate)- entries = _get_descriptor_components(raw_content, validate)-- if validate:- if 'dir-key-certificate-version' != list(entries.keys())[0]:- raise ValueError("Key certificates must start with a 'dir-key-certificate-version' line:\n%s" % (raw_content))- elif 'dir-key-certification' != list(entries.keys())[-1]:- raise ValueError("Key certificates must end with a 'dir-key-certification' line:\n%s" % (raw_content))-- # check that we have mandatory fields and that our known fields only- # appear once-- for keyword, is_mandatory in KEY_CERTIFICATE_PARAMS:- if is_mandatory and keyword not in entries:- raise ValueError("Key certificates must have a '%s' line:\n%s" % (keyword, raw_content))-- entry_count = len(entries.get(keyword, []))- if entry_count > 1:- raise ValueError("Key certificates can only have a single '%s' line, got %i:\n%s" % (keyword, entry_count, raw_content))-- self._parse(entries, validate)- else:- self._entries = entries-- def _compare(self, other, method):- if not isinstance(other, KeyCertificate):- return False-- return method(str(self).strip(), str(other).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)---class DocumentSignature(object):- """- Directory signature of a v3 network status document.-- :var str method: algorithm used to make the signature- :var str identity: fingerprint of the authority that made the signature- :var str key_digest: digest of the signing key- :var str signature: document signature- :param bool validate: checks validity if **True**-- :raises: **ValueError** if a validity check fails- """-- def __init__(self, method, identity, key_digest, signature, validate = False):- # Checking that these attributes are valid. Technically the key- # digest isn't a fingerprint, but it has the same characteristics.-- if validate:- if not stem.util.tor_tools.is_valid_fingerprint(identity):- raise ValueError('Malformed fingerprint (%s) in the document signature' % identity)-- if not stem.util.tor_tools.is_valid_fingerprint(key_digest):- raise ValueError('Malformed key digest (%s) in the document signature' % key_digest)-- self.method = method- self.identity = identity- self.key_digest = key_digest- self.signature = signature-- def _compare(self, other, method):- if not isinstance(other, DocumentSignature):- return False-- for attr in ('method', 'identity', 'key_digest', 'signature'):- if getattr(self, attr) != getattr(other, attr):- return method(getattr(self, attr), getattr(other, attr))-- return method(True, True) # we're equal-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)---class BridgeNetworkStatusDocument(NetworkStatusDocument):- """- Network status document containing bridges. This is only available through- the metrics site.-- :var tuple routers: :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV2`- contained in the document- :var datetime published: time when the document was published- """-- def __init__(self, raw_content, validate = False):- super(BridgeNetworkStatusDocument, self).__init__(raw_content)-- self.published = None-- document_file = io.BytesIO(raw_content)- published_line = stem.util.str_tools._to_unicode(document_file.readline())-- if published_line.startswith('published '):- published_line = published_line.split(' ', 1)[1].strip()-- try:- self.published = stem.util.str_tools._parse_timestamp(published_line)- except ValueError:- if validate:- raise ValueError("Bridge network status document's 'published' time wasn't parsable: %s" % published_line)- elif validate:- raise ValueError("Bridge network status documents must start with a 'published' line:\n%s" % stem.util.str_tools._to_unicode(raw_content))-- router_iter = stem.descriptor.router_status_entry._parse_file(- document_file,- validate,- entry_class = RouterStatusEntryV2,- extra_args = (self,),- )-- self.routers = dict((desc.fingerprint, desc) for desc in router_iter)diff --git a/ext/stem/descriptor/reader.py b/ext/stem/descriptor/reader.pydeleted file mode 100644index a96406de..00000000--- a/ext/stem/descriptor/reader.py+++ /dev/null@@ -1,574 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Utilities for reading descriptors from local directories and archives. This is-mostly done through the :class:`~stem.descriptor.reader.DescriptorReader`-class, which is an iterator for the descriptor data in a series of-destinations. For example...--::-- my_descriptors = [- '/tmp/server-descriptors-2012-03.tar.bz2',- '/tmp/archived_descriptors/',- ]-- # prints the contents of all the descriptor files- with DescriptorReader(my_descriptors) as reader:- for descriptor in reader:- print descriptor--This ignores files that cannot be processed due to read errors or unparsable-content. To be notified of skipped files you can register a listener with-:func:`~stem.descriptor.reader.DescriptorReader.register_skip_listener`.--The :class:`~stem.descriptor.reader.DescriptorReader` keeps track of the last-modified timestamps for descriptor files that it has read so it can skip-unchanged files if run again. This listing of processed files can also be-persisted and applied to other-:class:`~stem.descriptor.reader.DescriptorReader` instances. For example, the-following prints descriptors as they're changed over the course of a minute,-and picks up where it left off if run again...--::-- reader = DescriptorReader(['/tmp/descriptor_data'])-- try:- processed_files = load_processed_files('/tmp/used_descriptors')- reader.set_processed_files(processed_files)- except: pass # could not load, maybe this is the first run-- start_time = time.time()-- while (time.time() - start_time) < 60:- # prints any descriptors that have changed since last checked- with reader:- for descriptor in reader:- print descriptor-- time.sleep(1)-- save_processed_files('/tmp/used_descriptors', reader.get_processed_files())--**Module Overview:**--::-- load_processed_files - Loads a listing of processed files- save_processed_files - Saves a listing of processed files-- DescriptorReader - Iterator for descriptor data on the local file system- |- get_processed_files - provides the listing of files that we've processed- |- set_processed_files - sets our tracking of the files we have processed- |- register_read_listener - adds a listener for when files are read- |- register_skip_listener - adds a listener that's notified of skipped files- |- start - begins reading descriptor data- |- stop - stops reading descriptor data- |- __enter__ / __exit__ - manages the descriptor reader thread in the context- +- __iter__ - iterates over descriptor data in unread files-- FileSkipped - Base exception for a file that was skipped- |- AlreadyRead - We've already read a file with this last modified timestamp- |- ParsingFailure - Contents can't be parsed as descriptor data- |- UnrecognizedType - File extension indicates non-descriptor data- +- ReadFailed - Wraps an error that was raised while reading the file- +- FileMissing - File does not exist-"""--import mimetypes-import os-import tarfile-import threading--try:- import queue-except ImportError:- import Queue as queue--import stem.descriptor-import stem.prereq-import stem.util.system--from stem import str_type--# flag to indicate when the reader thread is out of descriptor files to read-FINISHED = 'DONE'---class FileSkipped(Exception):- "Base error when we can't provide descriptor data from a file."---class AlreadyRead(FileSkipped):- """- Already read a file with this 'last modified' timestamp or later.-- :param int last_modified: unix timestamp for when the file was last modified- :param int last_modified_when_read: unix timestamp for the modification time- when we last read this file- """-- def __init__(self, last_modified, last_modified_when_read):- super(AlreadyRead, self).__init__('File has already been read since it was last modified. modification time: %s, last read: %s' % (last_modified, last_modified_when_read))- self.last_modified = last_modified- self.last_modified_when_read = last_modified_when_read---class ParsingFailure(FileSkipped):- """- File contents could not be parsed as descriptor data.-- :param ValueError exception: issue that arose when parsing- """-- def __init__(self, parsing_exception):- super(ParsingFailure, self).__init__(parsing_exception)- self.exception = parsing_exception---class UnrecognizedType(FileSkipped):- """- File doesn't contain descriptor data. This could either be due to its file- type or because it doesn't conform to a recognizable descriptor type.-- :param tuple mime_type: the (type, encoding) tuple provided by mimetypes.guess_type()- """-- def __init__(self, mime_type):- super(UnrecognizedType, self).__init__('Unrecognized mime type: %s (%s)' % mime_type)- self.mime_type = mime_type---class ReadFailed(FileSkipped):- """- An IOError occurred while trying to read the file.-- :param IOError exception: issue that arose when reading the file, **None** if- this arose due to the file not being present- """-- def __init__(self, read_exception):- super(ReadFailed, self).__init__(read_exception)- self.exception = read_exception---class FileMissing(ReadFailed):- 'File does not exist.'-- def __init__(self):- super(FileMissing, self).__init__('File does not exist')---def load_processed_files(path):- """- Loads a dictionary of 'path => last modified timestamp' mappings, as- persisted by :func:`~stem.descriptor.reader.save_processed_files`, from a- file.-- :param str path: location to load the processed files dictionary from-- :returns: **dict** of 'path (**str**) => last modified unix timestamp- (**int**)' mappings-- :raises:- * **IOError** if unable to read the file- * **TypeError** if unable to parse the file's contents- """-- processed_files = {}-- with open(path) as input_file:- for line in input_file.readlines():- line = line.strip()-- if not line:- continue # skip blank lines-- if ' ' not in line:- raise TypeError('Malformed line: %s' % line)-- path, timestamp = line.rsplit(' ', 1)-- if not os.path.isabs(path):- raise TypeError("'%s' is not an absolute path" % path)- elif not timestamp.isdigit():- raise TypeError("'%s' is not an integer timestamp" % timestamp)-- processed_files[path] = int(timestamp)-- return processed_files---def save_processed_files(path, processed_files):- """- Persists a dictionary of 'path => last modified timestamp' mappings (as- provided by the DescriptorReader's- :func:`~stem.descriptor.reader.DescriptorReader.get_processed_files` method)- so that they can be loaded later and applied to another- :class:`~stem.descriptor.reader.DescriptorReader`.-- :param str path: location to save the processed files dictionary to- :param dict processed_files: 'path => last modified' mappings-- :raises:- * **IOError** if unable to write to the file- * **TypeError** if processed_files is of the wrong type- """-- # makes the parent directory if it doesn't already exist- try:- path_dir = os.path.dirname(path)-- if not os.path.exists(path_dir):- os.makedirs(path_dir)- except OSError as exc:- raise IOError(exc)-- with open(path, 'w') as output_file:- for path, timestamp in list(processed_files.items()):- if not os.path.isabs(path):- raise TypeError('Only absolute paths are acceptable: %s' % path)-- output_file.write('%s %i\n' % (path, timestamp))---class DescriptorReader(object):- """- Iterator for the descriptor data on the local file system. This can process- text files, tarball archives (gzip or bzip2), or recurse directories.-- By default this limits the number of descriptors that we'll read ahead before- waiting for our caller to fetch some of them. This is included to avoid- unbounded memory usage.-- Our persistence_path argument is a convenient method to persist the listing- of files we have processed between runs, however it doesn't allow for error- handling. If you want that then use the- :func:`~stem.descriptor.reader.load_processed_files` and- :func:`~stem.descriptor.reader.save_processed_files` functions instead.-- :param str,list target: path or list of paths for files or directories to be read from- :param bool validate: checks the validity of the descriptor's content if- **True**, skips these checks otherwise- :param bool follow_links: determines if we'll follow symlinks when traversing- directories (requires python 2.6)- :param int buffer_size: descriptors we'll buffer before waiting for some to- be read, this is unbounded if zero- :param str persistence_path: if set we will load and save processed file- listings from this path, errors are ignored- :param stem.descriptor.__init__.DocumentHandler document_handler: method in- which to parse :class:`~stem.descriptor.networkstatus.NetworkStatusDocument`- :param dict kwargs: additional arguments for the descriptor constructor- """-- def __init__(self, target, validate = False, follow_links = False, buffer_size = 100, persistence_path = None, document_handler = stem.descriptor.DocumentHandler.ENTRIES, **kwargs):- if isinstance(target, (bytes, str_type)):- self._targets = [target]- else:- self._targets = target-- # expand any relative paths we got-- self._targets = list(map(os.path.abspath, self._targets))-- self._validate = validate- self._follow_links = follow_links- self._persistence_path = persistence_path- self._document_handler = document_handler- self._kwargs = kwargs- self._read_listeners = []- self._skip_listeners = []- self._processed_files = {}-- self._reader_thread = None- self._reader_thread_lock = threading.RLock()-- self._iter_lock = threading.RLock()- self._iter_notice = threading.Event()-- self._is_stopped = threading.Event()- self._is_stopped.set()-- # Descriptors that we have read but not yet provided to the caller. A- # FINISHED entry is used by the reading thread to indicate the end.-- self._unreturned_descriptors = queue.Queue(buffer_size)-- if self._persistence_path:- try:- processed_files = load_processed_files(self._persistence_path)- self.set_processed_files(processed_files)- except:- pass-- def get_processed_files(self):- """- For each file that we have read descriptor data from this provides a- mapping of the form...-- ::-- absolute path (str) => last modified unix timestamp (int)-- This includes entries set through the- :func:`~stem.descriptor.reader.DescriptorReader.set_processed_files`- method. Each run resets this to only the files that were present during- that run.-- :returns: **dict** with the absolute paths and unix timestamp for the last- modified times of the files we have processed- """-- # make sure that we only provide back absolute paths- return dict((os.path.abspath(k), v) for (k, v) in list(self._processed_files.items()))-- def set_processed_files(self, processed_files):- """- Sets the listing of the files we have processed. Most often this is used- with a newly created :class:`~stem.descriptor.reader.DescriptorReader` to- pre-populate the listing of descriptor files that we have seen.-- :param dict processed_files: mapping of absolute paths (**str**) to unix- timestamps for the last modified time (**int**)- """-- self._processed_files = dict(processed_files)-- def register_read_listener(self, listener):- """- Registers a listener for when files are read. This is executed prior to- processing files. Listeners are expected to be of the form...-- ::-- my_listener(path)-- :param functor listener: functor to be notified when files are read- """-- self._read_listeners.append(listener)-- def register_skip_listener(self, listener):- """- Registers a listener for files that are skipped. This listener is expected- to be a functor of the form...-- ::-- my_listener(path, exception)-- :param functor listener: functor to be notified of files that are skipped- to read errors or because they couldn't be parsed as valid descriptor data- """-- self._skip_listeners.append(listener)-- def get_buffered_descriptor_count(self):- """- Provides the number of descriptors that are waiting to be iterated over.- This is limited to the buffer_size that we were constructed with.-- :returns: **int** for the estimated number of currently enqueued- descriptors, this is not entirely reliable- """-- return self._unreturned_descriptors.qsize()-- def start(self):- """- Starts reading our descriptor files.-- :raises: **ValueError** if we're already reading the descriptor files- """-- with self._reader_thread_lock:- if self._reader_thread:- raise ValueError('Already running, you need to call stop() first')- else:- self._is_stopped.clear()- self._reader_thread = threading.Thread(target = self._read_descriptor_files, name='Descriptor Reader')- self._reader_thread.setDaemon(True)- self._reader_thread.start()-- def stop(self):- """- Stops further reading of descriptor files.- """-- with self._reader_thread_lock:- self._is_stopped.set()- self._iter_notice.set()-- # clears our queue to unblock enqueue calls-- try:- while True:- self._unreturned_descriptors.get_nowait()- except queue.Empty:- pass-- self._reader_thread.join()- self._reader_thread = None-- if self._persistence_path:- try:- processed_files = self.get_processed_files()- save_processed_files(self._persistence_path, processed_files)- except:- pass-- def _read_descriptor_files(self):- new_processed_files = {}- remaining_files = list(self._targets)-- while remaining_files and not self._is_stopped.is_set():- target = remaining_files.pop(0)-- if not os.path.exists(target):- self._notify_skip_listeners(target, FileMissing())- continue-- if os.path.isdir(target):- walker = os.walk(target, followlinks = self._follow_links)- self._handle_walker(walker, new_processed_files)- else:- self._handle_file(target, new_processed_files)-- self._processed_files = new_processed_files-- if not self._is_stopped.is_set():- self._unreturned_descriptors.put(FINISHED)-- self._iter_notice.set()-- def __iter__(self):- with self._iter_lock:- while not self._is_stopped.is_set():- try:- descriptor = self._unreturned_descriptors.get_nowait()-- if descriptor == FINISHED:- break- else:- yield descriptor- except queue.Empty:- self._iter_notice.wait()- self._iter_notice.clear()-- def _handle_walker(self, walker, new_processed_files):- for root, _, files in walker:- for filename in files:- self._handle_file(os.path.join(root, filename), new_processed_files)-- # this can take a while if, say, we're including the root directory- if self._is_stopped.is_set():- return-- def _handle_file(self, target, new_processed_files):- # This is a file. Register its last modified timestamp and check if- # it's a file that we should skip.-- try:- last_modified = int(os.stat(target).st_mtime)- last_used = self._processed_files.get(target)- new_processed_files[target] = last_modified- except OSError as exc:- self._notify_skip_listeners(target, ReadFailed(exc))- return-- if last_used and last_used >= last_modified:- self._notify_skip_listeners(target, AlreadyRead(last_modified, last_used))- return-- # Block devices and such are never descriptors, and can cause us to block- # for quite a while so skipping anything that isn't a regular file.-- if not os.path.isfile(target):- return-- # The mimetypes module only checks the file extension. To actually- # check the content (like the 'file' command) we'd need something like- # pymagic (https://github.com/cloudburst/pymagic).-- target_type = mimetypes.guess_type(target)-- if target_type[0] in (None, 'text/plain'):- # either '.txt' or an unknown type- self._handle_descriptor_file(target, target_type)- elif stem.util.system.is_tarfile(target):- # handles gzip, bz2, and decompressed tarballs among others- self._handle_archive(target)- else:- self._notify_skip_listeners(target, UnrecognizedType(target_type))-- def _handle_descriptor_file(self, target, mime_type):- try:- self._notify_read_listeners(target)-- with open(target, 'rb') as target_file:- for desc in stem.descriptor.parse_file(target_file, validate = self._validate, document_handler = self._document_handler, **self._kwargs):- if self._is_stopped.is_set():- return-- self._unreturned_descriptors.put(desc)- self._iter_notice.set()- except TypeError as exc:- self._notify_skip_listeners(target, UnrecognizedType(mime_type))- except ValueError as exc:- self._notify_skip_listeners(target, ParsingFailure(exc))- except IOError as exc:- self._notify_skip_listeners(target, ReadFailed(exc))-- def _handle_archive(self, target):- # TODO: When dropping python 2.6 support go back to using 'with' for- # tarfiles...- #- # http://bugs.python.org/issue7232-- tar_file = None-- try:- self._notify_read_listeners(target)- tar_file = tarfile.open(target)-- for tar_entry in tar_file:- if tar_entry.isfile():- entry = tar_file.extractfile(tar_entry)-- try:- for desc in stem.descriptor.parse_file(entry, validate = self._validate, document_handler = self._document_handler, **self._kwargs):- if self._is_stopped.is_set():- return-- desc._set_path(os.path.abspath(target))- desc._set_archive_path(tar_entry.name)- self._unreturned_descriptors.put(desc)- self._iter_notice.set()- except TypeError as exc:- self._notify_skip_listeners(target, ParsingFailure(exc))- except ValueError as exc:- self._notify_skip_listeners(target, ParsingFailure(exc))- finally:- entry.close()- except IOError as exc:- self._notify_skip_listeners(target, ReadFailed(exc))- finally:- if tar_file:- tar_file.close()-- def _notify_read_listeners(self, path):- for listener in self._read_listeners:- listener(path)-- def _notify_skip_listeners(self, path, exception):- for listener in self._skip_listeners:- listener(path, exception)-- def __enter__(self):- self.start()- return self-- def __exit__(self, exit_type, value, traceback):- self.stop()diff --git a/ext/stem/descriptor/remote.py b/ext/stem/descriptor/remote.pydeleted file mode 100644index 4d3423d0..00000000--- a/ext/stem/descriptor/remote.py+++ /dev/null@@ -1,777 +0,0 @@-# Copyright 2013-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Module for remotely retrieving descriptors from directory authorities and-mirrors. This is most easily done through the-:class:`~stem.descriptor.remote.DescriptorDownloader` class, which issues-:class:`~stem.descriptor.remote.Query` instances to get you the descriptor-content. For example...--::-- from stem.descriptor.remote import DescriptorDownloader-- downloader = DescriptorDownloader(- use_mirrors = True,- timeout = 10,- )-- query = downloader.get_server_descriptors()-- print 'Exit Relays:'-- try:- for desc in query.run():- if desc.exit_policy.is_exiting_allowed():- print ' %s (%s)' % (desc.nickname, desc.fingerprint)-- print 'Query took %0.2f seconds' % query.runtime- except Exception as exc:- print 'Unable to retrieve the server descriptors: %s' % exc--If you don't care about errors then you can also simply iterate over the query-itself...--::-- for desc in downloader.get_server_descriptors():- if desc.exit_policy.is_exiting_allowed():- print ' %s (%s)' % (desc.nickname, desc.fingerprint)--::-- get_authorities - Provides tor directory information.-- DirectoryAuthority - Information about a tor directory authority.-- Query - Asynchronous request to download tor descriptors- |- start - issues the query if it isn't already running- +- run - blocks until the request is finished and provides the results-- DescriptorDownloader - Configurable class for issuing queries- |- use_directory_mirrors - use directory mirrors to download future descriptors- |- get_server_descriptors - provides present server descriptors- |- get_extrainfo_descriptors - provides present extrainfo descriptors- |- get_microdescriptors - provides present microdescriptors- |- get_consensus - provides the present consensus or router status entries- |- get_key_certificates - provides present authority key certificates- +- query - request an arbitrary descriptor resource--.. versionadded:: 1.1.0--.. data:: MAX_FINGERPRINTS-- Maximum number of descriptors that can requested at a time by their- fingerprints.--.. data:: MAX_MICRODESCRIPTOR_HASHES-- Maximum number of microdescriptors that can requested at a time by their- hashes.-"""--import io-import random-import sys-import threading-import time-import zlib--try:- import urllib.request as urllib-except ImportError:- import urllib2 as urllib--import stem.descriptor--from stem import Flag-from stem.util import log--# Tor has a limited number of descriptors we can fetch explicitly by their-# fingerprint or hashes due to a limit on the url length by squid proxies.--MAX_FINGERPRINTS = 96-MAX_MICRODESCRIPTOR_HASHES = 92--# We commonly only want authorities that vote in the consensus, and hence have-# a v3ident.--HAS_V3IDENT = lambda auth: auth.v3ident is not None---def _guess_descriptor_type(resource):- # Attempts to determine the descriptor type based on the resource url. This- # raises a ValueError if the resource isn't recognized.-- if resource.startswith('/tor/server/'):- return 'server-descriptor 1.0'- elif resource.startswith('/tor/extra/'):- return 'extra-info 1.0'- elif resource.startswith('/tor/micro/'):- return 'microdescriptor 1.0'- elif resource.startswith('/tor/status-vote/'):- return 'network-status-consensus-3 1.0'- elif resource.startswith('/tor/keys/'):- return 'dir-key-certificate-3 1.0'- else:- raise ValueError("Unable to determine the descriptor type for '%s'" % resource)---class Query(object):- """- Asynchronous request for descriptor content from a directory authority or- mirror. These can either be made through the- :class:`~stem.descriptor.remote.DescriptorDownloader` or directly for more- advanced usage.-- To block on the response and get results either call- :func:`~stem.descriptor.remote.Query.run` or iterate over the Query. The- :func:`~stem.descriptor.remote.Query.run` method pass along any errors that- arise...-- ::-- from stem.descriptor.remote import Query-- query = Query(- '/tor/server/all.z',- block = True,- timeout = 30,- )-- print 'Current relays:'-- if not query.error:- for desc in query:- print desc.fingerprint- else:- print 'Unable to retrieve the server descriptors: %s' % query.error-- ... while iterating fails silently...-- ::-- print 'Current relays:'-- for desc in Query('/tor/server/all.z', 'server-descriptor 1.0'):- print desc.fingerprint-- In either case exceptions are available via our 'error' attribute.-- Tor provides quite a few different descriptor resources via its directory- protocol (see section 4.2 and later of the `dir-spec- <https://gitweb.torproject.org/torspec.git/tree/dir-spec.txt>`_).- Commonly useful ones include...-- ===================================== ===========- Resource Description- ===================================== ===========- /tor/server/all.z all present server descriptors- /tor/server/fp/<fp1>+<fp2>+<fp3>.z server descriptors with the given fingerprints- /tor/extra/all.z all present extrainfo descriptors- /tor/extra/fp/<fp1>+<fp2>+<fp3>.z extrainfo descriptors with the given fingerprints- /tor/micro/d/<hash1>-<hash2>.z microdescriptors with the given hashes- /tor/status-vote/current/consensus.z present consensus- /tor/keys/all.z key certificates for the authorities- /tor/keys/fp/<v3ident1>+<v3ident2>.z key certificates for specific authorities- ===================================== ===========-- The '.z' suffix can be excluded to get a plaintext rather than compressed- response. Compression is handled transparently, so this shouldn't matter to- the caller.-- :var str resource: resource being fetched, such as '/tor/server/all.z'- :var str descriptor_type: type of descriptors being fetched (for options see- :func:`~stem.descriptor.__init__.parse_file`), this is guessed from the- resource if **None**-- :var list endpoints: (address, dirport) tuples of the authority or mirror- we're querying, this uses authorities if undefined- :var int retries: number of times to attempt the request if downloading it- fails- :var bool fall_back_to_authority: when retrying request issues the last- request to a directory authority if **True**-- :var str content: downloaded descriptor content- :var Exception error: exception if a problem occured- :var bool is_done: flag that indicates if our request has finished- :var str download_url: last url used to download the descriptor, this is- unset until we've actually made a download attempt-- :var float start_time: unix timestamp when we first started running- :var float timeout: duration before we'll time out our request- :var float runtime: time our query took, this is **None** if it's not yet- finished-- :var bool validate: checks the validity of the descriptor's content if- **True**, skips these checks otherwise- :var stem.descriptor.__init__.DocumentHandler document_handler: method in- which to parse a :class:`~stem.descriptor.networkstatus.NetworkStatusDocument`- :var dict kwargs: additional arguments for the descriptor constructor-- :param bool start: start making the request when constructed (default is **True**)- :param bool block: only return after the request has been completed, this is- the same as running **query.run(True)** (default is **False**)- """-- def __init__(self, resource, descriptor_type = None, endpoints = None, retries = 2, fall_back_to_authority = False, timeout = None, start = True, block = False, validate = False, document_handler = stem.descriptor.DocumentHandler.ENTRIES, **kwargs):- if not resource.startswith('/'):- raise ValueError("Resources should start with a '/': %s" % resource)-- self.resource = resource-- if descriptor_type:- self.descriptor_type = descriptor_type- else:- self.descriptor_type = _guess_descriptor_type(resource)-- self.endpoints = endpoints if endpoints else []- self.retries = retries- self.fall_back_to_authority = fall_back_to_authority-- self.content = None- self.error = None- self.is_done = False- self.download_url = None-- self.start_time = None- self.timeout = timeout- self.runtime = None-- self.validate = validate- self.document_handler = document_handler- self.kwargs = kwargs-- self._downloader_thread = None- self._downloader_thread_lock = threading.RLock()-- if start:- self.start()-- if block:- self.run(True)-- def start(self):- """- Starts downloading the scriptors if we haven't started already.- """-- with self._downloader_thread_lock:- if self._downloader_thread is None:- self._downloader_thread = threading.Thread(- name = 'Descriptor Query',- target = self._download_descriptors,- args = (self.retries,)- )-- self._downloader_thread.setDaemon(True)- self._downloader_thread.start()-- def run(self, suppress = False):- """- Blocks until our request is complete then provides the descriptors. If we- haven't yet started our request then this does so.-- :param bool suppress: avoids raising exceptions if **True**-- :returns: list for the requested :class:`~stem.descriptor.__init__.Descriptor` instances-- :raises:- Using the iterator can fail with the following if **suppress** is- **False**...-- * **ValueError** if the descriptor contents is malformed- * **socket.timeout** if our request timed out- * **urllib2.URLError** for most request failures-- Note that the urllib2 module may fail with other exception types, in- which case we'll pass it along.- """-- return list(self._run(suppress))-- def _run(self, suppress):- with self._downloader_thread_lock:- self.start()- self._downloader_thread.join()-- if self.error:- if suppress:- return-- raise self.error- else:- if self.content is None:- if suppress:- return-- raise ValueError('BUG: _download_descriptors() finished without either results or an error')-- try:- results = stem.descriptor.parse_file(- io.BytesIO(self.content),- self.descriptor_type,- validate = self.validate,- document_handler = self.document_handler,- **self.kwargs- )-- for desc in results:- yield desc- except ValueError as exc:- self.error = exc # encountered a parsing error-- if suppress:- return-- raise self.error-- def __iter__(self):- for desc in self._run(True):- yield desc-- def _pick_url(self, use_authority = False):- """- Provides a url that can be queried. If we have multiple endpoints then one- will be picked randomly.-- :param bool use_authority: ignores our endpoints and uses a directory- authority instead-- :returns: **str** for the url being queried by this request- """-- if use_authority or not self.endpoints:- authority = random.choice(filter(HAS_V3IDENT, get_authorities().values()))- address, dirport = authority.address, authority.dir_port- else:- address, dirport = random.choice(self.endpoints)-- return 'http://%s:%i/%s' % (address, dirport, self.resource.lstrip('/'))-- def _download_descriptors(self, retries):- try:- use_authority = retries == 0 and self.fall_back_to_authority- self.download_url = self._pick_url(use_authority)-- self.start_time = time.time()- response = urllib.urlopen(self.download_url, timeout = self.timeout).read()-- if self.download_url.endswith('.z'):- response = zlib.decompress(response)-- self.content = response.strip()-- self.runtime = time.time() - self.start_time- log.trace("Descriptors retrieved from '%s' in %0.2fs" % (self.download_url, self.runtime))- except:- exc = sys.exc_info()[1]-- if retries > 0:- log.debug("Unable to download descriptors from '%s' (%i retries remaining): %s" % (self.download_url, retries, exc))- return self._download_descriptors(retries - 1)- else:- log.debug("Unable to download descriptors from '%s': %s" % (self.download_url, exc))- self.error = exc- finally:- self.is_done = True---class DescriptorDownloader(object):- """- Configurable class that issues :class:`~stem.descriptor.remote.Query`- instances on your behalf.-- :param bool use_mirrors: downloads the present consensus and uses the directory- mirrors to fetch future requests, this fails silently if the consensus- cannot be downloaded- :param default_args: default arguments for the- :class:`~stem.descriptor.remote.Query` constructor- """-- def __init__(self, use_mirrors = False, **default_args):- self._default_args = default_args-- authorities = filter(HAS_V3IDENT, get_authorities().values())- self._endpoints = [(auth.address, auth.dir_port) for auth in authorities]-- if use_mirrors:- try:- start_time = time.time()- self.use_directory_mirrors()- log.debug('Retrieved directory mirrors (took %0.2fs)' % (time.time() - start_time))- except Exception as exc:- log.debug('Unable to retrieve directory mirrors: %s' % exc)-- def use_directory_mirrors(self):- """- Downloads the present consensus and configures ourselves to use directory- mirrors, in addition to authorities.-- :returns: :class:`~stem.descriptor.networkstatus.NetworkStatusDocumentV3`- from which we got the directory mirrors-- :raises: **Exception** if unable to determine the directory mirrors- """-- authorities = filter(HAS_V3IDENT, get_authorities().values())- new_endpoints = set([(auth.address, auth.dir_port) for auth in authorities])-- consensus = list(self.get_consensus(document_handler = stem.descriptor.DocumentHandler.DOCUMENT).run())[0]-- for desc in consensus.routers.values():- if Flag.V2DIR in desc.flags:- new_endpoints.add((desc.address, desc.dir_port))-- # we need our endpoints to be a list rather than set for random.choice()-- self._endpoints = list(new_endpoints)-- return consensus-- def get_server_descriptors(self, fingerprints = None, **query_args):- """- Provides the server descriptors with the given fingerprints. If no- fingerprints are provided then this returns all descriptors in the present- consensus.-- :param str,list fingerprints: fingerprint or list of fingerprints to be- retrieved, gets all descriptors if **None**- :param query_args: additional arguments for the- :class:`~stem.descriptor.remote.Query` constructor-- :returns: :class:`~stem.descriptor.remote.Query` for the server descriptors-- :raises: **ValueError** if we request more than 96 descriptors by their- fingerprints (this is due to a limit on the url length by squid proxies).- """-- resource = '/tor/server/all.z'-- if isinstance(fingerprints, str):- fingerprints = [fingerprints]-- if fingerprints:- if len(fingerprints) > MAX_FINGERPRINTS:- raise ValueError('Unable to request more than %i descriptors at a time by their fingerprints' % MAX_FINGERPRINTS)-- resource = '/tor/server/fp/%s.z' % '+'.join(fingerprints)-- return self.query(resource, **query_args)-- def get_extrainfo_descriptors(self, fingerprints = None, **query_args):- """- Provides the extrainfo descriptors with the given fingerprints. If no- fingerprints are provided then this returns all descriptors in the present- consensus.-- :param str,list fingerprints: fingerprint or list of fingerprints to be- retrieved, gets all descriptors if **None**- :param query_args: additional arguments for the- :class:`~stem.descriptor.remote.Query` constructor-- :returns: :class:`~stem.descriptor.remote.Query` for the extrainfo descriptors-- :raises: **ValueError** if we request more than 96 descriptors by their- fingerprints (this is due to a limit on the url length by squid proxies).- """-- resource = '/tor/extra/all.z'-- if isinstance(fingerprints, str):- fingerprints = [fingerprints]-- if fingerprints:- if len(fingerprints) > MAX_FINGERPRINTS:- raise ValueError('Unable to request more than %i descriptors at a time by their fingerprints' % MAX_FINGERPRINTS)-- resource = '/tor/extra/fp/%s.z' % '+'.join(fingerprints)-- return self.query(resource, **query_args)-- def get_microdescriptors(self, hashes, **query_args):- """- Provides the microdescriptors with the given hashes. To get these see the- 'microdescriptor_hashes' attribute of- :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3`. Note- that these are only provided via a microdescriptor consensus (such as- 'cached-microdesc-consensus' in your data directory).-- :param str,list hashes: microdescriptor hash or list of hashes to be- retrieved- :param query_args: additional arguments for the- :class:`~stem.descriptor.remote.Query` constructor-- :returns: :class:`~stem.descriptor.remote.Query` for the microdescriptors-- :raises: **ValueError** if we request more than 92 microdescriptors by their- hashes (this is due to a limit on the url length by squid proxies).- """-- if isinstance(hashes, str):- hashes = [hashes]-- if len(hashes) > MAX_MICRODESCRIPTOR_HASHES:- raise ValueError('Unable to request more than %i microdescriptors at a time by their hashes' % MAX_MICRODESCRIPTOR_HASHES)-- return self.query('/tor/micro/d/%s.z' % '-'.join(hashes), **query_args)-- def get_consensus(self, authority_v3ident = None, **query_args):- """- Provides the present router status entries.-- :param str authority_v3ident: fingerprint of the authority key for which- to get the consensus, see `'v3ident' in tor's config.c- <https://gitweb.torproject.org/tor.git/tree/src/or/config.c#n819>`_- for the values.- :param query_args: additional arguments for the- :class:`~stem.descriptor.remote.Query` constructor-- :returns: :class:`~stem.descriptor.remote.Query` for the router status- entries- """-- resource = '/tor/status-vote/current/consensus'-- if authority_v3ident:- resource += '/%s' % authority_v3ident-- return self.query(resource + '.z', **query_args)-- def get_vote(self, authority, **query_args):- """- Provides the present vote for a given directory authority.-- :param stem.descriptor.remote.DirectoryAuthority authority: authority for which to retrieve a vote for- :param query_args: additional arguments for the- :class:`~stem.descriptor.remote.Query` constructor-- :returns: :class:`~stem.descriptor.remote.Query` for the router status- entries- """-- resource = '/tor/status-vote/current/authority'-- if 'endpoint' not in query_args:- query_args['endpoints'] = [(authority.address, authority.dir_port)]-- return self.query(resource + '.z', **query_args)-- def get_key_certificates(self, authority_v3idents = None, **query_args):- """- Provides the key certificates for authorities with the given fingerprints.- If no fingerprints are provided then this returns all present key- certificates.-- :param str authority_v3idents: fingerprint or list of fingerprints of the- authority keys, see `'v3ident' in tor's config.c- <https://gitweb.torproject.org/tor.git/tree/src/or/config.c#n819>`_- for the values.- :param query_args: additional arguments for the- :class:`~stem.descriptor.remote.Query` constructor-- :returns: :class:`~stem.descriptor.remote.Query` for the key certificates-- :raises: **ValueError** if we request more than 96 key certificates by- their identity fingerprints (this is due to a limit on the url length by- squid proxies).- """-- resource = '/tor/keys/all.z'-- if isinstance(authority_v3idents, str):- authority_v3idents = [authority_v3idents]-- if authority_v3idents:- if len(authority_v3idents) > MAX_FINGERPRINTS:- raise ValueError('Unable to request more than %i key certificates at a time by their identity fingerprints' % MAX_FINGERPRINTS)-- resource = '/tor/keys/fp/%s.z' % '+'.join(authority_v3idents)-- return self.query(resource, **query_args)-- def query(self, resource, **query_args):- """- Issues a request for the given resource.-- :param str resource: resource being fetched, such as '/tor/server/all.z'- :param query_args: additional arguments for the- :class:`~stem.descriptor.remote.Query` constructor-- :returns: :class:`~stem.descriptor.remote.Query` for the descriptors-- :raises: **ValueError** if resource is clearly invalid or the descriptor- type can't be determined when 'descriptor_type' is **None**- """-- args = dict(self._default_args)- args.update(query_args)-- if 'endpoints' not in args:- args['endpoints'] = self._endpoints-- if 'fall_back_to_authority' not in args:- args['fall_back_to_authority'] = True-- return Query(- resource,- **args- )---class DirectoryAuthority(object):- """- Tor directory authority, a special type of relay `hardcoded into tor- <https://gitweb.torproject.org/tor.git/tree/src/or/config.c#n819>`_- that enumerates the other relays within the network.-- At a very high level tor works as follows...-- 1. A volunteer starts up a new tor relay, during which it sends a `server- descriptor <server_descriptor.html>`_ to each of the directory- authorities.-- 2. Each hour the directory authorities make a `vote <networkstatus.html>`_- that says who they think the active relays are in the network and some- attributes about them.-- 3. The directory authorities send each other their votes, and compile that- into the `consensus <networkstatus.html>`_. This document is very similar- to the votes, the only difference being that the majority of the- authorities agree upon and sign this document. The idividual relay entries- in the vote or consensus is called `router status entries- <router_status_entry.html>`_.-- 4. Tor clients (people using the service) download the consensus from one of- the authorities or a mirror to determine the active relays within the- network. They in turn use this to construct their circuits and use the- network.-- .. versionchanged:: 1.3.0- Added the is_bandwidth_authority attribute.-- :var str nickname: nickname of the authority- :var str address: IP address of the authority, currently they're all IPv4 but- this may not always be the case- :var int or_port: port on which the relay services relay traffic- :var int dir_port: port on which directory information is available- :var str fingerprint: relay fingerprint- :var str v3ident: identity key fingerprint used to sign votes and consensus- """-- def __init__(self, nickname = None, address = None, or_port = None, dir_port = None, is_bandwidth_authority = False, fingerprint = None, v3ident = None):- self.nickname = nickname- self.address = address- self.or_port = or_port- self.dir_port = dir_port- self.is_bandwidth_authority = is_bandwidth_authority- self.fingerprint = fingerprint- self.v3ident = v3ident---DIRECTORY_AUTHORITIES = {- 'moria1': DirectoryAuthority(- nickname = 'moria1',- address = '128.31.0.39',- or_port = 9101,- dir_port = 9131,- is_bandwidth_authority = True,- fingerprint = '9695DFC35FFEB861329B9F1AB04C46397020CE31',- v3ident = 'D586D18309DED4CD6D57C18FDB97EFA96D330566',- ),- 'tor26': DirectoryAuthority(- nickname = 'tor26',- address = '86.59.21.38',- or_port = 443,- dir_port = 80,- is_bandwidth_authority = True,- fingerprint = '847B1F850344D7876491A54892F904934E4EB85D',- v3ident = '14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4',- ),- 'dizum': DirectoryAuthority(- nickname = 'dizum',- address = '194.109.206.212',- or_port = 443,- dir_port = 80,- is_bandwidth_authority = False,- fingerprint = '7EA6EAD6FD83083C538F44038BBFA077587DD755',- v3ident = 'E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58',- ),- 'Tonga': DirectoryAuthority(- nickname = 'Tonga',- address = '82.94.251.203',- or_port = 443,- dir_port = 80,- is_bandwidth_authority = False,- fingerprint = '4A0CCD2DDC7995083D73F5D667100C8A5831F16D',- v3ident = None, # does not vote in the consensus- ),- 'gabelmoo': DirectoryAuthority(- nickname = 'gabelmoo',- address = '131.188.40.189',- or_port = 443,- dir_port = 80,- is_bandwidth_authority = True,- fingerprint = 'F2044413DAC2E02E3D6BCF4735A19BCA1DE97281',- v3ident = 'ED03BB616EB2F60BEC80151114BB25CEF515B226',- ),- 'dannenberg': DirectoryAuthority(- nickname = 'dannenberg',- address = '193.23.244.244',- or_port = 443,- dir_port = 80,- is_bandwidth_authority = False,- fingerprint = '7BE683E65D48141321C5ED92F075C55364AC7123',- v3ident = '585769C78764D58426B8B52B6651A5A71137189A',- ),- 'urras': DirectoryAuthority(- nickname = 'urras',- address = '208.83.223.34',- or_port = 80,- dir_port = 443,- is_bandwidth_authority = False,- fingerprint = '0AD3FA884D18F89EEA2D89C019379E0E7FD94417',- v3ident = '80550987E1D626E3EBA5E5E75A458DE0626D088C',- ),- 'maatuska': DirectoryAuthority(- nickname = 'maatuska',- address = '171.25.193.9',- or_port = 80,- dir_port = 443,- is_bandwidth_authority = True,- fingerprint = 'BD6A829255CB08E66FBE7D3748363586E46B3810',- v3ident = '49015F787433103580E3B66A1707A00E60F2D15B',- ),- 'Faravahar': DirectoryAuthority(- nickname = 'Faravahar',- address = '154.35.175.225',- or_port = 443,- dir_port = 80,- is_bandwidth_authority = False,- fingerprint = 'CF6D0AAFB385BE71B8E111FC5CFF4B47923733BC',- v3ident = 'EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97',- ),- 'longclaw': DirectoryAuthority(- nickname = 'longclaw',- address = '199.254.238.52',- or_port = 443,- dir_port = 80,- is_bandwidth_authority = True,- fingerprint = '74A910646BCEEFBCD2E874FC1DC997430F968145',- v3ident = '23D15D965BC35114467363C165C4F724B64B4F66',- ),-}---def get_authorities():- """- Provides the Tor directory authority information as of **Tor on 11/21/14**.- The directory information hardcoded into Tor and occasionally changes, so the- information this provides might not necessarily match your version of tor.-- :returns: dict of str nicknames to :class:`~stem.descriptor.remote.DirectoryAuthority` instances- """-- return dict(DIRECTORY_AUTHORITIES)diff --git a/ext/stem/descriptor/router_status_entry.py b/ext/stem/descriptor/router_status_entry.pydeleted file mode 100644index c33baa39..00000000--- a/ext/stem/descriptor/router_status_entry.py+++ /dev/null@@ -1,635 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Parsing for router status entries, the information for individual routers-within a network status document. This information is provided from a few-sources...--* control port via 'GETINFO ns/\*' and 'GETINFO md/\*' queries-* router entries in a network status document, like the cached-consensus--**Module Overview:**--::-- RouterStatusEntry - Common parent for router status entries- |- RouterStatusEntryV2 - Entry for a network status v2 document- |- RouterStatusEntryV3 - Entry for a network status v3 document- +- RouterStatusEntryMicroV3 - Entry for a microdescriptor flavored v3 document-"""--import base64-import binascii--import stem.exit_policy-import stem.prereq-import stem.util.str_tools--from stem.descriptor import (- KEYWORD_LINE,- Descriptor,- _value,- _values,- _get_descriptor_components,- _read_until_keywords,-)---def _parse_file(document_file, validate, entry_class, entry_keyword = 'r', start_position = None, end_position = None, section_end_keywords = (), extra_args = ()):- """- Reads a range of the document_file containing some number of entry_class- instances. We deliminate the entry_class entries by the keyword on their- first line (entry_keyword). When finished the document is left at the- end_position.-- Either an end_position or section_end_keywords must be provided.-- :param file document_file: file with network status document content- :param bool validate: checks the validity of the document's contents if- **True**, skips these checks otherwise- :param class entry_class: class to construct instance for- :param str entry_keyword: first keyword for the entry instances- :param int start_position: start of the section, default is the current position- :param int end_position: end of the section- :param tuple section_end_keywords: keyword(s) that deliminate the end of the- section if no end_position was provided- :param tuple extra_args: extra arguments for the entry_class (after the- content and validate flag)-- :returns: iterator over entry_class instances-- :raises:- * **ValueError** if the contents is malformed and validate is **True**- * **IOError** if the file can't be read- """-- if start_position:- document_file.seek(start_position)- else:- start_position = document_file.tell()-- # check if we're starting at the end of the section (ie, there's no entries to read)- if section_end_keywords:- first_keyword = None- line_match = KEYWORD_LINE.match(stem.util.str_tools._to_unicode(document_file.readline()))-- if line_match:- first_keyword = line_match.groups()[0]-- document_file.seek(start_position)-- if first_keyword in section_end_keywords:- return-- while end_position is None or document_file.tell() < end_position:- desc_lines, ending_keyword = _read_until_keywords(- (entry_keyword,) + section_end_keywords,- document_file,- ignore_first = True,- end_position = end_position,- include_ending_keyword = True- )-- desc_content = bytes.join(b'', desc_lines)-- if desc_content:- yield entry_class(desc_content, validate, *extra_args)-- # check if we stopped at the end of the section- if ending_keyword in section_end_keywords:- break- else:- break---def _parse_r_line(descriptor, entries):- # Parses a RouterStatusEntry's 'r' line. They're very nearly identical for- # all current entry types (v2, v3, and microdescriptor v3) with one little- # wrinkle: only the microdescriptor flavor excludes a 'digest' field.- #- # For v2 and v3 router status entries:- # "r" nickname identity digest publication IP ORPort DirPort- # example: r mauer BD7xbfsCFku3+tgybEZsg8Yjhvw itcuKQ6PuPLJ7m/Oi928WjO2j8g 2012-06-22 13:19:32 80.101.105.103 9001 0- #- # For v3 microdescriptor router status entries:- # "r" nickname identity publication IP ORPort DirPort- # example: r Konata ARIJF2zbqirB9IwsW0mQznccWww 2012-09-24 13:40:40 69.64.48.168 9001 9030-- value = _value('r', entries)- include_digest = not isinstance(descriptor, RouterStatusEntryMicroV3)-- r_comp = value.split(' ')-- # inject a None for the digest to normalize the field positioning- if not include_digest:- r_comp.insert(2, None)-- if len(r_comp) < 8:- expected_field_count = 'eight' if include_digest else 'seven'- raise ValueError("%s 'r' line must have %s values: r %s" % (descriptor._name(), expected_field_count, value))-- if not stem.util.tor_tools.is_valid_nickname(r_comp[0]):- raise ValueError("%s nickname isn't valid: %s" % (descriptor._name(), r_comp[0]))- elif not stem.util.connection.is_valid_ipv4_address(r_comp[5]):- raise ValueError("%s address isn't a valid IPv4 address: %s" % (descriptor._name(), r_comp[5]))- elif not stem.util.connection.is_valid_port(r_comp[6]):- raise ValueError('%s ORPort is invalid: %s' % (descriptor._name(), r_comp[6]))- elif not stem.util.connection.is_valid_port(r_comp[7], allow_zero = True):- raise ValueError('%s DirPort is invalid: %s' % (descriptor._name(), r_comp[7]))-- descriptor.nickname = r_comp[0]- descriptor.fingerprint = _base64_to_hex(r_comp[1])-- if include_digest:- descriptor.digest = _base64_to_hex(r_comp[2])-- descriptor.address = r_comp[5]- descriptor.or_port = int(r_comp[6])- descriptor.dir_port = None if r_comp[7] == '0' else int(r_comp[7])-- try:- published = '%s %s' % (r_comp[3], r_comp[4])- descriptor.published = stem.util.str_tools._parse_timestamp(published)- except ValueError:- raise ValueError("Publication time time wasn't parsable: r %s" % value)---def _parse_a_line(descriptor, entries):- # "a" SP address ":" portlist- # example: a [2001:888:2133:0:82:94:251:204]:9001-- or_addresses = []-- for value in _values('a', entries):- if ':' not in value:- raise ValueError("%s 'a' line must be of the form '[address]:[ports]': a %s" % (descriptor._name(), value))-- address, port = value.rsplit(':', 1)- is_ipv6 = address.startswith('[') and address.endswith(']')-- if is_ipv6:- address = address[1:-1] # remove brackets-- if not ((not is_ipv6 and stem.util.connection.is_valid_ipv4_address(address)) or- (is_ipv6 and stem.util.connection.is_valid_ipv6_address(address))):- raise ValueError("%s 'a' line must start with an IPv6 address: a %s" % (descriptor._name(), value))-- if stem.util.connection.is_valid_port(port):- or_addresses.append((address, int(port), is_ipv6))- else:- raise ValueError("%s 'a' line had an invalid port (%s): a %s" % (descriptor._name(), port, value))-- descriptor.or_addresses = or_addresses---def _parse_s_line(descriptor, entries):- # "s" Flags- # example: s Named Running Stable Valid-- value = _value('s', entries)- flags = [] if value == '' else value.split(' ')- descriptor.flags = flags-- for flag in flags:- if flags.count(flag) > 1:- raise ValueError('%s had duplicate flags: s %s' % (descriptor._name(), value))- elif flag == '':- raise ValueError("%s had extra whitespace on its 's' line: s %s" % (descriptor._name(), value))---def _parse_v_line(descriptor, entries):- # "v" version- # example: v Tor 0.2.2.35- #- # The spec says that if this starts with "Tor " then what follows is a- # tor version. If not then it has "upgraded to a more sophisticated- # protocol versioning system".-- value = _value('v', entries)- descriptor.version_line = value-- if value.startswith('Tor '):- try:- descriptor.version = stem.version._get_version(value[4:])- except ValueError as exc:- raise ValueError('%s has a malformed tor version (%s): v %s' % (descriptor._name(), exc, value))---def _parse_w_line(descriptor, entries):- # "w" "Bandwidth=" INT ["Measured=" INT] ["Unmeasured=1"]- # example: w Bandwidth=7980-- value = _value('w', entries)- w_comp = value.split(' ')-- if len(w_comp) < 1:- raise ValueError("%s 'w' line is blank: w %s" % (descriptor._name(), value))- elif not w_comp[0].startswith('Bandwidth='):- raise ValueError("%s 'w' line needs to start with a 'Bandwidth=' entry: w %s" % (descriptor._name(), value))-- bandwidth = None- measured = None- is_unmeasured = False- unrecognized_bandwidth_entries = []-- for w_entry in w_comp:- if '=' in w_entry:- w_key, w_value = w_entry.split('=', 1)- else:- w_key, w_value = w_entry, None-- if w_key == 'Bandwidth':- if not (w_value and w_value.isdigit()):- raise ValueError("%s 'Bandwidth=' entry needs to have a numeric value: w %s" % (descriptor._name(), value))-- bandwidth = int(w_value)- elif w_key == 'Measured':- if not (w_value and w_value.isdigit()):- raise ValueError("%s 'Measured=' entry needs to have a numeric value: w %s" % (descriptor._name(), value))-- measured = int(w_value)- elif w_key == 'Unmeasured':- if w_value != '1':- raise ValueError("%s 'Unmeasured=' should only have the value of '1': w %s" % (descriptor._name(), value))-- is_unmeasured = True- else:- unrecognized_bandwidth_entries.append(w_entry)-- descriptor.bandwidth = bandwidth- descriptor.measured = measured- descriptor.is_unmeasured = is_unmeasured- descriptor.unrecognized_bandwidth_entries = unrecognized_bandwidth_entries---def _parse_p_line(descriptor, entries):- # "p" ("accept" / "reject") PortList- # p reject 1-65535- # example: p accept 80,110,143,443,993,995,6660-6669,6697,7000-7001-- value = _value('p', entries)-- try:- descriptor.exit_policy = stem.exit_policy.MicroExitPolicy(value)- except ValueError as exc:- raise ValueError('%s exit policy is malformed (%s): p %s' % (descriptor._name(), exc, value))---def _parse_m_line(descriptor, entries):- # "m" methods 1*(algorithm "=" digest)- # example: m 8,9,10,11,12 sha256=g1vx9si329muxV3tquWIXXySNOIwRGMeAESKs/v4DWs-- all_hashes = []-- for value in _values('m', entries):- m_comp = value.split(' ')-- if not (descriptor.document and descriptor.document.is_vote):- vote_status = 'vote' if descriptor.document else '<undefined document>'- raise ValueError("%s 'm' line should only appear in votes (appeared in a %s): m %s" % (descriptor._name(), vote_status, value))- elif len(m_comp) < 1:- raise ValueError("%s 'm' line needs to start with a series of methods: m %s" % (descriptor._name(), value))-- try:- methods = [int(entry) for entry in m_comp[0].split(',')]- except ValueError:- raise ValueError('%s microdescriptor methods should be a series of comma separated integers: m %s' % (descriptor._name(), value))-- hashes = {}-- for entry in m_comp[1:]:- if '=' not in entry:- raise ValueError("%s can only have a series of 'algorithm=digest' mappings after the methods: m %s" % (descriptor._name(), value))-- hash_name, digest = entry.split('=', 1)- hashes[hash_name] = digest-- all_hashes.append((methods, hashes))-- descriptor.microdescriptor_hashes = all_hashes---def _parse_microdescriptor_m_line(descriptor, entries):- # "m" digest- # example: m aiUklwBrua82obG5AsTX+iEpkjQA2+AQHxZ7GwMfY70-- descriptor.digest = _base64_to_hex(_value('m', entries), check_if_fingerprint = False)---def _base64_to_hex(identity, check_if_fingerprint = True):- """- Decodes a base64 value to hex. For example...-- ::-- >>> _base64_to_hex('p1aag7VwarGxqctS7/fS0y5FU+s')- 'A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB'-- :param str identity: encoded fingerprint from the consensus- :param bool check_if_fingerprint: asserts that the result is a fingerprint if **True**-- :returns: **str** with the uppercase hex encoding of the relay's fingerprint-- :raises: **ValueError** if the result isn't a valid fingerprint- """-- # trailing equal signs were stripped from the identity- missing_padding = len(identity) % 4- identity += '=' * missing_padding-- try:- identity_decoded = base64.b64decode(stem.util.str_tools._to_bytes(identity))- except (TypeError, binascii.Error):- raise ValueError("Unable to decode identity string '%s'" % identity)-- fingerprint = binascii.b2a_hex(identity_decoded).upper()-- if stem.prereq.is_python_3():- fingerprint = stem.util.str_tools._to_unicode(fingerprint)-- if check_if_fingerprint:- if not stem.util.tor_tools.is_valid_fingerprint(fingerprint):- raise ValueError("Decoded '%s' to be '%s', which isn't a valid fingerprint" % (identity, fingerprint))-- return fingerprint---class RouterStatusEntry(Descriptor):- """- Information about an individual router stored within a network status- document. This is the common parent for concrete status entry types.-- :var stem.descriptor.networkstatus.NetworkStatusDocument document: **\*** document that this descriptor came from-- :var str nickname: **\*** router's nickname- :var str fingerprint: **\*** router's fingerprint- :var datetime published: **\*** router's publication- :var str address: **\*** router's IP address- :var int or_port: **\*** router's ORPort- :var int dir_port: **\*** router's DirPort-- :var list flags: **\*** list of :data:`~stem.Flag` associated with the relay-- :var stem.version.Version version: parsed version of tor, this is **None** if- the relay's using a new versioning scheme- :var str version_line: versioning information reported by the relay- """-- ATTRIBUTES = {- 'nickname': (None, _parse_r_line),- 'fingerprint': (None, _parse_r_line),- 'published': (None, _parse_r_line),- 'address': (None, _parse_r_line),- 'or_port': (None, _parse_r_line),- 'dir_port': (None, _parse_r_line),-- 'flags': (None, _parse_s_line),-- 'version_line': (None, _parse_v_line),- 'version': (None, _parse_v_line),- }-- PARSER_FOR_LINE = {- 'r': _parse_r_line,- 's': _parse_s_line,- 'v': _parse_v_line,- }-- def __init__(self, content, validate = False, document = None):- """- Parse a router descriptor in a network status document.-- :param str content: router descriptor content to be parsed- :param NetworkStatusDocument document: document this descriptor came from- :param bool validate: checks the validity of the content if **True**, skips- these checks otherwise-- :raises: **ValueError** if the descriptor data is invalid- """-- super(RouterStatusEntry, self).__init__(content, lazy_load = not validate)- self.document = document- entries = _get_descriptor_components(content, validate)-- if validate:- for keyword in self._required_fields():- if keyword not in entries:- raise ValueError("%s must have a '%s' line:\n%s" % (self._name(True), keyword, str(self)))-- for keyword in self._single_fields():- if keyword in entries and len(entries[keyword]) > 1:- raise ValueError("%s can only have a single '%s' line, got %i:\n%s" % (self._name(True), keyword, len(entries[keyword]), str(self)))-- if 'r' != list(entries.keys())[0]:- raise ValueError("%s are expected to start with a 'r' line:\n%s" % (self._name(True), str(self)))-- self._parse(entries, validate)- else:- self._entries = entries-- def _name(self, is_plural = False):- """- Name for this descriptor type.- """-- return 'Router status entries' if is_plural else 'Router status entry'-- def _required_fields(self):- """- Provides lines that must appear in the descriptor.- """-- return ()-- def _single_fields(self):- """- Provides lines that can only appear in the descriptor once.- """-- return ()-- def _compare(self, other, method):- if not isinstance(other, RouterStatusEntry):- return False-- return method(str(self).strip(), str(other).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)---class RouterStatusEntryV2(RouterStatusEntry):- """- Information about an individual router stored within a version 2 network- status document.-- :var str digest: **\*** router's upper-case hex digest-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as **None** if undefined- """-- ATTRIBUTES = dict(RouterStatusEntry.ATTRIBUTES, **{- 'digest': (None, _parse_r_line),- })-- def _name(self, is_plural = False):- return 'Router status entries (v2)' if is_plural else 'Router status entry (v2)'-- def _required_fields(self):- return ('r')-- def _single_fields(self):- return ('r', 's', 'v')-- def _compare(self, other, method):- if not isinstance(other, RouterStatusEntryV2):- return False-- return method(str(self).strip(), str(other).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)---class RouterStatusEntryV3(RouterStatusEntry):- """- Information about an individual router stored within a version 3 network- status document.-- :var list or_addresses: **\*** relay's OR addresses, this is a tuple listing- of the form (address (**str**), port (**int**), is_ipv6 (**bool**))- :var str digest: **\*** router's upper-case hex digest-- :var int bandwidth: bandwidth claimed by the relay (in kb/s)- :var int measured: bandwidth measured to be available by the relay, this is a- unit-less heuristic generated by the Bandwidth authoritites to weight relay- selection- :var bool is_unmeasured: bandwidth measurement isn't based on three or more- measurements- :var list unrecognized_bandwidth_entries: **\*** bandwidth weighting- information that isn't yet recognized-- :var stem.exit_policy.MicroExitPolicy exit_policy: router's exit policy-- :var list microdescriptor_hashes: **\*** tuples of two values, the list of- consensus methods for generating a set of digests and the 'algorithm =>- digest' mappings-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as **None** if undefined- """-- ATTRIBUTES = dict(RouterStatusEntry.ATTRIBUTES, **{- 'digest': (None, _parse_r_line),- 'or_addresses': ([], _parse_a_line),-- 'bandwidth': (None, _parse_w_line),- 'measured': (None, _parse_w_line),- 'is_unmeasured': (False, _parse_w_line),- 'unrecognized_bandwidth_entries': ([], _parse_w_line),-- 'exit_policy': (None, _parse_p_line),- 'microdescriptor_hashes': ([], _parse_m_line),- })-- PARSER_FOR_LINE = dict(RouterStatusEntry.PARSER_FOR_LINE, **{- 'a': _parse_a_line,- 'w': _parse_w_line,- 'p': _parse_p_line,- 'm': _parse_m_line,- })-- def _name(self, is_plural = False):- return 'Router status entries (v3)' if is_plural else 'Router status entry (v3)'-- def _required_fields(self):- return ('r', 's')-- def _single_fields(self):- return ('r', 's', 'v', 'w', 'p')-- def _compare(self, other, method):- if not isinstance(other, RouterStatusEntryV3):- return False-- return method(str(self).strip(), str(other).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)---class RouterStatusEntryMicroV3(RouterStatusEntry):- """- Information about an individual router stored within a microdescriptor- flavored network status document.-- :var int bandwidth: bandwidth claimed by the relay (in kb/s)- :var int measured: bandwidth measured to be available by the relay- :var bool is_unmeasured: bandwidth measurement isn't based on three or more- measurements- :var list unrecognized_bandwidth_entries: **\*** bandwidth weighting- information that isn't yet recognized-- :var str digest: **\*** router's hex encoded digest of our corresponding microdescriptor-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as **None** if undefined- """-- ATTRIBUTES = dict(RouterStatusEntry.ATTRIBUTES, **{- 'bandwidth': (None, _parse_w_line),- 'measured': (None, _parse_w_line),- 'is_unmeasured': (False, _parse_w_line),- 'unrecognized_bandwidth_entries': ([], _parse_w_line),-- 'digest': (None, _parse_microdescriptor_m_line),- })-- PARSER_FOR_LINE = dict(RouterStatusEntry.PARSER_FOR_LINE, **{- 'w': _parse_w_line,- 'm': _parse_microdescriptor_m_line,- })-- def _name(self, is_plural = False):- return 'Router status entries (micro v3)' if is_plural else 'Router status entry (micro v3)'-- def _required_fields(self):- return ('r', 's', 'm')-- def _single_fields(self):- return ('r', 's', 'v', 'w', 'm')-- def _compare(self, other, method):- if not isinstance(other, RouterStatusEntryMicroV3):- return False-- return method(str(self).strip(), str(other).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)diff --git a/ext/stem/descriptor/server_descriptor.py b/ext/stem/descriptor/server_descriptor.pydeleted file mode 100644index b375066f..00000000--- a/ext/stem/descriptor/server_descriptor.py+++ /dev/null@@ -1,822 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Parsing for Tor server descriptors, which contains the infrequently changing-information about a Tor relay (contact information, exit policy, public keys,-etc). This information is provided from a few sources...--* The control port via 'GETINFO desc/\*' queries.--* The 'cached-descriptors' file in Tor's data directory.--* Archived descriptors provided by CollecTor- (https://collector.torproject.org/).--* Directory authorities and mirrors via their DirPort.--**Module Overview:**--::-- ServerDescriptor - Tor server descriptor.- |- RelayDescriptor - Server descriptor for a relay.- |- |- BridgeDescriptor - Scrubbed server descriptor for a bridge.- | |- is_scrubbed - checks if our content has been properly scrubbed- | +- get_scrubbing_issues - description of issues with our scrubbing- |- |- digest - calculates the upper-case hex digest value for our content- |- get_annotations - dictionary of content prior to the descriptor entry- +- get_annotation_lines - lines that provided the annotations-"""--import functools-import hashlib-import re--import stem.descriptor.extrainfo_descriptor-import stem.exit_policy-import stem.prereq-import stem.util.connection-import stem.util.str_tools-import stem.util.tor_tools-import stem.version--from stem import str_type--from stem.descriptor import (- PGP_BLOCK_END,- Descriptor,- _get_descriptor_components,- _read_until_keywords,- _bytes_for_block,- _value,- _values,- _parse_simple_line,- _parse_bytes_line,- _parse_timestamp_line,- _parse_forty_character_hex,- _parse_key_block,-)--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache--# relay descriptors must have exactly one of the following-REQUIRED_FIELDS = (- 'router',- 'bandwidth',- 'published',- 'onion-key',- 'signing-key',- 'router-signature',-)--# optional entries that can appear at most once-SINGLE_FIELDS = (- 'platform',- 'fingerprint',- 'hibernating',- 'uptime',- 'contact',- 'read-history',- 'write-history',- 'eventdns',- 'family',- 'caches-extra-info',- 'extra-info-digest',- 'hidden-service-dir',- 'protocols',- 'allow-single-hop-exits',- 'ntor-onion-key',-)--DEFAULT_IPV6_EXIT_POLICY = stem.exit_policy.MicroExitPolicy('reject 1-65535')-REJECT_ALL_POLICY = stem.exit_policy.ExitPolicy('reject *:*')---def _parse_file(descriptor_file, is_bridge = False, validate = False, **kwargs):- """- Iterates over the server descriptors in a file.-- :param file descriptor_file: file with descriptor content- :param bool is_bridge: parses the file as being a bridge descriptor- :param bool validate: checks the validity of the descriptor's content if- **True**, skips these checks otherwise- :param dict kwargs: additional arguments for the descriptor constructor-- :returns: iterator for ServerDescriptor instances in the file-- :raises:- * **ValueError** if the contents is malformed and validate is True- * **IOError** if the file can't be read- """-- # Handler for relay descriptors- #- # Cached descriptors consist of annotations followed by the descriptor- # itself. For instance...- #- # @downloaded-at 2012-03-14 16:31:05- # @source "145.53.65.130"- # router caerSidi 71.35.143.157 9001 0 0- # platform Tor 0.2.1.30 on Linux x86_64- # <rest of the descriptor content>- # router-signature- # -----BEGIN SIGNATURE------ # <signature for the above descriptor>- # -----END SIGNATURE------ #- # Metrics descriptor files are the same, but lack any annotations. The- # following simply does the following...- #- # - parse as annotations until we get to 'router'- # - parse as descriptor content until we get to 'router-signature' followed- # by the end of the signature block- # - construct a descriptor and provide it back to the caller- #- # Any annotations after the last server descriptor is ignored (never provided- # to the caller).-- while True:- annotations = _read_until_keywords('router', descriptor_file)-- if not is_bridge:- descriptor_content = _read_until_keywords('router-signature', descriptor_file)-- # we've reached the 'router-signature', now include the pgp style block-- block_end_prefix = PGP_BLOCK_END.split(' ', 1)[0]- descriptor_content += _read_until_keywords(block_end_prefix, descriptor_file, True)- else:- descriptor_content = _read_until_keywords('router-digest', descriptor_file, True)-- if descriptor_content:- if descriptor_content[0].startswith(b'@type'):- descriptor_content = descriptor_content[1:]-- # strip newlines from annotations- annotations = list(map(bytes.strip, annotations))-- descriptor_text = bytes.join(b'', descriptor_content)-- if is_bridge:- yield BridgeDescriptor(descriptor_text, validate, annotations, **kwargs)- else:- yield RelayDescriptor(descriptor_text, validate, annotations, **kwargs)- else:- if validate and annotations:- orphaned_annotations = stem.util.str_tools._to_unicode(b'\n'.join(annotations))- raise ValueError('Content conform to being a server descriptor:\n%s' % orphaned_annotations)-- break # done parsing descriptors---def _parse_router_line(descriptor, entries):- # "router" nickname address ORPort SocksPort DirPort-- value = _value('router', entries)- router_comp = value.split()-- if len(router_comp) < 5:- raise ValueError('Router line must have five values: router %s' % value)- elif not stem.util.tor_tools.is_valid_nickname(router_comp[0]):- raise ValueError("Router line entry isn't a valid nickname: %s" % router_comp[0])- elif not stem.util.connection.is_valid_ipv4_address(router_comp[1]):- raise ValueError("Router line entry isn't a valid IPv4 address: %s" % router_comp[1])- elif not stem.util.connection.is_valid_port(router_comp[2], allow_zero = True):- raise ValueError("Router line's ORPort is invalid: %s" % router_comp[2])- elif not stem.util.connection.is_valid_port(router_comp[3], allow_zero = True):- raise ValueError("Router line's SocksPort is invalid: %s" % router_comp[3])- elif not stem.util.connection.is_valid_port(router_comp[4], allow_zero = True):- raise ValueError("Router line's DirPort is invalid: %s" % router_comp[4])-- descriptor.nickname = router_comp[0]- descriptor.address = router_comp[1]- descriptor.or_port = int(router_comp[2])- descriptor.socks_port = None if router_comp[3] == '0' else int(router_comp[3])- descriptor.dir_port = None if router_comp[4] == '0' else int(router_comp[4])---def _parse_bandwidth_line(descriptor, entries):- # "bandwidth" bandwidth-avg bandwidth-burst bandwidth-observed-- value = _value('bandwidth', entries)- bandwidth_comp = value.split()-- if len(bandwidth_comp) < 3:- raise ValueError('Bandwidth line must have three values: bandwidth %s' % value)- elif not bandwidth_comp[0].isdigit():- raise ValueError("Bandwidth line's average rate isn't numeric: %s" % bandwidth_comp[0])- elif not bandwidth_comp[1].isdigit():- raise ValueError("Bandwidth line's burst rate isn't numeric: %s" % bandwidth_comp[1])- elif not bandwidth_comp[2].isdigit():- raise ValueError("Bandwidth line's observed rate isn't numeric: %s" % bandwidth_comp[2])-- descriptor.average_bandwidth = int(bandwidth_comp[0])- descriptor.burst_bandwidth = int(bandwidth_comp[1])- descriptor.observed_bandwidth = int(bandwidth_comp[2])---def _parse_platform_line(descriptor, entries):- # "platform" string-- _parse_bytes_line('platform', 'platform')(descriptor, entries)-- # The platform attribute was set earlier. This line can contain any- # arbitrary data, but tor seems to report its version followed by the- # os like the following...- #- # platform Tor 0.2.2.35 (git-73ff13ab3cc9570d) on Linux x86_64- #- # There's no guarantee that we'll be able to pick these out the- # version, but might as well try to save our caller the effort.-- value = _value('platform', entries)- platform_match = re.match('^(?:node-)?Tor (\S*).* on (.*)$', value)-- if platform_match:- version_str, descriptor.operating_system = platform_match.groups()-- try:- descriptor.tor_version = stem.version._get_version(version_str)- except ValueError:- pass---def _parse_fingerprint_line(descriptor, entries):- # This is forty hex digits split into space separated groups of four.- # Checking that we match this pattern.-- value = _value('fingerprint', entries)- fingerprint = value.replace(' ', '')-- for grouping in value.split(' '):- if len(grouping) != 4:- raise ValueError('Fingerprint line should have groupings of four hex digits: %s' % value)-- if not stem.util.tor_tools.is_valid_fingerprint(fingerprint):- raise ValueError('Tor relay fingerprints consist of forty hex digits: %s' % value)-- descriptor.fingerprint = fingerprint---def _parse_hibernating_line(descriptor, entries):- # "hibernating" 0|1 (in practice only set if one)-- value = _value('hibernating', entries)-- if value not in ('0', '1'):- raise ValueError('Hibernating line had an invalid value, must be zero or one: %s' % value)-- descriptor.hibernating = value == '1'---def _parse_hidden_service_dir_line(descriptor, entries):- value = _value('hidden-service-dir', entries)-- if value:- descriptor.hidden_service_dir = value.split(' ')- else:- descriptor.hidden_service_dir = ['2']---def _parse_uptime_line(descriptor, entries):- # We need to be tolerant of negative uptimes to accommodate a past tor- # bug...- #- # Changes in version 0.1.2.7-alpha - 2007-02-06- # - If our system clock jumps back in time, don't publish a negative- # uptime in the descriptor. Also, don't let the global rate limiting- # buckets go absurdly negative.- #- # After parsing all of the attributes we'll double check that negative- # uptimes only occurred prior to this fix.-- value = _value('uptime', entries)-- try:- descriptor.uptime = int(value)- except ValueError:- raise ValueError('Uptime line must have an integer value: %s' % value)---def _parse_protocols_line(descriptor, entries):- value = _value('protocols', entries)- protocols_match = re.match('^Link (.*) Circuit (.*)$', value)-- if not protocols_match:- raise ValueError('Protocols line did not match the expected pattern: protocols %s' % value)-- link_versions, circuit_versions = protocols_match.groups()- descriptor.link_protocols = link_versions.split(' ')- descriptor.circuit_protocols = circuit_versions.split(' ')---def _parse_or_address_line(descriptor, entries):- all_values = _values('or-address', entries)- or_addresses = []-- for entry in all_values:- line = 'or-address %s' % entry-- if ':' not in entry:- raise ValueError('or-address line missing a colon: %s' % line)-- address, port = entry.rsplit(':', 1)- is_ipv6 = address.startswith('[') and address.endswith(']')-- if is_ipv6:- address = address[1:-1] # remove brackets-- if not ((not is_ipv6 and stem.util.connection.is_valid_ipv4_address(address)) or- (is_ipv6 and stem.util.connection.is_valid_ipv6_address(address))):- raise ValueError('or-address line has a malformed address: %s' % line)-- if not stem.util.connection.is_valid_port(port):- raise ValueError('or-address line has a malformed port: %s' % line)-- or_addresses.append((address, int(port), is_ipv6))-- descriptor.or_addresses = or_addresses---def _parse_history_line(keyword, history_end_attribute, history_interval_attribute, history_values_attribute, descriptor, entries):- value = _value(keyword, entries)- timestamp, interval, remainder = stem.descriptor.extrainfo_descriptor._parse_timestamp_and_interval(keyword, value)-- try:- if remainder:- history_values = [int(entry) for entry in remainder.split(',')]- else:- history_values = []- except ValueError:- raise ValueError('%s line has non-numeric values: %s %s' % (keyword, keyword, value))-- setattr(descriptor, history_end_attribute, timestamp)- setattr(descriptor, history_interval_attribute, interval)- setattr(descriptor, history_values_attribute, history_values)---def _parse_exit_policy(descriptor, entries):- if hasattr(descriptor, '_unparsed_exit_policy'):- if descriptor._unparsed_exit_policy == [str_type('reject *:*')]:- descriptor.exit_policy = REJECT_ALL_POLICY- else:- descriptor.exit_policy = stem.exit_policy.ExitPolicy(*descriptor._unparsed_exit_policy)-- del descriptor._unparsed_exit_policy---_parse_contact_line = _parse_bytes_line('contact', 'contact')-_parse_published_line = _parse_timestamp_line('published', 'published')-_parse_extrainfo_digest_line = _parse_forty_character_hex('extra-info-digest', 'extra_info_digest')-_parse_read_history_line = functools.partial(_parse_history_line, 'read-history', 'read_history_end', 'read_history_interval', 'read_history_values')-_parse_write_history_line = functools.partial(_parse_history_line, 'write-history', 'write_history_end', 'write_history_interval', 'write_history_values')-_parse_ipv6_policy_line = lambda descriptor, entries: setattr(descriptor, 'exit_policy_v6', stem.exit_policy.MicroExitPolicy(_value('ipv6-policy', entries)))-_parse_allow_single_hop_exits_line = lambda descriptor, entries: setattr(descriptor, 'allow_single_hop_exits', 'allow_single_hop_exits' in entries)-_parse_caches_extra_info_line = lambda descriptor, entries: setattr(descriptor, 'extra_info_cache', 'extra_info_cache' in entries)-_parse_family_line = lambda descriptor, entries: setattr(descriptor, 'family', set(_value('family', entries).split(' ')))-_parse_eventdns_line = lambda descriptor, entries: setattr(descriptor, 'eventdns', _value('eventdns', entries) == '1')-_parse_onion_key_line = _parse_key_block('onion-key', 'onion_key', 'RSA PUBLIC KEY')-_parse_signing_key_line = _parse_key_block('signing-key', 'signing_key', 'RSA PUBLIC KEY')-_parse_router_signature_line = _parse_key_block('router-signature', 'signature', 'SIGNATURE')-_parse_ntor_onion_key_line = _parse_simple_line('ntor-onion-key', 'ntor_onion_key')-_parse_router_digest_line = _parse_forty_character_hex('router-digest', '_digest')---class ServerDescriptor(Descriptor):- """- Common parent for server descriptors.-- :var str nickname: **\*** relay's nickname- :var str fingerprint: identity key fingerprint- :var datetime published: **\*** time in UTC when this descriptor was made-- :var str address: **\*** IPv4 address of the relay- :var int or_port: **\*** port used for relaying- :var int socks_port: **\*** port used as client (deprecated, always **None**)- :var int dir_port: **\*** port used for descriptor mirroring-- :var bytes platform: line with operating system and tor version- :var stem.version.Version tor_version: version of tor- :var str operating_system: operating system- :var int uptime: uptime when published in seconds- :var bytes contact: contact information- :var stem.exit_policy.ExitPolicy exit_policy: **\*** stated exit policy- :var stem.exit_policy.MicroExitPolicy exit_policy_v6: **\*** exit policy for IPv6- :var set family: **\*** nicknames or fingerprints of declared family-- :var int average_bandwidth: **\*** average rate it's willing to relay in bytes/s- :var int burst_bandwidth: **\*** burst rate it's willing to relay in bytes/s- :var int observed_bandwidth: **\*** estimated capacity based on usage in bytes/s-- :var list link_protocols: link protocols supported by the relay- :var list circuit_protocols: circuit protocols supported by the relay- :var bool hibernating: **\*** hibernating when published- :var bool allow_single_hop_exits: **\*** flag if single hop exiting is allowed- :var bool extra_info_cache: **\*** flag if a mirror for extra-info documents- :var str extra_info_digest: upper-case hex encoded digest of our extra-info document- :var bool eventdns: flag for evdns backend (deprecated, always unset)- :var list or_addresses: **\*** alternative for our address/or_port- attributes, each entry is a tuple of the form (address (**str**), port- (**int**), is_ipv6 (**bool**))-- Deprecated, moved to extra-info descriptor...-- :var datetime read_history_end: end of the sampling interval- :var int read_history_interval: seconds per interval- :var list read_history_values: bytes read during each interval-- :var datetime write_history_end: end of the sampling interval- :var int write_history_interval: seconds per interval- :var list write_history_values: bytes written during each interval-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as **None** if undefined- """-- ATTRIBUTES = {- 'nickname': (None, _parse_router_line),- 'fingerprint': (None, _parse_fingerprint_line),- 'contact': (None, _parse_contact_line),- 'published': (None, _parse_published_line),- 'exit_policy': (None, _parse_exit_policy),-- 'address': (None, _parse_router_line),- 'or_port': (None, _parse_router_line),- 'socks_port': (None, _parse_router_line),- 'dir_port': (None, _parse_router_line),-- 'platform': (None, _parse_platform_line),- 'tor_version': (None, _parse_platform_line),- 'operating_system': (None, _parse_platform_line),- 'uptime': (None, _parse_uptime_line),- 'exit_policy_v6': (DEFAULT_IPV6_EXIT_POLICY, _parse_ipv6_policy_line),- 'family': (set(), _parse_family_line),-- 'average_bandwidth': (None, _parse_bandwidth_line),- 'burst_bandwidth': (None, _parse_bandwidth_line),- 'observed_bandwidth': (None, _parse_bandwidth_line),-- 'link_protocols': (None, _parse_protocols_line),- 'circuit_protocols': (None, _parse_protocols_line),- 'hibernating': (False, _parse_hibernating_line),- 'allow_single_hop_exits': (False, _parse_allow_single_hop_exits_line),- 'extra_info_cache': (False, _parse_caches_extra_info_line),- 'extra_info_digest': (None, _parse_extrainfo_digest_line),- 'hidden_service_dir': (None, _parse_hidden_service_dir_line),- 'eventdns': (None, _parse_eventdns_line),- 'or_addresses': ([], _parse_or_address_line),-- 'read_history_end': (None, _parse_read_history_line),- 'read_history_interval': (None, _parse_read_history_line),- 'read_history_values': (None, _parse_read_history_line),-- 'write_history_end': (None, _parse_write_history_line),- 'write_history_interval': (None, _parse_write_history_line),- 'write_history_values': (None, _parse_write_history_line),- }-- PARSER_FOR_LINE = {- 'router': _parse_router_line,- 'bandwidth': _parse_bandwidth_line,- 'platform': _parse_platform_line,- 'published': _parse_published_line,- 'fingerprint': _parse_fingerprint_line,- 'contact': _parse_contact_line,- 'hibernating': _parse_hibernating_line,- 'extra-info-digest': _parse_extrainfo_digest_line,- 'hidden-service-dir': _parse_hidden_service_dir_line,- 'uptime': _parse_uptime_line,- 'protocols': _parse_protocols_line,- 'or-address': _parse_or_address_line,- 'read-history': _parse_read_history_line,- 'write-history': _parse_write_history_line,- 'ipv6-policy': _parse_ipv6_policy_line,- 'allow-single-hop-exits': _parse_allow_single_hop_exits_line,- 'caches-extra-info': _parse_caches_extra_info_line,- 'family': _parse_family_line,- 'eventdns': _parse_eventdns_line,- }-- def __init__(self, raw_contents, validate = False, annotations = None):- """- Server descriptor constructor, created from an individual relay's- descriptor content (as provided by 'GETINFO desc/*', cached descriptors,- and metrics).-- By default this validates the descriptor's content as it's parsed. This- validation can be disables to either improve performance or be accepting of- malformed data.-- :param str raw_contents: descriptor content provided by the relay- :param bool validate: checks the validity of the descriptor's content if- **True**, skips these checks otherwise- :param list annotations: lines that appeared prior to the descriptor-- :raises: **ValueError** if the contents is malformed and validate is True- """-- super(ServerDescriptor, self).__init__(raw_contents, lazy_load = not validate)- self._annotation_lines = annotations if annotations else []-- # A descriptor contains a series of 'keyword lines' which are simply a- # keyword followed by an optional value. Lines can also be followed by a- # signature block.- #- # We care about the ordering of 'accept' and 'reject' entries because this- # influences the resulting exit policy, but for everything else the order- # does not matter so breaking it into key / value pairs.-- entries, self._unparsed_exit_policy = _get_descriptor_components(stem.util.str_tools._to_unicode(raw_contents), validate, ('accept', 'reject'))-- if validate:- self._parse(entries, validate)-- _parse_exit_policy(self, entries)-- # if we have a negative uptime and a tor version that shouldn't exhibit- # this bug then fail validation-- if validate and self.uptime and self.tor_version:- if self.uptime < 0 and self.tor_version >= stem.version.Version('0.1.2.7'):- raise ValueError("Descriptor for version '%s' had a negative uptime value: %i" % (self.tor_version, self.uptime))-- self._check_constraints(entries)- else:- self._entries = entries-- def digest(self):- """- Provides the hex encoded sha1 of our content. This value is part of the- network status entry for this relay.-- :returns: **unicode** with the upper-case hex digest value for this server descriptor- """-- raise NotImplementedError('Unsupported Operation: this should be implemented by the ServerDescriptor subclass')-- @lru_cache()- def get_annotations(self):- """- Provides content that appeared prior to the descriptor. If this comes from- the cached-descriptors file then this commonly contains content like...-- ::-- @downloaded-at 2012-03-18 21:18:29- @source "173.254.216.66"-- :returns: **dict** with the key/value pairs in our annotations- """-- annotation_dict = {}-- for line in self._annotation_lines:- if b' ' in line:- key, value = line.split(b' ', 1)- annotation_dict[key] = value- else:- annotation_dict[line] = None-- return annotation_dict-- def get_annotation_lines(self):- """- Provides the lines of content that appeared prior to the descriptor. This- is the same as the- :func:`~stem.descriptor.server_descriptor.ServerDescriptor.get_annotations`- results, but with the unparsed lines and ordering retained.-- :returns: **list** with the lines of annotation that came before this descriptor- """-- return self._annotation_lines-- def _check_constraints(self, entries):- """- Does a basic check that the entries conform to this descriptor type's- constraints.-- :param dict entries: keyword => (value, pgp key) entries-- :raises: **ValueError** if an issue arises in validation- """-- for keyword in self._required_fields():- if keyword not in entries:- raise ValueError("Descriptor must have a '%s' entry" % keyword)-- for keyword in self._single_fields():- if keyword in entries and len(entries[keyword]) > 1:- raise ValueError("The '%s' entry can only appear once in a descriptor" % keyword)-- expected_first_keyword = self._first_keyword()- if expected_first_keyword and expected_first_keyword != list(entries.keys())[0]:- raise ValueError("Descriptor must start with a '%s' entry" % expected_first_keyword)-- expected_last_keyword = self._last_keyword()- if expected_last_keyword and expected_last_keyword != list(entries.keys())[-1]:- raise ValueError("Descriptor must end with a '%s' entry" % expected_last_keyword)-- if not self.exit_policy:- raise ValueError("Descriptor must have at least one 'accept' or 'reject' entry")-- # Constraints that the descriptor must meet to be valid. These can be None if- # not applicable.-- def _required_fields(self):- return REQUIRED_FIELDS-- def _single_fields(self):- return REQUIRED_FIELDS + SINGLE_FIELDS-- def _first_keyword(self):- return 'router'-- def _last_keyword(self):- return 'router-signature'---class RelayDescriptor(ServerDescriptor):- """- Server descriptor (`descriptor specification- <https://gitweb.torproject.org/torspec.git/tree/dir-spec.txt>`_)-- :var str onion_key: **\*** key used to encrypt EXTEND cells- :var str ntor_onion_key: base64 key used to encrypt EXTEND in the ntor protocol- :var str signing_key: **\*** relay's long-term identity key- :var str signature: **\*** signature for this descriptor-- **\*** attribute is required when we're parsed with validation- """-- ATTRIBUTES = dict(ServerDescriptor.ATTRIBUTES, **{- 'onion_key': (None, _parse_onion_key_line),- 'ntor_onion_key': (None, _parse_ntor_onion_key_line),- 'signing_key': (None, _parse_signing_key_line),- 'signature': (None, _parse_router_signature_line),- })-- PARSER_FOR_LINE = dict(ServerDescriptor.PARSER_FOR_LINE, **{- 'onion-key': _parse_onion_key_line,- 'ntor-onion-key': _parse_ntor_onion_key_line,- 'signing-key': _parse_signing_key_line,- 'router-signature': _parse_router_signature_line,- })-- def __init__(self, raw_contents, validate = False, annotations = None):- super(RelayDescriptor, self).__init__(raw_contents, validate, annotations)-- if validate:- if self.fingerprint:- key_hash = hashlib.sha1(_bytes_for_block(self.signing_key)).hexdigest()-- if key_hash != self.fingerprint.lower():- raise ValueError('Fingerprint does not match the hash of our signing key (fingerprint: %s, signing key hash: %s)' % (self.fingerprint.lower(), key_hash))-- if stem.prereq.is_crypto_available():- signed_digest = self._digest_for_signature(self.signing_key, self.signature)-- if signed_digest != self.digest():- raise ValueError('Decrypted digest does not match local digest (calculated: %s, local: %s)' % (signed_digest, self.digest()))-- @lru_cache()- def digest(self):- """- Provides the digest of our descriptor's content.-- :returns: the digest string encoded in uppercase hex-- :raises: ValueError if the digest canot be calculated- """-- return self._digest_for_content(b'router ', b'\nrouter-signature\n')-- def _compare(self, other, method):- if not isinstance(other, RelayDescriptor):- return False-- return method(str(self).strip(), str(other).strip())-- def __hash__(self):- return hash(str(self).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)---class BridgeDescriptor(ServerDescriptor):- """- Bridge descriptor (`bridge descriptor specification- <https://collector.torproject.org/formats.html#bridge-descriptors>`_)- """-- ATTRIBUTES = dict(ServerDescriptor.ATTRIBUTES, **{- '_digest': (None, _parse_router_digest_line),- })-- PARSER_FOR_LINE = dict(ServerDescriptor.PARSER_FOR_LINE, **{- 'router-digest': _parse_router_digest_line,- })-- def digest(self):- return self._digest-- def is_scrubbed(self):- """- Checks if we've been properly scrubbed in accordance with the `bridge- descriptor specification- <https://collector.torproject.org/formats.html#bridge-descriptors>`_.- Validation is a moving target so this may not be fully up to date.-- :returns: **True** if we're scrubbed, **False** otherwise- """-- return self.get_scrubbing_issues() == []-- @lru_cache()- def get_scrubbing_issues(self):- """- Provides issues with our scrubbing.-- :returns: **list** of strings which describe issues we have with our- scrubbing, this list is empty if we're properly scrubbed- """-- issues = []-- if not self.address.startswith('10.'):- issues.append("Router line's address should be scrubbed to be '10.x.x.x': %s" % self.address)-- if self.contact and self.contact != 'somebody':- issues.append("Contact line should be scrubbed to be 'somebody', but instead had '%s'" % self.contact)-- for address, _, is_ipv6 in self.or_addresses:- if not is_ipv6 and not address.startswith('10.'):- issues.append("or-address line's address should be scrubbed to be '10.x.x.x': %s" % address)- elif is_ipv6 and not address.startswith('fd9f:2e19:3bcf::'):- # TODO: this check isn't quite right because we aren't checking that- # the next grouping of hex digits contains 1-2 digits- issues.append("or-address line's address should be scrubbed to be 'fd9f:2e19:3bcf::xx:xxxx': %s" % address)-- for line in self.get_unrecognized_lines():- if line.startswith('onion-key '):- issues.append('Bridge descriptors should have their onion-key scrubbed: %s' % line)- elif line.startswith('signing-key '):- issues.append('Bridge descriptors should have their signing-key scrubbed: %s' % line)- elif line.startswith('router-signature '):- issues.append('Bridge descriptors should have their signature scrubbed: %s' % line)-- return issues-- def _required_fields(self):- # bridge required fields are the same as a relay descriptor, minus items- # excluded according to the format page-- excluded_fields = [- 'onion-key',- 'signing-key',- 'router-signature',- ]-- included_fields = [- 'router-digest',- ]-- return tuple(included_fields + [f for f in REQUIRED_FIELDS if f not in excluded_fields])-- def _single_fields(self):- return self._required_fields() + SINGLE_FIELDS-- def _last_keyword(self):- return None-- def _compare(self, other, method):- if not isinstance(other, BridgeDescriptor):- return False-- return method(str(self).strip(), str(other).strip())-- def __hash__(self):- return hash(str(self).strip())-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __lt__(self, other):- return self._compare(other, lambda s, o: s < o)-- def __le__(self, other):- return self._compare(other, lambda s, o: s <= o)diff --git a/ext/stem/descriptor/tordnsel.py b/ext/stem/descriptor/tordnsel.pydeleted file mode 100644index 75a252bd..00000000--- a/ext/stem/descriptor/tordnsel.py+++ /dev/null@@ -1,117 +0,0 @@-# Copyright 2013-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Parsing for `TorDNSEL <https://www.torproject.org/projects/tordnsel.html.en>`_-exit list files.--::-- TorDNSEL - Exit list provided by TorDNSEL-"""--import stem.util.connection-import stem.util.str_tools-import stem.util.tor_tools--from stem.descriptor import (- Descriptor,- _read_until_keywords,- _get_descriptor_components,-)---def _parse_file(tordnsel_file, validate = False, **kwargs):- """- Iterates over a tordnsel file.-- :returns: iterator for :class:`~stem.descriptor.tordnsel.TorDNSEL`- instances in the file-- :raises:- * **ValueError** if the contents is malformed and validate is **True**- * **IOError** if the file can't be read- """-- # skip content prior to the first ExitNode- _read_until_keywords('ExitNode', tordnsel_file, skip = True)-- while True:- contents = _read_until_keywords('ExitAddress', tordnsel_file)- contents += _read_until_keywords('ExitNode', tordnsel_file)-- if contents:- yield TorDNSEL(bytes.join(b'', contents), validate, **kwargs)- else:- break # done parsing file---class TorDNSEL(Descriptor):- """- TorDNSEL descriptor (`exitlist specification- <https://www.torproject.org/tordnsel/exitlist-spec.txt>`_)-- :var str fingerprint: **\*** authority's fingerprint- :var datetime published: **\*** time in UTC when this descriptor was made- :var datetime last_status: **\*** time in UTC when the relay was seen in a v2 network status- :var list exit_addresses: **\*** list of (str address, datetime date) tuples consisting of the found IPv4 exit address and the time-- **\*** attribute is either required when we're parsed with validation or has- a default value, others are left as **None** if undefined- """-- def __init__(self, raw_contents, validate):- super(TorDNSEL, self).__init__(raw_contents)- raw_contents = stem.util.str_tools._to_unicode(raw_contents)- entries = _get_descriptor_components(raw_contents, validate)-- self.fingerprint = None- self.published = None- self.last_status = None- self.exit_addresses = []-- self._parse(entries, validate)-- def _parse(self, entries, validate):-- for keyword, values in list(entries.items()):- value, block_type, block_content = values[0]-- if validate and block_content:- raise ValueError('Unexpected block content: %s' % block_content)-- if keyword == 'ExitNode':- if validate and not stem.util.tor_tools.is_valid_fingerprint(value):- raise ValueError('Tor relay fingerprints consist of forty hex digits: %s' % value)-- self.fingerprint = value- elif keyword == 'Published':- try:- self.published = stem.util.str_tools._parse_timestamp(value)- except ValueError:- if validate:- raise ValueError("Published time wasn't parsable: %s" % value)- elif keyword == 'LastStatus':- try:- self.last_status = stem.util.str_tools._parse_timestamp(value)- except ValueError:- if validate:- raise ValueError("LastStatus time wasn't parsable: %s" % value)- elif keyword == 'ExitAddress':- for value, block_type, block_content in values:- address, date = value.split(' ', 1)-- if validate:- if not stem.util.connection.is_valid_ipv4_address(address):- raise ValueError("ExitAddress isn't a valid IPv4 address: %s" % address)- elif block_content:- raise ValueError('Unexpected block content: %s' % block_content)-- try:- date = stem.util.str_tools._parse_timestamp(date)- self.exit_addresses.append((address, date))- except ValueError:- if validate:- raise ValueError("ExitAddress found time wasn't parsable: %s" % value)- elif validate:- raise ValueError('Unrecognized keyword: %s' % keyword)diff --git a/ext/stem/exit_policy.py b/ext/stem/exit_policy.pydeleted file mode 100644index 62b9a12f..00000000--- a/ext/stem/exit_policy.py+++ /dev/null@@ -1,1094 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Representation of tor exit policies. These can be easily used to check if-exiting to a destination is permissible or not. For instance...--::-- >>> from stem.exit_policy import ExitPolicy, MicroExitPolicy- >>> policy = ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')- >>> print(policy)- accept *:80, accept *:443, reject *:*- >>> print(policy.summary())- accept 80, 443- >>> policy.can_exit_to('75.119.206.243', 80)- True-- >>> policy = MicroExitPolicy('accept 80,443')- >>> print(policy)- accept 80,443- >>> policy.can_exit_to('75.119.206.243', 80)- True--::-- ExitPolicy - Exit policy for a Tor relay- |- MicroExitPolicy - Microdescriptor exit policy- |- |- can_exit_to - check if exiting to this destination is allowed or not- |- is_exiting_allowed - check if any exiting is allowed- |- summary - provides a short label, similar to a microdescriptor- |- has_private - checks if policy has anything expanded from the 'private' keyword- |- strip_private - provides a copy of the policy without 'private' entries- |- has_default - checks if policy ends with the defaultly appended suffix- |- strip_default - provides a copy of the policy without the default suffix- |- __str__ - string representation- +- __iter__ - ExitPolicyRule entries that this contains-- ExitPolicyRule - Single rule of an exit policy chain- |- MicroExitPolicyRule - Single rule for a microdescriptor policy- |- |- is_address_wildcard - checks if we'll accept any address- |- is_port_wildcard - checks if we'll accept any port- |- get_address_type - provides the protocol our ip address belongs to- |- is_match - checks if we match a given destination- |- get_mask - provides the address representation of our mask- |- get_masked_bits - provides the bit representation of our mask- |- is_default - flag indicating if this was part of the default end of a policy- |- is_private - flag indicating if this was expanded from a 'private' keyword- +- __str__ - string representation for this rule-- get_config_policy - provides the ExitPolicy based on torrc rules--.. data:: AddressType (enum)-- Enumerations for IP address types that can be in an exit policy.-- ============ ===========- AddressType Description- ============ ===========- **WILDCARD** any address of either IPv4 or IPv6- **IPv4** IPv4 address- **IPv6** IPv6 address- ============ ===========-"""--from __future__ import absolute_import--import socket-import zlib--import stem.prereq-import stem.util.connection-import stem.util.enum-import stem.util.str_tools--from stem import str_type--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache--AddressType = stem.util.enum.Enum(('WILDCARD', 'Wildcard'), ('IPv4', 'IPv4'), ('IPv6', 'IPv6'))--# Addresses aliased by the 'private' policy. From the tor man page...-#-# To specify all internal and link-local networks (including 0.0.0.0/8,-# 169.254.0.0/16, 127.0.0.0/8, 192.168.0.0/16, 10.0.0.0/8, and 172.16.0.0/12),-# you can use the 'private' alias instead of an address.--PRIVATE_ADDRESSES = (- '0.0.0.0/8',- '169.254.0.0/16',- '127.0.0.0/8',- '192.168.0.0/16',- '10.0.0.0/8',- '172.16.0.0/12',-)---def get_config_policy(rules, ip_address = None):- """- Converts an ExitPolicy found in a torrc to a proper exit pattern. This- accounts for...-- * ports being optional- * the 'private' keyword-- :param str,list rules: comma separated rules or list to be converted- :param str ip_address: this relay's IP address for the 'private' policy if- it's present, this defaults to the local address-- :returns: :class:`~stem.exit_policy.ExitPolicy` reflected by the rules-- :raises: **ValueError** if input isn't a valid tor exit policy- """-- if ip_address and not (stem.util.connection.is_valid_ipv4_address(ip_address) or stem.util.connection.is_valid_ipv6_address(ip_address)):- raise ValueError("%s isn't a valid IP address" % ip_address)-- if isinstance(rules, (bytes, str_type)):- rules = rules.split(',')-- result = []-- for rule in rules:- rule = rule.strip()-- if not rule:- continue-- if ':' not in rule:- rule = '%s:*' % rule-- if 'private' in rule:- acceptance = rule.split(' ', 1)[0]- port = rule.split(':', 1)[1]- addresses = list(PRIVATE_ADDRESSES)-- if ip_address:- addresses.append(ip_address)- else:- try:- addresses.append(socket.gethostbyname(socket.gethostname()))- except:- pass # we might not have a network connection-- for private_addr in addresses:- result.append(ExitPolicyRule('%s %s:%s' % (acceptance, private_addr, port)))- else:- result.append(ExitPolicyRule(rule))-- # torrc policies can apply to IPv4 or IPv6, so we need to make sure /0- # addresses aren't treated as being a full wildcard-- for rule in result:- rule._submask_wildcard = False-- return ExitPolicy(*result)---def _flag_private_rules(rules):- """- Determine if part of our policy was expanded from the 'private' keyword. This- doesn't differentiate if this actually came from the 'private' keyword or a- series of rules exactly matching it.- """-- matches = []-- for i, rule in enumerate(rules):- if i + len(PRIVATE_ADDRESSES) + 1 > len(rules):- break-- rule_str = '%s/%s' % (rule.address, rule.get_masked_bits())-- if rule_str == PRIVATE_ADDRESSES[0]:- matches.append(i)-- for start_index in matches:- # To match the private policy the following must all be true...- #- # * series of addresses and bit masks match PRIVATE_ADDRESSES- # * all rules have the same port range and acceptance- # * all rules have the same acceptance (all accept or reject entries)-- rule_set = rules[start_index:start_index + len(PRIVATE_ADDRESSES) + 1]- is_match = True-- min_port, max_port = rule_set[0].min_port, rule_set[0].max_port- is_accept = rule_set[0].is_accept-- for i, rule in enumerate(rule_set[:-1]):- rule_str = '%s/%s' % (rule.address, rule.get_masked_bits())-- if rule_str != PRIVATE_ADDRESSES[i] or rule.min_port != min_port or rule.max_port != max_port or rule.is_accept != is_accept:- is_match = False- break-- # The last rule is for the relay's public address, so it's dynamic.-- last_rule = rule_set[-1]-- if last_rule.is_address_wildcard() or last_rule.min_port != min_port or last_rule.max_port != max_port or last_rule.is_accept != is_accept:- is_match = False- if is_match:- for rule in rule_set:- rule._is_private = True---def _flag_default_rules(rules):- """- Determine if part of our policy ends with the defaultly appended suffix.- """-- if len(rules) >= len(DEFAULT_POLICY_RULES):- rules_suffix = tuple(rules[-len(DEFAULT_POLICY_RULES):])-- if rules_suffix == DEFAULT_POLICY_RULES:- for rule in rules_suffix:- rule._is_default_suffix = True---class ExitPolicy(object):- """- Policy for the destinations that a relay allows or denies exiting to. This- is, in effect, just a list of :class:`~stem.exit_policy.ExitPolicyRule`- entries.-- :param list rules: **str** or :class:`~stem.exit_policy.ExitPolicyRule`- entries that make up this policy- """-- def __init__(self, *rules):- # sanity check the types-- for rule in rules:- if not isinstance(rule, (bytes, str_type, ExitPolicyRule)):- raise TypeError('Exit policy rules can only contain strings or ExitPolicyRules, got a %s (%s)' % (type(rule), rules))-- # Unparsed representation of the rules we were constructed with. Our- # _get_rules() method consumes this to provide ExitPolicyRule instances.- # This is lazily evaluated so we don't need to actually parse the exit- # policy if it's never used.-- is_all_str = True-- for rule in rules:- if not isinstance(rule, (bytes, str_type)):- is_all_str = False-- if rules and is_all_str:- byte_rules = [stem.util.str_tools._to_bytes(r) for r in rules]- self._input_rules = zlib.compress(b','.join(byte_rules))- else:- self._input_rules = rules-- self._rules = None- self._hash = None-- # Result when no rules apply. According to the spec policies default to 'is- # allowed', but our microdescriptor policy subclass might want to change- # this.-- self._is_allowed_default = True-- @lru_cache()- def can_exit_to(self, address = None, port = None, strict = False):- """- Checks if this policy allows exiting to a given destination or not. If the- address or port is omitted then this will check if we're allowed to exit to- any instances of the defined address or port.-- :param str address: IPv4 or IPv6 address (with or without brackets)- :param int port: port number- :param bool strict: if the address or port is excluded then check if we can- exit to **all** instances of the defined address or port-- :returns: **True** if exiting to this destination is allowed, **False** otherwise- """-- for rule in self._get_rules():- if rule.is_match(address, port, strict):- return rule.is_accept-- return self._is_allowed_default-- @lru_cache()- def is_exiting_allowed(self):- """- Provides **True** if the policy allows exiting whatsoever, **False**- otherwise.- """-- rejected_ports = set()-- for rule in self._get_rules():- if rule.is_accept:- for port in range(rule.min_port, rule.max_port + 1):- if port not in rejected_ports:- return True- elif rule.is_address_wildcard():- if rule.is_port_wildcard():- return False- else:- rejected_ports.update(range(rule.min_port, rule.max_port + 1))-- return self._is_allowed_default-- @lru_cache()- def summary(self):- """- Provides a short description of our policy chain, similar to a- microdescriptor. This excludes entries that don't cover all IP- addresses, and is either white-list or blacklist policy based on- the final entry. For instance...-- ::-- >>> policy = ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')- >>> policy.summary()- 'accept 80, 443'-- >>> policy = ExitPolicy('accept *:443', 'reject *:1-1024', 'accept *:*')- >>> policy.summary()- 'reject 1-442, 444-1024'-- :returns: **str** with a concise summary for our policy- """-- # determines if we're a white-list or blacklist- is_whitelist = not self._is_allowed_default-- for rule in self._get_rules():- if rule.is_address_wildcard() and rule.is_port_wildcard():- is_whitelist = not rule.is_accept- break-- # Iterates over the policies and adds the the ports we'll return (ie,- # allows if a white-list and rejects if a blacklist). Regardless of a- # port's allow/reject policy, all further entries with that port are- # ignored since policies respect the first matching policy.-- display_ports, skip_ports = [], set()-- for rule in self._get_rules():- if not rule.is_address_wildcard():- continue- elif rule.is_port_wildcard():- break-- for port in range(rule.min_port, rule.max_port + 1):- if port in skip_ports:- continue-- # if accept + white-list or reject + blacklist then add- if rule.is_accept == is_whitelist:- display_ports.append(port)-- # all further entries with this port should be ignored- skip_ports.add(port)-- # convert port list to a list of ranges (ie, ['1-3'] rather than [1, 2, 3])- if display_ports:- display_ranges, temp_range = [], []- display_ports.sort()- display_ports.append(None) # ending item to include last range in loop-- for port in display_ports:- if not temp_range or temp_range[-1] + 1 == port:- temp_range.append(port)- else:- if len(temp_range) > 1:- display_ranges.append('%i-%i' % (temp_range[0], temp_range[-1]))- else:- display_ranges.append(str(temp_range[0]))-- temp_range = [port]- else:- # everything for the inverse- is_whitelist = not is_whitelist- display_ranges = ['1-65535']-- # constructs the summary string- label_prefix = 'accept ' if is_whitelist else 'reject '-- return (label_prefix + ', '.join(display_ranges)).strip()-- def has_private(self):- """- Checks if we have any rules expanded from the 'private' keyword. Tor- appends these by default to the start of the policy and includes a dynamic- address (the relay's public IP).-- .. versionadded:: 1.3.0-- :returns: **True** if we have any private rules expanded from the 'private'- keyword, **False** otherwise- """-- for rule in self._get_rules():- if rule.is_private():- return True-- return False-- def strip_private(self):- """- Provides a copy of this policy without 'private' policy entries.-- .. versionadded:: 1.3.0-- :returns: **ExitPolicy** without private rules- """-- return ExitPolicy(*[rule for rule in self._get_rules() if not rule.is_private()])-- def has_default(self):- """- Checks if we have the default policy suffix.-- .. versionadded:: 1.3.0-- :returns: **True** if we have the default policy suffix, **False** otherwise- """-- for rule in self._get_rules():- if rule.is_default():- return True-- return False-- def strip_default(self):- """- Provides a copy of this policy without the default policy suffix.-- .. versionadded:: 1.3.0-- :returns: **ExitPolicy** without default rules- """-- return ExitPolicy(*[rule for rule in self._get_rules() if not rule.is_default()])-- def _get_rules(self):- if self._rules is None:- rules = []- is_all_accept, is_all_reject = True, True-- if isinstance(self._input_rules, bytes):- decompressed_rules = zlib.decompress(self._input_rules).split(b',')- else:- decompressed_rules = self._input_rules-- for rule in decompressed_rules:- if isinstance(rule, bytes):- rule = stem.util.str_tools._to_unicode(rule)-- if isinstance(rule, str_type):- rule = ExitPolicyRule(rule.strip())-- if rule.is_accept:- is_all_reject = False- else:- is_all_accept = False-- rules.append(rule)-- if rule.is_address_wildcard() and rule.is_port_wildcard():- break # this is a catch-all, no reason to include more-- # If we only have one kind of entry *and* end with a wildcard then- # we might as well use the simpler version. For instance...- #- # reject *:80, reject *:443, reject *:*- #- # ... could also be represented as simply...- #- # reject *:*- #- # This mostly comes up with reject-all policies because the- # 'reject private:*' appends an extra seven rules that have no- # effect.-- if rules and (rules[-1].is_address_wildcard() and rules[-1].is_port_wildcard()):- if is_all_accept:- rules = [ExitPolicyRule('accept *:*')]- elif is_all_reject:- rules = [ExitPolicyRule('reject *:*')]-- _flag_private_rules(rules)- _flag_default_rules(rules)-- self._rules = rules- self._input_rules = None-- return self._rules-- def __len__(self):- return len(self._get_rules())-- def __iter__(self):- for rule in self._get_rules():- yield rule-- @lru_cache()- def __str__(self):- return ', '.join([str(rule) for rule in self._get_rules()])-- def __hash__(self):- if self._hash is None:- my_hash = 0-- for rule in self._get_rules():- my_hash *= 1024- my_hash += hash(rule)-- self._hash = my_hash-- return self._hash-- def __eq__(self, other):- if isinstance(other, ExitPolicy):- return self._get_rules() == list(other)- else:- return False---class MicroExitPolicy(ExitPolicy):- """- Exit policy provided by the microdescriptors. This is a distilled version of- a normal :class:`~stem.exit_policy.ExitPolicy` contains, just consisting of a- list of ports that are either accepted or rejected. For instance...-- ::-- accept 80,443 # only accepts common http ports- reject 1-1024 # only accepts non-privileged ports-- Since these policies are a subset of the exit policy information (lacking IP- ranges) clients can only use them to guess if a relay will accept traffic or- not. To quote the `dir-spec <https://gitweb.torproject.org/torspec.git/tree/dir-spec.txt>`_ (section 3.2.1)...-- ::-- With microdescriptors, clients don't learn exact exit policies:- clients can only guess whether a relay accepts their request, try the- BEGIN request, and might get end-reason-exit-policy if they guessed- wrong, in which case they'll have to try elsewhere.-- :var bool is_accept: **True** if these are ports that we accept, **False** if- they're ports that we reject-- :param str policy: policy string that describes this policy- """-- def __init__(self, policy):- # Microdescriptor policies are of the form...- #- # MicrodescriptrPolicy ::= ("accept" / "reject") SP PortList NL- # PortList ::= PortOrRange- # PortList ::= PortList "," PortOrRange- # PortOrRange ::= INT "-" INT / INT-- self._policy = policy-- if policy.startswith('accept'):- self.is_accept = True- elif policy.startswith('reject'):- self.is_accept = False- else:- raise ValueError("A microdescriptor exit policy must start with either 'accept' or 'reject': %s" % policy)-- policy = policy[6:]-- if not policy.startswith(' ') or (len(policy) - 1 != len(policy.lstrip())):- raise ValueError('A microdescriptor exit policy should have a space separating accept/reject from its port list: %s' % self._policy)-- policy = policy[1:]-- # convert our port list into MicroExitPolicyRule- rules = []-- for port_entry in policy.split(','):- if '-' in port_entry:- min_port, max_port = port_entry.split('-', 1)- else:- min_port = max_port = port_entry-- if not stem.util.connection.is_valid_port(min_port) or \- not stem.util.connection.is_valid_port(max_port):- raise ValueError("'%s' is an invalid port range" % port_entry)-- rules.append(MicroExitPolicyRule(self.is_accept, int(min_port), int(max_port)))-- super(MicroExitPolicy, self).__init__(*rules)- self._is_allowed_default = not self.is_accept-- def __str__(self):- return self._policy-- def __hash__(self):- return hash(str(self))-- def __eq__(self, other):- if isinstance(other, MicroExitPolicy):- return str(self) == str(other)- else:- return False---class ExitPolicyRule(object):- """- Single rule from the user's exit policy. These rules are chained together to- form complete policies that describe where a relay will and will not allow- traffic to exit.-- The format of these rules are formally described in the `dir-spec- <https://gitweb.torproject.org/torspec.git/tree/dir-spec.txt>`_ as an- 'exitpattern'. Note that while these are similar to tor's man page entry for- ExitPolicies, it's not the exact same. An exitpattern is better defined and- stricter in what it'll accept. For instance, ports are not optional and it- does not contain the 'private' alias.-- This should be treated as an immutable object.-- :var bool is_accept: indicates if exiting is allowed or disallowed-- :var str address: address that this rule is for-- :var int min_port: lower end of the port range that we include (inclusive)- :var int max_port: upper end of the port range that we include (inclusive)-- :param str rule: exit policy rule to be parsed-- :raises: **ValueError** if input isn't a valid tor exit policy rule- """-- def __init__(self, rule):- # policy ::= "accept" exitpattern | "reject" exitpattern- # exitpattern ::= addrspec ":" portspec-- if rule.startswith('accept'):- self.is_accept = True- elif rule.startswith('reject'):- self.is_accept = False- else:- raise ValueError("An exit policy must start with either 'accept' or 'reject': %s" % rule)-- exitpattern = rule[6:]-- if not exitpattern.startswith(' ') or (len(exitpattern) - 1 != len(exitpattern.lstrip())):- raise ValueError('An exit policy should have a space separating its accept/reject from the exit pattern: %s' % rule)-- exitpattern = exitpattern[1:]-- if ':' not in exitpattern:- raise ValueError("An exitpattern must be of the form 'addrspec:portspec': %s" % rule)-- self.address = None- self._address_type = None- self._masked_bits = None- self.min_port = self.max_port = None- self._hash = None-- # Our mask in ip notation (ex. '255.255.255.0'). This is only set if we- # either have a custom mask that can't be represented by a number of bits,- # or the user has called mask(), lazily loading this.-- self._mask = None-- addrspec, portspec = exitpattern.rsplit(':', 1)- self._apply_addrspec(rule, addrspec)- self._apply_portspec(rule, portspec)-- # If true then a submask of /0 is treated by is_address_wildcard() as being- # a wildcard.-- self._submask_wildcard = True-- # Flags to indicate if this rule seems to be expanded from the 'private'- # keyword or tor's default policy suffix.-- self._is_private = False- self._is_default_suffix = False-- def is_address_wildcard(self):- """- **True** if we'll match against any address, **False** otherwise.-- Note that if this policy can apply to both IPv4 and IPv6 then this is- different from being for a /0 (since, for instance, 0.0.0.0/0 wouldn't- match against an IPv6 address). That said, /0 addresses are highly unusual- and most things citing exit policies are IPv4 specific anyway, making this- moot.-- :returns: **bool** for if our address matching is a wildcard- """-- if self._submask_wildcard and self.get_masked_bits() == 0:- return True-- return self._address_type == _address_type_to_int(AddressType.WILDCARD)-- def is_port_wildcard(self):- """- **True** if we'll match against any port, **False** otherwise.-- :returns: **bool** for if our port matching is a wildcard- """-- return self.min_port in (0, 1) and self.max_port == 65535-- def is_match(self, address = None, port = None, strict = False):- """- **True** if we match against the given destination, **False** otherwise. If- the address or port is omitted then this will check if we're allowed to- exit to any instances of the defined address or port.-- :param str address: IPv4 or IPv6 address (with or without brackets)- :param int port: port number- :param bool strict: if the address or port is excluded then check if we can- exit to **all** instances of the defined address or port-- :returns: **bool** indicating if we match against this destination-- :raises: **ValueError** if provided with a malformed address or port- """-- # validate our input and check if the argument doesn't match our address type-- if address is not None:- address_type = self.get_address_type()-- if stem.util.connection.is_valid_ipv4_address(address):- if address_type == AddressType.IPv6:- return False- elif stem.util.connection.is_valid_ipv6_address(address, allow_brackets = True):- if address_type == AddressType.IPv4:- return False-- address = address.lstrip('[').rstrip(']')- else:- raise ValueError("'%s' isn't a valid IPv4 or IPv6 address" % address)-- if port is not None and not stem.util.connection.is_valid_port(port):- raise ValueError("'%s' isn't a valid port" % port)-- # If we're not matching against an address or port but the rule has one- # then we're a fuzzy match. When that happens...- #- # * If strict and a reject rule then we're a match ('can exit to *all* instances').- # * If not strict and an accept rule then match ('an exit ot *any* instance').-- fuzzy_match = False-- if not self.is_address_wildcard():- # Already got the integer representation of our mask and our address- # with the mask applied. Just need to check if this address with the- # mask applied matches.-- if address is None:- fuzzy_match = True- else:- comparison_addr_bin = int(stem.util.connection._get_address_binary(address), 2)- comparison_addr_bin &= self._get_mask_bin()-- if self._get_address_bin() != comparison_addr_bin:- return False-- if not self.is_port_wildcard():- if port is None:- fuzzy_match = True- elif port < self.min_port or port > self.max_port:- return False-- if fuzzy_match:- return strict != self.is_accept- else:- return True-- def get_address_type(self):- """- Provides the :data:`~stem.exit_policy.AddressType` for our policy.-- :returns: :data:`~stem.exit_policy.AddressType` for the type of address that we have- """-- return _int_to_address_type(self._address_type)-- def get_mask(self, cache = True):- """- Provides the address represented by our mask. This is **None** if our- address type is a wildcard.-- :param bool cache: caches the result if **True**-- :returns: str of our subnet mask for the address (ex. '255.255.255.0')- """-- # Lazy loading our mask because it very infrequently requested. There's- # no reason to usually usse memory for it.-- if not self._mask:- address_type = self.get_address_type()-- if address_type == AddressType.WILDCARD:- mask = None- elif address_type == AddressType.IPv4:- mask = stem.util.connection.get_mask_ipv4(self._masked_bits)- elif address_type == AddressType.IPv6:- mask = stem.util.connection.get_mask_ipv6(self._masked_bits)-- if not cache:- return mask-- self._mask = mask-- return self._mask-- def get_masked_bits(self):- """- Provides the number of bits our subnet mask represents. This is **None** if- our mask can't have a bit representation.-- :returns: int with the bit representation of our mask- """-- return self._masked_bits-- def is_private(self):- """- Checks if this rule was expanded from the 'private' policy keyword.-- .. versionadded:: 1.3.0-- :returns: **True** if this rule was expanded from the 'private' keyword, **False** otherwise.- """-- return self._is_private-- def is_default(self):- """- Checks if this rule belongs to the default exit policy suffix.-- .. versionadded:: 1.3.0-- :returns: **True** if this rule was part of the default end of a policy, **False** otherwise.- """-- return self._is_default_suffix-- @lru_cache()- def __str__(self):- """- Provides the string representation of our policy. This does not- necessarily match the rule that we were constructed from (due to things- like IPv6 address collapsing or the multiple representations that our mask- can have). However, it is a valid that would be accepted by our constructor- to re-create this rule.- """-- label = 'accept ' if self.is_accept else 'reject '-- if self.is_address_wildcard():- label += '*:'- else:- address_type = self.get_address_type()-- if address_type == AddressType.IPv4:- label += self.address- else:- label += '[%s]' % self.address-- # Including our mask label as follows...- # - exclude our mask if it doesn't do anything- # - use our masked bit count if we can- # - use the mask itself otherwise-- if (address_type == AddressType.IPv4 and self._masked_bits == 32) or \- (address_type == AddressType.IPv6 and self._masked_bits == 128):- label += ':'- elif self._masked_bits is not None:- label += '/%i:' % self._masked_bits- else:- label += '/%s:' % self.get_mask()-- if self.is_port_wildcard():- label += '*'- elif self.min_port == self.max_port:- label += str(self.min_port)- else:- label += '%i-%i' % (self.min_port, self.max_port)-- return label-- def __hash__(self):- if self._hash is None:- my_hash = 0-- for attr in ('is_accept', 'address', 'min_port', 'max_port'):- my_hash *= 1024-- attr_value = getattr(self, attr)-- if attr_value is not None:- my_hash += hash(attr_value)-- my_hash *= 1024- my_hash += hash(self.get_mask(False))-- self._hash = my_hash-- return self._hash-- @lru_cache()- def _get_mask_bin(self):- # provides an integer representation of our mask-- return int(stem.util.connection._get_address_binary(self.get_mask(False)), 2)-- @lru_cache()- def _get_address_bin(self):- # provides an integer representation of our address-- return int(stem.util.connection._get_address_binary(self.address), 2) & self._get_mask_bin()-- def _apply_addrspec(self, rule, addrspec):- # Parses the addrspec...- # addrspec ::= "*" | ip4spec | ip6spec-- if '/' in addrspec:- self.address, addr_extra = addrspec.split('/', 1)- else:- self.address, addr_extra = addrspec, None-- if addrspec == '*':- self._address_type = _address_type_to_int(AddressType.WILDCARD)- self.address = self._masked_bits = None- elif stem.util.connection.is_valid_ipv4_address(self.address):- # ipv4spec ::= ip4 | ip4 "/" num_ip4_bits | ip4 "/" ip4mask- # ip4 ::= an IPv4 address in dotted-quad format- # ip4mask ::= an IPv4 mask in dotted-quad format- # num_ip4_bits ::= an integer between 0 and 32-- self._address_type = _address_type_to_int(AddressType.IPv4)-- if addr_extra is None:- self._masked_bits = 32- elif stem.util.connection.is_valid_ipv4_address(addr_extra):- # provided with an ip4mask- try:- self._masked_bits = stem.util.connection._get_masked_bits(addr_extra)- except ValueError:- # mask can't be represented as a number of bits (ex. '255.255.0.255')- self._mask = addr_extra- self._masked_bits = None- elif addr_extra.isdigit():- # provided with a num_ip4_bits- self._masked_bits = int(addr_extra)-- if self._masked_bits < 0 or self._masked_bits > 32:- raise ValueError('IPv4 masks must be in the range of 0-32 bits')- else:- raise ValueError("The '%s' isn't a mask nor number of bits: %s" % (addr_extra, rule))- elif self.address.startswith('[') and self.address.endswith(']') and \- stem.util.connection.is_valid_ipv6_address(self.address[1:-1]):- # ip6spec ::= ip6 | ip6 "/" num_ip6_bits- # ip6 ::= an IPv6 address, surrounded by square brackets.- # num_ip6_bits ::= an integer between 0 and 128-- self.address = stem.util.connection.expand_ipv6_address(self.address[1:-1].upper())- self._address_type = _address_type_to_int(AddressType.IPv6)-- if addr_extra is None:- self._masked_bits = 128- elif addr_extra.isdigit():- # provided with a num_ip6_bits- self._masked_bits = int(addr_extra)-- if self._masked_bits < 0 or self._masked_bits > 128:- raise ValueError('IPv6 masks must be in the range of 0-128 bits')- else:- raise ValueError("The '%s' isn't a number of bits: %s" % (addr_extra, rule))- else:- raise ValueError("Address isn't a wildcard, IPv4, or IPv6 address: %s" % rule)-- def _apply_portspec(self, rule, portspec):- # Parses the portspec...- # portspec ::= "*" | port | port "-" port- # port ::= an integer between 1 and 65535, inclusive.- #- # Due to a tor bug the spec says that we should accept port of zero, but- # connections to port zero are never permitted.-- if portspec == '*':- self.min_port, self.max_port = 1, 65535- elif portspec.isdigit():- # provided with a single port- if stem.util.connection.is_valid_port(portspec, allow_zero = True):- self.min_port = self.max_port = int(portspec)- else:- raise ValueError("'%s' isn't within a valid port range: %s" % (portspec, rule))- elif '-' in portspec:- # provided with a port range- port_comp = portspec.split('-', 1)-- if stem.util.connection.is_valid_port(port_comp, allow_zero = True):- self.min_port = int(port_comp[0])- self.max_port = int(port_comp[1])-- if self.min_port > self.max_port:- raise ValueError("Port range has a lower bound that's greater than its upper bound: %s" % rule)- else:- raise ValueError('Malformed port range: %s' % rule)- else:- raise ValueError("Port value isn't a wildcard, integer, or range: %s" % rule)-- def __eq__(self, other):- if isinstance(other, ExitPolicyRule):- # Our string representation encompasses our effective policy. Technically- # this isn't quite right since our rule attribute may differ (ie, 'accept- # 0.0.0.0/0' == 'accept 0.0.0.0/0.0.0.0' will be True), but these- # policies are effectively equivalent.-- return hash(self) == hash(other)- else:- return False---def _address_type_to_int(address_type):- return AddressType.index_of(address_type)---def _int_to_address_type(address_type_int):- return list(AddressType)[address_type_int]---class MicroExitPolicyRule(ExitPolicyRule):- """- Lighter weight ExitPolicyRule derivative for microdescriptors.- """-- def __init__(self, is_accept, min_port, max_port):- self.is_accept = is_accept- self.address = None # wildcard address- self.min_port = min_port- self.max_port = max_port- self._hash = None-- def is_address_wildcard(self):- return True-- def get_address_type(self):- return AddressType.WILDCARD-- def get_mask(self, cache = True):- return None-- def get_masked_bits(self):- return None-- def __hash__(self):- if self._hash is None:- my_hash = 0-- for attr in ('is_accept', 'min_port', 'max_port'):- my_hash *= 1024-- attr_value = getattr(self, attr)-- if attr_value is not None:- my_hash += hash(attr_value)-- self._hash = my_hash-- return self._hash---DEFAULT_POLICY_RULES = tuple([ExitPolicyRule(rule) for rule in (- 'reject *:25',- 'reject *:119',- 'reject *:135-139',- 'reject *:445',- 'reject *:563',- 'reject *:1214',- 'reject *:4661-4666',- 'reject *:6346-6429',- 'reject *:6699',- 'reject *:6881-6999',- 'accept *:*',-)])diff --git a/ext/stem/interpreter/__init__.py b/ext/stem/interpreter/__init__.pydeleted file mode 100644index cf69d63a..00000000--- a/ext/stem/interpreter/__init__.py+++ /dev/null@@ -1,141 +0,0 @@-# Copyright 2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Interactive interpreter for interacting with Tor directly. This adds usability-features such as tab completion, history, and IRC-style functions (like /help).-"""--__all__ = [- 'arguments',- 'autocomplete',- 'commands',- 'help',-]--import os-import sys--import stem-import stem.connection-import stem.prereq-import stem.process-import stem.util.conf-import stem.util.system-import stem.util.term--from stem.util.term import Attr, Color, format--PROMPT = format('>>> ', Color.GREEN, Attr.BOLD, Attr.READLINE_ESCAPE)--STANDARD_OUTPUT = (Color.BLUE, )-BOLD_OUTPUT = (Color.BLUE, Attr.BOLD)-HEADER_OUTPUT = (Color.GREEN, )-HEADER_BOLD_OUTPUT = (Color.GREEN, Attr.BOLD)-ERROR_OUTPUT = (Attr.BOLD, Color.RED)--settings_path = os.path.join(os.path.dirname(__file__), 'settings.cfg')-uses_settings = stem.util.conf.uses_settings('stem_interpreter', settings_path)---@uses_settings-def msg(message, config, **attr):- return config.get(message).format(**attr)---def main():- import readline-- import stem.interpreter.arguments- import stem.interpreter.autocomplete- import stem.interpreter.commands-- try:- args = stem.interpreter.arguments.parse(sys.argv[1:])- except ValueError as exc:- print(exc)- sys.exit(1)-- if args.print_help:- print(stem.interpreter.arguments.get_help())- sys.exit()-- if args.disable_color:- global PROMPT- stem.util.term.DISABLE_COLOR_SUPPORT = True- PROMPT = '>>> '-- # If the user isn't connecting to something in particular then offer to start- # tor if it isn't running.-- if not (args.user_provided_port or args.user_provided_socket):- is_tor_running = stem.util.system.is_running('tor') or stem.util.system.is_running('tor.real')-- if not is_tor_running:- if not stem.util.system.is_available('tor'):- print(format(msg('msg.tor_unavailable'), *ERROR_OUTPUT))- sys.exit(1)- else:- print(format(msg('msg.starting_tor'), *HEADER_OUTPUT))-- stem.process.launch_tor_with_config(- config = {- 'SocksPort': '0',- 'ControlPort': str(args.control_port),- 'CookieAuthentication': '1',- 'ExitPolicy': 'reject *:*',- },- completion_percent = 5,- take_ownership = True,- )-- control_port = (args.control_address, args.control_port)- control_socket = args.control_socket-- # If the user explicitely specified an endpoint then just try to connect to- # that.-- if args.user_provided_socket and not args.user_provided_port:- control_port = None- elif args.user_provided_port and not args.user_provided_socket:- control_socket = None-- controller = stem.connection.connect(- control_port = control_port,- control_socket = control_socket,- password_prompt = True,- )-- if controller is None:- sys.exit(1)-- with controller:- autocompleter = stem.interpreter.autocomplete.Autocompleter(controller)- readline.parse_and_bind('tab: complete')- readline.set_completer(autocompleter.complete)- readline.set_completer_delims('\n')-- interpreter = stem.interpreter.commands.ControlInterpretor(controller)-- for line in msg('msg.startup_banner').splitlines():- line_format = HEADER_BOLD_OUTPUT if line.startswith(' ') else HEADER_OUTPUT- print(format(line, *line_format))-- print('')-- while True:- try:- prompt = '... ' if interpreter.is_multiline_context else PROMPT-- if stem.prereq.is_python_3():- user_input = input(prompt)- else:- user_input = raw_input(prompt)-- response = interpreter.run_command(user_input)-- if response is not None:- print(response)- except (KeyboardInterrupt, EOFError, stem.SocketClosed) as exc:- print('') # move cursor to the following line- breakdiff --git a/ext/stem/interpreter/arguments.py b/ext/stem/interpreter/arguments.pydeleted file mode 100644index eadd0436..00000000--- a/ext/stem/interpreter/arguments.py+++ /dev/null@@ -1,94 +0,0 @@-# Copyright 2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Commandline argument parsing for our interpreter prompt.-"""--import collections-import getopt--import stem.interpreter-import stem.util.connection--DEFAULT_ARGS = {- 'control_address': '127.0.0.1',- 'control_port': 9051,- 'user_provided_port': False,- 'control_socket': '/var/run/tor/control',- 'user_provided_socket': False,- 'disable_color': False,- 'print_help': False,-}--OPT = 'i:s:h'-OPT_EXPANDED = ['interface=', 'socket=', 'no-color', 'help']---def parse(argv):- """- Parses our arguments, providing a named tuple with their values.-- :param list argv: input arguments to be parsed-- :returns: a **named tuple** with our parsed arguments-- :raises: **ValueError** if we got an invalid argument- """-- args = dict(DEFAULT_ARGS)-- try:- recognized_args, unrecognized_args = getopt.getopt(argv, OPT, OPT_EXPANDED)-- if unrecognized_args:- error_msg = "aren't recognized arguments" if len(unrecognized_args) > 1 else "isn't a recognized argument"- raise getopt.GetoptError("'%s' %s" % ("', '".join(unrecognized_args), error_msg))- except Exception as exc:- raise ValueError('%s (for usage provide --help)' % exc)-- for opt, arg in recognized_args:- if opt in ('-i', '--interface'):- if ':' in arg:- address, port = arg.split(':', 1)- else:- address, port = None, arg-- if address is not None:- if not stem.util.connection.is_valid_ipv4_address(address):- raise ValueError("'%s' isn't a valid IPv4 address" % address)-- args['control_address'] = address-- if not stem.util.connection.is_valid_port(port):- raise ValueError("'%s' isn't a valid port number" % port)-- args['control_port'] = int(port)- args['user_provided_port'] = True- elif opt in ('-s', '--socket'):- args['control_socket'] = arg- args['user_provided_socket'] = True- elif opt == '--no-color':- args['disable_color'] = True- elif opt in ('-h', '--help'):- args['print_help'] = True-- # translates our args dict into a named tuple-- Args = collections.namedtuple('Args', args.keys())- return Args(**args)---def get_help():- """- Provides our --help usage information.-- :returns: **str** with our usage information- """-- return stem.interpreter.msg(- 'msg.help',- address = DEFAULT_ARGS['control_address'],- port = DEFAULT_ARGS['control_port'],- socket = DEFAULT_ARGS['control_socket'],- )diff --git a/ext/stem/interpreter/autocomplete.py b/ext/stem/interpreter/autocomplete.pydeleted file mode 100644index a6d940db..00000000--- a/ext/stem/interpreter/autocomplete.py+++ /dev/null@@ -1,115 +0,0 @@-# Copyright 2014-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Tab completion for our interpreter prompt.-"""--from stem.interpreter import uses_settings--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache---@uses_settings-def _get_commands(controller, config):- """- Provides commands recognized by tor.- """-- commands = config.get('autocomplete', [])-- if controller is None:- return commands-- # GETINFO commands. Lines are of the form '[option] -- [description]'. This- # strips '*' from options that accept values.-- results = controller.get_info('info/names', None)-- if results:- for line in results.splitlines():- option = line.split(' ', 1)[0].rstrip('*')- commands.append('GETINFO %s' % option)- else:- commands.append('GETINFO ')-- # GETCONF, SETCONF, and RESETCONF commands. Lines are of the form- # '[option] [type]'.-- results = controller.get_info('config/names', None)-- if results:- for line in results.splitlines():- option = line.split(' ', 1)[0]-- commands.append('GETCONF %s' % option)- commands.append('SETCONF %s' % option)- commands.append('RESETCONF %s' % option)- else:- commands += ['GETCONF ', 'SETCONF ', 'RESETCONF ']-- # SETEVENT, USEFEATURE, and SIGNAL commands. For each of these the GETINFO- # results are simply a space separated lists of the values they can have.-- options = (- ('SETEVENTS ', 'events/names'),- ('USEFEATURE ', 'features/names'),- ('SIGNAL ', 'signal/names'),- )-- for prefix, getinfo_cmd in options:- results = controller.get_info(getinfo_cmd, None)-- if results:- commands += [prefix + value for value in results.split()]- else:- commands.append(prefix)-- # Adds /help commands.-- usage_info = config.get('help.usage', {})-- for cmd in usage_info.keys():- commands.append('/help ' + cmd)-- return commands---class Autocompleter(object):- def __init__(self, controller):- self._commands = _get_commands(controller)-- @lru_cache()- def matches(self, text):- """- Provides autocompletion matches for the given text.-- :param str text: text to check for autocompletion matches with-- :returns: **list** with possible matches- """-- lowercase_text = text.lower()- return [cmd for cmd in self._commands if cmd.lower().startswith(lowercase_text)]-- def complete(self, text, state):- """- Provides case insensetive autocompletion options, acting as a functor for- the readlines set_completer function.-- :param str text: text to check for autocompletion matches with- :param int state: index of result to be provided, readline fetches matches- until this function provides None-- :returns: **str** with the autocompletion match, **None** if eithe none- exists or state is higher than our number of matches- """-- try:- return self.matches(text)[state]- except IndexError:- return Nonediff --git a/ext/stem/interpreter/commands.py b/ext/stem/interpreter/commands.pydeleted file mode 100644index 40475178..00000000--- a/ext/stem/interpreter/commands.py+++ /dev/null@@ -1,354 +0,0 @@-# Copyright 2014-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Handles making requests and formatting the responses.-"""--import code-import socket--import stem-import stem.control-import stem.descriptor.remote-import stem.interpreter.help-import stem.util.connection-import stem.util.str_tools-import stem.util.tor_tools--from stem.interpreter import STANDARD_OUTPUT, BOLD_OUTPUT, ERROR_OUTPUT, uses_settings, msg-from stem.util.term import format---def _get_fingerprint(arg, controller):- """- Resolves user input into a relay fingerprint. This accepts...-- * Fingerprints- * Nicknames- * IPv4 addresses, either with or without an ORPort- * Empty input, which is resolved to ourselves if we're a relay-- :param str arg: input to be resolved to a relay fingerprint- :param stem.control.Controller controller: tor control connection-- :returns: **str** for the relay fingerprint-- :raises: **ValueError** if we're unable to resolve the input to a relay- """-- if not arg:- try:- return controller.get_info('fingerprint')- except:- raise ValueError("We aren't a relay, no information to provide")- elif stem.util.tor_tools.is_valid_fingerprint(arg):- return arg- elif stem.util.tor_tools.is_valid_nickname(arg):- try:- return controller.get_network_status(arg).fingerprint- except:- raise ValueError("Unable to find a relay with the nickname of '%s'" % arg)- elif ':' in arg or stem.util.connection.is_valid_ipv4_address(arg):- if ':' in arg:- address, port = arg.split(':', 1)-- if not stem.util.connection.is_valid_ipv4_address(address):- raise ValueError("'%s' isn't a valid IPv4 address" % address)- elif port and not stem.util.connection.is_valid_port(port):- raise ValueError("'%s' isn't a valid port" % port)-- port = int(port)- else:- address, port = arg, None-- matches = {}-- for desc in controller.get_network_statuses():- if desc.address == address:- if not port or desc.or_port == port:- matches[desc.or_port] = desc.fingerprint-- if len(matches) == 0:- raise ValueError('No relays found at %s' % arg)- elif len(matches) == 1:- return list(matches.values())[0]- else:- response = "There's multiple relays at %s, include a port to specify which.\n\n" % arg-- for i, or_port in enumerate(matches):- response += ' %i. %s:%s, fingerprint: %s\n' % (i + 1, address, or_port, matches[or_port])-- raise ValueError(response)- else:- raise ValueError("'%s' isn't a fingerprint, nickname, or IP address" % arg)---class ControlInterpretor(code.InteractiveConsole):- """- Handles issuing requests and providing nicely formed responses, with support- for special irc style subcommands.- """-- def __init__(self, controller):- self._received_events = []-- code.InteractiveConsole.__init__(self, {- 'stem': stem,- 'stem.control': stem.control,- 'controller': controller,- 'events': self.get_events,- })-- self._controller = controller- self._run_python_commands = True-- # Indicates if we're processing a multiline command, such as conditional- # block or loop.-- self.is_multiline_context = False-- # Intercept events our controller hears about at a pretty low level since- # the user will likely be requesting them by direct 'SETEVENTS' calls.-- handle_event_real = self._controller._handle_event-- def handle_event_wrapper(event_message):- handle_event_real(event_message)- self._received_events.append(event_message)-- self._controller._handle_event = handle_event_wrapper-- def get_events(self, *event_types):- events = list(self._received_events)- event_types = list(map(str.upper, event_types)) # make filtering case insensitive-- if event_types:- events = [e for e in events if e.type in event_types]-- return events-- def do_help(self, arg):- """- Performs the '/help' operation, giving usage information for the given- argument or a general summary if there wasn't one.- """-- return stem.interpreter.help.response(self._controller, arg)-- def do_events(self, arg):- """- Performs the '/events' operation, dumping the events that we've received- belonging to the given types. If no types are specified then this provides- all buffered events.-- If the user runs '/events clear' then this clears the list of events we've- received.- """-- event_types = arg.upper().split()-- if 'CLEAR' in event_types:- del self._received_events[:]- return format('cleared event backlog', *STANDARD_OUTPUT)-- return '\n'.join([format(str(e), *STANDARD_OUTPUT) for e in self.get_events(*event_types)])-- def do_info(self, arg):- """- Performs the '/info' operation, looking up a relay by fingerprint, IP- address, or nickname and printing its descriptor and consensus entries in a- pretty fashion.- """-- try:- fingerprint = _get_fingerprint(arg, self._controller)- except ValueError as exc:- return format(str(exc), *ERROR_OUTPUT)-- ns_desc = self._controller.get_network_status(fingerprint, None)- server_desc = self._controller.get_server_descriptor(fingerprint, None)- extrainfo_desc = None- micro_desc = self._controller.get_microdescriptor(fingerprint, None)-- # We'll mostly rely on the router status entry. Either the server- # descriptor or microdescriptor will be missing, so we'll treat them as- # being optional.-- if not ns_desc:- return format('Unable to find consensus information for %s' % fingerprint, *ERROR_OUTPUT)-- # More likely than not we'll have the microdescriptor but not server and- # extrainfo descriptors. If so then fetching them.-- downloader = stem.descriptor.remote.DescriptorDownloader(timeout = 5)- server_desc_query = downloader.get_server_descriptors(fingerprint)- extrainfo_desc_query = downloader.get_extrainfo_descriptors(fingerprint)-- for desc in server_desc_query:- server_desc = desc-- for desc in extrainfo_desc_query:- extrainfo_desc = desc-- address_extrainfo = []-- try:- address_extrainfo.append(socket.gethostbyaddr(ns_desc.address)[0])- except:- pass-- try:- address_extrainfo.append(self._controller.get_info('ip-to-country/%s' % ns_desc.address))- except:- pass-- address_extrainfo_label = ' (%s)' % ', '.join(address_extrainfo) if address_extrainfo else ''-- if server_desc:- exit_policy_label = str(server_desc.exit_policy)- elif micro_desc:- exit_policy_label = str(micro_desc.exit_policy)- else:- exit_policy_label = 'Unknown'-- lines = [- '%s (%s)' % (ns_desc.nickname, fingerprint),- format('address: ', *BOLD_OUTPUT) + '%s:%s%s' % (ns_desc.address, ns_desc.or_port, address_extrainfo_label),- ]-- if server_desc:- lines.append(format('tor version: ', *BOLD_OUTPUT) + str(server_desc.tor_version))-- lines.append(format('flags: ', *BOLD_OUTPUT) + ', '.join(ns_desc.flags))- lines.append(format('exit policy: ', *BOLD_OUTPUT) + exit_policy_label)-- if server_desc and server_desc.contact:- contact = stem.util.str_tools._to_unicode(server_desc.contact)-- # clears up some highly common obscuring-- for alias in (' at ', ' AT '):- contact = contact.replace(alias, '@')-- for alias in (' dot ', ' DOT '):- contact = contact.replace(alias, '.')-- lines.append(format('contact: ', *BOLD_OUTPUT) + contact)-- descriptor_section = [- ('Server Descriptor:', server_desc),- ('Extrainfo Descriptor:', extrainfo_desc),- ('Microdescriptor:', micro_desc),- ('Router Status Entry:', ns_desc),- ]-- div = format('-' * 80, *STANDARD_OUTPUT)-- for label, desc in descriptor_section:- if desc:- lines += ['', div, format(label, *BOLD_OUTPUT), div, '']- lines += [format(l, *STANDARD_OUTPUT) for l in str(desc).splitlines()]-- return '\n'.join(lines)-- def do_python(self, arg):- """- Performs the '/python' operation, toggling if we accept python commands or- not.- """-- if not arg:- status = 'enabled' if self._run_python_commands else 'disabled'- return format('Python support is currently %s.' % status, *STANDARD_OUTPUT)- elif arg.lower() == 'enable':- self._run_python_commands = True- elif arg.lower() == 'disable':- self._run_python_commands = False- else:- return format("'%s' is not recognized. Please run either '/python enable' or '/python disable'." % arg, *ERROR_OUTPUT)-- if self._run_python_commands:- response = "Python support enabled, we'll now run non-interpreter commands as python."- else:- response = "Python support disabled, we'll now pass along all commands to tor."-- return format(response, *STANDARD_OUTPUT)-- @uses_settings- def run_command(self, command, config):- """- Runs the given command. Requests starting with a '/' are special commands- to the interpreter, and anything else is sent to the control port.-- :param stem.control.Controller controller: tor control connection- :param str command: command to be processed-- :returns: **list** out output lines, each line being a list of- (msg, format) tuples-- :raises: **stem.SocketClosed** if the control connection has been severed- """-- if not self._controller.is_alive():- raise stem.SocketClosed()-- # Commands fall into three categories:- #- # * Interpretor commands. These start with a '/'.- #- # * Controller commands stem knows how to handle. We use our Controller's- # methods for these to take advantage of caching and present nicer- # output.- #- # * Other tor commands. We pass these directly on to the control port.-- cmd, arg = command.strip(), ''-- if ' ' in cmd:- cmd, arg = cmd.split(' ', 1)-- output = ''-- if cmd.startswith('/'):- cmd = cmd.lower()-- if cmd == '/quit':- raise stem.SocketClosed()- elif cmd == '/events':- output = self.do_events(arg)- elif cmd == '/info':- output = self.do_info(arg)- elif cmd == '/python':- output = self.do_python(arg)- elif cmd == '/help':- output = self.do_help(arg)- else:- output = format("'%s' isn't a recognized command" % command, *ERROR_OUTPUT)- else:- cmd = cmd.upper() # makes commands uppercase to match the spec-- if cmd.replace('+', '') in ('LOADCONF', 'POSTDESCRIPTOR'):- # provides a notice that multi-line controller input isn't yet implemented- output = format(msg('msg.multiline_unimplemented_notice'), *ERROR_OUTPUT)- elif cmd == 'QUIT':- self._controller.msg(command)- raise stem.SocketClosed()- else:- is_tor_command = cmd in config.get('help.usage', {}) and cmd.lower() != 'events'-- if self._run_python_commands and not is_tor_command:- self.is_multiline_context = code.InteractiveConsole.push(self, command)- return- else:- try:- output = format(self._controller.msg(command).raw_content().strip(), *STANDARD_OUTPUT)- except stem.ControllerError as exc:- if isinstance(exc, stem.SocketClosed):- raise exc- else:- output = format(str(exc), *ERROR_OUTPUT)-- output += '\n' # give ourselves an extra line before the next prompt-- return outputdiff --git a/ext/stem/interpreter/help.py b/ext/stem/interpreter/help.pydeleted file mode 100644index 83db0b1b..00000000--- a/ext/stem/interpreter/help.py+++ /dev/null@@ -1,145 +0,0 @@-# Copyright 2014-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Provides our /help responses.-"""--from stem.interpreter import (- STANDARD_OUTPUT,- BOLD_OUTPUT,- ERROR_OUTPUT,- msg,- uses_settings,-)--from stem.util.term import format--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache---def response(controller, arg):- """- Provides our /help response.-- :param stem.control.Controller controller: tor control connection- :param str arg: controller or interpreter command to provide help output for-- :returns: **str** with our help response- """-- # Normalizing inputs first so we can better cache responses.-- return _response(controller, _normalize(arg))---def _normalize(arg):- arg = arg.upper()-- # If there's multiple arguments then just take the first. This is- # particularly likely if they're trying to query a full command (for- # instance "/help GETINFO version")-- arg = arg.split(' ')[0]-- # strip slash if someone enters an interpreter command (ex. "/help /help")-- if arg.startswith('/'):- arg = arg[1:]-- return arg---@lru_cache()-@uses_settings-def _response(controller, arg, config):- if not arg:- return _general_help()-- usage_info = config.get('help.usage', {})-- if arg not in usage_info:- return format("No help information available for '%s'..." % arg, *ERROR_OUTPUT)-- output = format(usage_info[arg] + '\n', *BOLD_OUTPUT)-- description = config.get('help.description.%s' % arg.lower(), '')-- for line in description.splitlines():- output += format(' ' + line, *STANDARD_OUTPUT) + '\n'-- output += '\n'-- if arg == 'GETINFO':- results = controller.get_info('info/names', None)-- if results:- for line in results.splitlines():- if ' -- ' in line:- opt, summary = line.split(' -- ', 1)-- output += format('%-33s' % opt, *BOLD_OUTPUT)- output += format(' - %s' % summary, *STANDARD_OUTPUT) + '\n'- elif arg == 'GETCONF':- results = controller.get_info('config/names', None)-- if results:- options = [opt.split(' ', 1)[0] for opt in results.splitlines()]-- for i in range(0, len(options), 2):- line = ''-- for entry in options[i:i + 2]:- line += '%-42s' % entry-- output += format(line.rstrip(), *STANDARD_OUTPUT) + '\n'- elif arg == 'SIGNAL':- signal_options = config.get('help.signal.options', {})-- for signal, summary in signal_options.items():- output += format('%-15s' % signal, *BOLD_OUTPUT)- output += format(' - %s' % summary, *STANDARD_OUTPUT) + '\n'- elif arg == 'SETEVENTS':- results = controller.get_info('events/names', None)-- if results:- entries = results.split()-- # displays four columns of 20 characters-- for i in range(0, len(entries), 4):- line = ''-- for entry in entries[i:i + 4]:- line += '%-20s' % entry-- output += format(line.rstrip(), *STANDARD_OUTPUT) + '\n'- elif arg == 'USEFEATURE':- results = controller.get_info('features/names', None)-- if results:- output += format(results, *STANDARD_OUTPUT) + '\n'- elif arg in ('LOADCONF', 'POSTDESCRIPTOR'):- # gives a warning that this option isn't yet implemented- output += format(msg('msg.multiline_unimplemented_notice'), *ERROR_OUTPUT) + '\n'-- return output.rstrip()---def _general_help():- lines = []-- for line in msg('help.general').splitlines():- div = line.find(' - ')-- if div != -1:- cmd, description = line[:div], line[div:]- lines.append(format(cmd, *BOLD_OUTPUT) + format(description, *STANDARD_OUTPUT))- else:- lines.append(format(line, *BOLD_OUTPUT))-- return '\n'.join(lines)diff --git a/ext/stem/interpreter/settings.cfg b/ext/stem/interpreter/settings.cfgdeleted file mode 100644index 1bacf1cb..00000000--- a/ext/stem/interpreter/settings.cfg+++ /dev/null@@ -1,326 +0,0 @@-################################################################################-#-# Configuration data used by Stem's interpreter prompt.-#-################################################################################-- ##################-# GENERAL MESSAGES #- ##################--msg.multiline_unimplemented_notice Multi-line control options like this are not yet implemented.--msg.help-|Interactive interpreter for Tor. This provides you with direct access-|to Tor's control interface via either python or direct requests.-|-| -i, --interface [ADDRESS:]PORT change control interface from {address}:{port}-| -s, --socket SOCKET_PATH attach using unix domain socket if present,-| SOCKET_PATH defaults to: {socket}-| --no-color disables colorized output-| -h, --help presents this help-|--msg.startup_banner-|Welcome to Stem's interpreter prompt. This provides you with direct access to-|Tor's control interface.-|-|This acts like a standard python interpreter with a Tor connection available-|via your 'controller' variable...-|-| >>> controller.get_info('version')-| '0.2.5.1-alpha-dev (git-245ecfff36c0cecc)'-|-|You can also issue requests directly to Tor...-|-| >>> GETINFO version-| 250-version=0.2.5.1-alpha-dev (git-245ecfff36c0cecc)-| 250 OK-|-|For more information run '/help'.-|--msg.tor_unavailable Tor isn't running and the command currently isn't in your PATH.--msg.starting_tor-|Tor isn't running. Starting a temporary Tor instance for our interpreter to-|interact with. This will have a minimal non-relaying configuration, and be-|shut down when you're done.-|-|---------------------------------------------------------------------------------|-- #################-# OUTPUT OF /HELP #- #################--# Response for the '/help' command without any arguments.--help.general-|Interpretor commands include:-| /help - provides information for interpreter and tor commands-| /events - prints events that we've received-| /info - general information for a relay-| /python - enable or disable support for running python commands-| /quit - shuts down the interpreter-|-|Tor commands include:-| GETINFO - queries information from tor-| GETCONF, SETCONF, RESETCONF - show or edit a configuration option-| SIGNAL - issues control signal to the process (for resetting, stopping, etc)-| SETEVENTS - configures the events tor will notify us of-|-| USEFEATURE - enables custom behavior for the controller-| SAVECONF - writes tor's current configuration to our torrc-| LOADCONF - loads the given input like it was part of our torrc-| MAPADDRESS - replaces requests for one address with another-| POSTDESCRIPTOR - adds a relay descriptor to our cache-| EXTENDCIRCUIT - create or extend a tor circuit-| SETCIRCUITPURPOSE - configures the purpose associated with a circuit-| CLOSECIRCUIT - closes the given circuit-| ATTACHSTREAM - associates an application's stream with a tor circuit-| REDIRECTSTREAM - sets a stream's destination-| CLOSESTREAM - closes the given stream-| ADD_ONION - create a new hidden service-| DEL_ONION - delete a hidden service that was created with ADD_ONION-| HSFETCH - retrieve a hidden service descriptor, providing it in a HS_DESC_CONTENT event-| HSPOST - uploads a hidden service descriptor-| RESOLVE - issues an asynchronous dns or rdns request over tor-| TAKEOWNERSHIP - instructs tor to quit when this control connection is closed-| PROTOCOLINFO - queries version and controller authentication information-| QUIT - disconnect the control connection-|-|For more information use '/help [OPTION]'.--# Usage of tor and interpreter commands.--help.usage HELP => /help [OPTION]-help.usage EVENTS => /events [types]-help.usage INFO => /info [relay fingerprint, nickname, or IP address]-help.usage PYTHON => /python [enable,disable]-help.usage QUIT => /quit-help.usage GETINFO => GETINFO OPTION-help.usage GETCONF => GETCONF OPTION-help.usage SETCONF => SETCONF PARAM[=VALUE]-help.usage RESETCONF => RESETCONF PARAM[=VALUE]-help.usage SIGNAL => SIGNAL SIG-help.usage SETEVENTS => SETEVENTS [EXTENDED] [EVENTS]-help.usage USEFEATURE => USEFEATURE OPTION-help.usage SAVECONF => SAVECONF-help.usage LOADCONF => LOADCONF...-help.usage MAPADDRESS => MAPADDRESS SOURCE_ADDR=DESTINATION_ADDR-help.usage POSTDESCRIPTOR => POSTDESCRIPTOR [purpose=general/controller/bridge] [cache=yes/no]...-help.usage EXTENDCIRCUIT => EXTENDCIRCUIT CircuitID [PATH] [purpose=general/controller]-help.usage SETCIRCUITPURPOSE => SETCIRCUITPURPOSE CircuitID purpose=general/controller-help.usage CLOSECIRCUIT => CLOSECIRCUIT CircuitID [IfUnused]-help.usage ATTACHSTREAM => ATTACHSTREAM StreamID CircuitID [HOP=HopNum]-help.usage REDIRECTSTREAM => REDIRECTSTREAM StreamID Address [Port]-help.usage CLOSESTREAM => CLOSESTREAM StreamID Reason [Flag]-help.usage ADD_ONION => KeyType:KeyBlob [Flags=Flag] (Port=Port [,Target])...-help.usage DEL_ONION => ServiceID-help.usage HSFETCH => HSFETCH (HSAddress/v2-DescId) [SERVER=Server]...-help.usage HSPOST => [SERVER=Server] DESCRIPTOR-help.usage RESOLVE => RESOLVE [mode=reverse] address-help.usage TAKEOWNERSHIP => TAKEOWNERSHIP-help.usage PROTOCOLINFO => PROTOCOLINFO [ProtocolVersion]--# Longer description of what tor and interpreter commands do.--help.description.help-|Provides usage information for the given interpreter, tor command, or tor-|configuration option.-|-|Example:-| /help info # provides a description of the '/info' option-| /help GETINFO # usage information for tor's GETINFO controller option--help.description.events-|Provides events that we've received belonging to the given event types. If-|no types are specified then this provides all the messages that we've-|received.-|-|You can also run '/events clear' to clear the backlog of events we've-|received.--help.description.info-|Provides information for a relay that's currently in the consensus. If no-|relay is specified then this provides information on ourselves.--help.description.python-|Enables or disables support for running python commands. This determines how-|we treat commands this interpreter doesn't recognize...-|-|* If enabled then unrecognized commands are executed as python.-|* If disabled then unrecognized commands are passed along to tor.--help.description.quit-|Terminates the interpreter.--help.description.getinfo-|Queries the tor process for information. Options are...-|--help.description.getconf-|Provides the current value for a given configuration value. Options include...-|--help.description.setconf-|Sets the given configuration parameters. Values can be quoted or non-quoted-|strings, and reverts the option to 0 or NULL if not provided.-|-|Examples:-| * Sets a contact address and resets our family to NULL-| SETCONF MyFamily [email protected]-|-| * Sets an exit policy that only includes port 80/443-| SETCONF ExitPolicy=\"accept *:80, accept *:443, reject *:*\"\--help.description.resetconf-|Reverts the given configuration options to their default values. If a value-|is provided then this behaves in the same way as SETCONF.-|-|Examples:-| * Returns both of our accounting parameters to their defaults-| RESETCONF AccountingMax AccountingStart-|-| * Uses the default exit policy and sets our nickname to be 'Goomba'-| RESETCONF ExitPolicy Nickname=Goomba--help.description.signal-|Issues a signal that tells the tor process to reload its torrc, dump its-|stats, halt, etc.--help.description.setevents-|Sets the events that we will receive. This turns off any events that aren't-|listed so sending 'SETEVENTS' without any values will turn off all event reporting.-|-|For Tor versions between 0.1.1.9 and 0.2.2.1 adding 'EXTENDED' causes some-|events to give us additional information. After version 0.2.2.1 this is-|always on.-|-|Events include...-|--help.description.usefeature-|Customizes the behavior of the control port. Options include...-|--help.description.saveconf-|Writes Tor's current configuration to its torrc.--help.description.loadconf-|Reads the given text like it belonged to our torrc.-|-|Example:-| +LOADCONF-| # sets our exit policy to just accept ports 80 and 443-| ExitPolicy accept *:80-| ExitPolicy accept *:443-| ExitPolicy reject *:*-| .--help.description.mapaddress-|Replaces future requests for one address with another.-|-|Example:-| MAPADDRESS 0.0.0.0=torproject.org 1.2.3.4=tor.freehaven.net--help.description.postdescriptor-|Simulates getting a new relay descriptor.--help.description.extendcircuit-|Extends the given circuit or create a new one if the CircuitID is zero. The-|PATH is a comma separated list of fingerprints. If it isn't set then this-|uses Tor's normal path selection.--help.description.setcircuitpurpose-|Sets the purpose attribute for a circuit.--help.description.closecircuit-|Closes the given circuit. If "IfUnused" is included then this only closes-|the circuit if it isn't currently being used.--help.description.attachstream-|Attaches a stream with the given built circuit (tor picks one on its own if-|CircuitID is zero). If HopNum is given then this hop is used to exit the-|circuit, otherwise the last relay is used.--help.description.redirectstream-|Sets the destination for a given stream. This can only be done after a-|stream is created but before it's attached to a circuit.--help.description.closestream-|Closes the given stream, the reason being an integer matching a reason as-|per section 6.3 of the tor-spec.--help.description.add_onion-|Creates a new hidden service. Unlike 'SETCONF HiddenServiceDir...' this-|doesn't persist the service to disk.--help.description.del_onion-|Delete a hidden service that was created with ADD_ONION.--help.description.hsfetch-|Retrieves the descriptor for a hidden service. This is an asynchronous-|request, with the descriptor provided by a HS_DESC_CONTENT event.--help.description.hspost-|Uploads a descriptor to a hidden service directory.--help.description.resolve-|Performs IPv4 DNS resolution over tor, doing a reverse lookup instead if-|"mode=reverse" is included. This request is processed in the background and-|results in a ADDRMAP event with the response.--help.description.takeownership-|Instructs Tor to gracefully shut down when this control connection is closed.--help.description.protocolinfo-|Provides bootstrapping information that a controller might need when first-|starting, like Tor's version and controller authentication. This can be done-|before authenticating to the control port.--help.signal.options RELOAD / HUP => reload our torrc-help.signal.options SHUTDOWN / INT => gracefully shut down, waiting 30 seconds if we're a relay-help.signal.options DUMP / USR1 => logs information about open connections and circuits-help.signal.options DEBUG / USR2 => makes us log at the DEBUG runlevel-help.signal.options HALT / TERM => immediately shut down-help.signal.options CLEARDNSCACHE => clears any cached DNS results-help.signal.options NEWNYM => clears the DNS cache and uses new circuits for future connections-- ################-# TAB COMPLETION #- ################--# Commands we'll autocomplete when the user hits tab. This is just the start of-# our autocompletion list - more are determined dynamically by checking what-# tor supports.--autocomplete /help-autocomplete /events-autocomplete /info-autocomplete /quit-autocomplete SAVECONF-autocomplete MAPADDRESS-autocomplete EXTENDCIRCUIT-autocomplete SETCIRCUITPURPOSE-autocomplete SETROUTERPURPOSE-autocomplete ATTACHSTREAM-#autocomplete +POSTDESCRIPTOR # TODO: needs multi-line support-autocomplete REDIRECTSTREAM-autocomplete CLOSESTREAM-autocomplete CLOSECIRCUIT-autocomplete QUIT-autocomplete RESOLVE-autocomplete PROTOCOLINFO-#autocomplete +LOADCONF # TODO: needs multi-line support-autocomplete TAKEOWNERSHIP-autocomplete AUTHCHALLENGE-autocomplete DROPGUARDS-autocomplete ADD_ONION NEW:BEST-autocomplete ADD_ONION NEW:RSA1024-autocomplete ADD_ONION RSA1024:-autocomplete DEL_ONION-autocomplete HSFETCH-autocomplete HSPOST-diff --git a/ext/stem/prereq.py b/ext/stem/prereq.pydeleted file mode 100644index 5ed87efc..00000000--- a/ext/stem/prereq.py+++ /dev/null@@ -1,132 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Checks for stem dependencies. We require python 2.6 or greater (including the-3.x series). Other requirements for complete functionality are...--* pycrypto module-- * validating descriptor signature integrity--::-- check_requirements - checks for minimum requirements for running stem-- is_python_27 - checks if python 2.7 or later is available- is_python_3 - checks if python 3.0 or later is available-- is_crypto_available - checks if the pycrypto module is available-"""--import inspect-import sys--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache--CRYPTO_UNAVAILABLE = "Unable to import the pycrypto module. Because of this we'll be unable to verify descriptor signature integrity. You can get pycrypto from: https://www.dlitz.net/software/pycrypto/"---def check_requirements():- """- Checks that we meet the minimum requirements to run stem. If we don't then- this raises an ImportError with the issue.-- :raises: **ImportError** with the problem if we don't meet stem's- requirements- """-- major_version, minor_version = sys.version_info[0:2]-- if major_version < 2 or (major_version == 2 and minor_version < 6):- raise ImportError('stem requires python version 2.6 or greater')---def is_python_27():- """- Checks if we're running python 2.7 or above (including the 3.x series).-- :returns: **True** if we meet this requirement and **False** otherwise- """-- major_version, minor_version = sys.version_info[0:2]-- return major_version > 2 or (major_version == 2 and minor_version >= 7)---def is_python_3():- """- Checks if we're in the 3.0 - 3.x range.-- :returns: **True** if we meet this requirement and **False** otherwise- """-- return sys.version_info[0] == 3---@lru_cache()-def is_crypto_available():- """- Checks if the pycrypto functions we use are available. This is used for- verifying relay descriptor signatures.-- :returns: **True** if we can use pycrypto and **False** otherwise- """-- from stem.util import log-- try:- from Crypto.PublicKey import RSA- from Crypto.Util import asn1- from Crypto.Util.number import long_to_bytes- return True- except ImportError:- log.log_once('stem.prereq.is_crypto_available', log.INFO, CRYPTO_UNAVAILABLE)- return False---@lru_cache()-def is_mock_available():- """- Checks if the mock module is available. In python 3.3 and up it is a builtin- unittest module, but before this it needed to be `installed separately- <https://pypi.python.org/pypi/mock/>`_. Imports should be as follows....-- ::-- try:- # added in python 3.3- from unittest.mock import Mock- except ImportError:- from mock import Mock-- :returns: **True** if the mock module is available and **False** otherwise- """-- try:- # checks for python 3.3 version- import unittest.mock- return True- except ImportError:- pass-- try:- import mock-- # check for mock's patch.dict() which was introduced in version 0.7.0-- if not hasattr(mock.patch, 'dict'):- raise ImportError()-- # check for mock's new_callable argument for patch() which was introduced in version 0.8.0-- if 'new_callable' not in inspect.getargspec(mock.patch).args:- raise ImportError()-- return True- except ImportError:- return Falsediff --git a/ext/stem/process.py b/ext/stem/process.pydeleted file mode 100644index b8b1f92f..00000000--- a/ext/stem/process.py+++ /dev/null@@ -1,272 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Helper functions for working with tor as a process.--:NO_TORRC:- when provided as a torrc_path tor is ran with a blank configuration--:DEFAULT_INIT_TIMEOUT:- number of seconds before we time out our attempt to start a tor instance--**Module Overview:**--::-- launch_tor - starts up a tor process- launch_tor_with_config - starts a tor process with a custom torrc-"""--import os-import re-import signal-import subprocess-import tempfile--import stem.prereq-import stem.util.str_tools-import stem.util.system-import stem.version--NO_TORRC = '<no torrc>'-DEFAULT_INIT_TIMEOUT = 90---def launch_tor(tor_cmd = 'tor', args = None, torrc_path = None, completion_percent = 100, init_msg_handler = None, timeout = DEFAULT_INIT_TIMEOUT, take_ownership = False, stdin = None):- """- Initializes a tor process. This blocks until initialization completes or we- error out.-- If tor's data directory is missing or stale then bootstrapping will include- making several requests to the directory authorities which can take a little- while. Usually this is done in 50 seconds or so, but occasionally calls seem- to get stuck, taking well over the default timeout.-- **To work to must log at NOTICE runlevel to stdout.** It does this by- default, but if you have a 'Log' entry in your torrc then you'll also need- 'Log NOTICE stdout'.-- Note: The timeout argument does not work on Windows, and relies on the global- state of the signal module.-- :param str tor_cmd: command for starting tor- :param list args: additional arguments for tor- :param str torrc_path: location of the torrc for us to use- :param int completion_percent: percent of bootstrap completion at which- this'll return- :param functor init_msg_handler: optional functor that will be provided with- tor's initialization stdout as we get it- :param int timeout: time after which the attempt to start tor is aborted, no- timeouts are applied if **None**- :param bool take_ownership: asserts ownership over the tor process so it- aborts if this python process terminates or a :class:`~stem.control.Controller`- we establish to it disconnects- :param str stdin: content to provide on stdin-- :returns: **subprocess.Popen** instance for the tor subprocess-- :raises: **OSError** if we either fail to create the tor process or reached a- timeout without success- """-- if stem.util.system.is_windows():- timeout = None-- # sanity check that we got a tor binary-- if os.path.sep in tor_cmd:- # got a path (either relative or absolute), check what it leads to-- if os.path.isdir(tor_cmd):- raise OSError("'%s' is a directory, not the tor executable" % tor_cmd)- elif not os.path.isfile(tor_cmd):- raise OSError("'%s' doesn't exist" % tor_cmd)- elif not stem.util.system.is_available(tor_cmd):- raise OSError("'%s' isn't available on your system. Maybe it's not in your PATH?" % tor_cmd)-- # double check that we have a torrc to work with- if torrc_path not in (None, NO_TORRC) and not os.path.exists(torrc_path):- raise OSError("torrc doesn't exist (%s)" % torrc_path)-- # starts a tor subprocess, raising an OSError if it fails- runtime_args, temp_file = [tor_cmd], None-- if args:- runtime_args += args-- if torrc_path:- if torrc_path == NO_TORRC:- temp_file = tempfile.mkstemp(prefix = 'empty-torrc-', text = True)[1]- runtime_args += ['-f', temp_file]- else:- runtime_args += ['-f', torrc_path]-- if take_ownership:- runtime_args += ['__OwningControllerProcess', str(os.getpid())]-- tor_process = subprocess.Popen(runtime_args, stdout = subprocess.PIPE, stdin = subprocess.PIPE, stderr = subprocess.PIPE)-- if stdin:- tor_process.stdin.write(stem.util.str_tools._to_bytes(stdin))- tor_process.stdin.close()-- if timeout:- def timeout_handler(signum, frame):- # terminates the uninitialized tor process and raise on timeout-- tor_process.kill()- raise OSError('reached a %i second timeout without success' % timeout)-- signal.signal(signal.SIGALRM, timeout_handler)- signal.alarm(timeout)-- bootstrap_line = re.compile('Bootstrapped ([0-9]+)%: ')- problem_line = re.compile('\[(warn|err)\] (.*)$')- last_problem = 'Timed out'-- try:- while True:- # Tor's stdout will be read as ASCII bytes. This is fine for python 2, but- # in python 3 that means it'll mismatch with other operations (for instance- # the bootstrap_line.search() call later will fail).- #- # It seems like python 2.x is perfectly happy for this to be unicode, so- # normalizing to that.-- init_line = tor_process.stdout.readline().decode('utf-8', 'replace').strip()-- # this will provide empty results if the process is terminated-- if not init_line:- tor_process.kill() # ... but best make sure- raise OSError('Process terminated: %s' % last_problem)-- # provide the caller with the initialization message if they want it-- if init_msg_handler:- init_msg_handler(init_line)-- # return the process if we're done with bootstrapping-- bootstrap_match = bootstrap_line.search(init_line)- problem_match = problem_line.search(init_line)-- if bootstrap_match and int(bootstrap_match.group(1)) >= completion_percent:- return tor_process- elif problem_match:- runlevel, msg = problem_match.groups()-- if 'see warnings above' not in msg:- if ': ' in msg:- msg = msg.split(': ')[-1].strip()-- last_problem = msg- finally:- if timeout:- signal.alarm(0) # stop alarm-- tor_process.stdout.close()- tor_process.stderr.close()-- if temp_file:- try:- os.remove(temp_file)- except:- pass---def launch_tor_with_config(config, tor_cmd = 'tor', completion_percent = 100, init_msg_handler = None, timeout = DEFAULT_INIT_TIMEOUT, take_ownership = False):- """- Initializes a tor process, like :func:`~stem.process.launch_tor`, but with a- customized configuration. This writes a temporary torrc to disk, launches- tor, then deletes the torrc.-- For example...-- ::-- tor_process = stem.process.launch_tor_with_config(- config = {- 'ControlPort': '2778',- 'Log': [- 'NOTICE stdout',- 'ERR file /tmp/tor_error_log',- ],- },- )-- :param dict config: configuration options, such as "{'ControlPort': '9051'}",- values can either be a **str** or **list of str** if for multiple values- :param str tor_cmd: command for starting tor- :param int completion_percent: percent of bootstrap completion at which- this'll return- :param functor init_msg_handler: optional functor that will be provided with- tor's initialization stdout as we get it- :param int timeout: time after which the attempt to start tor is aborted, no- timeouts are applied if **None**- :param bool take_ownership: asserts ownership over the tor process so it- aborts if this python process terminates or a :class:`~stem.control.Controller`- we establish to it disconnects-- :returns: **subprocess.Popen** instance for the tor subprocess-- :raises: **OSError** if we either fail to create the tor process or reached a- timeout without success- """-- # TODO: Drop this version check when tor 0.2.6.3 or higher is the only game- # in town.-- try:- use_stdin = stem.version.get_system_tor_version(tor_cmd) >= stem.version.Requirement.TORRC_VIA_STDIN- except IOError:- use_stdin = False-- # we need to be sure that we're logging to stdout to figure out when we're- # done bootstrapping-- if 'Log' in config:- stdout_options = ['DEBUG stdout', 'INFO stdout', 'NOTICE stdout']-- if isinstance(config['Log'], str):- config['Log'] = [config['Log']]-- has_stdout = False-- for log_config in config['Log']:- if log_config in stdout_options:- has_stdout = True- break-- if not has_stdout:- config['Log'].append('NOTICE stdout')-- config_str = ''-- for key, values in list(config.items()):- if isinstance(values, str):- config_str += '%s %s\n' % (key, values)- else:- for value in values:- config_str += '%s %s\n' % (key, value)-- if use_stdin:- return launch_tor(tor_cmd, ['-f', '-'], None, completion_percent, init_msg_handler, timeout, take_ownership, stdin = config_str)- else:- torrc_descriptor, torrc_path = tempfile.mkstemp(prefix = 'torrc-', text = True)-- try:- with open(torrc_path, 'w') as torrc_file:- torrc_file.write(config_str)-- # prevents tor from erroring out due to a missing torrc if it gets a sighup- args = ['__ReloadTorrcOnSIGHUP', '0']-- return launch_tor(tor_cmd, args, torrc_path, completion_percent, init_msg_handler, timeout, take_ownership)- finally:- try:- os.close(torrc_descriptor)- os.remove(torrc_path)- except:- passdiff --git a/ext/stem/response/__init__.py b/ext/stem/response/__init__.pydeleted file mode 100644index df534a91..00000000--- a/ext/stem/response/__init__.py+++ /dev/null@@ -1,588 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Parses replies from the control socket.--**Module Overview:**--::-- convert - translates a ControlMessage into a particular response subclass-- ControlMessage - Message that's read from the control socket.- |- SingleLineResponse - Simple tor response only including a single line of information.- |- |- from_str - provides a ControlMessage for the given string- |- is_ok - response had a 250 status- |- content - provides the parsed message content- |- raw_content - unparsed socket data- |- __str__ - content stripped of protocol formatting- +- __iter__ - ControlLine entries for the content of the message-- ControlLine - String subclass with methods for parsing controller responses.- |- remainder - provides the unparsed content- |- is_empty - checks if the remaining content is empty- |- is_next_quoted - checks if the next entry is a quoted value- |- is_next_mapping - checks if the next entry is a KEY=VALUE mapping- |- peek_key - provides the key of the next entry- |- pop - removes and returns the next entry- +- pop_mapping - removes and returns the next entry as a KEY=VALUE mapping-"""--__all__ = [- 'add_onion',- 'events',- 'getinfo',- 'getconf',- 'protocolinfo',- 'authchallenge',- 'convert',- 'ControlMessage',- 'ControlLine',- 'SingleLineResponse',-]--import re-import threading--try:- from StringIO import StringIO-except ImportError:- from io import StringIO--import stem.socket--KEY_ARG = re.compile('^(\S+)=')--# Escape sequences from the 'esc_for_log' function of tor's 'common/util.c'.-# It's hard to tell what controller functions use this in practice, but direct-# users are...-# - 'COOKIEFILE' field of PROTOCOLINFO responses-# - logged messages about bugs-# - the 'getinfo_helper_listeners' function of control.c--CONTROL_ESCAPES = {r'\\': '\\', r'\"': '\"', r'\'': '\'',- r'\r': '\r', r'\n': '\n', r'\t': '\t'}---def convert(response_type, message, **kwargs):- """- Converts a :class:`~stem.response.ControlMessage` into a particular kind of- tor response. This does an in-place conversion of the message from being a- :class:`~stem.response.ControlMessage` to a subclass for its response type.- Recognized types include...-- =================== =====- response_type Class- =================== =====- **GETINFO** :class:`stem.response.getinfo.GetInfoResponse`- **GETCONF** :class:`stem.response.getconf.GetConfResponse`- **MAPADDRESS** :class:`stem.response.mapaddress.MapAddressResponse`- **EVENT** :class:`stem.response.events.Event` subclass- **PROTOCOLINFO** :class:`stem.response.protocolinfo.ProtocolInfoResponse`- **AUTHCHALLENGE** :class:`stem.response.authchallenge.AuthChallengeResponse`- **SINGLELINE** :class:`stem.response.SingleLineResponse`- =================== =====-- :param str response_type: type of tor response to convert to- :param stem.response.ControlMessage message: message to be converted- :param kwargs: optional keyword arguments to be passed to the parser method-- :raises:- * :class:`stem.ProtocolError` the message isn't a proper response of- that type- * :class:`stem.InvalidArguments` the arguments given as input are- invalid, this is can only be raised if the response_type is: **GETINFO**,- **GETCONF**- * :class:`stem.InvalidRequest` the arguments given as input are- invalid, this is can only be raised if the response_type is:- **MAPADDRESS**- * :class:`stem.OperationFailed` if the action the event represents failed,- this is can only be raised if the response_type is: **MAPADDRESS**- * **TypeError** if argument isn't a :class:`~stem.response.ControlMessage`- or response_type isn't supported- """-- import stem.response.add_onion- import stem.response.authchallenge- import stem.response.events- import stem.response.getinfo- import stem.response.getconf- import stem.response.mapaddress- import stem.response.protocolinfo-- if not isinstance(message, ControlMessage):- raise TypeError('Only able to convert stem.response.ControlMessage instances')-- response_types = {- 'ADD_ONION': stem.response.add_onion.AddOnionResponse,- 'AUTHCHALLENGE': stem.response.authchallenge.AuthChallengeResponse,- 'EVENT': stem.response.events.Event,- 'GETINFO': stem.response.getinfo.GetInfoResponse,- 'GETCONF': stem.response.getconf.GetConfResponse,- 'MAPADDRESS': stem.response.mapaddress.MapAddressResponse,- 'SINGLELINE': SingleLineResponse,- 'PROTOCOLINFO': stem.response.protocolinfo.ProtocolInfoResponse,- }-- try:- response_class = response_types[response_type]- except TypeError:- raise TypeError('Unsupported response type: %s' % response_type)-- message.__class__ = response_class- message._parse_message(**kwargs)---class ControlMessage(object):- """- Message from the control socket. This is iterable and can be stringified for- individual message components stripped of protocol formatting. Messages are- never empty.- """-- @staticmethod- def from_str(content, msg_type = None, **kwargs):- """- Provides a ControlMessage for the given content.-- .. versionadded:: 1.1.0-- :param str content: message to construct the message from- :param str msg_type: type of tor reply to parse the content as- :param kwargs: optional keyword arguments to be passed to the parser method-- :returns: stem.response.ControlMessage instance- """-- msg = stem.socket.recv_message(StringIO(content))-- if msg_type is not None:- convert(msg_type, msg, **kwargs)-- return msg-- def __init__(self, parsed_content, raw_content):- if not parsed_content:- raise ValueError("ControlMessages can't be empty")-- self._parsed_content = parsed_content- self._raw_content = raw_content-- def is_ok(self):- """- Checks if any of our lines have a 250 response.-- :returns: **True** if any lines have a 250 response code, **False** otherwise- """-- for code, _, _ in self._parsed_content:- if code == '250':- return True-- return False-- def content(self, get_bytes = False):- """- Provides the parsed message content. These are entries of the form...-- ::-- (status_code, divider, content)-- **status_code**- Three character code for the type of response (defined in section 4 of- the control-spec).-- **divider**- Single character to indicate if this is mid-reply, data, or an end to the- message (defined in section 2.3 of the control-spec).-- **content**- The following content is the actual payload of the line.-- For data entries the content is the full multi-line payload with newline- linebreaks and leading periods unescaped.-- The **status_code** and **divider** are both strings (**bytes** in python- 2.x and **unicode** in python 3.x). The **content** however is **bytes** if- **get_bytes** is **True**.-- .. versionchanged:: 1.1.0- Added the get_bytes argument.-- :param bool get_bytes: provides **bytes** for the **content** rather than a **str**-- :returns: **list** of (str, str, str) tuples for the components of this message- """-- if stem.prereq.is_python_3() and not get_bytes:- return [(code, div, stem.util.str_tools._to_unicode(content)) for (code, div, content) in self._parsed_content]- else:- return list(self._parsed_content)-- def raw_content(self, get_bytes = False):- """- Provides the unparsed content read from the control socket.-- .. versionchanged:: 1.1.0- Added the get_bytes argument.-- :param bool get_bytes: if **True** then this provides **bytes** rather than a **str**-- :returns: **str** of the socket data used to generate this message- """-- if stem.prereq.is_python_3() and not get_bytes:- return stem.util.str_tools._to_unicode(self._raw_content)- else:- return self._raw_content-- def __str__(self):- """- Content of the message, stripped of status code and divider protocol- formatting.- """-- return '\n'.join(list(self))-- def __iter__(self):- """- Provides :class:`~stem.response.ControlLine` instances for the content of- the message. This is stripped of status codes and dividers, for instance...-- ::-- 250+info/names=- desc/id/* -- Router descriptors by ID.- desc/name/* -- Router descriptors by nickname.- .- 250 OK-- Would provide two entries...-- ::-- 1st - "info/names=- desc/id/* -- Router descriptors by ID.- desc/name/* -- Router descriptors by nickname."- 2nd - "OK"- """-- for _, _, content in self._parsed_content:- if stem.prereq.is_python_3():- content = stem.util.str_tools._to_unicode(content)-- yield ControlLine(content)-- def __len__(self):- """- :returns: number of ControlLines- """-- return len(self._parsed_content)-- def __getitem__(self, index):- """- :returns: :class:`~stem.response.ControlLine` at the index- """-- content = self._parsed_content[index][2]-- if stem.prereq.is_python_3():- content = stem.util.str_tools._to_unicode(content)-- return ControlLine(content)---class ControlLine(str):- """- String subclass that represents a line of controller output. This behaves as- a normal string with additional methods for parsing and popping entries from- a space delimited series of elements like a stack.-- None of these additional methods effect ourselves as a string (which is still- immutable). All methods are thread safe.- """-- def __new__(self, value):- return str.__new__(self, value)-- def __init__(self, value):- self._remainder = value- self._remainder_lock = threading.RLock()-- def remainder(self):- """- Provides our unparsed content. This is an empty string after we've popped- all entries.-- :returns: **str** of the unparsed content- """-- return self._remainder-- def is_empty(self):- """- Checks if we have further content to pop or not.-- :returns: **True** if we have additional content, **False** otherwise- """-- return self._remainder == ''-- def is_next_quoted(self, escaped = False):- """- Checks if our next entry is a quoted value or not.-- :param bool escaped: unescapes the CONTROL_ESCAPES escape sequences-- :returns: **True** if the next entry can be parsed as a quoted value, **False** otherwise- """-- start_quote, end_quote = _get_quote_indices(self._remainder, escaped)- return start_quote == 0 and end_quote != -1-- def is_next_mapping(self, key = None, quoted = False, escaped = False):- """- Checks if our next entry is a KEY=VALUE mapping or not.-- :param str key: checks that the key matches this value, skipping the check if **None**- :param bool quoted: checks that the mapping is to a quoted value- :param bool escaped: unescapes the CONTROL_ESCAPES escape sequences-- :returns: **True** if the next entry can be parsed as a key=value mapping,- **False** otherwise- """-- remainder = self._remainder # temp copy to avoid locking- key_match = KEY_ARG.match(remainder)-- if key_match:- if key and key != key_match.groups()[0]:- return False-- if quoted:- # checks that we have a quoted value and that it comes after the 'key='- start_quote, end_quote = _get_quote_indices(remainder, escaped)- return start_quote == key_match.end() and end_quote != -1- else:- return True # we just needed to check for the key- else:- return False # doesn't start with a key-- def peek_key(self):- """- Provides the key of the next entry, providing **None** if it isn't a- key/value mapping.-- :returns: **str** with the next entry's key- """-- remainder = self._remainder- key_match = KEY_ARG.match(remainder)-- if key_match:- return key_match.groups()[0]- else:- return None-- def pop(self, quoted = False, escaped = False):- """- Parses the next space separated entry, removing it and the space from our- remaining content. Examples...-- ::-- >>> line = ControlLine("\\"We're all mad here.\\" says the grinning cat.")- >>> print line.pop(True)- "We're all mad here."- >>> print line.pop()- "says"- >>> print line.remainder()- "the grinning cat."-- >>> line = ControlLine("\\"this has a \\\\\\" and \\\\\\\\ in it\\" foo=bar more_data")- >>> print line.pop(True, True)- "this has a \\" and \\\\ in it"-- :param bool quoted: parses the next entry as a quoted value, removing the quotes- :param bool escaped: unescapes the CONTROL_ESCAPES escape sequences-- :returns: **str** of the next space separated entry-- :raises:- * **ValueError** if quoted is True without the value being quoted- * **IndexError** if we don't have any remaining content left to parse- """-- with self._remainder_lock:- next_entry, remainder = _parse_entry(self._remainder, quoted, escaped)- self._remainder = remainder- return next_entry-- def pop_mapping(self, quoted = False, escaped = False):- """- Parses the next space separated entry as a KEY=VALUE mapping, removing it- and the space from our remaining content.-- :param bool quoted: parses the value as being quoted, removing the quotes- :param bool escaped: unescapes the CONTROL_ESCAPES escape sequences-- :returns: **tuple** of the form (key, value)-- :raises: **ValueError** if this isn't a KEY=VALUE mapping or if quoted is- **True** without the value being quoted- :raises: **IndexError** if there's nothing to parse from the line- """-- with self._remainder_lock:- if self.is_empty():- raise IndexError('no remaining content to parse')-- key_match = KEY_ARG.match(self._remainder)-- if not key_match:- raise ValueError("the next entry isn't a KEY=VALUE mapping: " + self._remainder)-- # parse off the key- key = key_match.groups()[0]- remainder = self._remainder[key_match.end():]-- next_entry, remainder = _parse_entry(remainder, quoted, escaped)- self._remainder = remainder- return (key, next_entry)---def _parse_entry(line, quoted, escaped):- """- Parses the next entry from the given space separated content.-- :param str line: content to be parsed- :param bool quoted: parses the next entry as a quoted value, removing the quotes- :param bool escaped: unescapes the CONTROL_ESCAPES escape sequences-- :returns: **tuple** of the form (entry, remainder)-- :raises:- * **ValueError** if quoted is True without the next value being quoted- * **IndexError** if there's nothing to parse from the line- """-- if line == '':- raise IndexError('no remaining content to parse')-- next_entry, remainder = '', line-- if quoted:- # validate and parse the quoted value- start_quote, end_quote = _get_quote_indices(remainder, escaped)-- if start_quote != 0 or end_quote == -1:- raise ValueError("the next entry isn't a quoted value: " + line)-- next_entry, remainder = remainder[1:end_quote], remainder[end_quote + 1:]- else:- # non-quoted value, just need to check if there's more data afterward- if ' ' in remainder:- next_entry, remainder = remainder.split(' ', 1)- else:- next_entry, remainder = remainder, ''-- if escaped:- next_entry = _unescape(next_entry)-- return (next_entry, remainder.lstrip())---def _get_quote_indices(line, escaped):- """- Provides the indices of the next two quotes in the given content.-- :param str line: content to be parsed- :param bool escaped: unescapes the CONTROL_ESCAPES escape sequences-- :returns: **tuple** of two ints, indices being -1 if a quote doesn't exist- """-- indices, quote_index = [], -1-- for _ in range(2):- quote_index = line.find('"', quote_index + 1)-- # if we have escapes then we need to skip any r'\"' entries- if escaped:- # skip check if index is -1 (no match) or 0 (first character)- while quote_index >= 1 and line[quote_index - 1] == '\\':- quote_index = line.find('"', quote_index + 1)-- indices.append(quote_index)-- return tuple(indices)---def _unescape(entry):- # Unescapes the given string with the mappings in CONTROL_ESCAPES.- #- # This can't be a simple series of str.replace() calls because replacements- # need to be excluded from consideration for further unescaping. For- # instance, '\\t' should be converted to '\t' rather than a tab.-- def _pop_with_unescape(entry):- # Pop either the first character or the escape sequence conversion the- # entry starts with. This provides a tuple of...- #- # (unescaped prefix, remaining entry)-- for esc_sequence, replacement in CONTROL_ESCAPES.items():- if entry.startswith(esc_sequence):- return (replacement, entry[len(esc_sequence):])-- return (entry[0], entry[1:])-- result = []-- while entry:- prefix, entry = _pop_with_unescape(entry)- result.append(prefix)-- return ''.join(result)---class SingleLineResponse(ControlMessage):- """- Reply to a request that performs an action rather than querying data. These- requests only contain a single line, which is 'OK' if successful, and a- description of the problem if not.-- :var str code: status code for our line- :var str message: content of the line- """-- def is_ok(self, strict = False):- """- Checks if the response code is "250". If strict is **True** then this- checks if the response is "250 OK"-- :param bool strict: checks for a "250 OK" message if **True**-- :returns:- * If strict is **False**: **True** if the response code is "250", **False** otherwise- * If strict is **True**: **True** if the response is "250 OK", **False** otherwise- """-- if strict:- return self.content()[0] == ('250', ' ', 'OK')-- return self.content()[0][0] == '250'-- def _parse_message(self):- content = self.content()-- if len(content) > 1:- raise stem.ProtocolError('Received multi-line response')- elif len(content) == 0:- raise stem.ProtocolError('Received empty response')- else:- self.code, _, self.message = content[0]diff --git a/ext/stem/response/add_onion.py b/ext/stem/response/add_onion.pydeleted file mode 100644index 1472668a..00000000--- a/ext/stem/response/add_onion.py+++ /dev/null@@ -1,43 +0,0 @@-# Copyright 2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--import stem.response---class AddOnionResponse(stem.response.ControlMessage):- """- ADD_ONION response.-- :var str service_id: hidden service address without the '.onion' suffix- :var str private_key: base64 encoded hidden service private key- :var str private_key_type: crypto used to generate the hidden service private- key (such as RSA1024)- """-- def _parse_message(self):- # Example:- # 250-ServiceID=gfzprpioee3hoppz- # 250-PrivateKey=RSA1024:MIICXgIBAAKBgQDZvYVxv...- # 250 OK-- self.service_id = None- self.private_key = None- self.private_key_type = None-- if not self.is_ok():- raise stem.ProtocolError("ADD_ONION response didn't have an OK status: %s" % self)-- if not str(self).startswith('ServiceID='):- raise stem.ProtocolError('ADD_ONION response should start with the service id: %s' % self)-- for line in list(self):- if '=' in line:- key, value = line.split('=', 1)-- if key == 'ServiceID':- self.service_id = value- elif key == 'PrivateKey':- if ':' not in value:- raise stem.ProtocolError("ADD_ONION PrivateKey lines should be of the form 'PrivateKey=[type]:[key]: %s" % self)-- self.private_key_type, self.private_key = value.split(':', 1)diff --git a/ext/stem/response/authchallenge.py b/ext/stem/response/authchallenge.pydeleted file mode 100644index 60f39970..00000000--- a/ext/stem/response/authchallenge.py+++ /dev/null@@ -1,56 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--import binascii--import stem.response-import stem.socket-import stem.util.str_tools-import stem.util.tor_tools---class AuthChallengeResponse(stem.response.ControlMessage):- """- AUTHCHALLENGE query response.-- :var str server_hash: server hash provided by tor- :var str server_nonce: server nonce provided by tor- """-- def _parse_message(self):- # Example:- # 250 AUTHCHALLENGE SERVERHASH=680A73C9836C4F557314EA1C4EDE54C285DB9DC89C83627401AEF9D7D27A95D5 SERVERNONCE=F8EA4B1F2C8B40EF1AF68860171605B910E3BBCABADF6FC3DB1FA064F4690E85-- self.server_hash = None- self.server_nonce = None-- if not self.is_ok():- raise stem.ProtocolError("AUTHCHALLENGE response didn't have an OK status:\n%s" % self)- elif len(self) > 1:- raise stem.ProtocolError('Received multiline AUTHCHALLENGE response:\n%s' % self)-- line = self[0]-- # sanity check that we're a AUTHCHALLENGE response- if not line.pop() == 'AUTHCHALLENGE':- raise stem.ProtocolError('Message is not an AUTHCHALLENGE response (%s)' % self)-- if line.is_next_mapping('SERVERHASH'):- value = line.pop_mapping()[1]-- if not stem.util.tor_tools.is_hex_digits(value, 64):- raise stem.ProtocolError('SERVERHASH has an invalid value: %s' % value)-- self.server_hash = binascii.a2b_hex(stem.util.str_tools._to_bytes(value))- else:- raise stem.ProtocolError('Missing SERVERHASH mapping: %s' % line)-- if line.is_next_mapping('SERVERNONCE'):- value = line.pop_mapping()[1]-- if not stem.util.tor_tools.is_hex_digits(value, 64):- raise stem.ProtocolError('SERVERNONCE has an invalid value: %s' % value)-- self.server_nonce = binascii.a2b_hex(stem.util.str_tools._to_bytes(value))- else:- raise stem.ProtocolError('Missing SERVERNONCE mapping: %s' % line)diff --git a/ext/stem/response/events.py b/ext/stem/response/events.pydeleted file mode 100644index 9c386495..00000000--- a/ext/stem/response/events.py+++ /dev/null@@ -1,1331 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--import io-import re-import time--import stem-import stem.control-import stem.descriptor.router_status_entry-import stem.response-import stem.version--from stem import str_type, int_type-from stem.util import connection, log, str_tools, tor_tools--# Matches keyword=value arguments. This can't be a simple "(.*)=(.*)" pattern-# because some positional arguments, like circuit paths, can have an equal-# sign.--KW_ARG = re.compile('^(.*) ([A-Za-z0-9_]+)=(\S*)$')-QUOTED_KW_ARG = re.compile('^(.*) ([A-Za-z0-9_]+)="(.*)"$')-CELL_TYPE = re.compile('^[a-z0-9_]+$')---class Event(stem.response.ControlMessage):- """- Base for events we receive asynchronously, as described in section 4.1 of the- `control-spec- <https://gitweb.torproject.org/torspec.git/tree/control-spec.txt>`_.-- :var str type: event type- :var int arrived_at: unix timestamp for when the message arrived- :var list positional_args: positional arguments of the event- :var dict keyword_args: key/value arguments of the event- """-- _POSITIONAL_ARGS = () # attribute names for recognized positional arguments- _KEYWORD_ARGS = {} # map of 'keyword => attribute' for recognized attributes- _QUOTED = () # positional arguments that are quoted- _OPTIONALLY_QUOTED = () # positional arguments that may or may not be quoted- _SKIP_PARSING = False # skip parsing contents into our positional_args and keyword_args- _VERSION_ADDED = stem.version.Version('0.1.1.1-alpha') # minimum version with control-spec V1 event support-- def _parse_message(self, arrived_at = None):- if arrived_at is None:- arrived_at = int(time.time())-- if not str(self).strip():- raise stem.ProtocolError('Received a blank tor event. Events must at the very least have a type.')-- self.type = str(self).split()[0]- self.arrived_at = arrived_at-- # if we're a recognized event type then translate ourselves into that subclass-- if self.type in EVENT_TYPE_TO_CLASS:- self.__class__ = EVENT_TYPE_TO_CLASS[self.type]-- self.positional_args = []- self.keyword_args = {}-- if not self._SKIP_PARSING:- self._parse_standard_attr()-- self._parse()-- def _parse_standard_attr(self):- """- Most events are of the form...- 650 *( positional_args ) *( key "=" value )-- This parses this standard format, populating our **positional_args** and- **keyword_args** attributes and creating attributes if it's in our event's- **_POSITIONAL_ARGS** and **_KEYWORD_ARGS**.- """-- # Tor events contain some number of positional arguments followed by- # key/value mappings. Parsing keyword arguments from the end until we hit- # something that isn't a key/value mapping. The rest are positional.-- content = str(self)-- while True:- match = QUOTED_KW_ARG.match(content)-- if not match:- match = KW_ARG.match(content)-- if match:- content, keyword, value = match.groups()- self.keyword_args[keyword] = value- else:- break-- # Setting attributes for the fields that we recognize.-- self.positional_args = content.split()[1:]- positional = list(self.positional_args)-- for attr_name in self._POSITIONAL_ARGS:- attr_value = None-- if positional:- if attr_name in self._QUOTED or (attr_name in self._OPTIONALLY_QUOTED and positional[0].startswith('"')):- attr_values = [positional.pop(0)]-- if not attr_values[0].startswith('"'):- raise stem.ProtocolError("The %s value should be quoted, but didn't have a starting quote: %s" % (attr_name, self))-- while True:- if not positional:- raise stem.ProtocolError("The %s value should be quoted, but didn't have an ending quote: %s" % (attr_name, self))-- attr_values.append(positional.pop(0))-- if attr_values[-1].endswith('"'):- break-- attr_value = ' '.join(attr_values)[1:-1]- else:- attr_value = positional.pop(0)-- setattr(self, attr_name, attr_value)-- for controller_attr_name, attr_name in self._KEYWORD_ARGS.items():- setattr(self, attr_name, self.keyword_args.get(controller_attr_name))-- # method overwritten by our subclasses for special handling that they do- def _parse(self):- pass-- def _log_if_unrecognized(self, attr, attr_enum):- """- Checks if an attribute exists in a given enumeration, logging a message if- it isn't. Attributes can either be for a string or collection of strings-- :param str attr: name of the attribute to check- :param stem.util.enum.Enum enum: enumeration to check against- """-- attr_values = getattr(self, attr)-- if attr_values:- if isinstance(attr_values, (bytes, str_type)):- attr_values = [attr_values]-- for value in attr_values:- if value not in attr_enum:- log_id = 'event.%s.unknown_%s.%s' % (self.type.lower(), attr, value)- unrecognized_msg = "%s event had an unrecognized %s (%s). Maybe a new addition to the control protocol? Full Event: '%s'" % (self.type, attr, value, self)- log.log_once(log_id, log.INFO, unrecognized_msg)---class AddrMapEvent(Event):- """- Event that indicates a new address mapping.-- The ADDRMAP event was one of the first Control Protocol V1 events and was- introduced in tor version 0.1.1.1-alpha.-- .. versionchanged:: 1.1.0- Added the cached attribute.-- :var str hostname: address being resolved- :var str destination: destionation of the resolution, this is usually an ip,- but could be a hostname if TrackHostExits is enabled or **NONE** if the- resolution failed- :var datetime expiry: expiration time of the resolution in local time- :var str error: error code if the resolution failed- :var datetime utc_expiry: expiration time of the resolution in UTC- :var bool cached: **True** if the resolution will be kept until it expires,- **False** otherwise or **None** if undefined- """-- _POSITIONAL_ARGS = ('hostname', 'destination', 'expiry')- _KEYWORD_ARGS = {- 'error': 'error',- 'EXPIRES': 'utc_expiry',- 'CACHED': 'cached',- }- _OPTIONALLY_QUOTED = ('expiry')-- def _parse(self):- if self.destination == '<error>':- self.destination = None-- if self.expiry is not None:- if self.expiry == 'NEVER':- self.expiry = None- else:- try:- self.expiry = stem.util.str_tools._parse_timestamp(self.expiry)- except ValueError:- raise stem.ProtocolError('Unable to parse date in ADDRMAP event: %s' % self)-- if self.utc_expiry is not None:- self.utc_expiry = stem.util.str_tools._parse_timestamp(self.utc_expiry)-- if self.cached is not None:- if self.cached == 'YES':- self.cached = True- elif self.cached == 'NO':- self.cached = False- else:- raise stem.ProtocolError("An ADDRMAP event's CACHED mapping can only be 'YES' or 'NO': %s" % self)---class AuthDirNewDescEvent(Event):- """- Event specific to directory authorities, indicating that we just received new- descriptors. The descriptor type contained within this event is unspecified- so the descriptor contents are left unparsed.-- The AUTHDIR_NEWDESCS event was introduced in tor version 0.1.1.10-alpha.-- :var stem.AuthDescriptorAction action: what is being done with the descriptor- :var str message: explanation of why we chose this action- :var str descriptor: content of the descriptor- """-- _SKIP_PARSING = True- _VERSION_ADDED = stem.version.Requirement.EVENT_AUTHDIR_NEWDESCS-- def _parse(self):- lines = str(self).split('\n')-- if len(lines) < 5:- raise stem.ProtocolError("AUTHDIR_NEWDESCS events must contain lines for at least the type, action, message, descriptor, and terminating 'OK'")- elif lines[-1] != 'OK':- raise stem.ProtocolError("AUTHDIR_NEWDESCS doesn't end with an 'OK'")-- # TODO: For stem 2.0.0 we should consider changing 'descriptor' to a- # ServerDescriptor instance.-- self.action = lines[1]- self.message = lines[2]- self.descriptor = '\n'.join(lines[3:-1])---class BandwidthEvent(Event):- """- Event emitted every second with the bytes sent and received by tor.-- The BW event was one of the first Control Protocol V1 events and was- introduced in tor version 0.1.1.1-alpha.-- :var long read: bytes received by tor that second- :var long written: bytes sent by tor that second- """-- _POSITIONAL_ARGS = ('read', 'written')-- def _parse(self):- if not self.read:- raise stem.ProtocolError('BW event is missing its read value')- elif not self.written:- raise stem.ProtocolError('BW event is missing its written value')- elif not self.read.isdigit() or not self.written.isdigit():- raise stem.ProtocolError("A BW event's bytes sent and received should be a positive numeric value, received: %s" % self)-- self.read = int_type(self.read)- self.written = int_type(self.written)---class BuildTimeoutSetEvent(Event):- """- Event indicating that the timeout value for a circuit has changed. This was- first added in tor version 0.2.2.7.-- The BUILDTIMEOUT_SET event was introduced in tor version 0.2.2.7-alpha.-- :var stem.TimeoutSetType set_type: way in which the timeout is changing- :var int total_times: circuit build times tor used to determine the timeout- :var int timeout: circuit timeout value in milliseconds- :var int xm: Pareto parameter Xm in milliseconds- :var float alpha: Pareto parameter alpha- :var float quantile: CDF quantile cutoff point- :var float timeout_rate: ratio of circuits that have time out- :var int close_timeout: duration to keep measurement circuits in milliseconds- :var float close_rate: ratio of measurement circuits that are closed- """-- _POSITIONAL_ARGS = ('set_type',)- _KEYWORD_ARGS = {- 'TOTAL_TIMES': 'total_times',- 'TIMEOUT_MS': 'timeout',- 'XM': 'xm',- 'ALPHA': 'alpha',- 'CUTOFF_QUANTILE': 'quantile',- 'TIMEOUT_RATE': 'timeout_rate',- 'CLOSE_MS': 'close_timeout',- 'CLOSE_RATE': 'close_rate',- }- _VERSION_ADDED = stem.version.Requirement.EVENT_BUILDTIMEOUT_SET-- def _parse(self):- # convert our integer and float parameters-- for param in ('total_times', 'timeout', 'xm', 'close_timeout'):- param_value = getattr(self, param)-- if param_value is not None:- try:- setattr(self, param, int(param_value))- except ValueError:- raise stem.ProtocolError('The %s of a BUILDTIMEOUT_SET should be an integer: %s' % (param, self))-- for param in ('alpha', 'quantile', 'timeout_rate', 'close_rate'):- param_value = getattr(self, param)-- if param_value is not None:- try:- setattr(self, param, float(param_value))- except ValueError:- raise stem.ProtocolError('The %s of a BUILDTIMEOUT_SET should be a float: %s' % (param, self))-- self._log_if_unrecognized('set_type', stem.TimeoutSetType)---class CircuitEvent(Event):- """- Event that indicates that a circuit has changed.-- The fingerprint or nickname values in our 'path' may be **None** if the- VERBOSE_NAMES feature isn't enabled. The option was first introduced in tor- version 0.1.2.2, and on by default after 0.2.2.1.-- The CIRC event was one of the first Control Protocol V1 events and was- introduced in tor version 0.1.1.1-alpha.-- .. versionchanged:: 1.4.0- Added the socks_username and socks_password attributes which is used for- `stream isolation- <https://gitweb.torproject.org/torspec.git/tree/proposals/171-separate-streams.txt>`_.-- :var str id: circuit identifier- :var stem.CircStatus status: reported status for the circuit- :var tuple path: relays involved in the circuit, these are- **(fingerprint, nickname)** tuples- :var tuple build_flags: :data:`~stem.CircBuildFlag` attributes- governing how the circuit is built- :var stem.CircPurpose purpose: purpose that the circuit is intended for- :var stem.HiddenServiceState hs_state: status if this is a hidden service circuit- :var str rend_query: circuit's rendezvous-point if this is hidden service related- :var datetime created: time when the circuit was created or cannibalized- :var stem.CircClosureReason reason: reason for the circuit to be closed- :var stem.CircClosureReason remote_reason: remote side's reason for the circuit to be closed- :var str socks_username: username for using this circuit- :var str socks_password: password for using this circuit- """-- _POSITIONAL_ARGS = ('id', 'status', 'path')- _KEYWORD_ARGS = {- 'BUILD_FLAGS': 'build_flags',- 'PURPOSE': 'purpose',- 'HS_STATE': 'hs_state',- 'REND_QUERY': 'rend_query',- 'TIME_CREATED': 'created',- 'REASON': 'reason',- 'REMOTE_REASON': 'remote_reason',- 'SOCKS_USERNAME': 'socks_username',- 'SOCKS_PASSWORD': 'socks_password',- }-- def _parse(self):- self.path = tuple(stem.control._parse_circ_path(self.path))-- if self.build_flags is not None:- self.build_flags = tuple(self.build_flags.split(','))-- if self.created is not None:- try:- self.created = str_tools._parse_iso_timestamp(self.created)- except ValueError as exc:- raise stem.ProtocolError('Unable to parse create date (%s): %s' % (exc, self))-- if not tor_tools.is_valid_circuit_id(self.id):- raise stem.ProtocolError("Circuit IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))-- self._log_if_unrecognized('status', stem.CircStatus)- self._log_if_unrecognized('build_flags', stem.CircBuildFlag)- self._log_if_unrecognized('purpose', stem.CircPurpose)- self._log_if_unrecognized('hs_state', stem.HiddenServiceState)- self._log_if_unrecognized('reason', stem.CircClosureReason)- self._log_if_unrecognized('remote_reason', stem.CircClosureReason)-- def _compare(self, other, method):- if not isinstance(other, CircuitEvent):- return False-- for attr in ('id', 'status', 'path', 'build_flags', 'purpose', 'hs_state', 'rend_query', 'created', 'reason', 'remote_reason', 'socks_username', 'socks_port'):- my_attr = getattr(self, attr)- other_attr = getattr(other, attr)-- # Our id attribute is technically a string, but Tor conventionally uses- # ints. Attempt to handle as ints if that's the case so we get numeric- # ordering.-- if attr == 'id' and my_attr and other_attr:- if my_attr.isdigit() and other_attr.isdigit():- my_attr = int(my_attr)- other_attr = int(other_attr)-- if my_attr is None:- my_attr = ''-- if other_attr is None:- other_attr = ''-- if my_attr != other_attr:- return method(my_attr, other_attr)-- return True-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __gt__(self, other):- return self._compare(other, lambda s, o: s > o)-- def __ge__(self, other):- return self._compare(other, lambda s, o: s >= o)---class CircMinorEvent(Event):- """- Event providing information about minor changes in our circuits. This was- first added in tor version 0.2.3.11.-- The CIRC_MINOR event was introduced in tor version 0.2.3.11-alpha.-- :var str id: circuit identifier- :var stem.CircEvent event: type of change in the circuit- :var tuple path: relays involved in the circuit, these are- **(fingerprint, nickname)** tuples- :var tuple build_flags: :data:`~stem.CircBuildFlag` attributes- governing how the circuit is built- :var stem.CircPurpose purpose: purpose that the circuit is intended for- :var stem.HiddenServiceState hs_state: status if this is a hidden service circuit- :var str rend_query: circuit's rendezvous-point if this is hidden service related- :var datetime created: time when the circuit was created or cannibalized- :var stem.CircPurpose old_purpose: prior purpose for the circuit- :var stem.HiddenServiceState old_hs_state: prior status as a hidden service circuit- """-- _POSITIONAL_ARGS = ('id', 'event', 'path')- _KEYWORD_ARGS = {- 'BUILD_FLAGS': 'build_flags',- 'PURPOSE': 'purpose',- 'HS_STATE': 'hs_state',- 'REND_QUERY': 'rend_query',- 'TIME_CREATED': 'created',- 'OLD_PURPOSE': 'old_purpose',- 'OLD_HS_STATE': 'old_hs_state',- }- _VERSION_ADDED = stem.version.Requirement.EVENT_CIRC_MINOR-- def _parse(self):- self.path = tuple(stem.control._parse_circ_path(self.path))-- if self.build_flags is not None:- self.build_flags = tuple(self.build_flags.split(','))-- if self.created is not None:- try:- self.created = str_tools._parse_iso_timestamp(self.created)- except ValueError as exc:- raise stem.ProtocolError('Unable to parse create date (%s): %s' % (exc, self))-- if not tor_tools.is_valid_circuit_id(self.id):- raise stem.ProtocolError("Circuit IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))-- self._log_if_unrecognized('event', stem.CircEvent)- self._log_if_unrecognized('build_flags', stem.CircBuildFlag)- self._log_if_unrecognized('purpose', stem.CircPurpose)- self._log_if_unrecognized('hs_state', stem.HiddenServiceState)- self._log_if_unrecognized('old_purpose', stem.CircPurpose)- self._log_if_unrecognized('old_hs_state', stem.HiddenServiceState)---class ClientsSeenEvent(Event):- """- Periodic event on bridge relays that provides a summary of our users.-- The CLIENTS_SEEN event was introduced in tor version 0.2.1.10-alpha.-- :var datetime start_time: time in UTC that we started collecting these stats- :var dict locales: mapping of country codes to a rounded count for the number of users- :var dict ip_versions: mapping of ip protocols to a rounded count for the number of users- """-- _KEYWORD_ARGS = {- 'TimeStarted': 'start_time',- 'CountrySummary': 'locales',- 'IPVersions': 'ip_versions',- }- _VERSION_ADDED = stem.version.Requirement.EVENT_CLIENTS_SEEN-- def _parse(self):- if self.start_time is not None:- self.start_time = stem.util.str_tools._parse_timestamp(self.start_time)-- if self.locales is not None:- locale_to_count = {}-- for entry in self.locales.split(','):- if '=' not in entry:- raise stem.ProtocolError("The CLIENTS_SEEN's CountrySummary should be a comma separated listing of '<locale>=<count>' mappings: %s" % self)-- locale, count = entry.split('=', 1)-- if len(locale) != 2:- raise stem.ProtocolError("Locales should be a two character code, got '%s': %s" % (locale, self))- elif not count.isdigit():- raise stem.ProtocolError('Locale count was non-numeric (%s): %s' % (count, self))- elif locale in locale_to_count:- raise stem.ProtocolError("CountrySummary had multiple mappings for '%s': %s" % (locale, self))-- locale_to_count[locale] = int(count)-- self.locales = locale_to_count-- if self.ip_versions is not None:- protocol_to_count = {}-- for entry in self.ip_versions.split(','):- if '=' not in entry:- raise stem.ProtocolError("The CLIENTS_SEEN's IPVersions should be a comma separated listing of '<protocol>=<count>' mappings: %s" % self)-- protocol, count = entry.split('=', 1)-- if not count.isdigit():- raise stem.ProtocolError('IP protocol count was non-numeric (%s): %s' % (count, self))-- protocol_to_count[protocol] = int(count)-- self.ip_versions = protocol_to_count---class ConfChangedEvent(Event):- """- Event that indicates that our configuration changed, either in response to a- SETCONF or RELOAD signal.-- The CONF_CHANGED event was introduced in tor version 0.2.3.3-alpha.-- :var dict config: mapping of configuration options to their new values- (**None** if the option is being unset)- """-- _SKIP_PARSING = True- _VERSION_ADDED = stem.version.Requirement.EVENT_CONF_CHANGED-- def _parse(self):- self.config = {}-- # Skip first and last line since they're the header and footer. For- # instance...- #- # 650-CONF_CHANGED- # 650-ExitNodes=caerSidi- # 650-ExitPolicy- # 650-MaxCircuitDirtiness=20- # 650 OK-- for line in str(self).splitlines()[1:-1]:- if '=' in line:- key, value = line.split('=', 1)- else:- key, value = line, None-- self.config[key] = value---class DescChangedEvent(Event):- """- Event that indicates that our descriptor has changed.-- The DESCCHANGED event was introduced in tor version 0.1.2.2-alpha.- """-- _VERSION_ADDED = stem.version.Requirement.EVENT_DESCCHANGED---class GuardEvent(Event):- """- Event that indicates that our guard relays have changed. The 'endpoint' could- be either a...-- * fingerprint- * 'fingerprint=nickname' pair-- The derived 'endpoint_*' attributes are generally more useful.-- The GUARD event was introduced in tor version 0.1.2.5-alpha.-- :var stem.GuardType guard_type: purpose the guard relay is for- :var str endpoint: relay that the event concerns- :var str endpoint_fingerprint: endpoint's finterprint- :var str endpoint_nickname: endpoint's nickname if it was provided- :var stem.GuardStatus status: status of the guard relay- """-- _VERSION_ADDED = stem.version.Requirement.EVENT_GUARD- _POSITIONAL_ARGS = ('guard_type', 'endpoint', 'status')-- def _parse(self):- self.endpoint_fingerprint = None- self.endpoint_nickname = None-- try:- self.endpoint_fingerprint, self.endpoint_nickname = \- stem.control._parse_circ_entry(self.endpoint)- except stem.ProtocolError:- raise stem.ProtocolError("GUARD's endpoint doesn't match a ServerSpec: %s" % self)-- self._log_if_unrecognized('guard_type', stem.GuardType)- self._log_if_unrecognized('status', stem.GuardStatus)---class HSDescEvent(Event):- """- Event triggered when we fetch a hidden service descriptor that currently isn't in our cache.-- The HS_DESC event was introduced in tor version 0.2.5.2-alpha.-- .. versionadded:: 1.2.0-- .. versionchanged:: 1.3.0- Added the reason attribute.-- :var stem.HSDescAction action: what is happening with the descriptor- :var str address: hidden service address- :var stem.HSAuth authentication: service's authentication method- :var str directory: hidden service directory servicing the request- :var str directory_fingerprint: hidden service directory's finterprint- :var str directory_nickname: hidden service directory's nickname if it was provided- :var str descriptor_id: descriptor identifier- :var stem.HSDescReason reason: reason the descriptor failed to be fetched- """-- _VERSION_ADDED = stem.version.Requirement.EVENT_HS_DESC- _POSITIONAL_ARGS = ('action', 'address', 'authentication', 'directory', 'descriptor_id')- _KEYWORD_ARGS = {'REASON': 'reason'}-- def _parse(self):- self.directory_fingerprint = None- self.directory_nickname = None-- try:- self.directory_fingerprint, self.directory_nickname = \- stem.control._parse_circ_entry(self.directory)- except stem.ProtocolError:- raise stem.ProtocolError("HS_DESC's directory doesn't match a ServerSpec: %s" % self)-- self._log_if_unrecognized('action', stem.HSDescAction)- self._log_if_unrecognized('authentication', stem.HSAuth)---class HSDescContentEvent(Event):- """- Provides the content of hidden service descriptors we fetch.-- The HS_DESC_CONTENT event was introduced in tor version 0.2.7.1-alpha.-- .. versionadded:: 1.4.0-- :var str address: hidden service address- :var str descriptor_id: descriptor identifier- :var str directory: hidden service directory servicing the request- :var str directory_fingerprint: hidden service directory's finterprint- :var str directory_nickname: hidden service directory's nickname if it was provided- :var stem.descriptor.hidden_service_descriptor.HiddenServiceDescriptor descriptor: descriptor that was retrieved- """-- _VERSION_ADDED = stem.version.Requirement.EVENT_HS_DESC_CONTENT- _POSITIONAL_ARGS = ('address', 'descriptor_id', 'directory')-- def _parse(self):- if self.address == 'UNKNOWN':- self.address = None-- self.directory_fingerprint = None- self.directory_nickname = None-- try:- self.directory_fingerprint, self.directory_nickname = \- stem.control._parse_circ_entry(self.directory)- except stem.ProtocolError:- raise stem.ProtocolError("HS_DESC_CONTENT's directory doesn't match a ServerSpec: %s" % self)-- # skip the first line (our positional arguments) and last ('OK')-- desc_content = str_tools._to_bytes('\n'.join(str(self).splitlines()[1:-1]))- self.descriptor = None-- if desc_content:- self.descriptor = list(stem.descriptor.hidden_service_descriptor._parse_file(io.BytesIO(desc_content)))[0]---class LogEvent(Event):- """- Tor logging event. These are the most visible kind of event since, by- default, tor logs at the NOTICE :data:`~stem.Runlevel` to stdout.-- The logging events were some of the first Control Protocol V1 events- and were introduced in tor version 0.1.1.1-alpha.-- :var stem.Runlevel runlevel: runlevel of the logged message- :var str message: logged message- """-- _SKIP_PARSING = True-- def _parse(self):- self.runlevel = self.type- self._log_if_unrecognized('runlevel', stem.Runlevel)-- # message is our content, minus the runlevel and ending "OK" if a- # multi-line message-- self.message = str(self)[len(self.runlevel) + 1:].rstrip('\nOK')---class NetworkStatusEvent(Event):- """- Event for when our copy of the consensus has changed. This was introduced in- tor version 0.1.2.3.-- The NS event was introduced in tor version 0.1.2.3-alpha.-- :var list desc: :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` for the changed descriptors- """-- _SKIP_PARSING = True- _VERSION_ADDED = stem.version.Requirement.EVENT_NS-- def _parse(self):- content = str(self).lstrip('NS\n').rstrip('\nOK')-- # TODO: For stem 2.0.0 consider changing 'desc' to 'descriptors' to match- # our other events.-- self.desc = list(stem.descriptor.router_status_entry._parse_file(- io.BytesIO(str_tools._to_bytes(content)),- True,- entry_class = stem.descriptor.router_status_entry.RouterStatusEntryV3,- ))---class NewConsensusEvent(Event):- """- Event for when we have a new consensus. This is similar to- :class:`~stem.response.events.NetworkStatusEvent`, except that it contains- the whole consensus so anything not listed is implicitly no longer- recommended.-- The NEWCONSENSUS event was introduced in tor version 0.2.1.13-alpha.-- :var list desc: :class:`~stem.descriptor.router_status_entry.RouterStatusEntryV3` for the changed descriptors- """-- _SKIP_PARSING = True- _VERSION_ADDED = stem.version.Requirement.EVENT_NEWCONSENSUS-- def _parse(self):- content = str(self).lstrip('NEWCONSENSUS\n').rstrip('\nOK')-- # TODO: For stem 2.0.0 consider changing 'desc' to 'descriptors' to match- # our other events.-- self.desc = list(stem.descriptor.router_status_entry._parse_file(- io.BytesIO(str_tools._to_bytes(content)),- True,- entry_class = stem.descriptor.router_status_entry.RouterStatusEntryV3,- ))---class NewDescEvent(Event):- """- Event that indicates that a new descriptor is available.-- The fingerprint or nickname values in our 'relays' may be **None** if the- VERBOSE_NAMES feature isn't enabled. The option was first introduced in tor- version 0.1.2.2, and on by default after 0.2.2.1.-- The NEWDESC event was one of the first Control Protocol V1 events and was- introduced in tor version 0.1.1.1-alpha.-- :var tuple relays: **(fingerprint, nickname)** tuples for the relays with- new descriptors- """-- def _parse(self):- self.relays = tuple([stem.control._parse_circ_entry(entry) for entry in str(self).split()[1:]])---class ORConnEvent(Event):- """- Event that indicates a change in a relay connection. The 'endpoint' could be- any of several things including a...-- * fingerprint- * nickname- * 'fingerprint=nickname' pair- * address:port-- The derived 'endpoint_*' attributes are generally more useful.-- The ORCONN event was one of the first Control Protocol V1 events and was- introduced in tor version 0.1.1.1-alpha. Its id attribute was added in- version 0.2.5.2-alpha.-- .. versionchanged:: 1.2.0- Added the id attribute.-- :var str id: connection identifier- :var str endpoint: relay that the event concerns- :var str endpoint_fingerprint: endpoint's finterprint if it was provided- :var str endpoint_nickname: endpoint's nickname if it was provided- :var str endpoint_address: endpoint's address if it was provided- :var int endpoint_port: endpoint's port if it was provided- :var stem.ORStatus status: state of the connection- :var stem.ORClosureReason reason: reason for the connection to be closed- :var int circ_count: number of established and pending circuits- """-- _POSITIONAL_ARGS = ('endpoint', 'status')- _KEYWORD_ARGS = {- 'REASON': 'reason',- 'NCIRCS': 'circ_count',- 'ID': 'id',- }-- def _parse(self):- self.endpoint_fingerprint = None- self.endpoint_nickname = None- self.endpoint_address = None- self.endpoint_port = None-- try:- self.endpoint_fingerprint, self.endpoint_nickname = \- stem.control._parse_circ_entry(self.endpoint)- except stem.ProtocolError:- if ':' not in self.endpoint:- raise stem.ProtocolError("ORCONN endpoint is neither a relay nor 'address:port': %s" % self)-- address, port = self.endpoint.split(':', 1)-- if not connection.is_valid_port(port):- raise stem.ProtocolError("ORCONN's endpoint location's port is invalid: %s" % self)-- self.endpoint_address = address- self.endpoint_port = int(port)-- if self.circ_count is not None:- if not self.circ_count.isdigit():- raise stem.ProtocolError('ORCONN event got a non-numeric circuit count (%s): %s' % (self.circ_count, self))-- self.circ_count = int(self.circ_count)-- if self.id and not tor_tools.is_valid_connection_id(self.id):- raise stem.ProtocolError("Connection IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))-- self._log_if_unrecognized('status', stem.ORStatus)- self._log_if_unrecognized('reason', stem.ORClosureReason)---class SignalEvent(Event):- """- Event that indicates that tor has received and acted upon a signal being sent- to the process. As of tor version 0.2.4.6 the only signals conveyed by this- event are...-- * RELOAD- * DUMP- * DEBUG- * NEWNYM- * CLEARDNSCACHE-- The SIGNAL event was introduced in tor version 0.2.3.1-alpha.-- :var stem.Signal signal: signal that tor received- """-- _POSITIONAL_ARGS = ('signal',)- _VERSION_ADDED = stem.version.Requirement.EVENT_SIGNAL-- def _parse(self):- # log if we recieved an unrecognized signal- expected_signals = (- stem.Signal.RELOAD,- stem.Signal.DUMP,- stem.Signal.DEBUG,- stem.Signal.NEWNYM,- stem.Signal.CLEARDNSCACHE,- )-- self._log_if_unrecognized('signal', expected_signals)---class StatusEvent(Event):- """- Notification of a change in tor's state. These are generally triggered for- the same sort of things as log messages of the NOTICE level or higher.- However, unlike :class:`~stem.response.events.LogEvent` these contain well- formed data.-- The STATUS_GENERAL, STATUS_CLIENT, STATUS_SERVER events were introduced- in tor version 0.1.2.3-alpha.-- :var stem.StatusType status_type: category of the status event- :var stem.Runlevel runlevel: runlevel of the logged message- :var str action: activity that caused this message- :var dict arguments: attributes about the event- """-- _POSITIONAL_ARGS = ('runlevel', 'action')- _VERSION_ADDED = stem.version.Requirement.EVENT_STATUS-- def _parse(self):- if self.type == 'STATUS_GENERAL':- self.status_type = stem.StatusType.GENERAL- elif self.type == 'STATUS_CLIENT':- self.status_type = stem.StatusType.CLIENT- elif self.type == 'STATUS_SERVER':- self.status_type = stem.StatusType.SERVER- else:- raise ValueError("BUG: Unrecognized status type (%s), likely an EVENT_TYPE_TO_CLASS addition without revising how 'status_type' is assigned." % self.type)-- # Just an alias for our parent class' keyword_args since that already- # parses these for us. Unlike our other event types Tor commonly supplies- # arbitrary key/value pairs for these, so making an alias here to better- # draw attention that the StatusEvent will likely have them.-- self.arguments = self.keyword_args-- self._log_if_unrecognized('runlevel', stem.Runlevel)---class StreamEvent(Event):- """- Event that indicates that a stream has changed.-- The STREAM event was one of the first Control Protocol V1 events and was- introduced in tor version 0.1.1.1-alpha.-- :var str id: stream identifier- :var stem.StreamStatus status: reported status for the stream- :var str circ_id: circuit that the stream is attached to, this is **None** of- the stream is unattached- :var str target: destination of the stream- :var str target_address: destination address (ip, hostname, or '(Tor_internal)')- :var int target_port: destination port- :var stem.StreamClosureReason reason: reason for the stream to be closed- :var stem.StreamClosureReason remote_reason: remote side's reason for the stream to be closed- :var stem.StreamSource source: origin of the REMAP request- :var str source_addr: requester of the connection- :var str source_address: requester address (ip or hostname)- :var int source_port: requester port- :var stem.StreamPurpose purpose: purpose for the stream- """-- _POSITIONAL_ARGS = ('id', 'status', 'circ_id', 'target')- _KEYWORD_ARGS = {- 'REASON': 'reason',- 'REMOTE_REASON': 'remote_reason',- 'SOURCE': 'source',- 'SOURCE_ADDR': 'source_addr',- 'PURPOSE': 'purpose',- }-- def _parse(self):- if self.target is None:- raise stem.ProtocolError("STREAM event didn't have a target: %s" % self)- else:- if ':' not in self.target:- raise stem.ProtocolError("Target location must be of the form 'address:port': %s" % self)-- address, port = self.target.rsplit(':', 1)-- if not connection.is_valid_port(port, allow_zero = True):- raise stem.ProtocolError("Target location's port is invalid: %s" % self)-- self.target_address = address- self.target_port = int(port)-- if self.source_addr is None:- self.source_address = None- self.source_port = None- else:- if ':' not in self.source_addr:- raise stem.ProtocolError("Source location must be of the form 'address:port': %s" % self)-- address, port = self.source_addr.split(':', 1)-- if not connection.is_valid_port(port, allow_zero = True):- raise stem.ProtocolError("Source location's port is invalid: %s" % self)-- self.source_address = address- self.source_port = int(port)-- # spec specifies a circ_id of zero if the stream is unattached-- if self.circ_id == '0':- self.circ_id = None-- self._log_if_unrecognized('reason', stem.StreamClosureReason)- self._log_if_unrecognized('remote_reason', stem.StreamClosureReason)- self._log_if_unrecognized('purpose', stem.StreamPurpose)---class StreamBwEvent(Event):- """- Event (emitted approximately every second) with the bytes sent and received- by the application since the last such event on this stream.-- The STREAM_BW event was introduced in tor version 0.1.2.8-beta.-- :var str id: stream identifier- :var long written: bytes sent by the application- :var long read: bytes received by the application- """-- _POSITIONAL_ARGS = ('id', 'written', 'read')- _VERSION_ADDED = stem.version.Requirement.EVENT_STREAM_BW-- def _parse(self):- if not tor_tools.is_valid_stream_id(self.id):- raise stem.ProtocolError("Stream IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))- elif not self.written:- raise stem.ProtocolError('STREAM_BW event is missing its written value')- elif not self.read:- raise stem.ProtocolError('STREAM_BW event is missing its read value')- elif not self.read.isdigit() or not self.written.isdigit():- raise stem.ProtocolError("A STREAM_BW event's bytes sent and received should be a positive numeric value, received: %s" % self)-- self.read = int_type(self.read)- self.written = int_type(self.written)---class TransportLaunchedEvent(Event):- """- Event triggered when a pluggable transport is launched.-- The TRANSPORT_LAUNCHED event was introduced in tor version 0.2.5.0-alpha.-- .. versionadded:: 1.1.0-- :var str type: 'server' or 'client'- :var str name: name of the pluggable transport- :var str address: IPv4 or IPv6 address where the transport is listening for- connections- :var int port: port where the transport is listening for connections- """-- _POSITIONAL_ARGS = ('type', 'name', 'address', 'port')- _VERSION_ADDED = stem.version.Requirement.EVENT_TRANSPORT_LAUNCHED-- def _parse(self):- if self.type not in ('server', 'client'):- raise stem.ProtocolError("Transport type should either be 'server' or 'client': %s" % self)-- if not connection.is_valid_ipv4_address(self.address) and \- not connection.is_valid_ipv6_address(self.address):- raise stem.ProtocolError("Transport address isn't a valid IPv4 or IPv6 address: %s" % self)-- if not connection.is_valid_port(self.port):- raise stem.ProtocolError('Transport port is invalid: %s' % self)-- self.port = int(self.port)---class ConnectionBandwidthEvent(Event):- """- Event emitted every second with the bytes sent and received by tor on a- per-connection basis.-- The CONN_BW event was introduced in tor version 0.2.5.2-alpha.-- .. versionadded:: 1.2.0-- :var str id: connection identifier- :var stem.ConnectionType type: connection type- :var long read: bytes received by tor that second- :var long written: bytes sent by tor that second- """-- _KEYWORD_ARGS = {- 'ID': 'id',- 'TYPE': 'type',- 'READ': 'read',- 'WRITTEN': 'written',- }-- _VERSION_ADDED = stem.version.Requirement.EVENT_CONN_BW-- def _parse(self):- if not self.id:- raise stem.ProtocolError('CONN_BW event is missing its id')- elif not self.type:- raise stem.ProtocolError('CONN_BW event is missing its type')- elif not self.read:- raise stem.ProtocolError('CONN_BW event is missing its read value')- elif not self.written:- raise stem.ProtocolError('CONN_BW event is missing its written value')- elif not self.read.isdigit() or not self.written.isdigit():- raise stem.ProtocolError("A CONN_BW event's bytes sent and received should be a positive numeric value, received: %s" % self)- elif not tor_tools.is_valid_connection_id(self.id):- raise stem.ProtocolError("Connection IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))-- self.read = int_type(self.read)- self.written = int_type(self.written)-- self._log_if_unrecognized('type', stem.ConnectionType)---class CircuitBandwidthEvent(Event):- """- Event emitted every second with the bytes sent and received by tor on a- per-circuit basis.-- The CIRC_BW event was introduced in tor version 0.2.5.2-alpha.-- .. versionadded:: 1.2.0-- :var str id: circuit identifier- :var long read: bytes received by tor that second- :var long written: bytes sent by tor that second- """-- _KEYWORD_ARGS = {- 'ID': 'id',- 'READ': 'read',- 'WRITTEN': 'written',- }-- _VERSION_ADDED = stem.version.Requirement.EVENT_CIRC_BW-- def _parse(self):- if not self.id:- raise stem.ProtocolError('CIRC_BW event is missing its id')- elif not self.read:- raise stem.ProtocolError('CIRC_BW event is missing its read value')- elif not self.written:- raise stem.ProtocolError('CIRC_BW event is missing its written value')- elif not self.read.isdigit() or not self.written.isdigit():- raise stem.ProtocolError("A CIRC_BW event's bytes sent and received should be a positive numeric value, received: %s" % self)- elif not tor_tools.is_valid_circuit_id(self.id):- raise stem.ProtocolError("Circuit IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))-- self.read = int_type(self.read)- self.written = int_type(self.written)---class CellStatsEvent(Event):- """- Event emitted every second with a count of the number of cells types broken- down by the circuit. **These events are only emitted if TestingTorNetwork is- set.**-- The CELL_STATS event was introduced in tor version 0.2.5.2-alpha.-- .. versionadded:: 1.2.0-- :var str id: circuit identifier- :var str inbound_queue: inbound queue identifier- :var str inbound_connection: inbound connection identifier- :var dict inbound_added: mapping of added inbound cell types to their count- :var dict inbound_removed: mapping of removed inbound cell types to their count- :var dict inbound_time: mapping of inbound cell types to the time they took to write in milliseconds- :var str outbound_queue: outbound queue identifier- :var str outbound_connection: outbound connection identifier- :var dict outbound_added: mapping of added outbound cell types to their count- :var dict outbound_removed: mapping of removed outbound cell types to their count- :var dict outbound_time: mapping of outbound cell types to the time they took to write in milliseconds- """-- _KEYWORD_ARGS = {- 'ID': 'id',- 'InboundQueue': 'inbound_queue',- 'InboundConn': 'inbound_connection',- 'InboundAdded': 'inbound_added',- 'InboundRemoved': 'inbound_removed',- 'InboundTime': 'inbound_time',- 'OutboundQueue': 'outbound_queue',- 'OutboundConn': 'outbound_connection',- 'OutboundAdded': 'outbound_added',- 'OutboundRemoved': 'outbound_removed',- 'OutboundTime': 'outbound_time',- }-- _VERSION_ADDED = stem.version.Requirement.EVENT_CELL_STATS-- def _parse(self):- if self.id and not tor_tools.is_valid_circuit_id(self.id):- raise stem.ProtocolError("Circuit IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))- elif self.inbound_queue and not tor_tools.is_valid_circuit_id(self.inbound_queue):- raise stem.ProtocolError("Queue IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.inbound_queue, self))- elif self.inbound_connection and not tor_tools.is_valid_connection_id(self.inbound_connection):- raise stem.ProtocolError("Connection IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.inbound_connection, self))- elif self.outbound_queue and not tor_tools.is_valid_circuit_id(self.outbound_queue):- raise stem.ProtocolError("Queue IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.outbound_queue, self))- elif self.outbound_connection and not tor_tools.is_valid_connection_id(self.outbound_connection):- raise stem.ProtocolError("Connection IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.outbound_connection, self))-- self.inbound_added = _parse_cell_type_mapping(self.inbound_added)- self.inbound_removed = _parse_cell_type_mapping(self.inbound_removed)- self.inbound_time = _parse_cell_type_mapping(self.inbound_time)- self.outbound_added = _parse_cell_type_mapping(self.outbound_added)- self.outbound_removed = _parse_cell_type_mapping(self.outbound_removed)- self.outbound_time = _parse_cell_type_mapping(self.outbound_time)---class TokenBucketEmptyEvent(Event):- """- Event emitted when refilling an empty token bucket. **These events are only- emitted if TestingTorNetwork is set.**-- The TB_EMPTY event was introduced in tor version 0.2.5.2-alpha.-- .. versionadded:: 1.2.0-- :var stem.TokenBucket bucket: bucket being refilled- :var str id: connection identifier- :var int read: time in milliseconds since the read bucket was last refilled- :var int written: time in milliseconds since the write bucket was last refilled- :var int last_refill: time in milliseconds the bucket has been empty since last refilled- """-- _POSITIONAL_ARGS = ('bucket',)- _KEYWORD_ARGS = {- 'ID': 'id',- 'READ': 'read',- 'WRITTEN': 'written',- 'LAST': 'last_refill',- }-- _VERSION_ADDED = stem.version.Requirement.EVENT_TB_EMPTY-- def _parse(self):- if self.id and not tor_tools.is_valid_connection_id(self.id):- raise stem.ProtocolError("Connection IDs must be one to sixteen alphanumeric characters, got '%s': %s" % (self.id, self))- elif not self.read.isdigit():- raise stem.ProtocolError("A TB_EMPTY's READ value should be a positive numeric value, received: %s" % self)- elif not self.written.isdigit():- raise stem.ProtocolError("A TB_EMPTY's WRITTEN value should be a positive numeric value, received: %s" % self)- elif not self.last_refill.isdigit():- raise stem.ProtocolError("A TB_EMPTY's LAST value should be a positive numeric value, received: %s" % self)-- self.read = int(self.read)- self.written = int(self.written)- self.last_refill = int(self.last_refill)-- self._log_if_unrecognized('bucket', stem.TokenBucket)---def _parse_cell_type_mapping(mapping):- """- Parses a mapping of the form...-- key1:value1,key2:value2...-- ... in which keys are strings and values are integers.-- :param str mapping: value to be parsed-- :returns: dict of **str => int** mappings-- :rasies: **stem.ProtocolError** if unable to parse the mapping- """-- if mapping is None:- return None-- results = {}-- for entry in mapping.split(','):- if ':' not in entry:- raise stem.ProtocolError("Mappings are expected to be of the form 'key:value', got '%s': %s" % (entry, mapping))-- key, value = entry.split(':', 1)-- if not CELL_TYPE.match(key):- raise stem.ProtocolError("Key had invalid characters, got '%s': %s" % (key, mapping))- elif not value.isdigit():- raise stem.ProtocolError("Values should just be integers, got '%s': %s" % (value, mapping))-- results[key] = int(value)-- return results---EVENT_TYPE_TO_CLASS = {- 'ADDRMAP': AddrMapEvent,- 'AUTHDIR_NEWDESCS': AuthDirNewDescEvent,- 'BUILDTIMEOUT_SET': BuildTimeoutSetEvent,- 'BW': BandwidthEvent,- 'CELL_STATS': CellStatsEvent,- 'CIRC': CircuitEvent,- 'CIRC_BW': CircuitBandwidthEvent,- 'CIRC_MINOR': CircMinorEvent,- 'CLIENTS_SEEN': ClientsSeenEvent,- 'CONF_CHANGED': ConfChangedEvent,- 'CONN_BW': ConnectionBandwidthEvent,- 'DEBUG': LogEvent,- 'DESCCHANGED': DescChangedEvent,- 'ERR': LogEvent,- 'GUARD': GuardEvent,- 'HS_DESC': HSDescEvent,- 'HS_DESC_CONTENT': HSDescContentEvent,- 'INFO': LogEvent,- 'NEWCONSENSUS': NewConsensusEvent,- 'NEWDESC': NewDescEvent,- 'NOTICE': LogEvent,- 'NS': NetworkStatusEvent,- 'ORCONN': ORConnEvent,- 'SIGNAL': SignalEvent,- 'STATUS_CLIENT': StatusEvent,- 'STATUS_GENERAL': StatusEvent,- 'STATUS_SERVER': StatusEvent,- 'STREAM': StreamEvent,- 'STREAM_BW': StreamBwEvent,- 'TB_EMPTY': TokenBucketEmptyEvent,- 'TRANSPORT_LAUNCHED': TransportLaunchedEvent,- 'WARN': LogEvent,-- # accounting for a bug in tor 0.2.0.22- 'STATUS_SEVER': StatusEvent,-}diff --git a/ext/stem/response/getconf.py b/ext/stem/response/getconf.pydeleted file mode 100644index ce145532..00000000--- a/ext/stem/response/getconf.py+++ /dev/null@@ -1,55 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--import stem.response-import stem.socket---class GetConfResponse(stem.response.ControlMessage):- """- Reply for a GETCONF query.-- Note that configuration parameters won't match what we queried for if it's one- of the special mapping options (ex. 'HiddenServiceOptions').-- :var dict entries: mapping between the config parameter (**str**) and their- values (**list** of **str**)- """-- def _parse_message(self):- # Example:- # 250-CookieAuthentication=0- # 250-ControlPort=9100- # 250-DataDirectory=/home/neena/.tor- # 250 DirPort-- self.entries = {}- remaining_lines = list(self)-- if self.content() == [('250', ' ', 'OK')]:- return-- if not self.is_ok():- unrecognized_keywords = []- for code, _, line in self.content():- if code == '552' and line.startswith('Unrecognized configuration key "') and line.endswith('"'):- unrecognized_keywords.append(line[32:-1])-- if unrecognized_keywords:- raise stem.InvalidArguments('552', 'GETCONF request contained unrecognized keywords: %s' % ', '.join(unrecognized_keywords), unrecognized_keywords)- else:- raise stem.ProtocolError('GETCONF response contained a non-OK status code:\n%s' % self)-- while remaining_lines:- line = remaining_lines.pop(0)-- if line.is_next_mapping():- key, value = line.split('=', 1)- else:- key, value = (line.pop(), None)-- if key not in self.entries:- self.entries[key] = []-- if value is not None:- self.entries[key].append(value)diff --git a/ext/stem/response/getinfo.py b/ext/stem/response/getinfo.pydeleted file mode 100644index 07985934..00000000--- a/ext/stem/response/getinfo.py+++ /dev/null@@ -1,78 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--import stem.response-import stem.socket---class GetInfoResponse(stem.response.ControlMessage):- """- Reply for a GETINFO query.-- :var dict entries: mapping between the queried options and their bytes values- """-- def _parse_message(self):- # Example:- # 250-version=0.2.3.11-alpha-dev (git-ef0bc7f8f26a917c)- # 250+config-text=- # ControlPort 9051- # DataDirectory /home/atagar/.tor- # ExitPolicy reject *:*- # Log notice stdout- # Nickname Unnamed- # ORPort 9050- # .- # 250 OK-- self.entries = {}- remaining_lines = [content for (code, div, content) in self.content(get_bytes = True)]-- if not self.is_ok() or not remaining_lines.pop() == b'OK':- unrecognized_keywords = []- for code, _, line in self.content():- if code == '552' and line.startswith('Unrecognized key "') and line.endswith('"'):- unrecognized_keywords.append(line[18:-1])-- if unrecognized_keywords:- raise stem.InvalidArguments('552', 'GETINFO request contained unrecognized keywords: %s\n' % ', '.join(unrecognized_keywords), unrecognized_keywords)- else:- raise stem.ProtocolError("GETINFO response didn't have an OK status:\n%s" % self)-- while remaining_lines:- try:- key, value = remaining_lines.pop(0).split(b'=', 1)- except ValueError:- raise stem.ProtocolError('GETINFO replies should only contain parameter=value mappings:\n%s' % self)-- if stem.prereq.is_python_3():- key = stem.util.str_tools._to_unicode(key)-- # if the value is a multiline value then it *must* be of the form- # '<key>=\n<value>'-- if b'\n' in value:- if not value.startswith(b'\n'):- raise stem.ProtocolError("GETINFO response contained a multi-line value that didn't start with a newline:\n%s" % self)-- value = value[1:]-- self.entries[key] = value-- def _assert_matches(self, params):- """- Checks if we match a given set of parameters, and raise a ProtocolError if not.-- :param set params: parameters to assert that we contain-- :raises:- * :class:`stem.ProtocolError` if parameters don't match this response- """-- reply_params = set(self.entries.keys())-- if params != reply_params:- requested_label = ', '.join(params)- reply_label = ', '.join(reply_params)-- raise stem.ProtocolError("GETINFO reply doesn't match the parameters that we requested. Queried '%s' but got '%s'." % (requested_label, reply_label))diff --git a/ext/stem/response/mapaddress.py b/ext/stem/response/mapaddress.pydeleted file mode 100644index 5d2b418e..00000000--- a/ext/stem/response/mapaddress.py+++ /dev/null@@ -1,42 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--import stem.response-import stem.socket---class MapAddressResponse(stem.response.ControlMessage):- """- Reply for a MAPADDRESS query.- Doesn't raise an exception unless no addresses were mapped successfully.-- :var dict entries: mapping between the original and replacement addresses-- :raises:- * :class:`stem.OperationFailed` if Tor was unable to satisfy the request- * :class:`stem.InvalidRequest` if the addresses provided were invalid- """-- def _parse_message(self):- # Example:- # 250-127.192.10.10=torproject.org- # 250 1.2.3.4=tor.freehaven.net-- if not self.is_ok():- for code, _, message in self.content():- if code == '512':- raise stem.InvalidRequest(code, message)- elif code == '451':- raise stem.OperationFailed(code, message)- else:- raise stem.ProtocolError('MAPADDRESS returned unexpected response code: %s', code)-- self.entries = {}-- for code, _, message in self.content():- if code == '250':- try:- key, value = message.split('=', 1)- self.entries[key] = value- except ValueError:- raise stem.ProtocolError(None, "MAPADDRESS returned '%s', which isn't a mapping" % message)diff --git a/ext/stem/response/protocolinfo.py b/ext/stem/response/protocolinfo.pydeleted file mode 100644index 97201de5..00000000--- a/ext/stem/response/protocolinfo.py+++ /dev/null@@ -1,122 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--import stem.response-import stem.socket-import stem.version--from stem.connection import AuthMethod-from stem.util import log---class ProtocolInfoResponse(stem.response.ControlMessage):- """- Version one PROTOCOLINFO query response.-- The protocol_version is the only mandatory data for a valid PROTOCOLINFO- response, so all other values are None if undefined or empty if a collection.-- :var int protocol_version: protocol version of the response- :var stem.version.Version tor_version: version of the tor process- :var tuple auth_methods: :data:`stem.connection.AuthMethod` types that tor will accept- :var tuple unknown_auth_methods: strings of unrecognized auth methods- :var str cookie_path: path of tor's authentication cookie- """-- def _parse_message(self):- # Example:- # 250-PROTOCOLINFO 1- # 250-AUTH METHODS=COOKIE COOKIEFILE="/home/atagar/.tor/control_auth_cookie"- # 250-VERSION Tor="0.2.1.30"- # 250 OK-- self.protocol_version = None- self.tor_version = None- self.auth_methods = ()- self.unknown_auth_methods = ()- self.cookie_path = None-- auth_methods, unknown_auth_methods = [], []- remaining_lines = list(self)-- if not self.is_ok() or not remaining_lines.pop() == 'OK':- raise stem.ProtocolError("PROTOCOLINFO response didn't have an OK status:\n%s" % self)-- # sanity check that we're a PROTOCOLINFO response- if not remaining_lines[0].startswith('PROTOCOLINFO'):- raise stem.ProtocolError('Message is not a PROTOCOLINFO response:\n%s' % self)-- while remaining_lines:- line = remaining_lines.pop(0)- line_type = line.pop()-- if line_type == 'PROTOCOLINFO':- # Line format:- # FirstLine = "PROTOCOLINFO" SP PIVERSION CRLF- # PIVERSION = 1*DIGIT-- if line.is_empty():- raise stem.ProtocolError("PROTOCOLINFO response's initial line is missing the protocol version: %s" % line)-- try:- self.protocol_version = int(line.pop())- except ValueError:- raise stem.ProtocolError('PROTOCOLINFO response version is non-numeric: %s' % line)-- # The piversion really should be '1' but, according to the spec, tor- # does not necessarily need to provide the PROTOCOLINFO version that we- # requested. Log if it's something we aren't expecting but still make- # an effort to parse like a v1 response.-- if self.protocol_version != 1:- log.info("We made a PROTOCOLINFO version 1 query but got a version %i response instead. We'll still try to use it, but this may cause problems." % self.protocol_version)- elif line_type == 'AUTH':- # Line format:- # AuthLine = "250-AUTH" SP "METHODS=" AuthMethod *("," AuthMethod)- # *(SP "COOKIEFILE=" AuthCookieFile) CRLF- # AuthMethod = "NULL" / "HASHEDPASSWORD" / "COOKIE"- # AuthCookieFile = QuotedString-- # parse AuthMethod mapping- if not line.is_next_mapping('METHODS'):- raise stem.ProtocolError("PROTOCOLINFO response's AUTH line is missing its mandatory 'METHODS' mapping: %s" % line)-- for method in line.pop_mapping()[1].split(','):- if method == 'NULL':- auth_methods.append(AuthMethod.NONE)- elif method == 'HASHEDPASSWORD':- auth_methods.append(AuthMethod.PASSWORD)- elif method == 'COOKIE':- auth_methods.append(AuthMethod.COOKIE)- elif method == 'SAFECOOKIE':- auth_methods.append(AuthMethod.SAFECOOKIE)- else:- unknown_auth_methods.append(method)- message_id = 'stem.response.protocolinfo.unknown_auth_%s' % method- log.log_once(message_id, log.INFO, "PROTOCOLINFO response included a type of authentication that we don't recognize: %s" % method)-- # our auth_methods should have a single AuthMethod.UNKNOWN entry if- # any unknown authentication methods exist- if AuthMethod.UNKNOWN not in auth_methods:- auth_methods.append(AuthMethod.UNKNOWN)-- # parse optional COOKIEFILE mapping (quoted and can have escapes)- if line.is_next_mapping('COOKIEFILE', True, True):- self.cookie_path = line.pop_mapping(True, True)[1]- elif line_type == 'VERSION':- # Line format:- # VersionLine = "250-VERSION" SP "Tor=" TorVersion OptArguments CRLF- # TorVersion = QuotedString-- if not line.is_next_mapping('Tor', True):- raise stem.ProtocolError("PROTOCOLINFO response's VERSION line is missing its mandatory tor version mapping: %s" % line)-- try:- self.tor_version = stem.version.Version(line.pop_mapping(True)[1])- except ValueError as exc:- raise stem.ProtocolError(exc)- else:- log.debug("Unrecognized PROTOCOLINFO line type '%s', ignoring it: %s" % (line_type, line))-- self.auth_methods = tuple(auth_methods)- self.unknown_auth_methods = tuple(unknown_auth_methods)diff --git a/ext/stem/socket.py b/ext/stem/socket.pydeleted file mode 100644index 8024098e..00000000--- a/ext/stem/socket.py+++ /dev/null@@ -1,663 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Supports communication with sockets speaking the Tor control protocol. This-allows us to send messages as basic strings, and receive responses as-:class:`~stem.response.ControlMessage` instances.--**This module only consists of low level components, and is not intended for-users.** See our `tutorials <../tutorials.html>`_ and `Control Module-<control.html>`_ if you're new to Stem and looking to get started.--With that aside, these can still be used for raw socket communication with-Tor...--::-- import stem- import stem.connection- import stem.socket-- if __name__ == '__main__':- try:- control_socket = stem.socket.ControlPort(port = 9051)- stem.connection.authenticate(control_socket)- except stem.SocketError as exc:- print 'Unable to connect to tor on port 9051: %s' % exc- sys.exit(1)- except stem.connection.AuthenticationFailure as exc:- print 'Unable to authenticate: %s' % exc- sys.exit(1)-- print "Issuing 'GETINFO version' query...\\n"- control_socket.send('GETINFO version')- print control_socket.recv()--::-- % python example.py- Issuing 'GETINFO version' query...-- version=0.2.4.10-alpha-dev (git-8be6058d8f31e578)- OK--**Module Overview:**--::-- ControlSocket - Socket wrapper that speaks the tor control protocol.- |- ControlPort - Control connection via a port.- | |- get_address - provides the ip address of our socket- | +- get_port - provides the port of our socket- |- |- ControlSocketFile - Control connection via a local file socket.- | +- get_socket_path - provides the path of the socket we connect to- |- |- send - sends a message to the socket- |- recv - receives a ControlMessage from the socket- |- is_alive - reports if the socket is known to be closed- |- is_localhost - returns if the socket is for the local system or not- |- connect - connects a new socket- |- close - shuts down the socket- +- __enter__ / __exit__ - manages socket connection-- send_message - Writes a message to a control socket.- recv_message - Reads a ControlMessage from a control socket.- send_formatting - Performs the formatting expected from sent messages.-"""--from __future__ import absolute_import--import re-import socket-import threading-import time--import stem.prereq-import stem.response-import stem.util.str_tools--from stem.util import log---class ControlSocket(object):- """- Wrapper for a socket connection that speaks the Tor control protocol. To the- better part this transparently handles the formatting for sending and- receiving complete messages. All methods are thread safe.-- Callers should not instantiate this class directly, but rather use subclasses- which are expected to implement the **_make_socket()** method.- """-- def __init__(self):- self._socket, self._socket_file = None, None- self._is_alive = False- self._connection_time = 0.0 # time when we last connected or disconnected-- # Tracks sending and receiving separately. This should be safe, and doing- # so prevents deadlock where we block writes because we're waiting to read- # a message that isn't coming.-- self._send_lock = threading.RLock()- self._recv_lock = threading.RLock()-- def send(self, message, raw = False):- """- Formats and sends a message to the control socket. For more information see- the :func:`~stem.socket.send_message` function.-- :param str message: message to be formatted and sent to the socket- :param bool raw: leaves the message formatting untouched, passing it to the socket as-is-- :raises:- * :class:`stem.SocketError` if a problem arises in using the socket- * :class:`stem.SocketClosed` if the socket is known to be shut down- """-- with self._send_lock:- try:- if not self.is_alive():- raise stem.SocketClosed()-- send_message(self._socket_file, message, raw)- except stem.SocketClosed as exc:- # if send_message raises a SocketClosed then we should properly shut- # everything down-- if self.is_alive():- self.close()-- raise exc-- def recv(self):- """- Receives a message from the control socket, blocking until we've received- one. For more information see the :func:`~stem.socket.recv_message` function.-- :returns: :class:`~stem.response.ControlMessage` for the message received-- :raises:- * :class:`stem.ProtocolError` the content from the socket is malformed- * :class:`stem.SocketClosed` if the socket closes before we receive a complete message- """-- with self._recv_lock:- try:- # makes a temporary reference to the _socket_file because connect()- # and close() may set or unset it-- socket_file = self._socket_file-- if not socket_file:- raise stem.SocketClosed()-- return recv_message(socket_file)- except stem.SocketClosed as exc:- # If recv_message raises a SocketClosed then we should properly shut- # everything down. However, there's a couple cases where this will- # cause deadlock...- #- # * this socketClosed was *caused by* a close() call, which is joining- # on our thread- #- # * a send() call that's currently in flight is about to call close(),- # also attempting to join on us- #- # To resolve this we make a non-blocking call to acquire the send lock.- # If we get it then great, we can close safely. If not then one of the- # above are in progress and we leave the close to them.-- if self.is_alive():- if self._send_lock.acquire(False):- self.close()- self._send_lock.release()-- raise exc-- def is_alive(self):- """- Checks if the socket is known to be closed. We won't be aware if it is- until we either use it or have explicitily shut it down.-- In practice a socket derived from a port knows about its disconnection- after a failed :func:`~stem.socket.ControlSocket.recv` call. Socket file- derived connections know after either a- :func:`~stem.socket.ControlSocket.send` or- :func:`~stem.socket.ControlSocket.recv`.-- This means that to have reliable detection for when we're disconnected- you need to continually pull from the socket (which is part of what the- :class:`~stem.control.BaseController` does).-- :returns: **bool** that's **True** if our socket is connected and **False** otherwise- """-- return self._is_alive-- def is_localhost(self):- """- Returns if the connection is for the local system or not.-- :returns: **bool** that's **True** if the connection is for the local host and **False** otherwise- """-- return False-- def connection_time(self):- """- Provides the unix timestamp for when our socket was either connected or- disconnected. That is to say, the time we connected if we're currently- connected and the time we disconnected if we're not connected.-- .. versionadded:: 1.3.0-- :returns: **float** for when we last connected or disconnected, zero if- we've never connected- """-- return self._connection_time-- def connect(self):- """- Connects to a new socket, closing our previous one if we're already- attached.-- :raises: :class:`stem.SocketError` if unable to make a socket- """-- with self._send_lock:- # Closes the socket if we're currently attached to one. Once we're no- # longer alive it'll be safe to acquire the recv lock because recv()- # calls no longer block (raising SocketClosed instead).-- if self.is_alive():- self.close()-- with self._recv_lock:- self._socket = self._make_socket()- self._socket_file = self._socket.makefile(mode = 'rwb')- self._is_alive = True- self._connection_time = time.time()-- # It's possible for this to have a transient failure...- # SocketError: [Errno 4] Interrupted system call- #- # It's safe to retry, so give it another try if it fails.-- try:- self._connect()- except stem.SocketError:- self._connect() # single retry-- def close(self):- """- Shuts down the socket. If it's already closed then this is a no-op.- """-- with self._send_lock:- # Function is idempotent with one exception: we notify _close() if this- # is causing our is_alive() state to change.-- is_change = self.is_alive()-- if self._socket:- # if we haven't yet established a connection then this raises an error- # socket.error: [Errno 107] Transport endpoint is not connected-- try:- self._socket.shutdown(socket.SHUT_RDWR)- except socket.error:- pass-- # Suppressing unexpected exceptions from close. For instance, if the- # socket's file has already been closed then with python 2.7 that raises- # with...- # error: [Errno 32] Broken pipe-- try:- self._socket.close()- except:- pass-- if self._socket_file:- try:- self._socket_file.close()- except:- pass-- self._socket = None- self._socket_file = None- self._is_alive = False- self._connection_time = time.time()-- if is_change:- self._close()-- def _get_send_lock(self):- """- The send lock is useful to classes that interact with us at a deep level- because it's used to lock :func:`stem.socket.ControlSocket.connect` /- :func:`stem.socket.ControlSocket.close`, and by extension our- :func:`stem.socket.ControlSocket.is_alive` state changes.-- :returns: **threading.RLock** that governs sending messages to our socket- and state changes- """-- return self._send_lock-- def __enter__(self):- return self-- def __exit__(self, exit_type, value, traceback):- self.close()-- def _connect(self):- """- Connection callback that can be overwritten by subclasses and wrappers.- """-- pass-- def _close(self):- """- Disconnection callback that can be overwritten by subclasses and wrappers.- """-- pass-- def _make_socket(self):- """- Constructs and connects new socket. This is implemented by subclasses.-- :returns: **socket.socket** for our configuration-- :raises:- * :class:`stem.SocketError` if unable to make a socket- * **NotImplementedError** if not implemented by a subclass- """-- raise NotImplementedError('Unsupported Operation: this should be implemented by the ControlSocket subclass')---class ControlPort(ControlSocket):- """- Control connection to tor. For more information see tor's ControlPort torrc- option.- """-- def __init__(self, address = '127.0.0.1', port = 9051, connect = True):- """- ControlPort constructor.-- :param str address: ip address of the controller- :param int port: port number of the controller- :param bool connect: connects to the socket if True, leaves it unconnected otherwise-- :raises: :class:`stem.SocketError` if connect is **True** and we're- unable to establish a connection- """-- super(ControlPort, self).__init__()- self._control_addr = address- self._control_port = port-- if connect:- self.connect()-- def get_address(self):- """- Provides the ip address our socket connects to.-- :returns: str with the ip address of our socket- """-- return self._control_addr-- def get_port(self):- """- Provides the port our socket connects to.-- :returns: int with the port of our socket- """-- return self._control_port-- def is_localhost(self):- return self._control_addr == '127.0.0.1'-- def _make_socket(self):- try:- control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- control_socket.connect((self._control_addr, self._control_port))- return control_socket- except socket.error as exc:- raise stem.SocketError(exc)---class ControlSocketFile(ControlSocket):- """- Control connection to tor. For more information see tor's ControlSocket torrc- option.- """-- def __init__(self, path = '/var/run/tor/control', connect = True):- """- ControlSocketFile constructor.-- :param str socket_path: path where the control socket is located- :param bool connect: connects to the socket if True, leaves it unconnected otherwise-- :raises: :class:`stem.SocketError` if connect is **True** and we're- unable to establish a connection- """-- super(ControlSocketFile, self).__init__()- self._socket_path = path-- if connect:- self.connect()-- def get_socket_path(self):- """- Provides the path our socket connects to.-- :returns: str with the path for our control socket- """-- return self._socket_path-- def is_localhost(self):- return True-- def _make_socket(self):- try:- control_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- control_socket.connect(self._socket_path)- return control_socket- except socket.error as exc:- raise stem.SocketError(exc)---def send_message(control_file, message, raw = False):- """- Sends a message to the control socket, adding the expected formatting for- single verses multi-line messages. Neither message type should contain an- ending newline (if so it'll be treated as a multi-line message with a blank- line at the end). If the message doesn't contain a newline then it's sent- as...-- ::-- <message>\\r\\n-- and if it does contain newlines then it's split on ``\\n`` and sent as...-- ::-- +<line 1>\\r\\n- <line 2>\\r\\n- <line 3>\\r\\n- .\\r\\n-- :param file control_file: file derived from the control socket (see the- socket's makefile() method for more information)- :param str message: message to be sent on the control socket- :param bool raw: leaves the message formatting untouched, passing it to the- socket as-is-- :raises:- * :class:`stem.SocketError` if a problem arises in using the socket- * :class:`stem.SocketClosed` if the socket is known to be shut down- """-- if not raw:- message = send_formatting(message)-- try:- control_file.write(stem.util.str_tools._to_bytes(message))- control_file.flush()-- log_message = message.replace('\r\n', '\n').rstrip()- log.trace('Sent to tor:\n' + log_message)- except socket.error as exc:- log.info('Failed to send message: %s' % exc)-- # When sending there doesn't seem to be a reliable method for- # distinguishing between failures from a disconnect verses other things.- # Just accounting for known disconnection responses.-- if str(exc) == '[Errno 32] Broken pipe':- raise stem.SocketClosed(exc)- else:- raise stem.SocketError(exc)- except AttributeError:- # if the control_file has been closed then flush will receive:- # AttributeError: 'NoneType' object has no attribute 'sendall'-- log.info('Failed to send message: file has been closed')- raise stem.SocketClosed('file has been closed')---def recv_message(control_file):- """- Pulls from a control socket until we either have a complete message or- encounter a problem.-- :param file control_file: file derived from the control socket (see the- socket's makefile() method for more information)-- :returns: :class:`~stem.response.ControlMessage` read from the socket-- :raises:- * :class:`stem.ProtocolError` the content from the socket is malformed- * :class:`stem.SocketClosed` if the socket closes before we receive- a complete message- """-- parsed_content, raw_content = [], b''- logging_prefix = 'Error while receiving a control message (%s): '-- while True:- try:- # From a real socket readline() would always provide bytes, but during- # tests we might be given a StringIO in which case it's unicode under- # python 3.x.-- line = stem.util.str_tools._to_bytes(control_file.readline())- except AttributeError:- # if the control_file has been closed then we will receive:- # AttributeError: 'NoneType' object has no attribute 'recv'-- prefix = logging_prefix % 'SocketClosed'- log.info(prefix + 'socket file has been closed')- raise stem.SocketClosed('socket file has been closed')- except (socket.error, ValueError) as exc:- # When disconnected we get...- #- # Python 2:- # socket.error: [Errno 107] Transport endpoint is not connected- #- # Python 3:- # ValueError: I/O operation on closed file.-- prefix = logging_prefix % 'SocketClosed'- log.info(prefix + 'received exception "%s"' % exc)- raise stem.SocketClosed(exc)-- raw_content += line-- # Parses the tor control lines. These are of the form...- # <status code><divider><content>\r\n-- if len(line) == 0:- # if the socket is disconnected then the readline() method will provide- # empty content-- prefix = logging_prefix % 'SocketClosed'- log.info(prefix + 'empty socket content')- raise stem.SocketClosed('Received empty socket content.')- elif len(line) < 4:- prefix = logging_prefix % 'ProtocolError'- log.info(prefix + 'line too short, "%s"' % log.escape(line))- raise stem.ProtocolError('Badly formatted reply line: too short')- elif not re.match(b'^[a-zA-Z0-9]{3}[-+ ]', line):- prefix = logging_prefix % 'ProtocolError'- log.info(prefix + 'malformed status code/divider, "%s"' % log.escape(line))- raise stem.ProtocolError('Badly formatted reply line: beginning is malformed')- elif not line.endswith(b'\r\n'):- prefix = logging_prefix % 'ProtocolError'- log.info(prefix + 'no CRLF linebreak, "%s"' % log.escape(line))- raise stem.ProtocolError('All lines should end with CRLF')-- line = line[:-2] # strips off the CRLF- status_code, divider, content = line[:3], line[3:4], line[4:]-- if stem.prereq.is_python_3():- status_code = stem.util.str_tools._to_unicode(status_code)- divider = stem.util.str_tools._to_unicode(divider)-- if divider == '-':- # mid-reply line, keep pulling for more content- parsed_content.append((status_code, divider, content))- elif divider == ' ':- # end of the message, return the message- parsed_content.append((status_code, divider, content))-- log_message = raw_content.replace(b'\r\n', b'\n').rstrip()- log.trace('Received from tor:\n' + stem.util.str_tools._to_unicode(log_message))-- return stem.response.ControlMessage(parsed_content, raw_content)- elif divider == '+':- # data entry, all of the following lines belong to the content until we- # get a line with just a period-- while True:- try:- line = stem.util.str_tools._to_bytes(control_file.readline())- except socket.error as exc:- prefix = logging_prefix % 'SocketClosed'- log.info(prefix + 'received an exception while mid-way through a data reply (exception: "%s", read content: "%s")' % (exc, log.escape(raw_content)))- raise stem.SocketClosed(exc)-- raw_content += line-- if not line.endswith(b'\r\n'):- prefix = logging_prefix % 'ProtocolError'- log.info(prefix + 'CRLF linebreaks missing from a data reply, "%s"' % log.escape(raw_content))- raise stem.ProtocolError('All lines should end with CRLF')- elif line == b'.\r\n':- break # data block termination-- line = line[:-2] # strips off the CRLF-- # lines starting with a period are escaped by a second period (as per- # section 2.4 of the control-spec)-- if line.startswith(b'..'):- line = line[1:]-- # appends to previous content, using a newline rather than CRLF- # separator (more conventional for multi-line string content outside- # the windows world)-- content += b'\n' + line-- parsed_content.append((status_code, divider, content))- else:- # this should never be reached due to the prefix regex, but might as well- # be safe...- prefix = logging_prefix % 'ProtocolError'- log.warn(prefix + "\"%s\" isn't a recognized divider type" % divider)- raise stem.ProtocolError("Unrecognized divider type '%s': %s" % (divider, stem.util.str_tools._to_unicode(line)))---def send_formatting(message):- """- Performs the formatting expected from sent control messages. For more- information see the :func:`~stem.socket.send_message` function.-- :param str message: message to be formatted-- :returns: **str** of the message wrapped by the formatting expected from- controllers- """-- # From control-spec section 2.2...- # Command = Keyword OptArguments CRLF / "+" Keyword OptArguments CRLF CmdData- # Keyword = 1*ALPHA- # OptArguments = [ SP *(SP / VCHAR) ]- #- # A command is either a single line containing a Keyword and arguments, or a- # multiline command whose initial keyword begins with +, and whose data- # section ends with a single "." on a line of its own.-- # if we already have \r\n entries then standardize on \n to start with- message = message.replace('\r\n', '\n')-- if '\n' in message:- return '+%s\r\n.\r\n' % message.replace('\n', '\r\n')- else:- return message + '\r\n'diff --git a/ext/stem/util/__init__.py b/ext/stem/util/__init__.pydeleted file mode 100644index 1c18df3a..00000000--- a/ext/stem/util/__init__.py+++ /dev/null@@ -1,20 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Utility functions used by the stem library.-"""--__all__ = [- 'conf',- 'connection',- 'enum',- 'log',- 'lru_cache',- 'ordereddict',- 'proc',- 'system',- 'term',- 'test_tools',- 'tor_tools',-]diff --git a/ext/stem/util/conf.py b/ext/stem/util/conf.pydeleted file mode 100644index 6b0efd71..00000000--- a/ext/stem/util/conf.py+++ /dev/null@@ -1,745 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Handlers for text configuration files. Configurations are simple string to-string mappings, with the configuration files using the following rules...--* the key/value is separated by a space-* anything after a '#' is ignored as a comment-* excess whitespace is trimmed-* empty lines are ignored-* multi-line values can be defined by following the key with lines starting- with a '|'--For instance...--::-- # This is my sample config- user.name Galen- user.password yabba1234 # here's an inline comment- user.notes takes a fancy to pepperjack cheese- blankEntry.example-- msg.greeting- |Multi-line message exclaiming of the- |wonder and awe that is pepperjack!--... would be loaded as...--::-- config = {- 'user.name': 'Galen',- 'user.password': 'yabba1234',- 'user.notes': 'takes a fancy to pepperjack cheese',- 'blankEntry.example': '',- 'msg.greeting': 'Multi-line message exclaiming of the\\nwonder and awe that is pepperjack!',- }--Configurations are managed via the :class:`~stem.util.conf.Config` class. The-:class:`~stem.util.conf.Config` can be be used directly with its-:func:`~stem.util.conf.Config.get` and :func:`~stem.util.conf.Config.set`-methods, but usually modules will want a local dictionary with just the-configurations that it cares about.--To do this use the :func:`~stem.util.conf.config_dict` function. For example...--::-- import getpass- from stem.util import conf, connection-- def config_validator(key, value):- if key == 'timeout':- # require at least a one second timeout- return max(1, value)- elif key == 'endpoint':- if not connection.is_valid_ipv4_address(value):- raise ValueError("'%s' isn't a valid IPv4 address" % value)- elif key == 'port':- if not connection.is_valid_port(value):- raise ValueError("'%s' isn't a valid port" % value)- elif key == 'retries':- # negative retries really don't make sense- return max(0, value)-- CONFIG = conf.config_dict('ssh_login', {- 'username': getpass.getuser(),- 'password': '',- 'timeout': 10,- 'endpoint': '263.12.8.0',- 'port': 22,- 'reconnect': False,- 'retries': 3,- }, config_validator)--There's several things going on here so lets take it step by step...--* The :func:`~stem.util.conf.config_dict` provides a dictionary that's bound- to a given configuration. If the "ssh_proxy_config" configuration changes- then so will the contents of CONFIG.--* The dictionary we're passing to :func:`~stem.util.conf.config_dict` provides- two important pieces of information: default values and their types. See the- Config's :func:`~stem.util.conf.Config.get` method for how these type- inferences work.--* The config_validator is a hook we're adding to make sure CONFIG only gets- values we think are valid. In this case it ensures that our timeout value- is at least one second, and rejects endpoints or ports that are invalid.--Now lets say our user has the following configuration file...--::-- username waddle_doo- password jabberwocky- timeout -15- port 9000000- retries lots- reconnect true- logging debug--... and we load it as follows...--::-- >>> from stem.util import conf- >>> our_config = conf.get_config('ssh_login')- >>> our_config.load('/home/atagar/user_config')- >>> print CONFIG # doctest: +SKIP- {- "username": "waddle_doo",- "password": "jabberwocky",- "timeout": 1,- "endpoint": "263.12.8.0",- "port": 22,- "reconnect": True,- "retries": 3,- }--Here's an expanation of what happened...--* the username, password, and reconnect attributes took the values in the- configuration file--* the 'config_validator' we added earlier allows for a minimum timeout of one- and rejected the invalid port (with a log message)--* we weren't able to convert the retries' "lots" value to an integer so it kept- its default value and logged a warning--* the user didn't supply an endpoint so that remained unchanged--* our CONFIG didn't have a 'logging' attribute so it was ignored--**Module Overview:**--::-- config_dict - provides a dictionary that's kept in sync with our config- get_config - singleton for getting configurations- uses_settings - provides an annotation for functions that use configurations- parse_enum_csv - helper funcion for parsing confguration entries for enums-- Config - Custom configuration- |- load - reads a configuration file- |- save - writes the current configuration to a file- |- clear - empties our loaded configuration contents- |- add_listener - notifies the given listener when an update occurs- |- clear_listeners - removes any attached listeners- |- keys - provides keys in the loaded configuration- |- set - sets the given key/value pair- |- unused_keys - provides keys that have never been requested- |- get - provides the value for a given key, with type inference- +- get_value - provides the value for a given key as a string-"""--import inspect-import os-import threading--from stem.util import log--try:- # added in python 2.7- from collections import OrderedDict-except ImportError:- from stem.util.ordereddict import OrderedDict--CONFS = {} # mapping of identifier to singleton instances of configs---class _SyncListener(object):- def __init__(self, config_dict, interceptor):- self.config_dict = config_dict- self.interceptor = interceptor-- def update(self, config, key):- if key in self.config_dict:- new_value = config.get(key, self.config_dict[key])-- if new_value == self.config_dict[key]:- return # no change-- if self.interceptor:- interceptor_value = self.interceptor(key, new_value)-- if interceptor_value:- new_value = interceptor_value-- self.config_dict[key] = new_value---def config_dict(handle, conf_mappings, handler = None):- """- Makes a dictionary that stays synchronized with a configuration.-- This takes a dictionary of 'config_key => default_value' mappings and- changes the values to reflect our current configuration. This will leave- the previous values alone if...-- * we don't have a value for that config_key- * we can't convert our value to be the same type as the default_value-- If a handler is provided then this is called just prior to assigning new- values to the config_dict. The handler function is expected to accept the- (key, value) for the new values and return what we should actually insert- into the dictionary. If this returns None then the value is updated as- normal.-- For more information about how we convert types see our- :func:`~stem.util.conf.Config.get` method.-- **The dictionary you get from this is manged by the- :class:`~stem.util.conf.Config` class and should be treated as being- read-only.**-- :param str handle: unique identifier for a config instance- :param dict conf_mappings: config key/value mappings used as our defaults- :param functor handler: function referred to prior to assigning values- """-- selected_config = get_config(handle)- selected_config.add_listener(_SyncListener(conf_mappings, handler).update)- return conf_mappings---def get_config(handle):- """- Singleton constructor for configuration file instances. If a configuration- already exists for the handle then it's returned. Otherwise a fresh instance- is constructed.-- :param str handle: unique identifier used to access this config instance- """-- if handle not in CONFS:- CONFS[handle] = Config()-- return CONFS[handle]---def uses_settings(handle, path, lazy_load = True):- """- Provides a function that can be used as a decorator for other functions that- require settings to be loaded. Functions with this decorator will be provided- with the configuration as its 'config' keyword argument.-- .. versionchanged:: 1.3.0- Omits the 'config' argument if the funcion we're decorating doesn't accept- it.-- ::-- uses_settings = stem.util.conf.uses_settings('my_app', '/path/to/settings.cfg')-- @uses_settings- def my_function(config):- print 'hello %s!' % config.get('username', '')-- :param str handle: hande for the configuration- :param str path: path where the configuration should be loaded from- :param bool lazy_load: loads the configuration file when the decorator is- used if true, otherwise it's loaded right away-- :returns: **function** that can be used as a decorator to provide the- configuration-- :raises: **IOError** if we fail to read the configuration file, if- **lazy_load** is true then this arises when we use the decorator- """-- config = get_config(handle)-- if not lazy_load and not config.get('settings_loaded', False):- config.load(path)- config.set('settings_loaded', 'true')-- def decorator(func):- def wrapped(*args, **kwargs):- if lazy_load and not config.get('settings_loaded', False):- config.load(path)- config.set('settings_loaded', 'true')-- if 'config' in inspect.getargspec(func).args:- return func(*args, config = config, **kwargs)- else:- return func(*args, **kwargs)-- return wrapped-- return decorator---def parse_enum(key, value, enumeration):- """- Provides the enumeration value for a given key. This is a case insensitive- lookup and raises an exception if the enum key doesn't exist.-- :param str key: configuration key being looked up- :param str value: value to be parsed- :param stem.util.enum.Enum enumeration: enumeration the values should be in-- :returns: enumeration value-- :raises: **ValueError** if the **value** isn't among the enumeration keys- """-- return parse_enum_csv(key, value, enumeration, 1)[0]---def parse_enum_csv(key, value, enumeration, count = None):- """- Parses a given value as being a comma separated listing of enumeration keys,- returning the corresponding enumeration values. This is intended to be a- helper for config handlers. The checks this does are case insensitive.-- The **count** attribute can be used to make assertions based on the number of- values. This can be...-- * None to indicate that there's no restrictions.- * An int to indicate that we should have this many values.- * An (int, int) tuple to indicate the range that values can be in. This range- is inclusive and either can be None to indicate the lack of a lower or- upper bound.-- :param str key: configuration key being looked up- :param str value: value to be parsed- :param stem.util.enum.Enum enumeration: enumeration the values should be in- :param int,tuple count: validates that we have this many items-- :returns: list with the enumeration values-- :raises: **ValueError** if the count assertion fails or the **value** entries- don't match the enumeration keys- """-- values = [val.upper().strip() for val in value.split(',')]-- if values == ['']:- return []-- if count is None:- pass # no count validateion checks to do- elif isinstance(count, int):- if len(values) != count:- raise ValueError("Config entry '%s' is expected to be %i comma separated values, got '%s'" % (key, count, value))- elif isinstance(count, tuple) and len(count) == 2:- minimum, maximum = count-- if minimum is not None and len(values) < minimum:- raise ValueError("Config entry '%s' must have at least %i comma separated values, got '%s'" % (key, minimum, value))-- if maximum is not None and len(values) > maximum:- raise ValueError("Config entry '%s' can have at most %i comma separated values, got '%s'" % (key, maximum, value))- else:- raise ValueError("The count must be None, an int, or two value tuple. Got '%s' (%s)'" % (count, type(count)))-- result = []- enum_keys = [k.upper() for k in list(enumeration.keys())]- enum_values = list(enumeration)-- for val in values:- if val in enum_keys:- result.append(enum_values[enum_keys.index(val)])- else:- raise ValueError("The '%s' entry of config entry '%s' wasn't in the enumeration (expected %s)" % (val, key, ', '.join(enum_keys)))-- return result---class Config(object):- """- Handler for easily working with custom configurations, providing persistence- to and from files. All operations are thread safe.-- **Example usage:**-- User has a file at '/home/atagar/myConfig' with...-- ::-- destination.ip 1.2.3.4- destination.port blarg-- startup.run export PATH=$PATH:~/bin- startup.run alias l=ls-- And they have a script with...-- ::-- from stem.util import conf-- # Configuration values we'll use in this file. These are mappings of- # configuration keys to the default values we'll use if the user doesn't- # have something different in their config file (or it doesn't match this- # type).-- ssh_config = conf.config_dict('ssh_login', {- 'login.user': 'atagar',- 'login.password': 'pepperjack_is_awesome!',- 'destination.ip': '127.0.0.1',- 'destination.port': 22,- 'startup.run': [],- })-- # Makes an empty config instance with the handle of 'ssh_login'. This is- # a singleton so other classes can fetch this same configuration from- # this handle.-- user_config = conf.get_config('ssh_login')-- # Loads the user's configuration file, warning if this fails.-- try:- user_config.load("/home/atagar/myConfig")- except IOError as exc:- print "Unable to load the user's config: %s" % exc-- # This replace the contents of ssh_config with the values from the user's- # config file if...- #- # * the key is present in the config file- # * we're able to convert the configuration file's value to the same type- # as what's in the mapping (see the Config.get() method for how these- # type inferences work)- #- # For instance in this case...- #- # * the login values are left alone because they aren't in the user's- # config file- #- # * the 'destination.port' is also left with the value of 22 because we- # can't turn "blarg" into an integer- #- # The other values are replaced, so ssh_config now becomes...- #- # {'login.user': 'atagar',- # 'login.password': 'pepperjack_is_awesome!',- # 'destination.ip': '1.2.3.4',- # 'destination.port': 22,- # 'startup.run': ['export PATH=$PATH:~/bin', 'alias l=ls']}- #- # Information for what values fail to load and why are reported to- # 'stem.util.log'.- """-- def __init__(self):- self._path = None # location we last loaded from or saved to- self._contents = {} # configuration key/value pairs- self._listeners = [] # functors to be notified of config changes-- # used for accessing _contents- self._contents_lock = threading.RLock()-- # keys that have been requested (used to provide unused config contents)- self._requested_keys = set()-- def load(self, path = None):- """- Reads in the contents of the given path, adding its configuration values- to our current contents. If the path is a directory then this loads each- of the files, recursively.-- .. versionchanged:: 1.3.0- Added support for directories.-- :param str path: file or directory path to be loaded, this uses the last- loaded path if not provided-- :raises:- * **IOError** if we fail to read the file (it doesn't exist, insufficient- permissions, etc)- * **ValueError** if no path was provided and we've never been provided one- """-- if path:- self._path = path- elif not self._path:- raise ValueError('Unable to load configuration: no path provided')-- if os.path.isdir(self._path):- for root, dirnames, filenames in os.walk(self._path):- for filename in filenames:- self.load(os.path.join(root, filename))-- return-- with open(self._path, 'r') as config_file:- read_contents = config_file.readlines()-- with self._contents_lock:- while read_contents:- line = read_contents.pop(0)-- # strips any commenting or excess whitespace- comment_start = line.find('#')-- if comment_start != -1:- line = line[:comment_start]-- line = line.strip()-- # parse the key/value pair- if line:- try:- key, value = line.split(' ', 1)- value = value.strip()- except ValueError:- log.debug("Config entry '%s' is expected to be of the format 'Key Value', defaulting to '%s' -> ''" % (line, line))- key, value = line, ''-- if not value:- # this might be a multi-line entry, try processing it as such- multiline_buffer = []-- while read_contents and read_contents[0].lstrip().startswith('|'):- content = read_contents.pop(0).lstrip()[1:] # removes '\s+|' prefix- content = content.rstrip('\n') # trailing newline- multiline_buffer.append(content)-- if multiline_buffer:- self.set(key, '\n'.join(multiline_buffer), False)- continue-- self.set(key, value, False)-- def save(self, path = None):- """- Saves configuration contents to disk. If a path is provided then it- replaces the configuration location that we track.-- :param str path: location to be saved to-- :raises: **ValueError** if no path was provided and we've never been provided one- """-- if path:- self._path = path- elif not self._path:- raise ValueError('Unable to save configuration: no path provided')-- with self._contents_lock:- with open(self._path, 'w') as output_file:- for entry_key in sorted(self.keys()):- for entry_value in self.get_value(entry_key, multiple = True):- # check for multi line entries- if '\n' in entry_value:- entry_value = '\n|' + entry_value.replace('\n', '\n|')-- output_file.write('%s %s\n' % (entry_key, entry_value))-- def clear(self):- """- Drops the configuration contents and reverts back to a blank, unloaded- state.- """-- with self._contents_lock:- self._contents.clear()- self._requested_keys = set()-- def add_listener(self, listener, backfill = True):- """- Registers the function to be notified of configuration updates. Listeners- are expected to be functors which accept (config, key).-- :param functor listener: function to be notified when our configuration is changed- :param bool backfill: calls the function with our current values if **True**- """-- with self._contents_lock:- self._listeners.append(listener)-- if backfill:- for key in self.keys():- listener(self, key)-- def clear_listeners(self):- """- Removes all attached listeners.- """-- self._listeners = []-- def keys(self):- """- Provides all keys in the currently loaded configuration.-- :returns: **list** if strings for the configuration keys we've loaded- """-- return list(self._contents.keys())-- def unused_keys(self):- """- Provides the configuration keys that have never been provided to a caller- via :func:`~stem.util.conf.config_dict` or the- :func:`~stem.util.conf.Config.get` and- :func:`~stem.util.conf.Config.get_value` methods.-- :returns: **set** of configuration keys we've loaded but have never been requested- """-- return set(self.keys()).difference(self._requested_keys)-- def set(self, key, value, overwrite = True):- """- Appends the given key/value configuration mapping, behaving the same as if- we'd loaded this from a configuration file.-- :param str key: key for the configuration mapping- :param str,list value: value we're setting the mapping to- :param bool overwrite: replaces the previous value if **True**, otherwise- the values are appended- """-- with self._contents_lock:- if isinstance(value, str):- if not overwrite and key in self._contents:- self._contents[key].append(value)- else:- self._contents[key] = [value]-- for listener in self._listeners:- listener(self, key)- elif isinstance(value, (list, tuple)):- if not overwrite and key in self._contents:- self._contents[key] += value- else:- self._contents[key] = value-- for listener in self._listeners:- listener(self, key)- else:- raise ValueError("Config.set() only accepts str, list, or tuple. Provided value was a '%s'" % type(value))-- def get(self, key, default = None):- """- Fetches the given configuration, using the key and default value to- determine the type it should be. Recognized inferences are:-- * **default is a boolean => boolean**-- * values are case insensitive- * provides the default if the value isn't "true" or "false"-- * **default is an integer => int**-- * provides the default if the value can't be converted to an int-- * **default is a float => float**-- * provides the default if the value can't be converted to a float-- * **default is a list => list**-- * string contents for all configuration values with this key-- * **default is a tuple => tuple**-- * string contents for all configuration values with this key-- * **default is a dictionary => dict**-- * values without "=>" in them are ignored- * values are split into key/value pairs on "=>" with extra whitespace- stripped-- :param str key: config setting to be fetched- :param default object: value provided if no such key exists or fails to be converted-- :returns: given configuration value with its type inferred with the above rules- """-- is_multivalue = isinstance(default, (list, tuple, dict))- val = self.get_value(key, default, is_multivalue)-- if val == default:- return val # don't try to infer undefined values-- if isinstance(default, bool):- if val.lower() == 'true':- val = True- elif val.lower() == 'false':- val = False- else:- log.debug("Config entry '%s' is expected to be a boolean, defaulting to '%s'" % (key, str(default)))- val = default- elif isinstance(default, int):- try:- val = int(val)- except ValueError:- log.debug("Config entry '%s' is expected to be an integer, defaulting to '%i'" % (key, default))- val = default- elif isinstance(default, float):- try:- val = float(val)- except ValueError:- log.debug("Config entry '%s' is expected to be a float, defaulting to '%f'" % (key, default))- val = default- elif isinstance(default, list):- val = list(val) # make a shallow copy- elif isinstance(default, tuple):- val = tuple(val)- elif isinstance(default, dict):- val_map = OrderedDict()- for entry in val:- if '=>' in entry:- entry_key, entry_val = entry.split('=>', 1)- val_map[entry_key.strip()] = entry_val.strip()- else:- log.debug('Ignoring invalid %s config entry (expected a mapping, but "%s" was missing "=>")' % (key, entry))- val = val_map-- return val-- def get_value(self, key, default = None, multiple = False):- """- This provides the current value associated with a given key.-- :param str key: config setting to be fetched- :param object default: value provided if no such key exists- :param bool multiple: provides back a list of all values if **True**,- otherwise this returns the last loaded configuration value-- :returns: **str** or **list** of string configuration values associated- with the given key, providing the default if no such key exists- """-- with self._contents_lock:- if key in self._contents:- self._requested_keys.add(key)-- if multiple:- return self._contents[key]- else:- return self._contents[key][-1]- else:- message_id = 'stem.util.conf.missing_config_key_%s' % key- log.log_once(message_id, log.TRACE, "config entry '%s' not found, defaulting to '%s'" % (key, default))- return defaultdiff --git a/ext/stem/util/connection.py b/ext/stem/util/connection.pydeleted file mode 100644index 88d70d58..00000000--- a/ext/stem/util/connection.py+++ /dev/null@@ -1,651 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Connection and networking based utility functions.--**Module Overview:**--::-- get_connections - quieries the connections belonging to a given process- system_resolvers - provides connection resolution methods that are likely to be available- port_usage - brief description of the common usage for a port-- is_valid_ipv4_address - checks if a string is a valid IPv4 address- is_valid_ipv6_address - checks if a string is a valid IPv6 address- is_valid_port - checks if something is a valid representation for a port- is_private_address - checks if an IPv4 address belongs to a private range or not-- expand_ipv6_address - provides an IPv6 address with its collapsed portions expanded- get_mask_ipv4 - provides the mask representation for a given number of bits- get_mask_ipv6 - provides the IPv6 mask representation for a given number of bits--.. data:: Resolver (enum)-- Method for resolving a process' connections.-- .. versionadded:: 1.1.0- .. versionchanged:: 1.4.0- Added **NETSTAT_WINDOWS**.-- ==================== ===========- Resolver Description- ==================== ===========- **PROC** /proc contents- **NETSTAT** netstat- **NETSTAT_WINDOWS** netstat command under Windows- **SS** ss command- **LSOF** lsof command- **SOCKSTAT** sockstat command under *nix- **BSD_SOCKSTAT** sockstat command under FreeBSD- **BSD_PROCSTAT** procstat command under FreeBSD- ==================== ===========-"""--import collections-import hashlib-import hmac-import os-import platform-import re--import stem.util.proc-import stem.util.system--from stem import str_type-from stem.util import conf, enum, log--# Connection resolution is risky to log about since it's highly likely to-# contain sensitive information. That said, it's also difficult to get right in-# a platform independent fashion. To opt into the logging requried to-# troubleshoot connection resolution set the following...--LOG_CONNECTION_RESOLUTION = False--Resolver = enum.Enum(- ('PROC', 'proc'),- ('NETSTAT', 'netstat'),- ('NETSTAT_WINDOWS', 'netstat (windows)'),- ('SS', 'ss'),- ('LSOF', 'lsof'),- ('SOCKSTAT', 'sockstat'),- ('BSD_SOCKSTAT', 'sockstat (bsd)'),- ('BSD_PROCSTAT', 'procstat (bsd)')-)--Connection = collections.namedtuple('Connection', [- 'local_address',- 'local_port',- 'remote_address',- 'remote_port',- 'protocol',-])--FULL_IPv4_MASK = '255.255.255.255'-FULL_IPv6_MASK = 'FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF'--CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE = os.urandom(32)--PORT_USES = None # port number => description--RESOLVER_COMMAND = {- Resolver.PROC: '',-- # -n = prevents dns lookups, -p = include process- Resolver.NETSTAT: 'netstat -np',-- # -a = show all TCP/UDP connections, -n = numeric addresses and ports, -o = include pid- Resolver.NETSTAT_WINDOWS: 'netstat -ano',-- # -n = numeric ports, -p = include process, -t = tcp sockets, -u = udp sockets- Resolver.SS: 'ss -nptu',-- # -n = prevent dns lookups, -P = show port numbers (not names), -i = ip only, -w = no warnings- # (lsof provides a '-p <pid>' but oddly in practice it seems to be ~11-28% slower)- Resolver.LSOF: 'lsof -wnPi',-- Resolver.SOCKSTAT: 'sockstat',-- # -4 = IPv4, -c = connected sockets- Resolver.BSD_SOCKSTAT: 'sockstat -4c',-- # -f <pid> = process pid- Resolver.BSD_PROCSTAT: 'procstat -f {pid}',-}--RESOLVER_FILTER = {- Resolver.PROC: '',-- # tcp 0 586 192.168.0.1:44284 38.229.79.2:443 ESTABLISHED 15843/tor- Resolver.NETSTAT: '^{protocol}\s+.*\s+{local_address}:{local_port}\s+{remote_address}:{remote_port}\s+ESTABLISHED\s+{pid}/{name}\s*$',-- # tcp 586 192.168.0.1:44284 38.229.79.2:443 ESTABLISHED 15843- Resolver.NETSTAT_WINDOWS: '^\s*{protocol}\s+{local_address}:{local_port}\s+{remote_address}:{remote_port}\s+ESTABLISHED\s+{pid}\s*$',-- # tcp ESTAB 0 0 192.168.0.20:44415 38.229.79.2:443 users:(("tor",15843,9))- Resolver.SS: '^{protocol}\s+ESTAB\s+.*\s+{local_address}:{local_port}\s+{remote_address}:{remote_port}\s+users:\(\("{name}",{pid},[0-9]+\)\)$',-- # tor 3873 atagar 45u IPv4 40994 0t0 TCP 10.243.55.20:45724->194.154.227.109:9001 (ESTABLISHED)- Resolver.LSOF: '^{name}\s+{pid}\s+.*\s+{protocol}\s+{local_address}:{local_port}->{remote_address}:{remote_port} \(ESTABLISHED\)$',-- # atagar tor 15843 tcp4 192.168.0.20:44092 68.169.35.102:443 ESTABLISHED- Resolver.SOCKSTAT: '^\S+\s+{name}\s+{pid}\s+{protocol}4\s+{local_address}:{local_port}\s+{remote_address}:{remote_port}\s+ESTABLISHED$',-- # _tor tor 4397 12 tcp4 172.27.72.202:54011 127.0.0.1:9001- Resolver.BSD_SOCKSTAT: '^\S+\s+{name}\s+{pid}\s+\S+\s+{protocol}4\s+{local_address}:{local_port}\s+{remote_address}:{remote_port}$',-- # 3561 tor 4 s - rw---n-- 2 0 TCP 10.0.0.2:9050 10.0.0.1:22370- Resolver.BSD_PROCSTAT: '^\s*{pid}\s+{name}\s+.*\s+{protocol}\s+{local_address}:{local_port}\s+{remote_address}:{remote_port}$',-}---def get_connections(resolver, process_pid = None, process_name = None):- """- Retrieves a list of the current connections for a given process. This- provides a list of Connection instances, which have five attributes...-- * **local_address** (str)- * **local_port** (int)- * **remote_address** (str)- * **remote_port** (int)- * **protocol** (str, generally either 'tcp' or 'udp')-- .. versionadded:: 1.1.0-- :param Resolver resolver: method of connection resolution to use- :param int process_pid: pid of the process to retrieve- :param str process_name: name of the process to retrieve-- :returns: **list** of Connection instances-- :raises:- * **ValueError** if using **Resolver.PROC** or **Resolver.BSD_PROCSTAT**- and the process_pid wasn't provided-- * **IOError** if no connections are available or resolution fails- (generally they're indistinguishable). The common causes are the- command being unavailable or permissions.- """-- def _log(msg):- if LOG_CONNECTION_RESOLUTION:- log.debug(msg)-- _log('=' * 80)- _log('Querying connections for resolver: %s, pid: %s, name: %s' % (resolver, process_pid, process_name))-- if isinstance(process_pid, str):- try:- process_pid = int(process_pid)- except ValueError:- raise ValueError('Process pid was non-numeric: %s' % process_pid)-- if process_pid is None and process_name and resolver == Resolver.NETSTAT_WINDOWS:- process_pid = stem.util.system.pid_by_name(process_name)-- if process_pid is None and resolver in (Resolver.NETSTAT_WINDOWS, Resolver.PROC, Resolver.BSD_PROCSTAT):- raise ValueError('%s resolution requires a pid' % resolver)-- if resolver == Resolver.PROC:- return [Connection(*conn) for conn in stem.util.proc.connections(process_pid)]-- resolver_command = RESOLVER_COMMAND[resolver].format(pid = process_pid)-- try:- results = stem.util.system.call(resolver_command)- except OSError as exc:- raise IOError("Unable to query '%s': %s" % (resolver_command, exc))-- resolver_regex_str = RESOLVER_FILTER[resolver].format(- protocol = '(?P<protocol>\S+)',- local_address = '(?P<local_address>[0-9.]+)',- local_port = '(?P<local_port>[0-9]+)',- remote_address = '(?P<remote_address>[0-9.]+)',- remote_port = '(?P<remote_port>[0-9]+)',- pid = process_pid if process_pid else '[0-9]*',- name = process_name if process_name else '\S*',- )-- _log('Resolver regex: %s' % resolver_regex_str)- _log('Resolver results:\n%s' % '\n'.join(results))-- connections = []- resolver_regex = re.compile(resolver_regex_str)-- for line in results:- match = resolver_regex.match(line)-- if match:- attr = match.groupdict()- local_addr = attr['local_address']- local_port = int(attr['local_port'])- remote_addr = attr['remote_address']- remote_port = int(attr['remote_port'])- protocol = attr['protocol'].lower()-- if remote_addr == '0.0.0.0':- continue # procstat response for unestablished connections-- if not (is_valid_ipv4_address(local_addr) and is_valid_ipv4_address(remote_addr)):- _log('Invalid address (%s or %s): %s' % (local_addr, remote_addr, line))- elif not (is_valid_port(local_port) and is_valid_port(remote_port)):- _log('Invalid port (%s or %s): %s' % (local_port, remote_port, line))- elif protocol not in ('tcp', 'udp'):- _log('Unrecognized protocol (%s): %s' % (protocol, line))-- conn = Connection(local_addr, local_port, remote_addr, remote_port, protocol)- connections.append(conn)- _log(str(conn))-- _log('%i connections found' % len(connections))-- if not connections:- raise IOError('No results found using: %s' % resolver_command)-- return connections---def system_resolvers(system = None):- """- Provides the types of connection resolvers likely to be available on this platform.-- .. versionadded:: 1.1.0-- .. versionchanged:: 1.3.0- Renamed from get_system_resolvers() to system_resolvers(). The old name- still works as an alias, but will be dropped in Stem version 2.0.0.-- :param str system: system to get resolvers for, this is determined by- platform.system() if not provided-- :returns: **list** of :data:`~stem.util.connection.Resolver` instances available on this platform- """- if system is None:- if stem.util.system.is_gentoo():- system = 'Gentoo'- else:- system = platform.system()-- if system == 'Windows':- resolvers = [Resolver.NETSTAT_WINDOWS]- elif system in ('Darwin', 'OpenBSD'):- resolvers = [Resolver.LSOF]- elif system == 'FreeBSD':- # Netstat is available, but lacks a '-p' equivalent so we can't associate- # the results to processes. The platform also has a ss command, but it- # belongs to a spreadsheet application.-- resolvers = [Resolver.BSD_SOCKSTAT, Resolver.BSD_PROCSTAT, Resolver.LSOF]- else:- # Sockstat isn't available by default on ubuntu.-- resolvers = [Resolver.NETSTAT, Resolver.SOCKSTAT, Resolver.LSOF, Resolver.SS]-- # remove any that aren't in the user's PATH-- resolvers = [r for r in resolvers if stem.util.system.is_available(RESOLVER_COMMAND[r])]-- # proc resolution, by far, outperforms the others so defaults to this is able-- if stem.util.proc.is_available() and os.access('/proc/net/tcp', os.R_OK) and os.access('/proc/net/udp', os.R_OK):- resolvers = [Resolver.PROC] + resolvers-- return resolvers---def port_usage(port):- """- Provides the common use of a given port. For example, 'HTTP' for port 80 or- 'SSH' for 22.-- .. versionadded:: 1.2.0-- :param int port: port number to look up-- :returns: **str** with a description for the port, **None** if none is known- """-- global PORT_USES-- if PORT_USES is None:- config = conf.Config()- config_path = os.path.join(os.path.dirname(__file__), 'ports.cfg')-- try:- config.load(config_path)- port_uses = {}-- for key, value in config.get('port', {}).items():- if key.isdigit():- port_uses[int(key)] = value- elif '-' in key:- min_port, max_port = key.split('-', 1)-- for port_entry in range(int(min_port), int(max_port) + 1):- port_uses[port_entry] = value- else:- raise ValueError("'%s' is an invalid key" % key)-- PORT_USES = port_uses- except Exception as exc:- log.warn("BUG: stem failed to load its internal port descriptions from '%s': %s" % (config_path, exc))-- if not PORT_USES:- return None-- if isinstance(port, str) and port.isdigit():- port = int(port)-- return PORT_USES.get(port)---def is_valid_ipv4_address(address):- """- Checks if a string is a valid IPv4 address.-- :param str address: string to be checked-- :returns: **True** if input is a valid IPv4 address, **False** otherwise- """-- if not isinstance(address, (bytes, str_type)):- return False-- # checks if theres four period separated values-- if address.count('.') != 3:- return False-- # checks that each value in the octet are decimal values between 0-255- for entry in address.split('.'):- if not entry.isdigit() or int(entry) < 0 or int(entry) > 255:- return False- elif entry[0] == '0' and len(entry) > 1:- return False # leading zeros, for instance in '1.2.3.001'-- return True---def is_valid_ipv6_address(address, allow_brackets = False):- """- Checks if a string is a valid IPv6 address.-- :param str address: string to be checked- :param bool allow_brackets: ignore brackets which form '[address]'-- :returns: **True** if input is a valid IPv6 address, **False** otherwise- """-- if allow_brackets:- if address.startswith('[') and address.endswith(']'):- address = address[1:-1]-- # addresses are made up of eight colon separated groups of four hex digits- # with leading zeros being optional- # https://en.wikipedia.org/wiki/IPv6#Address_format-- colon_count = address.count(':')-- if colon_count > 7:- return False # too many groups- elif colon_count != 7 and '::' not in address:- return False # not enough groups and none are collapsed- elif address.count('::') > 1 or ':::' in address:- return False # multiple groupings of zeros can't be collapsed-- for entry in address.split(':'):- if not re.match('^[0-9a-fA-f]{0,4}$', entry):- return False-- return True---def is_valid_port(entry, allow_zero = False):- """- Checks if a string or int is a valid port number.-- :param list,str,int entry: string, integer or list to be checked- :param bool allow_zero: accept port number of zero (reserved by definition)-- :returns: **True** if input is an integer and within the valid port range, **False** otherwise- """-- try:- value = int(entry)-- if str(value) != str(entry):- return False # invalid leading char, e.g. space or zero- elif allow_zero and value == 0:- return True- else:- return value > 0 and value < 65536- except TypeError:- if isinstance(entry, (tuple, list)):- for port in entry:- if not is_valid_port(port, allow_zero):- return False-- return True- else:- return False- except ValueError:- return False---def is_private_address(address):- """- Checks if the IPv4 address is in a range belonging to the local network or- loopback. These include:-- * Private ranges: 10.*, 172.16.* - 172.31.*, 192.168.*- * Loopback: 127.*-- .. versionadded:: 1.1.0-- :param str address: string to be checked-- :returns: **True** if input is in a private range, **False** otherwise-- :raises: **ValueError** if the address isn't a valid IPv4 address- """-- if not is_valid_ipv4_address(address):- raise ValueError("'%s' isn't a valid IPv4 address" % address)-- # checks for any of the simple wildcard ranges-- if address.startswith('10.') or address.startswith('192.168.') or address.startswith('127.'):- return True-- # checks for the 172.16.* - 172.31.* range-- if address.startswith('172.'):- second_octet = int(address.split('.')[1])-- if second_octet >= 16 and second_octet <= 31:- return True-- return False---def expand_ipv6_address(address):- """- Expands abbreviated IPv6 addresses to their full colon separated hex format.- For instance...-- ::-- >>> expand_ipv6_address('2001:db8::ff00:42:8329')- '2001:0db8:0000:0000:0000:ff00:0042:8329'-- >>> expand_ipv6_address('::')- '0000:0000:0000:0000:0000:0000:0000:0000'-- :param str address: IPv6 address to be expanded-- :raises: **ValueError** if the address can't be expanded due to being malformed- """-- if not is_valid_ipv6_address(address):- raise ValueError("'%s' isn't a valid IPv6 address" % address)-- # expands collapsed groupings, there can only be a single '::' in a valid- # address- if '::' in address:- missing_groups = 7 - address.count(':')- address = address.replace('::', '::' + ':' * missing_groups)-- # inserts missing zeros- for index in range(8):- start = index * 5- end = address.index(':', start) if index != 7 else len(address)- missing_zeros = 4 - (end - start)-- if missing_zeros > 0:- address = address[:start] + '0' * missing_zeros + address[start:]-- return address---def get_mask_ipv4(bits):- """- Provides the IPv4 mask for a given number of bits, in the dotted-quad format.-- :param int bits: number of bits to be converted-- :returns: **str** with the subnet mask representation for this many bits-- :raises: **ValueError** if given a number of bits outside the range of 0-32- """-- if bits > 32 or bits < 0:- raise ValueError('A mask can only be 0-32 bits, got %i' % bits)- elif bits == 32:- return FULL_IPv4_MASK-- # get the binary representation of the mask- mask_bin = _get_binary(2 ** bits - 1, 32)[::-1]-- # breaks it into eight character groupings- octets = [mask_bin[8 * i:8 * (i + 1)] for i in range(4)]-- # converts each octet into its integer value- return '.'.join([str(int(octet, 2)) for octet in octets])---def get_mask_ipv6(bits):- """- Provides the IPv6 mask for a given number of bits, in the hex colon-delimited- format.-- :param int bits: number of bits to be converted-- :returns: **str** with the subnet mask representation for this many bits-- :raises: **ValueError** if given a number of bits outside the range of 0-128- """-- if bits > 128 or bits < 0:- raise ValueError('A mask can only be 0-128 bits, got %i' % bits)- elif bits == 128:- return FULL_IPv6_MASK-- # get the binary representation of the mask- mask_bin = _get_binary(2 ** bits - 1, 128)[::-1]-- # breaks it into sixteen character groupings- groupings = [mask_bin[16 * i:16 * (i + 1)] for i in range(8)]-- # converts each group into its hex value- return ':'.join(['%04x' % int(group, 2) for group in groupings]).upper()---def _get_masked_bits(mask):- """- Provides the number of bits that an IPv4 subnet mask represents. Note that- not all masks can be represented by a bit count.-- :param str mask: mask to be converted-- :returns: **int** with the number of bits represented by the mask-- :raises: **ValueError** if the mask is invalid or can't be converted- """-- if not is_valid_ipv4_address(mask):- raise ValueError("'%s' is an invalid subnet mask" % mask)-- # converts octets to binary representation- mask_bin = _get_address_binary(mask)- mask_match = re.match('^(1*)(0*)$', mask_bin)-- if mask_match:- return 32 - len(mask_match.groups()[1])- else:- raise ValueError('Unable to convert mask to a bit count: %s' % mask)---def _get_binary(value, bits):- """- Provides the given value as a binary string, padded with zeros to the given- number of bits.-- :param int value: value to be converted- :param int bits: number of bits to pad to- """-- # http://www.daniweb.com/code/snippet216539.html- return ''.join([str((value >> y) & 1) for y in range(bits - 1, -1, -1)])---def _get_address_binary(address):- """- Provides the binary value for an IPv4 or IPv6 address.-- :returns: **str** with the binary representation of this address-- :raises: **ValueError** if address is neither an IPv4 nor IPv6 address- """-- if is_valid_ipv4_address(address):- return ''.join([_get_binary(int(octet), 8) for octet in address.split('.')])- elif is_valid_ipv6_address(address):- address = expand_ipv6_address(address)- return ''.join([_get_binary(int(grouping, 16), 16) for grouping in address.split(':')])- else:- raise ValueError("'%s' is neither an IPv4 or IPv6 address" % address)---def _hmac_sha256(key, msg):- """- Generates a sha256 digest using the given key and message.-- :param str key: starting key for the hash- :param str msg: message to be hashed-- :returns: sha256 digest of msg as bytes, hashed using the given key- """-- return hmac.new(key, msg, hashlib.sha256).digest()---def _cryptovariables_equal(x, y):- """- Compares two strings for equality securely.-- :param str x: string to be compared.- :param str y: the other string to be compared.-- :returns: **True** if both strings are equal, **False** otherwise.- """-- return (- _hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, x) ==- _hmac_sha256(CRYPTOVARIABLE_EQUALITY_COMPARISON_NONCE, y))--# TODO: drop with stem 2.x-# We renamed our methods to drop a redundant 'get_*' prefix, so alias the old-# names for backward compatability.--get_system_resolvers = system_resolversdiff --git a/ext/stem/util/enum.py b/ext/stem/util/enum.pydeleted file mode 100644index 5cf81b8b..00000000--- a/ext/stem/util/enum.py+++ /dev/null@@ -1,172 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Basic enumeration, providing ordered types for collections. These can be-constructed as simple type listings...--::-- >>> from stem.util import enum- >>> insects = enum.Enum('ANT', 'WASP', 'LADYBUG', 'FIREFLY')- >>> insects.ANT- 'Ant'- >>> tuple(insects)- ('Ant', 'Wasp', 'Ladybug', 'Firefly')--... or with overwritten string counterparts...--::-- >>> from stem.util import enum- >>> pets = enum.Enum(('DOG', 'Skippy'), 'CAT', ('FISH', 'Nemo'))- >>> pets.DOG- 'Skippy'- >>> pets.CAT- 'Cat'--**Module Overview:**--::-- UppercaseEnum - Provides an enum instance with capitalized values-- Enum - Provides a basic, ordered enumeration- |- keys - string representation of our enum keys- |- index_of - index of an enum value- |- next - provides the enum after a given enum value- |- previous - provides the enum before a given value- |- __getitem__ - provides the value for an enum key- +- __iter__ - iterator over our enum keys-"""--from stem import str_type---def UppercaseEnum(*args):- """- Provides an :class:`~stem.util.enum.Enum` instance where the values are- identical to the keys. Since the keys are uppercase by convention this means- the values are too. For instance...-- ::-- >>> from stem.util import enum- >>> runlevels = enum.UppercaseEnum('DEBUG', 'INFO', 'NOTICE', 'WARN', 'ERROR')- >>> runlevels.DEBUG- 'DEBUG'-- :param list args: enum keys to initialize with-- :returns: :class:`~stem.util.enum.Enum` instance with the given keys- """-- return Enum(*[(v, v) for v in args])---class Enum(object):- """- Basic enumeration.- """-- def __init__(self, *args):- from stem.util.str_tools import _to_camel_case-- # ordered listings of our keys and values- keys, values = [], []-- for entry in args:- if isinstance(entry, (bytes, str_type)):- key, val = entry, _to_camel_case(entry)- elif isinstance(entry, tuple) and len(entry) == 2:- key, val = entry- else:- raise ValueError('Unrecognized input: %s' % args)-- keys.append(key)- values.append(val)- setattr(self, key, val)-- self._keys = tuple(keys)- self._values = tuple(values)-- def keys(self):- """- Provides an ordered listing of the enumeration keys in this set.-- :returns: **list** with our enum keys- """-- return list(self._keys)-- def index_of(self, value):- """- Provides the index of the given value in the collection.-- :param str value: entry to be looked up-- :returns: **int** index of the given entry-- :raises: **ValueError** if no such element exists- """-- return self._values.index(value)-- def next(self, value):- """- Provides the next enumeration after the given value.-- :param str value: enumeration for which to get the next entry-- :returns: enum value following the given entry-- :raises: **ValueError** if no such element exists- """-- if value not in self._values:- raise ValueError('No such enumeration exists: %s (options: %s)' % (value, ', '.join(self._values)))-- next_index = (self._values.index(value) + 1) % len(self._values)- return self._values[next_index]-- def previous(self, value):- """- Provides the previous enumeration before the given value.-- :param str value: enumeration for which to get the previous entry-- :returns: enum value proceeding the given entry-- :raises: **ValueError** if no such element exists- """-- if value not in self._values:- raise ValueError('No such enumeration exists: %s (options: %s)' % (value, ', '.join(self._values)))-- prev_index = (self._values.index(value) - 1) % len(self._values)- return self._values[prev_index]-- def __getitem__(self, item):- """- Provides the values for the given key.-- :param str item: key to be looked up-- :returns: **str** with the value for the given key-- :raises: **ValueError** if the key doesn't exist- """-- if item in vars(self):- return getattr(self, item)- else:- keys = ', '.join(self.keys())- raise ValueError("'%s' isn't among our enumeration keys, which includes: %s" % (item, keys))-- def __iter__(self):- """- Provides an ordered listing of the enums in this set.- """-- for entry in self._values:- yield entrydiff --git a/ext/stem/util/log.py b/ext/stem/util/log.pydeleted file mode 100644index 4154706f..00000000--- a/ext/stem/util/log.py+++ /dev/null@@ -1,253 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Functions to aid library logging. The default logging-:data:`~stem.util.log.Runlevel` is usually NOTICE and above.--**Stem users are more than welcome to listen for stem events, but these-functions are not being vended to our users. They may change in the future, use-them at your own risk.**--**Module Overview:**--::-- get_logger - provides the stem's Logger instance- logging_level - converts a runlevel to its logging number- escape - escapes special characters in a message in preparation for logging-- log - logs a message at the given runlevel- log_once - logs a message, deduplicating if it has already been logged- trace - logs a message at the TRACE runlevel- debug - logs a message at the DEBUG runlevel- info - logs a message at the INFO runlevel- notice - logs a message at the NOTICE runlevel- warn - logs a message at the WARN runlevel- error - logs a message at the ERROR runlevel-- LogBuffer - Buffers logged events so they can be iterated over.- |- is_empty - checks if there's events in our buffer- +- __iter__ - iterates over and removes the buffered events-- log_to_stdout - reports further logged events to stdout--.. data:: Runlevel (enum)-- Enumeration for logging runlevels.-- ========== ===========- Runlevel Description- ========== ===========- **ERROR** critical issue occurred, the user needs to be notified- **WARN** non-critical issue occurred that the user should be aware of- **NOTICE** information that is helpful to the user- **INFO** high level library activity- **DEBUG** low level library activity- **TRACE** request/reply logging- ========== ===========-"""--import logging--import stem.prereq-import stem.util.enum-import stem.util.str_tools--# Logging runlevels. These are *very* commonly used so including shorter-# aliases (so they can be referenced as log.DEBUG, log.WARN, etc).--Runlevel = stem.util.enum.UppercaseEnum('TRACE', 'DEBUG', 'INFO', 'NOTICE', 'WARN', 'ERROR')-TRACE, DEBUG, INFO, NOTICE, WARN, ERR = list(Runlevel)--# mapping of runlevels to the logger module's values, TRACE and DEBUG aren't-# built into the module--LOG_VALUES = {- Runlevel.TRACE: logging.DEBUG - 5,- Runlevel.DEBUG: logging.DEBUG,- Runlevel.INFO: logging.INFO,- Runlevel.NOTICE: logging.INFO + 5,- Runlevel.WARN: logging.WARN,- Runlevel.ERROR: logging.ERROR,-}--logging.addLevelName(LOG_VALUES[TRACE], 'TRACE')-logging.addLevelName(LOG_VALUES[NOTICE], 'NOTICE')--LOGGER = logging.getLogger('stem')-LOGGER.setLevel(LOG_VALUES[TRACE])--# There's some messages that we don't want to log more than once. This set has-# the messages IDs that we've logged which fall into this category.-DEDUPLICATION_MESSAGE_IDS = set()--# Adds a default nullhandler for the stem logger, suppressing the 'No handlers-# could be found for logger "stem"' warning as per...-# http://docs.python.org/release/3.1.3/library/logging.html#configuring-logging-for-a-library---class _NullHandler(logging.Handler):- def emit(self, record):- pass--if not LOGGER.handlers:- LOGGER.addHandler(_NullHandler())---def get_logger():- """- Provides the stem logger.-- :return: **logging.Logger** for stem- """-- return LOGGER---def logging_level(runlevel):- """- Translates a runlevel into the value expected by the logging module.-- :param stem.util.log.Runlevel runlevel: runlevel to be returned, no logging if **None**- """-- if runlevel:- return LOG_VALUES[runlevel]- else:- return logging.FATAL + 5---def escape(message):- """- Escapes specific sequences for logging (newlines, tabs, carriage returns). If- the input is **bytes** then this converts it to **unicode** under python 3.x.-- :param str message: string to be escaped-- :returns: str that is escaped- """-- if stem.prereq.is_python_3():- message = stem.util.str_tools._to_unicode(message)-- for pattern, replacement in (('\n', '\\n'), ('\r', '\\r'), ('\t', '\\t')):- message = message.replace(pattern, replacement)-- return message---def log(runlevel, message):- """- Logs a message at the given runlevel.-- :param stem.util.log.Runlevel runlevel: runlevel to log the message at, logging is skipped if **None**- :param str message: message to be logged- """-- if runlevel:- LOGGER.log(LOG_VALUES[runlevel], message)---def log_once(message_id, runlevel, message):- """- Logs a message at the given runlevel. If a message with this ID has already- been logged then this is a no-op.-- :param str message_id: unique message identifier to deduplicate on- :param stem.util.log.Runlevel runlevel: runlevel to log the message at, logging is skipped if **None**- :param str message: message to be logged-- :returns: **True** if we log the message, **False** otherwise- """-- if not runlevel or message_id in DEDUPLICATION_MESSAGE_IDS:- return False- else:- DEDUPLICATION_MESSAGE_IDS.add(message_id)- log(runlevel, message)--# shorter aliases for logging at a runlevel---def trace(message):- log(Runlevel.TRACE, message)---def debug(message):- log(Runlevel.DEBUG, message)---def info(message):- log(Runlevel.INFO, message)---def notice(message):- log(Runlevel.NOTICE, message)---def warn(message):- log(Runlevel.WARN, message)---def error(message):- log(Runlevel.ERROR, message)---class LogBuffer(logging.Handler):- """- Basic log handler that listens for stem events and stores them so they can be- read later. Log entries are cleared as they are read.-- .. versionchanged:: 1.4.0- Added the yield_records argument.- """-- def __init__(self, runlevel, yield_records = False):- # TODO: At least in python 2.6 logging.Handler has a bug in that it doesn't- # extend object, causing our super() call to fail. When we drop python 2.6- # support we should switch back to using super() instead.- #- # super(LogBuffer, self).__init__(level = logging_level(runlevel))-- logging.Handler.__init__(self, level = logging_level(runlevel))-- self.formatter = logging.Formatter(- fmt = '%(asctime)s [%(levelname)s] %(message)s',- datefmt = '%m/%d/%Y %H:%M:%S')-- self._buffer = []- self._yield_records = yield_records-- def is_empty(self):- return not bool(self._buffer)-- def __iter__(self):- while self._buffer:- record = self._buffer.pop(0)- yield record if self._yield_records else self.formatter.format(record)-- def emit(self, record):- self._buffer.append(record)---class _StdoutLogger(logging.Handler):- def __init__(self, runlevel):- logging.Handler.__init__(self, level = logging_level(runlevel))-- self.formatter = logging.Formatter(- fmt = '%(asctime)s [%(levelname)s] %(message)s',- datefmt = '%m/%d/%Y %H:%M:%S')-- def emit(self, record):- print(self.formatter.format(record))---def log_to_stdout(runlevel):- """- Logs further events to stdout.-- :param stem.util.log.Runlevel runlevel: minimum runlevel a message needs to be to be logged- """-- get_logger().addHandler(_StdoutLogger(runlevel))diff --git a/ext/stem/util/lru_cache.py b/ext/stem/util/lru_cache.pydeleted file mode 100644index 011d4456..00000000--- a/ext/stem/util/lru_cache.py+++ /dev/null@@ -1,182 +0,0 @@-# Drop in replace for python 3.2's collections.lru_cache, from...-# http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/-#-# ... which is under the MIT license. Stem users should *not* rely upon this-# module. It will be removed when we drop support for python 3.2 and below.--"""-Memoization decorator that caches a function's return value. If later called-with the same arguments then the cached value is returned rather than-reevaluated.--This is a a python 2.x port of `functools.lru_cache-<http://docs.python.org/3/library/functools.html#functools.lru_cache>`_. If-using python 3.2 or later you should use that instead.-"""--from collections import namedtuple-from functools import update_wrapper-from threading import RLock--_CacheInfo = namedtuple('CacheInfo', ['hits', 'misses', 'maxsize', 'currsize'])---class _HashedSeq(list):- __slots__ = 'hashvalue'-- def __init__(self, tup, hash=hash):- self[:] = tup- self.hashvalue = hash(tup)-- def __hash__(self):- return self.hashvalue---def _make_key(args, kwds, typed,- kwd_mark = (object(),),- fasttypes = set([int, str, frozenset, type(None)]),- sorted=sorted, tuple=tuple, type=type, len=len):- 'Make a cache key from optionally typed positional and keyword arguments'- key = args- if kwds:- sorted_items = sorted(kwds.items())- key += kwd_mark- for item in sorted_items:- key += item- if typed:- key += tuple(type(v) for v in args)- if kwds:- key += tuple(type(v) for k, v in sorted_items)- elif len(key) == 1 and type(key[0]) in fasttypes:- return key[0]- return _HashedSeq(key)---def lru_cache(maxsize=100, typed=False):- """Least-recently-used cache decorator.-- If *maxsize* is set to None, the LRU features are disabled and the cache- can grow without bound.-- If *typed* is True, arguments of different types will be cached separately.- For example, f(3.0) and f(3) will be treated as distinct calls with- distinct results.-- Arguments to the cached function must be hashable.-- View the cache statistics named tuple (hits, misses, maxsize, currsize) with- f.cache_info(). Clear the cache and statistics with f.cache_clear().- Access the underlying function with f.__wrapped__.-- See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used-- """-- # Users should only access the lru_cache through its public API:- # cache_info, cache_clear, and f.__wrapped__- # The internals of the lru_cache are encapsulated for thread safety and- # to allow the implementation to change (including a possible C version).-- def decorating_function(user_function):-- cache = dict()- stats = [0, 0] # make statistics updateable non-locally- HITS, MISSES = 0, 1 # names for the stats fields- make_key = _make_key- cache_get = cache.get # bound method to lookup key or return None- _len = len # localize the global len() function- lock = RLock() # because linkedlist updates aren't threadsafe- root = [] # root of the circular doubly linked list- root[:] = [root, root, None, None] # initialize by pointing to self- nonlocal_root = [root] # make updateable non-locally- PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields-- if maxsize == 0:-- def wrapper(*args, **kwds):- # no caching, just do a statistics update after a successful call- result = user_function(*args, **kwds)- stats[MISSES] += 1- return result-- elif maxsize is None:-- def wrapper(*args, **kwds):- # simple caching without ordering or size limit- key = make_key(args, kwds, typed)- result = cache_get(key, root) # root used here as a unique not-found sentinel- if result is not root:- stats[HITS] += 1- return result- result = user_function(*args, **kwds)- cache[key] = result- stats[MISSES] += 1- return result-- else:-- def wrapper(*args, **kwds):- # size limited caching that tracks accesses by recency- key = make_key(args, kwds, typed) if kwds or typed else args- with lock:- link = cache_get(key)- if link is not None:- # record recent use of the key by moving it to the front of the list- root, = nonlocal_root- link_prev, link_next, key, result = link- link_prev[NEXT] = link_next- link_next[PREV] = link_prev- last = root[PREV]- last[NEXT] = root[PREV] = link- link[PREV] = last- link[NEXT] = root- stats[HITS] += 1- return result- result = user_function(*args, **kwds)- with lock:- root, = nonlocal_root- if key in cache:- # getting here means that this same key was added to the- # cache while the lock was released. since the link- # update is already done, we need only return the- # computed result and update the count of misses.- pass- elif _len(cache) >= maxsize:- # use the old root to store the new key and result- oldroot = root- oldroot[KEY] = key- oldroot[RESULT] = result- # empty the oldest link and make it the new root- root = nonlocal_root[0] = oldroot[NEXT]- oldkey = root[KEY]- root[KEY] = root[RESULT] = None- # now update the cache dictionary for the new links- del cache[oldkey]- cache[key] = oldroot- else:- # put result in a new link at the front of the list- last = root[PREV]- link = [last, root, key, result]- last[NEXT] = root[PREV] = cache[key] = link- stats[MISSES] += 1- return result-- def cache_info():- """Report cache statistics"""- with lock:- return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache))-- def cache_clear():- """Clear the cache and cache statistics"""- with lock:- cache.clear()- root = nonlocal_root[0]- root[:] = [root, root, None, None]- stats[:] = [0, 0]-- wrapper.__wrapped__ = user_function- wrapper.cache_info = cache_info- wrapper.cache_clear = cache_clear- return update_wrapper(wrapper, user_function)-- return decorating_functiondiff --git a/ext/stem/util/ordereddict.py b/ext/stem/util/ordereddict.pydeleted file mode 100644index 07c7d4ea..00000000--- a/ext/stem/util/ordereddict.py+++ /dev/null@@ -1,133 +0,0 @@-# Drop in replacement for python 2.7's OrderedDict, from...-# http://pypi.python.org/pypi/ordereddict-#-# Stem users should *not* rely upon this module. It will be removed when we-# drop support for python 2.6 and below.--# Copyright (c) 2009 Raymond Hettinger-#-# Permission is hereby granted, free of charge, to any person-# obtaining a copy of this software and associated documentation files-# (the "Software"), to deal in the Software without restriction,-# including without limitation the rights to use, copy, modify, merge,-# publish, distribute, sublicense, and/or sell copies of the Software,-# and to permit persons to whom the Software is furnished to do so,-# subject to the following conditions:-#-# The above copyright notice and this permission notice shall be-# included in all copies or substantial portions of the Software.-#-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,-# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES-# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND-# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT-# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,-# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING-# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR-# OTHER DEALINGS IN THE SOFTWARE.--from UserDict import DictMixin---class OrderedDict(dict, DictMixin):- def __init__(self, *args, **kwds):- if len(args) > 1:- raise TypeError('expected at most 1 arguments, got %d' % len(args))- try:- self.__end- except AttributeError:- self.clear()- self.update(*args, **kwds)-- def clear(self):- self.__end = end = []- end += [None, end, end] # sentinel node for doubly linked list- self.__map = {} # key --> [key, prev, next]- dict.clear(self)-- def __setitem__(self, key, value):- if key not in self:- end = self.__end- curr = end[1]- curr[2] = end[1] = self.__map[key] = [key, curr, end]- dict.__setitem__(self, key, value)-- def __delitem__(self, key):- dict.__delitem__(self, key)- key, prev, next = self.__map.pop(key)- prev[2] = next- next[1] = prev-- def __iter__(self):- end = self.__end- curr = end[2]- while curr is not end:- yield curr[0]- curr = curr[2]-- def __reversed__(self):- end = self.__end- curr = end[1]- while curr is not end:- yield curr[0]- curr = curr[1]-- def popitem(self, last=True):- if not self:- raise KeyError('dictionary is empty')- if last:- key = reversed(self).next()- else:- key = iter(self).next()- value = self.pop(key)- return key, value-- def __reduce__(self):- items = [[k, self[k]] for k in self]- tmp = self.__map, self.__end- del self.__map, self.__end- inst_dict = vars(self).copy()- self.__map, self.__end = tmp- if inst_dict:- return (self.__class__, (items,), inst_dict)- return self.__class__, (items,)-- def keys(self):- return list(self)-- setdefault = DictMixin.setdefault- update = DictMixin.update- pop = DictMixin.pop- values = DictMixin.values- items = DictMixin.items- iterkeys = DictMixin.iterkeys- itervalues = DictMixin.itervalues- iteritems = DictMixin.iteritems-- def __repr__(self):- if not self:- return '%s()' % (self.__class__.__name__,)- return '%s(%r)' % (self.__class__.__name__, self.items())-- def copy(self):- return self.__class__(self)-- @classmethod- def fromkeys(cls, iterable, value=None):- d = cls()- for key in iterable:- d[key] = value- return d-- def __eq__(self, other):- if isinstance(other, OrderedDict):- if len(self) != len(other):- return False- for p, q in zip(self.items(), other.items()):- if p != q:- return False- return True- return dict.__eq__(self, other)-- def __ne__(self, other):- return not self == otherdiff --git a/ext/stem/util/ports.cfg b/ext/stem/util/ports.cfgdeleted file mode 100644index 8b7829ed..00000000--- a/ext/stem/util/ports.cfg+++ /dev/null@@ -1,313 +0,0 @@-################################################################################-#-# Common usages for port . This is based on...-#-# https://secure.wikimedia.org/wikipedia/en/wiki/List_of_TCP_and_UDP_port numbers-# http://isc.sans.edu/services.html-#-################################################################################--port 1 => TCPMUX-port 2 => CompressNET-port 3 => CompressNET-port 5 => RJE-port 7 => Echo-port 9 => Discard-port 11 => SYSTAT-port 13 => Daytime-port 15 => netstat-port 17 => QOTD-port 18 => MSP-port 19 => CHARGEN-port 20 => FTP-port 21 => FTP-port 22 => SSH-port 23 => Telnet-port 24 => Priv-mail-port 25 => SMTP-port 34 => RF-port 35 => Printer-port 37 => TIME-port 39 => RLP-port 41 => Graphics-port 42 => WINS-port 43 => WHOIS-port 47 => NI FTP-port 49 => TACACS-port 50 => Remote Mail-port 51 => IMP-port 52 => XNS-port 53 => DNS-port 54 => XNS-port 55 => ISI-GL-port 56 => RAP-port 57 => MTP-port 58 => XNS-port 67 => BOOTP-port 68 => BOOTP-port 69 => TFTP-port 70 => Gopher-port 79 => Finger-port 80 => HTTP-port 81 => HTTP Alternate-port 82 => Torpark-port 83 => MIT ML-port 88 => Kerberos-port 90 => dnsix-port 99 => WIP-port 101 => NIC-port 102 => ISO-TSAP-port 104 => ACR/NEMA-port 105 => CCSO-port 107 => Telnet-port 108 => SNA-port 109 => POP2-port 110 => POP3-port 111 => ONC RPC-port 113 => ident-port 115 => SFTP-port 117 => UUCP-port 118 => SQL-port 119 => NNTP-port 123 => NTP-port 135 => DCE-port 137 => NetBIOS-port 138 => NetBIOS-port 139 => NetBIOS-port 143 => IMAP-port 152 => BFTP-port 153 => SGMP-port 156 => SQL-port 158 => DMSP-port 161 => SNMP-port 162 => SNMPTRAP-port 170 => Print-srv-port 177 => XDMCP-port 179 => BGP-port 194 => IRC-port 199 => SMUX-port 201 => AppleTalk-port 209 => QMTP-port 210 => ANSI-port 213 => IPX-port 218 => MPP-port 220 => IMAP-port 256 => 2DEV-port 259 => ESRO-port 264 => BGMP-port 308 => Novastor-port 311 => OSX Admin-port 318 => PKIX TSP-port 319 => PTP-port 320 => PTP-port 323 => IMMP-port 350 => MATIP-port 351 => MATIP-port 366 => ODMR-port 369 => Rpc2port ap-port 370 => codaauth2-port 371 => ClearCase-port 383 => HP Alarm Mgr-port 384 => ARNS-port 387 => AURP-port 389 => LDAP-port 401 => UPS-port 402 => Altiris-port 427 => SLP-port 443 => HTTPS-port 444 => SNPP-port 445 => SMB-port 464 => Kerberos (kpasswd)-port 465 => SMTP-port 475 => tcpnethaspsrv-port 497 => Retrospect-port 500 => ISAKMP-port 501 => STMF-port 502 => Modbus-port 504 => Citadel-port 510 => FirstClass-port 512 => Rexec-port 513 => rlogin-port 514 => rsh-port 515 => LPD-port 517 => Talk-port 518 => NTalk-port 520 => efs-port 524 => NCP-port 530 => RPC-port 531 => AIM/IRC-port 532 => netnews-port 533 => netwall-port 540 => UUCP-port 542 => commerce-port 543 => Kerberos (klogin)-port 544 => Kerberos (kshell)-port 545 => OSISoft PI-port 546 => DHCPv6-port 547 => DHCPv6-port 548 => AFP-port 550 => new-who-port 554 => RTSP-port 556 => RFS-port 560 => rmonitor-port 561 => monitor-port 563 => NNTPS-port 587 => SMTP-port 591 => FileMaker-port 593 => HTTP RPC-port 604 => TUNNEL-port 623 => ASF-RMCP-port 631 => CUPS-port 635 => RLZ DBase-port 636 => LDAPS-port 639 => MSDP-port 641 => Support oft-port 646 => LDP-port 647 => DHCP-port 648 => RRP-port 651 => IEEE-MMS-port 652 => DTCP-port 653 => Support oft-port 654 => MMS/MMP-port 657 => RMC-port 660 => OSX Admin-port 665 => sun-dr-port 666 => Doom-port 674 => ACAP-port 691 => MS Exchange-port 692 => Hyperwave-ISP-port 694 => Linux-HA-port 695 => IEEE-MMS-SSL-port 698 => OLSR-port 699 => Access Network-port 700 => EPP-port 701 => LMP-port 702 => IRIS-port 706 => SILC-port 711 => MPLS-port 712 => TBRPF-port 720 => SMQP-port 749 => Kerberos (admin)-port 750 => rfile-port 751 => pump-port 752 => qrh-port 753 => rrh-port 754 => tell send-port 760 => ns-port 782 => Conserver-port 783 => spamd-port 829 => CMP-port 843 => Flash-port 847 => DHCP-port 860 => iSCSI-port 873 => rsync-port 888 => CDDB-port 901 => SWAT-port 902-904 => VMware-port 911 => NCA-port 953 => DNS RNDC-port 981 => SofaWare Firewall-port 989 => FTPS-port 990 => FTPS-port 991 => NAS-port 992 => Telnets-port 993 => IMAPS-port 994 => IRCS-port 995 => POP3S-port 999 => ScimoreDB-port 1001 => JtoMB-port 1002 => cogbot--port 1080 => SOCKS-port 1085 => WebObjects-port 1109 => KPOP-port 1169 => Tripwire-port 1194 => OpenVPN-port 1214 => Kazaa-port 1220 => QuickTime-port 1234 => VLC-port 1241 => Nessus-port 1270 => SCOM-port 1293 => IPSec-port 1433 => MSSQL-port 1434 => MSSQL-port 1500 => NetGuard-port 1503 => MSN-port 1512 => WINS-port 1521 => Oracle-port 1526 => Oracle-port 1533 => Sametime-port 1666 => Perforce-port 1677 => GroupWise-port 1723 => PPTP-port 1725 => Steam-port 1863 => MSNP-port 2049 => NFS-port 2082 => Infowave-port 2083 => radsec-port 2086 => GNUnet-port 2087 => ELI-port 2095 => NBX SER-port 2096 => NBX DIR-port 2102-2104 => Zephyr-port 2401 => CVS-port 2525 => SMTP-port 2710 => BitTorrent-port 3074 => XBox LIVE-port 3101 => BlackBerry-port 3128 => SQUID-port 3306 => MySQL-port 3389 => WBT-port 3690 => SVN-port 3723 => Battle.net-port 3724 => WoW-port 4321 => RWHOIS-port 4643 => Virtuozzo-port 4662 => eMule-port 5003 => FileMaker-port 5050 => Yahoo IM-port 5060 => SIP-port 5061 => SIP-port 5190 => AIM/ICQ-port 5222 => Jabber-port 5223 => Jabber-port 5228 => Android Market-port 5269 => Jabber-port 5298 => Jabber-port 5432 => PostgreSQL-port 5500 => VNC-port 5556 => Freeciv-port 5666 => NRPE-port 5667 => NSCA-port 5800 => VNC-port 5900 => VNC-port 6346 => gnutella-port 6347 => gnutella-port 6660-6669 => IRC-port 6679 => IRC-port 6697 => IRC-port 6881-6999 => BitTorrent-port 8000 => iRDMI-port 8008 => HTTP Alternate-port 8010 => XMPP-port 8074 => Gadu-Gadu-port 8080 => HTTP Proxy-port 8087 => SPP-port 8088 => Radan HTTP-port 8118 => Privoxy-port 8123 => Polipo-port 8332-8333 => Bitcoin-port 8443 => PCsync HTTPS-port 8888 => NewsEDGE-port 9030 => Tor-port 9050 => Tor-port 9051 => Tor-port 9418 => Git-port 9999 => distinct-port 10000 => Webmin-port 19294 => Google Voice-port 19638 => Ensim-port 23399 => Skype-port 30301 => BitTorrent-port 33434 => traceroute-diff --git a/ext/stem/util/proc.py b/ext/stem/util/proc.pydeleted file mode 100644index e4a826ed..00000000--- a/ext/stem/util/proc.py+++ /dev/null@@ -1,547 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Helper functions for querying process and system information from the /proc-contents. Fetching information this way provides huge performance benefits-over lookups via system utilities (ps, netstat, etc). For instance, resolving-connections this way cuts the runtime by around 90% verses the alternatives.-These functions may not work on all platforms (only Linux?).--The method for reading these files (and a little code) are borrowed from-`psutil <https://code.google.com/p/psutil/>`_, which was written by Jay Loden,-Dave Daeschler, Giampaolo Rodola' and is under the BSD license.--**These functions are not being vended to stem users. They may change in the-future, use them at your own risk.**--.. versionchanged:: 1.3.0- Dropped the get_* prefix from several function names. The old names still- work, but are deprecated aliases.--**Module Overview:**--::-- is_available - checks if proc utilities can be used on this system- system_start_time - unix timestamp for when the system started- physical_memory - memory available on this system- cwd - provides the current working directory for a process- uid - provides the user id a process is running under- memory_usage - provides the memory usage of a process- stats - queries statistics about a process- file_descriptors_used - number of file descriptors used by a process- connections - provides the connections made by a process--.. data:: Stat (enum)-- Types of data available via the :func:`~stem.util.proc.stats` function.-- ============== ===========- Stat Description- ============== ===========- **COMMAND** command name under which the process is running- **CPU_UTIME** total user time spent on the process- **CPU_STIME** total system time spent on the process- **START_TIME** when this process began, in unix time- ============== ===========-"""--import base64-import os-import platform-import socket-import sys-import time--import stem.util.enum--from stem.util import log--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache--# os.sysconf is only defined on unix-try:- CLOCK_TICKS = os.sysconf(os.sysconf_names['SC_CLK_TCK'])-except AttributeError:- CLOCK_TICKS = None--Stat = stem.util.enum.Enum(- ('COMMAND', 'command'), ('CPU_UTIME', 'utime'),- ('CPU_STIME', 'stime'), ('START_TIME', 'start time')-)---@lru_cache()-def is_available():- """- Checks if proc information is available on this platform.-- :returns: **True** if proc contents exist on this platform, **False** otherwise- """-- if platform.system() != 'Linux':- return False- else:- # list of process independent proc paths we use- proc_paths = ('/proc/stat', '/proc/meminfo', '/proc/net/tcp', '/proc/net/udp')-- for path in proc_paths:- if not os.path.exists(path):- return False-- return True---@lru_cache()-def system_start_time():- """- Provides the unix time (seconds since epoch) when the system started.-- :returns: **float** for the unix time of when the system started-- :raises: **IOError** if it can't be determined- """-- start_time, parameter = time.time(), 'system start time'- btime_line = _get_line('/proc/stat', 'btime', parameter)-- try:- result = float(btime_line.strip().split()[1])- _log_runtime(parameter, '/proc/stat[btime]', start_time)- return result- except:- exc = IOError('unable to parse the /proc/stat btime entry: %s' % btime_line)- _log_failure(parameter, exc)- raise exc---@lru_cache()-def physical_memory():- """- Provides the total physical memory on the system in bytes.-- :returns: **int** for the bytes of physical memory this system has-- :raises: **IOError** if it can't be determined- """-- start_time, parameter = time.time(), 'system physical memory'- mem_total_line = _get_line('/proc/meminfo', 'MemTotal:', parameter)-- try:- result = int(mem_total_line.split()[1]) * 1024- _log_runtime(parameter, '/proc/meminfo[MemTotal]', start_time)- return result- except:- exc = IOError('unable to parse the /proc/meminfo MemTotal entry: %s' % mem_total_line)- _log_failure(parameter, exc)- raise exc---def cwd(pid):- """- Provides the current working directory for the given process.-- :param int pid: process id of the process to be queried-- :returns: **str** with the path of the working directory for the process-- :raises: **IOError** if it can't be determined- """-- start_time, parameter = time.time(), 'cwd'- proc_cwd_link = '/proc/%s/cwd' % pid-- if pid == 0:- cwd = ''- else:- try:- cwd = os.readlink(proc_cwd_link)- except OSError:- exc = IOError('unable to read %s' % proc_cwd_link)- _log_failure(parameter, exc)- raise exc-- _log_runtime(parameter, proc_cwd_link, start_time)- return cwd---def uid(pid):- """- Provides the user ID the given process is running under.-- :param int pid: process id of the process to be queried-- :returns: **int** with the user id for the owner of the process-- :raises: **IOError** if it can't be determined- """-- start_time, parameter = time.time(), 'uid'- status_path = '/proc/%s/status' % pid- uid_line = _get_line(status_path, 'Uid:', parameter)-- try:- result = int(uid_line.split()[1])- _log_runtime(parameter, '%s[Uid]' % status_path, start_time)- return result- except:- exc = IOError('unable to parse the %s Uid entry: %s' % (status_path, uid_line))- _log_failure(parameter, exc)- raise exc---def memory_usage(pid):- """- Provides the memory usage in bytes for the given process.-- :param int pid: process id of the process to be queried-- :returns: **tuple** of two ints with the memory usage of the process, of the- form **(resident_size, virtual_size)**-- :raises: **IOError** if it can't be determined- """-- # checks if this is the kernel process-- if pid == 0:- return (0, 0)-- start_time, parameter = time.time(), 'memory usage'- status_path = '/proc/%s/status' % pid- mem_lines = _get_lines(status_path, ('VmRSS:', 'VmSize:'), parameter)-- try:- residentSize = int(mem_lines['VmRSS:'].split()[1]) * 1024- virtualSize = int(mem_lines['VmSize:'].split()[1]) * 1024-- _log_runtime(parameter, '%s[VmRSS|VmSize]' % status_path, start_time)- return (residentSize, virtualSize)- except:- exc = IOError('unable to parse the %s VmRSS and VmSize entries: %s' % (status_path, ', '.join(mem_lines)))- _log_failure(parameter, exc)- raise exc---def stats(pid, *stat_types):- """- Provides process specific information. See the :data:`~stem.util.proc.Stat`- enum for valid options.-- :param int pid: process id of the process to be queried- :param Stat stat_types: information to be provided back-- :returns: **tuple** with all of the requested statistics as strings-- :raises: **IOError** if it can't be determined- """-- if CLOCK_TICKS is None:- raise IOError('Unable to look up SC_CLK_TCK')-- start_time, parameter = time.time(), 'process %s' % ', '.join(stat_types)-- # the stat file contains a single line, of the form...- # 8438 (tor) S 8407 8438 8407 34818 8438 4202496...- stat_path = '/proc/%s/stat' % pid- stat_line = _get_line(stat_path, str(pid), parameter)-- # breaks line into component values- stat_comp = []- cmd_start, cmd_end = stat_line.find('('), stat_line.find(')')-- if cmd_start != -1 and cmd_end != -1:- stat_comp.append(stat_line[:cmd_start])- stat_comp.append(stat_line[cmd_start + 1:cmd_end])- stat_comp += stat_line[cmd_end + 1:].split()-- if len(stat_comp) < 44 and _is_float(stat_comp[13], stat_comp[14], stat_comp[21]):- exc = IOError('stat file had an unexpected format: %s' % stat_path)- _log_failure(parameter, exc)- raise exc-- results = []- for stat_type in stat_types:- if stat_type == Stat.COMMAND:- if pid == 0:- results.append('sched')- else:- results.append(stat_comp[1])- elif stat_type == Stat.CPU_UTIME:- if pid == 0:- results.append('0')- else:- results.append(str(float(stat_comp[13]) / CLOCK_TICKS))- elif stat_type == Stat.CPU_STIME:- if pid == 0:- results.append('0')- else:- results.append(str(float(stat_comp[14]) / CLOCK_TICKS))- elif stat_type == Stat.START_TIME:- if pid == 0:- return system_start_time()- else:- # According to documentation, starttime is in field 21 and the unit is- # jiffies (clock ticks). We divide it for clock ticks, then add the- # uptime to get the seconds since the epoch.- p_start_time = float(stat_comp[21]) / CLOCK_TICKS- results.append(str(p_start_time + system_start_time()))-- _log_runtime(parameter, stat_path, start_time)- return tuple(results)---def file_descriptors_used(pid):- """- Provides the number of file descriptors currently being used by a process.-- .. versionadded:: 1.3.0-- :param int pid: process id of the process to be queried-- :returns: **int** of the number of file descriptors used-- :raises: **IOError** if it can't be determined- """-- try:- pid = int(pid)-- if pid < 0:- raise IOError("Process pids can't be negative: %s" % pid)- except (ValueError, TypeError):- raise IOError('Process pid was non-numeric: %s' % pid)-- try:- return len(os.listdir('/proc/%i/fd' % pid))- except Exception as exc:- raise IOError('Unable to check number of file descriptors used: %s' % exc)---def connections(pid):- """- Queries connection related information from the proc contents. This provides- similar results to netstat, lsof, sockstat, and other connection resolution- utilities (though the lookup is far quicker).-- :param int pid: process id of the process to be queried-- :returns: A listing of connection tuples of the form **[(local_ipAddr1,- local_port1, foreign_ipAddr1, foreign_port1, protocol), ...]** (addresses- and protocols are strings and ports are ints)-- :raises: **IOError** if it can't be determined- """-- try:- pid = int(pid)-- if pid < 0:- raise IOError("Process pids can't be negative: %s" % pid)- except (ValueError, TypeError):- raise IOError('Process pid was non-numeric: %s' % pid)-- if pid == 0:- return []-- # fetches the inode numbers for socket file descriptors-- start_time, parameter = time.time(), 'process connections'- inodes = []-- for fd in os.listdir('/proc/%s/fd' % pid):- fd_path = '/proc/%s/fd/%s' % (pid, fd)-- try:- # File descriptor link, such as 'socket:[30899]'-- fd_name = os.readlink(fd_path)-- if fd_name.startswith('socket:['):- inodes.append(fd_name[8:-1])- except OSError as exc:- if not os.path.exists(fd_path):- continue # descriptors may shift while we're in the middle of iterating over them-- # most likely couldn't be read due to permissions- exc = IOError('unable to determine file descriptor destination (%s): %s' % (exc, fd_path))- _log_failure(parameter, exc)- raise exc-- if not inodes:- # unable to fetch any connections for this process- return []-- # check for the connection information from the /proc/net contents-- conn = []-- for proc_file_path in ('/proc/net/tcp', '/proc/net/udp'):- try:- proc_file = open(proc_file_path)- proc_file.readline() # skip the first line-- for line in proc_file:- _, l_addr, f_addr, status, _, _, _, _, _, inode = line.split()[:10]-- if inode in inodes:- # if a tcp connection, skip if it isn't yet established- if proc_file_path.endswith('/tcp') and status != '01':- continue-- local_ip, local_port = _decode_proc_address_encoding(l_addr)- foreign_ip, foreign_port = _decode_proc_address_encoding(f_addr)- protocol = proc_file_path[10:]- conn.append((local_ip, local_port, foreign_ip, foreign_port, protocol))-- proc_file.close()- except IOError as exc:- exc = IOError("unable to read '%s': %s" % (proc_file_path, exc))- _log_failure(parameter, exc)- raise exc- except Exception as exc:- exc = IOError("unable to parse '%s': %s" % (proc_file_path, exc))- _log_failure(parameter, exc)- raise exc-- _log_runtime(parameter, '/proc/net/[tcp|udp]', start_time)- return conn---def _decode_proc_address_encoding(addr):- """- Translates an address entry in the /proc/net/* contents to a human readable- form (`reference <http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html>`_,- for instance:-- ::-- "0500000A:0016" -> ("10.0.0.5", 22)-- :param str addr: proc address entry to be decoded-- :returns: **tuple** of the form **(addr, port)**, with addr as a string and port an int- """-- ip, port = addr.split(':')-- # the port is represented as a two-byte hexadecimal number- port = int(port, 16)-- if sys.version_info >= (3,):- ip = ip.encode('ascii')-- # The IPv4 address portion is a little-endian four-byte hexadecimal number.- # That is, the least significant byte is listed first, so we need to reverse- # the order of the bytes to convert it to an IP address.- #- # This needs to account for the endian ordering as per...- # http://code.google.com/p/psutil/issues/detail?id=201- # https://trac.torproject.org/projects/tor/ticket/4777-- if sys.byteorder == 'little':- ip = socket.inet_ntop(socket.AF_INET, base64.b16decode(ip)[::-1])- else:- ip = socket.inet_ntop(socket.AF_INET, base64.b16decode(ip))-- return (ip, port)---def _is_float(*value):- try:- for v in value:- float(v)-- return True- except ValueError:- return False---def _get_line(file_path, line_prefix, parameter):- return _get_lines(file_path, (line_prefix, ), parameter)[line_prefix]---def _get_lines(file_path, line_prefixes, parameter):- """- Fetches lines with the given prefixes from a file. This only provides back- the first instance of each prefix.-- :param str file_path: path of the file to read- :param tuple line_prefixes: string prefixes of the lines to return- :param str parameter: description of the proc attribute being fetch-- :returns: mapping of prefixes to the matching line-- :raises: **IOError** if unable to read the file or can't find all of the prefixes- """-- try:- remaining_prefixes = list(line_prefixes)- proc_file, results = open(file_path), {}-- for line in proc_file:- if not remaining_prefixes:- break # found everything we're looking for-- for prefix in remaining_prefixes:- if line.startswith(prefix):- results[prefix] = line- remaining_prefixes.remove(prefix)- break-- proc_file.close()-- if remaining_prefixes:- if len(remaining_prefixes) == 1:- msg = '%s did not contain a %s entry' % (file_path, remaining_prefixes[0])- else:- msg = '%s did not contain %s entries' % (file_path, ', '.join(remaining_prefixes))-- raise IOError(msg)- else:- return results- except IOError as exc:- _log_failure(parameter, exc)- raise exc---def _log_runtime(parameter, proc_location, start_time):- """- Logs a message indicating a successful proc query.-- :param str parameter: description of the proc attribute being fetch- :param str proc_location: proc files we were querying- :param int start_time: unix time for when this query was started- """-- runtime = time.time() - start_time- log.debug('proc call (%s): %s (runtime: %0.4f)' % (parameter, proc_location, runtime))---def _log_failure(parameter, exc):- """- Logs a message indicating that the proc query failed.-- :param str parameter: description of the proc attribute being fetch- :param Exception exc: exception that we're raising- """-- log.debug('proc call failed (%s): %s' % (parameter, exc))--# TODO: drop with stem 2.x-# We renamed our methods to drop a redundant 'get_*' prefix, so alias the old-# names for backward compatability.--get_system_start_time = system_start_time-get_physical_memory = physical_memory-get_cwd = cwd-get_uid = uid-get_memory_usage = memory_usage-get_stats = stats-get_connections = connectionsdiff --git a/ext/stem/util/str_tools.py b/ext/stem/util/str_tools.pydeleted file mode 100644index 497564e3..00000000--- a/ext/stem/util/str_tools.py+++ /dev/null@@ -1,558 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Toolkit for various string activity.--.. versionchanged:: 1.3.0- Dropped the get_* prefix from several function names. The old names still- work, but are deprecated aliases.--**Module Overview:**--::-- crop - shortens string to a given length-- size_label - human readable label for a number of bytes- time_label - human readable label for a number of seconds- time_labels - human readable labels for each time unit- short_time_label - condensed time label output- parse_short_time_label - seconds represented by a short time label-"""--import codecs-import datetime-import re-import sys--import stem.prereq-import stem.util.enum--from stem import str_type--# label conversion tuples of the form...-# (bits / bytes / seconds, short label, long label)--SIZE_UNITS_BITS = (- (140737488355328.0, ' Pb', ' Petabit'),- (137438953472.0, ' Tb', ' Terabit'),- (134217728.0, ' Gb', ' Gigabit'),- (131072.0, ' Mb', ' Megabit'),- (128.0, ' Kb', ' Kilobit'),- (0.125, ' b', ' Bit'),-)--SIZE_UNITS_BYTES = (- (1125899906842624.0, ' PB', ' Petabyte'),- (1099511627776.0, ' TB', ' Terabyte'),- (1073741824.0, ' GB', ' Gigabyte'),- (1048576.0, ' MB', ' Megabyte'),- (1024.0, ' KB', ' Kilobyte'),- (1.0, ' B', ' Byte'),-)--TIME_UNITS = (- (86400.0, 'd', ' day'),- (3600.0, 'h', ' hour'),- (60.0, 'm', ' minute'),- (1.0, 's', ' second'),-)--_timestamp_re = re.compile(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})')--if stem.prereq.is_python_3():- def _to_bytes_impl(msg):- if isinstance(msg, str):- return codecs.latin_1_encode(msg, 'replace')[0]- else:- return msg-- def _to_unicode_impl(msg):- if msg is not None and not isinstance(msg, str):- return msg.decode('utf-8', 'replace')- else:- return msg-else:- def _to_bytes_impl(msg):- if msg is not None and isinstance(msg, str_type):- return codecs.latin_1_encode(msg, 'replace')[0]- else:- return msg-- def _to_unicode_impl(msg):- if msg is not None and not isinstance(msg, str_type):- return msg.decode('utf-8', 'replace')- else:- return msg---def _to_bytes(msg):- """- Provides the ASCII bytes for the given string. This is purely to provide- python 3 compatability, normalizing the unicode/ASCII change in the version- bump. For an explanation of this see...-- http://python3porting.com/problems.html#nicer-solutions-- :param str,unicode msg: string to be converted-- :returns: ASCII bytes for string- """-- return _to_bytes_impl(msg)---def _to_unicode(msg):- """- Provides the unicode string for the given ASCII bytes. This is purely to- provide python 3 compatability, normalizing the unicode/ASCII change in the- version bump.-- :param str,unicode msg: string to be converted-- :returns: unicode conversion- """-- return _to_unicode_impl(msg)---def _to_camel_case(label, divider = '_', joiner = ' '):- """- Converts the given string to camel case, ie:-- ::-- >>> _to_camel_case('I_LIKE_PEPPERJACK!')- 'I Like Pepperjack!'-- :param str label: input string to be converted- :param str divider: word boundary- :param str joiner: replacement for word boundaries-- :returns: camel cased string- """-- words = []- for entry in label.split(divider):- if len(entry) == 0:- words.append('')- elif len(entry) == 1:- words.append(entry.upper())- else:- words.append(entry[0].upper() + entry[1:].lower())-- return joiner.join(words)---# This needs to be defined after _to_camel_case() to avoid a circular-# dependency with the enum module.--Ending = stem.util.enum.Enum('ELLIPSE', 'HYPHEN')---def crop(msg, size, min_word_length = 4, min_crop = 0, ending = Ending.ELLIPSE, get_remainder = False):- """- Shortens a string to a given length.-- If we crop content then a given ending is included (counting itself toward- the size limitation). This crops on word breaks so we only include a word if- we can display at least **min_word_length** characters of it.-- If there isn't room for even a truncated single word (or one word plus the- ellipse if including those) then this provides an empty string.-- If a cropped string ends with a comma or period then it's stripped (unless- we're providing the remainder back). For example...-- >>> crop('This is a looooong message', 17)- 'This is a looo...'-- >>> crop('This is a looooong message', 12)- 'This is a...'-- >>> crop('This is a looooong message', 3)- ''-- The whole point of this method is to provide human friendly croppings, and as- such details of how this works might change in the future. Callers should not- rely on the details of how this crops.-- .. versionadded:: 1.3.0-- :param str msg: text to be processed- :param int size: space available for text- :param int min_word_length: minimum characters before which a word is- dropped, requires whole word if **None**- :param int min_crop: minimum characters that must be dropped if a word is- cropped- :param Ending ending: type of ending used when truncating, no special- truncation is used if **None**- :param bool get_remainder: returns a tuple with the second part being the- cropped portion of the message-- :returns: **str** of the text truncated to the given length- """-- # checks if there's room for the whole message-- if len(msg) <= size:- return (msg, '') if get_remainder else msg-- if size < 0:- raise ValueError("Crop size can't be negative (received %i)" % size)- elif min_word_length and min_word_length < 0:- raise ValueError("Crop's min_word_length can't be negative (received %i)" % min_word_length)- elif min_crop < 0:- raise ValueError("Crop's min_crop can't be negative (received %i)" % min_crop)-- # since we're cropping, the effective space available is less with an- # ellipse, and cropping words requires an extra space for hyphens-- if ending == Ending.ELLIPSE:- size -= 3- elif min_word_length and ending == Ending.HYPHEN:- min_word_length += 1-- if min_word_length is None:- min_word_length = sys.maxsize-- # checks if there isn't the minimum space needed to include anything-- last_wordbreak = msg.rfind(' ', 0, size + 1)-- if last_wordbreak == -1:- # we're splitting the first word-- if size < min_word_length:- return ('', msg) if get_remainder else ''-- include_crop = True- else:- last_wordbreak = len(msg[:last_wordbreak].rstrip()) # drops extra ending whitespaces- include_crop = size - last_wordbreak - 1 >= min_word_length-- # if there's a max crop size then make sure we're cropping at least that many characters-- if include_crop and min_crop:- next_wordbreak = msg.find(' ', size)-- if next_wordbreak == -1:- next_wordbreak = len(msg)-- include_crop = next_wordbreak - size + 1 >= min_crop-- if include_crop:- return_msg, remainder = msg[:size], msg[size:]-- if ending == Ending.HYPHEN:- remainder = return_msg[-1] + remainder- return_msg = return_msg[:-1].rstrip() + '-'- else:- return_msg, remainder = msg[:last_wordbreak], msg[last_wordbreak:]-- # if this is ending with a comma or period then strip it off-- if not get_remainder and return_msg and return_msg[-1] in (',', '.'):- return_msg = return_msg[:-1]-- if ending == Ending.ELLIPSE:- return_msg = return_msg.rstrip() + '...'-- return (return_msg, remainder) if get_remainder else return_msg---def size_label(byte_count, decimal = 0, is_long = False, is_bytes = True):- """- Converts a number of bytes into a human readable label in its most- significant units. For instance, 7500 bytes would return "7 KB". If the- is_long option is used this expands unit labels to be the properly pluralized- full word (for instance 'Kilobytes' rather than 'KB'). Units go up through- petabytes.-- ::-- >>> size_label(2000000)- '1 MB'-- >>> size_label(1050, 2)- '1.02 KB'-- >>> size_label(1050, 3, True)- '1.025 Kilobytes'-- :param int byte_count: number of bytes to be converted- :param int decimal: number of decimal digits to be included- :param bool is_long: expands units label- :param bool is_bytes: provides units in bytes if **True**, bits otherwise-- :returns: **str** with human readable representation of the size- """-- if is_bytes:- return _get_label(SIZE_UNITS_BYTES, byte_count, decimal, is_long)- else:- return _get_label(SIZE_UNITS_BITS, byte_count, decimal, is_long)---def time_label(seconds, decimal = 0, is_long = False):- """- Converts seconds into a time label truncated to its most significant units.- For instance, 7500 seconds would return "2h". Units go up through days.-- This defaults to presenting single character labels, but if the is_long- option is used this expands labels to be the full word (space included and- properly pluralized). For instance, "4h" would be "4 hours" and "1m" would- become "1 minute".-- ::-- >>> time_label(10000)- '2h'-- >>> time_label(61, 1, True)- '1.0 minute'-- >>> time_label(61, 2, True)- '1.01 minutes'-- :param int seconds: number of seconds to be converted- :param int decimal: number of decimal digits to be included- :param bool is_long: expands units label-- :returns: **str** with human readable representation of the time- """-- return _get_label(TIME_UNITS, seconds, decimal, is_long)---def time_labels(seconds, is_long = False):- """- Provides a list of label conversions for each time unit, starting with its- most significant units on down. Any counts that evaluate to zero are omitted.- For example...-- ::-- >>> time_labels(400)- ['6m', '40s']-- >>> time_labels(3640, True)- ['1 hour', '40 seconds']-- :param int seconds: number of seconds to be converted- :param bool is_long: expands units label-- :returns: **list** of strings with human readable representations of the time- """-- time_labels = []-- for count_per_unit, _, _ in TIME_UNITS:- if abs(seconds) >= count_per_unit:- time_labels.append(_get_label(TIME_UNITS, seconds, 0, is_long))- seconds %= count_per_unit-- return time_labels---def short_time_label(seconds):- """- Provides a time in the following format:- [[dd-]hh:]mm:ss-- ::-- >>> short_time_label(111)- '01:51'-- >>> short_time_label(544100)- '6-07:08:20'-- :param int seconds: number of seconds to be converted-- :returns: **str** with the short representation for the time-- :raises: **ValueError** if the input is negative- """-- if seconds < 0:- raise ValueError("Input needs to be a non-negative integer, got '%i'" % seconds)-- time_comp = {}-- for amount, _, label in TIME_UNITS:- count = int(seconds / amount)- seconds %= amount- time_comp[label.strip()] = count-- label = '%02i:%02i' % (time_comp['minute'], time_comp['second'])-- if time_comp['day']:- label = '%i-%02i:%s' % (time_comp['day'], time_comp['hour'], label)- elif time_comp['hour']:- label = '%02i:%s' % (time_comp['hour'], label)-- return label---def parse_short_time_label(label):- """- Provides the number of seconds corresponding to the formatting used for the- cputime and etime fields of ps:- [[dd-]hh:]mm:ss or mm:ss.ss-- ::-- >>> parse_short_time_label('01:51')- 111-- >>> parse_short_time_label('6-07:08:20')- 544100-- :param str label: time entry to be parsed-- :returns: **int** with the number of seconds represented by the label-- :raises: **ValueError** if input is malformed- """-- days, hours, minutes, seconds = '0', '0', '0', '0'-- if '-' in label:- days, label = label.split('-', 1)-- time_comp = label.split(':')-- if len(time_comp) == 3:- hours, minutes, seconds = time_comp- elif len(time_comp) == 2:- minutes, seconds = time_comp- else:- raise ValueError("Invalid time format, we expected '[[dd-]hh:]mm:ss' or 'mm:ss.ss': %s" % label)-- try:- time_sum = int(float(seconds))- time_sum += int(minutes) * 60- time_sum += int(hours) * 3600- time_sum += int(days) * 86400- return time_sum- except ValueError:- raise ValueError('Non-numeric value in time entry: %s' % label)---def _parse_timestamp(entry):- """- Parses the date and time that in format like like...-- ::-- 2012-11-08 16:48:41-- :param str entry: timestamp to be parsed-- :returns: **datetime** for the time represented by the timestamp-- :raises: **ValueError** if the timestamp is malformed- """-- if not isinstance(entry, (str, str_type)):- raise ValueError('parse_timestamp() input must be a str, got a %s' % type(entry))-- try:- time = [int(x) for x in _timestamp_re.match(entry).groups()]- except AttributeError:- raise ValueError('Expected timestamp in format YYYY-MM-DD HH:MM:ss but got ' + entry)-- return datetime.datetime(time[0], time[1], time[2], time[3], time[4], time[5])---def _parse_iso_timestamp(entry):- """- Parses the ISO 8601 standard that provides for timestamps like...-- ::-- 2012-11-08T16:48:41.420251-- :param str entry: timestamp to be parsed-- :returns: **datetime** for the time represented by the timestamp-- :raises: **ValueError** if the timestamp is malformed- """-- if not isinstance(entry, (str, str_type)):- raise ValueError('parse_iso_timestamp() input must be a str, got a %s' % type(entry))-- # based after suggestions from...- # http://stackoverflow.com/questions/127803/how-to-parse-iso-formatted-date-in-python-- if '.' in entry:- timestamp_str, microseconds = entry.split('.')- else:- timestamp_str, microseconds = entry, '000000'-- if len(microseconds) != 6 or not microseconds.isdigit():- raise ValueError("timestamp's microseconds should be six digits")-- if timestamp_str[10] == 'T':- timestamp_str = timestamp_str[:10] + ' ' + timestamp_str[11:]- else:- raise ValueError("timestamp didn't contain delimeter 'T' between date and time")-- timestamp = _parse_timestamp(timestamp_str)- return timestamp + datetime.timedelta(microseconds = int(microseconds))---def _get_label(units, count, decimal, is_long):- """- Provides label corresponding to units of the highest significance in the- provided set. This rounds down (ie, integer truncation after visible units).-- :param tuple units: type of units to be used for conversion, containing- (count_per_unit, short_label, long_label)- :param int count: number of base units being converted- :param int decimal: decimal precision of label- :param bool is_long: uses the long label if **True**, short label otherwise- """-- # formatted string for the requested number of digits- label_format = '%%.%if' % decimal-- if count < 0:- label_format = '-' + label_format- count = abs(count)- elif count == 0:- units_label = units[-1][2] + 's' if is_long else units[-1][1]- return '%s%s' % (label_format % count, units_label)-- for count_per_unit, short_label, long_label in units:- if count >= count_per_unit:- # Rounding down with a '%f' is a little clunky. Reducing the count so- # it'll divide evenly as the rounded down value.-- count -= count % (count_per_unit / (10 ** decimal))- count_label = label_format % (count / count_per_unit)-- if is_long:- # Pluralize if any of the visible units make it greater than one. For- # instance 1.0003 is plural but 1.000 isn't.-- if decimal > 0:- is_plural = count > count_per_unit- else:- is_plural = count >= count_per_unit * 2-- return count_label + long_label + ('s' if is_plural else '')- else:- return count_label + short_label--# TODO: drop with stem 2.x-# We renamed our methods to drop a redundant 'get_*' prefix, so alias the old-# names for backward compatability.--get_size_label = size_label-get_time_label = time_label-get_time_labels = time_labels-get_short_time_label = short_time_labeldiff --git a/ext/stem/util/system.py b/ext/stem/util/system.pydeleted file mode 100644index aa13cb98..00000000--- a/ext/stem/util/system.py+++ /dev/null@@ -1,1176 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Helper functions for working with the underlying system. These are mostly os-dependent, only working on linux, osx, and bsd. In almost all cases they're-best-effort, providing **None** if the lookup fails.--.. versionchanged:: 1.3.0- Dropped the get_* prefix from several function names. The old names still- work, but are deprecated aliases.--**Module Overview:**--::-- is_windows - checks if we're running on windows- is_mac - checks if we're running on a mac- is_gentoo - checks if we're running on gentoo- is_bsd - checks if we're running on the bsd family of operating systems-- is_available - determines if a command is available on this system- is_running - determines if a given process is running- call - runs the given system command and provides back the results-- name_by_pid - gets the name for a process by the given pid- pid_by_name - gets the pid for a process by the given name- pid_by_port - gets the pid for a process listening to a given port- pid_by_open_file - gets the pid for the process with an open file- cwd - provides the current working directory for a given process- user - provides the user a process is running under- start_time - provides the unix timestamp when the process started- tail - provides lines from the end of a file- bsd_jail_id - provides the BSD jail id a given process is running within- bsd_jail_path - provides the path of the given BSD jail-- is_tarfile - checks if the given path is a tarball- expand_path - expands relative paths and ~ entries- files_with_suffix - provides files with the given suffix-- get_process_name - provides our process' name- set_process_name - changes our process' name-"""--import ctypes-import ctypes.util-import distutils.spawn-import mimetypes-import os-import platform-import re-import subprocess-import tarfile-import time--import stem.util.proc-import stem.util.str_tools--from stem import UNDEFINED, str_type-from stem.util import log--# Mapping of commands to if they're available or not.--CMD_AVAILABLE_CACHE = {}--# An incomplete listing of commands provided by the shell. Expand this as-# needed. Some noteworthy things about shell commands...-#-# * They're not in the path so is_available() will fail.-# * subprocess.Popen() without the 'shell = True' argument will fail with...-# OSError: [Errno 2] No such file or directory--SHELL_COMMANDS = ['ulimit']--IS_RUNNING_PS_LINUX = 'ps -A co command'-IS_RUNNING_PS_BSD = 'ps -ao ucomm='-GET_NAME_BY_PID_PS = 'ps -p %s -o comm'-GET_PID_BY_NAME_PGREP = 'pgrep -x %s'-GET_PID_BY_NAME_PIDOF = 'pidof %s'-GET_PID_BY_NAME_PS_LINUX = 'ps -o pid -C %s'-GET_PID_BY_NAME_PS_BSD = 'ps axc'-GET_PID_BY_NAME_LSOF = 'lsof -tc %s'-GET_PID_BY_PORT_NETSTAT = 'netstat -npltu'-GET_PID_BY_PORT_SOCKSTAT = 'sockstat -4l -P tcp -p %s'-GET_PID_BY_PORT_LSOF = 'lsof -wnP -iTCP -sTCP:LISTEN'-GET_PID_BY_FILE_LSOF = 'lsof -tw %s'-GET_CWD_PWDX = 'pwdx %s'-GET_CWD_LSOF = 'lsof -a -p %s -d cwd -Fn'-GET_BSD_JAIL_ID_PS = 'ps -p %s -o jid'-GET_BSD_JAIL_PATH = 'jls -j %s'--BLOCK_SIZE = 1024--# flag for setting the process name, found in '/usr/include/linux/prctl.h'--PR_SET_NAME = 15--argc_t = ctypes.POINTER(ctypes.c_char_p)--# The following can fail with pypy...-# AttributeError: No symbol Py_GetArgcArgv found in library <None>--try:- Py_GetArgcArgv = ctypes.pythonapi.Py_GetArgcArgv- Py_GetArgcArgv.restype = None- Py_GetArgcArgv.argtypes = [- ctypes.POINTER(ctypes.c_int),- ctypes.POINTER(argc_t),- ]-except:- Py_GetArgcArgv = None--# This is both a cache for get_process_name() and tracks what we've changed our-# process name to.--_PROCESS_NAME = None--# Length of our original process name.-#-# The original author our process renaming is based on did a memset for 256,-# while Jake did it for the original process name length (capped at 1608). I'm-# not sure of the reasons for either of these limits, but setting it to-# anything higher than our original name length should be pointless, so opting-# for Jake's limit.--_MAX_NAME_LENGTH = -1---def is_windows():- """- Checks if we are running on Windows.-- :returns: **bool** to indicate if we're on Windows- """-- return platform.system() == 'Windows'---def is_mac():- """- Checks if we are running on Mac OSX.-- :returns: **bool** to indicate if we're on a Mac- """-- return platform.system() == 'Darwin'---def is_gentoo():- """- Checks if we're running on Gentoo.-- :returns: **bool** to indicate if we're on Gentoo- """-- return os.path.exists('/etc/gentoo-release')---def is_bsd():- """- Checks if we are within the BSD family of operating systems. This currently- recognizes Macs, FreeBSD, and OpenBSD but may be expanded later.-- :returns: **bool** to indicate if we're on a BSD OS- """-- return platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD')---def is_available(command, cached=True):- """- Checks the current PATH to see if a command is available or not. If more- than one command is present (for instance "ls -a | grep foo") then this- just checks the first.-- Note that shell (like cd and ulimit) aren't in the PATH so this lookup will- try to assume that it's available. This only happends for recognized shell- commands (those in SHELL_COMMANDS).-- :param str command: command to search for- :param bool cached: makes use of available cached results if **True**-- :returns: **True** if an executable we can use by that name exists in the- PATH, **False** otherwise- """-- if ' ' in command:- command = command.split(' ')[0]-- if command in SHELL_COMMANDS:- # we can't actually look it up, so hope the shell really provides it...-- return True- elif cached and command in CMD_AVAILABLE_CACHE:- return CMD_AVAILABLE_CACHE[command]- else:- cmd_exists = distutils.spawn.find_executable(command) is not None- CMD_AVAILABLE_CACHE[command] = cmd_exists- return cmd_exists---def is_running(command):- """- Checks for if a process with a given name is running or not.-- :param str command: process name to be checked-- :returns: **True** if the process is running, **False** if it's not among ps- results, and **None** if ps can't be queried- """-- # Linux and the BSD families have different variants of ps. Guess based on- # the is_bsd() check which to try first, then fall back to the other.- #- # Linux- # -A - Select all processes.- # -co command - Shows just the base command.- #- # Mac / BSD- # -a - Display information about other users' processes as well as- # our own.- # -o ucomm= - Shows just the ucomm attribute ("name to be used for- # accounting")-- if is_available('ps'):- if is_bsd():- primary_resolver = IS_RUNNING_PS_BSD- secondary_resolver = IS_RUNNING_PS_LINUX- else:- primary_resolver = IS_RUNNING_PS_LINUX- secondary_resolver = IS_RUNNING_PS_BSD-- command_listing = call(primary_resolver, None)-- if not command_listing:- command_listing = call(secondary_resolver, None)-- if command_listing:- command_listing = map(str_type.strip, command_listing)- return command in command_listing-- return None---def name_by_pid(pid):- """- Attempts to determine the name a given process is running under (not- including arguments). This uses...-- ::-- 1. Information from /proc- 2. ps -p <pid> -o command-- :param int pid: process id of the process to be queried-- :returns: **str** with the process name, **None** if it can't be determined- """-- process_name = None-- if stem.util.proc.is_available():- try:- process_name = stem.util.proc.stats(pid, stem.util.proc.Stat.COMMAND)[0]- except IOError:- pass-- # attempts to resolve using ps, failing if:- # - system's ps variant doesn't handle these flags (none known at the moment)- #- # example output:- # atagar@morrigan:~$ ps -p 5767 -o comm- # COMMAND- # vim-- if not process_name:- try:- results = call(GET_NAME_BY_PID_PS % pid)- except OSError:- results = None-- if results and len(results) == 2 and results[0] == 'COMMAND':- process_name = results[1].strip()-- return process_name---def pid_by_name(process_name, multiple = False):- """- Attempts to determine the process id for a running process, using...-- ::-- 1. pgrep -x <name>- 2. pidof <name>- 3. ps -o pid -C <name> (linux)- ps axc | egrep " <name>$" (bsd)- 4. lsof -tc <name>- 5. tasklist | str <name>.exe-- :param str process_name: process name for which to fetch the pid- :param bool multiple: provides a list of all pids if **True**, otherwise- results with multiple processes are discarded-- :returns:- Response depends upon the 'multiple' argument as follows...-- * if **False** then this provides an **int** with the process id or **None** if it can't be determined- * if **True** then this provides a **list** of all **int** process ids, and an empty list if it can't be determined- """-- # attempts to resolve using pgrep, failing if:- # - we're running on bsd (command unavailable)- #- # example output:- # atagar@morrigan:~$ pgrep -x vim- # 3283- # 3392-- if is_available('pgrep'):- results = call(GET_PID_BY_NAME_PGREP % process_name, None)-- if results:- try:- pids = list(map(int, results))-- if multiple:- return pids- elif len(pids) == 1:- return pids[0]- except ValueError:- pass-- # attempts to resolve using pidof, failing if:- # - we're running on bsd (command unavailable)- #- # example output:- # atagar@morrigan:~$ pidof vim- # 3392 3283-- if is_available('pidof'):- results = call(GET_PID_BY_NAME_PIDOF % process_name, None)-- if results and len(results) == 1:- try:- pids = list(map(int, results[0].split()))-- if multiple:- return pids- elif len(pids) == 1:- return pids[0]- except ValueError:- pass-- # attempts to resolve using ps, failing if:- # - system's ps variant doesn't handle these flags (none known at the moment)- #- # example output:- # atagar@morrigan:~/Desktop/stem$ ps -o pid -C vim- # PID- # 3283- # 3392- #- # atagar$ ps axc- # PID TT STAT TIME COMMAND- # 1 ?? Ss 9:00.22 launchd- # 10 ?? Ss 0:09.97 kextd- # 11 ?? Ss 5:47.36 DirectoryService- # 12 ?? Ss 3:01.44 notifyd-- if is_available('ps'):- if not is_bsd():- # linux variant of ps- results = call(GET_PID_BY_NAME_PS_LINUX % process_name, None)-- if results:- try:- pids = list(map(int, results[1:]))-- if multiple:- return pids- elif len(pids) == 1:- return pids[0]- except ValueError:- pass-- if is_bsd():- # bsd variant of ps- results = call(GET_PID_BY_NAME_PS_BSD, None)-- if results:- # filters results to those with our process name- results = [r.split()[0] for r in results if r.endswith(' %s' % process_name)]-- try:- pids = list(map(int, results))-- if multiple:- return pids- elif len(pids) == 1:- return pids[0]- except ValueError:- pass-- # resolves using lsof which works on both Linux and BSD, only failing if:- # - lsof is unavailable (not included by default on OpenBSD)- # - the process being run as a different user due to permissions- # - the process doesn't have any open files to be reported by lsof?- #- # flags:- # t - only show pids- # c - restrict results to that command- #- # example output:- # atagar@morrigan:~$ lsof -t -c vim- # 2470- # 2561-- if is_available('lsof'):- results = call(GET_PID_BY_NAME_LSOF % process_name, None)-- if results:- try:- pids = list(map(int, results))-- if multiple:- return pids- elif len(pids) == 1:- return pids[0]- except ValueError:- pass-- if is_available('tasklist') and is_windows():- if not process_name.endswith('.exe'):- process_name = process_name + '.exe'-- process_ids = []-- results = stem.util.system.call('tasklist', None)-- if results:- tasklist_regex = re.compile('^\s*%s\s+(?P<pid>[0-9]*)' % process_name)-- for line in results:- match = tasklist_regex.search(line)-- if match:- process_ids.append(int(match.group('pid')))-- if multiple:- return process_ids- elif len(process_ids) > 0:- return process_ids[0]-- log.debug("failed to resolve a pid for '%s'" % process_name)- return [] if multiple else None---def pid_by_port(port):- """- Attempts to determine the process id for a process with the given port,- using...-- ::-- 1. netstat -npltu | grep 127.0.0.1:<port>- 2. sockstat -4l -P tcp -p <port>- 3. lsof -wnP -iTCP -sTCP:LISTEN | grep ":<port>"-- Most queries limit results to listening TCP connections. This function likely- won't work on Mac OSX.-- :param int port: port where the process we're looking for is listening-- :returns: **int** with the process id, **None** if it can't be determined- """-- # attempts to resolve using netstat, failing if:- # - netstat doesn't accept these flags (Linux only)- # - the process being run as a different user due to permissions- #- # flags:- # n - numeric (disables hostname lookups)- # p - program (include pids)- # l - listening (include listening sockets)- # tu - show tcp and udp sockets, and nothing else- #- # example output:- # atagar@morrigan:~$ netstat -npltu- # Active Internet connections (only servers)- # Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name- # tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN -- # tcp 0 0 127.0.0.1:9051 0.0.0.0:* LISTEN 1641/tor- # tcp6 0 0 ::1:631 :::* LISTEN -- # udp 0 0 0.0.0.0:5353 0.0.0.0:* -- # udp6 0 0 fe80::7ae4:ff:fe2f::123 :::* --- if is_available('netstat'):- results = call(GET_PID_BY_PORT_NETSTAT, None)-- if results:- # filters to results with our port- results = [r for r in results if '127.0.0.1:%s' % port in r]-- if len(results) == 1 and len(results[0].split()) == 7:- results = results[0].split()[6] # process field (ex. "7184/tor")- pid = results[:results.find('/')]-- if pid.isdigit():- return int(pid)-- # attempts to resolve using sockstat, failing if:- # - sockstat doesn't accept the -4 flag (BSD only)- # - sockstat isn't available (encountered with OSX 10.5.8)- # - there are multiple instances using the same port on different addresses- #- # flags:- # 4 - only show IPv4 sockets- # l - listening sockets- # P tcp - only show tcp connections- # p - only includes results if the local or foreign port match this- #- # example output:- # # sockstat -4 | grep tor- # _tor tor 4397 7 tcp4 51.64.7.84:9050 *:*- # _tor tor 4397 8 udp4 51.64.7.84:53 *:*- # _tor tor 4397 12 tcp4 51.64.7.84:54011 80.3.121.7:9001- # _tor tor 4397 15 tcp4 51.64.7.84:59374 7.42.1.102:9001- # _tor tor 4397 20 tcp4 51.64.7.84:51946 32.83.7.104:443-- if is_available('sockstat'):- results = call(GET_PID_BY_PORT_SOCKSTAT % port, None)-- if results:- # filters to results where this is the local port- results = [r for r in results if (len(r.split()) == 7 and (':%s' % port) in r.split()[5])]-- if len(results) == 1:- pid = results[0].split()[2]-- if pid.isdigit():- return int(pid)-- # resolves using lsof which works on both Linux and BSD, only failing if:- # - lsof is unavailable (not included by default on OpenBSD)- # - lsof doesn't provide the port ip/port, nor accept the -i and -s args- # (encountered with OSX 10.5.8)- # - the process being run as a different user due to permissions- # - there are multiple instances using the same port on different addresses- #- # flags:- # w - disables warning messages- # n - numeric addresses (disables hostname lookups)- # P - numeric ports (disables replacement of ports with their protocol)- # iTCP - only show tcp connections- # sTCP:LISTEN - listening sockets- #- # example output:- # atagar@morrigan:~$ lsof -wnP -iTCP -sTCP:LISTEN- # COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME- # tor 1745 atagar 6u IPv4 14229 0t0 TCP 127.0.0.1:9051 (LISTEN)-- if is_available('lsof'):- results = call(GET_PID_BY_PORT_LSOF, None)-- if results:- # filters to results with our port- results = [r for r in results if (len(r.split()) == 10 and (':%s' % port) in r.split()[8])]-- if len(results) == 1:- pid = results[0].split()[1]-- if pid.isdigit():- return int(pid)-- return None # all queries failed---def pid_by_open_file(path):- """- Attempts to determine the process id for a process with the given open file,- using...-- ::-- lsof -w <path>-- :param str path: location of the socket file to query against-- :returns: **int** with the process id, **None** if it can't be determined- """-- # resolves using lsof which works on both Linux and BSD, only failing if:- # - lsof is unavailable (not included by default on OpenBSD)- # - the file can't be read due to permissions- #- # flags:- # t - only show pids- # w - disables warning messages- #- # example output:- # atagar@morrigan:~$ lsof -tw /tmp/foo- # 4762-- if is_available('lsof'):- results = call(GET_PID_BY_FILE_LSOF % path, [])-- if len(results) == 1:- pid = results[0].strip()-- if pid.isdigit():- return int(pid)-- return None # all queries failed---def cwd(pid):- """- Provides the working directory of the given process.-- :param int pid: process id of the process to be queried-- :returns: **str** with the absolute path for the process' present working- directory, **None** if it can't be determined- """-- # try fetching via the proc contents if it's available- if stem.util.proc.is_available():- try:- return stem.util.proc.cwd(pid)- except IOError:- pass-- # Fall back to a pwdx query. This isn't available on BSD.- logging_prefix = 'cwd(%s):' % pid-- if is_available('pwdx'):- # pwdx results are of the form:- # 3799: /home/atagar- # 5839: No such process-- results = call(GET_CWD_PWDX % pid, None)-- if not results:- log.debug("%s pwdx didn't return any results" % logging_prefix)- elif results[0].endswith('No such process'):- log.debug('%s pwdx processes reported for this pid' % logging_prefix)- elif len(results) != 1 or results[0].count(' ') != 1 or not results[0].startswith('%s: ' % pid):- log.debug('%s we got unexpected output from pwdx: %s' % (logging_prefix, results))- else:- return results[0].split(' ', 1)[1].strip()-- # Use lsof as the final fallback. This is available on both Linux and is the- # only lookup method here that works for BSD...- # https://trac.torproject.org/projects/tor/ticket/4236- #- # flags:- # a - presents the intersection of the following arguments- # p - limits results to this pid- # d cwd - limits results to just the cwd rather than all open files- # Fn - short listing in a single column, with just the pid and cwd- #- # example output:- # ~$ lsof -a -p 75717 -d cwd -Fn- # p75717- # n/Users/atagar/tor/src/or-- if is_available('lsof'):- results = call(GET_CWD_LSOF % pid, [])-- if len(results) == 2 and results[1].startswith('n/'):- lsof_result = results[1][1:].strip()-- # If we lack read permissions for the cwd then it returns...- # p2683- # n/proc/2683/cwd (readlink: Permission denied)-- if ' ' not in lsof_result:- return lsof_result- else:- log.debug('%s we got unexpected output from lsof: %s' % (logging_prefix, results))-- return None # all queries failed---def user(pid):- """- Provides the user a process is running under.-- :param int pid: process id of the process to be queried-- :returns: **str** with the username a process is running under, **None** if- it can't be determined- """-- if not isinstance(pid, int) or pid < 0:- return None-- if stem.util.proc.is_available():- try:- import pwd # only available on unix platforms-- uid = stem.util.proc.uid(pid)-- if uid and uid.isdigit():- return pwd.getpwuid(int(uid)).pw_name- except:- pass-- if is_available('ps'):- results = call('ps -o user %s' % pid, [])-- if len(results) >= 2:- return results[1].strip()-- return None---def start_time(pid):- """- Provides the unix timestamp when the given process started.-- :param int pid: process id of the process to be queried-- :returns: **float** for the unix timestamp when the process began, **None**- if it can't be determined- """-- if not isinstance(pid, int) or pid < 0:- return None-- if stem.util.proc.is_available():- try:- return float(stem.util.proc.stats(pid, stem.util.proc.Stat.START_TIME)[0])- except IOError:- pass-- try:- ps_results = call('ps -p %s -o etime' % pid, [])-- if len(ps_results) >= 2:- etime = ps_results[1].strip()- return time.time() - stem.util.str_tools.parse_short_time_label(etime)- except:- pass-- return None---def tail(target, lines = None):- """- Provides lines of a file starting with the end. For instance,- 'tail -n 50 /tmp/my_log' could be done with...-- ::-- reversed(list(tail('/tmp/my_log', 50)))-- :param str,file target: path or file object to read from- :param int lines: number of lines to read-- :returns: **generator** that reads lines, starting with the end-- :raises: **IOError** if unable to read the file- """-- if isinstance(target, str):- with open(target) as target_file:- for line in tail(target_file, lines):- yield line-- return-- # based on snippet from...- # https://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail-- target.seek(0, 2) # go to the end of the file- block_end_byte = target.tell()- block_number = -1- content = ''-- while (lines is None or lines > 0) and block_end_byte > 0:- if (block_end_byte - BLOCK_SIZE > 0):- # read the last block we haven't yet read- target.seek(block_number * BLOCK_SIZE, 2)- content, completed_lines = (target.read(BLOCK_SIZE) + content).split('\n', 1)- else:- # reached the start of the file, just read what's left- target.seek(0, 0)- completed_lines = target.read(block_end_byte) + content-- for line in reversed(completed_lines.splitlines()):- if lines is None or lines > 0:- if lines is not None:- lines -= 1-- yield line-- block_end_byte -= BLOCK_SIZE- block_number -= 1---def bsd_jail_id(pid):- """- Gets the jail id for a process. These seem to only exist for FreeBSD (this- style for jails does not exist on Linux, OSX, or OpenBSD).-- :param int pid: process id of the jail id to be queried-- :returns: **int** for the jail id, zero if this can't be determined- """-- # Output when called from a FreeBSD jail or when Tor isn't jailed:- # JID- # 0- #- # Otherwise it's something like:- # JID- # 1-- ps_output = call(GET_BSD_JAIL_ID_PS % pid, [])-- if len(ps_output) == 2 and len(ps_output[1].split()) == 1:- jid = ps_output[1].strip()-- if jid.isdigit():- return int(jid)-- os_name = platform.system()- if os_name == 'FreeBSD':- log.warn('Unable to get the jail id for process %s.' % pid)- else:- log.debug('bsd_jail_id(%s): jail ids do not exist on %s' % (pid, os_name))-- return 0---def bsd_jail_path(jid):- """- Provides the path of the given FreeBSD jail.-- :param int jid: jail id to be queried-- :returns: **str** of the path prefix, **None** if this can't be determined- """-- if jid != 0:- # Output should be something like:- # JID IP Address Hostname Path- # 1 10.0.0.2 tor-jail /usr/jails/tor-jail-- jls_output = call(GET_BSD_JAIL_PATH % jid, [])-- if len(jls_output) == 2 and len(jls_output[1].split()) == 4:- return jls_output[1].split()[3]-- return None---def is_tarfile(path):- """- Returns if the path belongs to a tarfile or not.-- .. versionadded:: 1.2.0-- :param str path: path to be checked-- :returns: **True** if the path belongs to a tarball, **False** otherwise- """-- # Checking if it's a tar file may fail due to permissions so failing back- # to the mime type...- #- # IOError: [Errno 13] Permission denied: '/vmlinuz.old'- #- # With python 3 insuffient permissions raises an AttributeError instead...- #- # http://bugs.python.org/issue17059-- try:- return tarfile.is_tarfile(path)- except (IOError, AttributeError):- return mimetypes.guess_type(path)[0] == 'application/x-tar'---def expand_path(path, cwd = None):- """- Provides an absolute path, expanding tildes with the user's home and- appending a current working directory if the path was relative.-- :param str path: path to be expanded- :param str cwd: current working directory to expand relative paths with, our- process' if this is **None**-- :returns: **str** of the path expanded to be an absolute path, never with an- ending slash- """-- if is_windows():- relative_path = path.replace('/', '\\').rstrip('\\')- else:- relative_path = path.rstrip('/')-- if not relative_path or os.path.isabs(relative_path):- # empty or already absolute - nothing to do- pass- elif relative_path.startswith('~'):- # prefixed with a ~ or ~user entry- relative_path = os.path.expanduser(relative_path)- else:- # relative path, expand with the cwd-- if not cwd:- cwd = os.getcwd()-- # we'll be dealing with both "my/path/" and "./my/path" entries, so- # cropping the later- if relative_path.startswith('./') or relative_path.startswith('.\\'):- relative_path = relative_path[2:]- elif relative_path == '.':- relative_path = ''-- if relative_path == '':- relative_path = cwd- else:- relative_path = os.path.join(cwd, relative_path)-- return relative_path---def files_with_suffix(base_path, suffix):- """- Iterates over files in a given directory, providing filenames with a certain- suffix.-- .. versionadded:: 1.2.0-- :param str base_path: directory to be iterated over- :param str suffix: filename suffix to look for-- :returns: iterator that yields the absolute path for files with the given suffix- """-- if os.path.isfile(base_path):- if base_path.endswith(suffix):- yield base_path- else:- for root, _, files in os.walk(base_path):- for filename in files:- if filename.endswith(suffix):- yield os.path.join(root, filename)---def call(command, default = UNDEFINED, ignore_exit_status = False):- """- Issues a command in a subprocess, blocking until completion and returning the- results. This is not actually ran in a shell so pipes and other shell syntax- are not permitted.-- :param str,list command: command to be issued- :param object default: response if the query fails- :param bool ignore_exit_status: reports failure if our command's exit status- was non-zero-- :returns: **list** with the lines of output from the command-- :raises: **OSError** if this fails and no default was provided- """-- if isinstance(command, str):- command_list = command.split(' ')- else:- command_list = command-- try:- is_shell_command = command_list[0] in SHELL_COMMANDS-- start_time = time.time()- process = subprocess.Popen(command_list, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = is_shell_command)-- stdout, stderr = process.communicate()- stdout, stderr = stdout.strip(), stderr.strip()- runtime = time.time() - start_time-- log.debug('System call: %s (runtime: %0.2f)' % (command, runtime))- trace_prefix = 'Received from system (%s)' % command-- if stdout and stderr:- log.trace(trace_prefix + ', stdout:\n%s\nstderr:\n%s' % (stdout, stderr))- elif stdout:- log.trace(trace_prefix + ', stdout:\n%s' % stdout)- elif stderr:- log.trace(trace_prefix + ', stderr:\n%s' % stderr)-- exit_code = process.poll()-- if not ignore_exit_status and exit_code != 0:- raise OSError('%s returned exit status %i' % (command, exit_code))-- if stdout:- return stdout.decode('utf-8', 'replace').splitlines()- else:- return []- except OSError as exc:- log.debug('System call (failed): %s (error: %s)' % (command, exc))-- if default != UNDEFINED:- return default- else:- raise exc---def get_process_name():- """- Provides the present name of our process.-- :returns: **str** with the present name of our process- """-- global _PROCESS_NAME, _MAX_NAME_LENGTH-- if _PROCESS_NAME is None:- # Example output...- #- # COMMAND- # python run_tests.py --unit-- ps_output = call('ps -p %i -o args' % os.getpid(), [])-- if len(ps_output) == 2 and ps_output[0] in ('COMMAND', 'ARGS'):- _PROCESS_NAME = ps_output[1]- else:- # Falling back on using ctypes to get our argv. Unfortunately the simple- # method for getting this...- #- # ' '.join(['python'] + sys.argv)- #- # ... doesn't do the trick since this will miss interpreter arguments.- #- # python -W ignore::DeprecationWarning my_script.py-- args, argc = [], argc_t()-- for i in range(100):- # The ending index can be either None or raise a ValueError when- # accessed...- #- # ValueError: NULL pointer access-- try:- if argc[i] is None:- break- except ValueError:- break-- args.append(str(argc[i]))-- _PROCESS_NAME = ' '.join(args)-- _MAX_NAME_LENGTH = len(_PROCESS_NAME)-- return _PROCESS_NAME---def set_process_name(process_name):- """- Renames our current process from "python <args>" to a custom name. This is- best-effort, not necessarily working on all platforms.-- **Note:** This might have issues on FreeBSD (:trac:`9804`).-- :param str process_name: new name for our process- """-- # This is mostly based on...- #- # http://www.rhinocerus.net/forum/lang-python/569677-setting-program-name-like-0-perl.html#post2272369- #- # ... and an adaptation by Jake...- #- # https://github.com/ioerror/chameleon- #- # A cleaner implementation is available at...- #- # https://github.com/cream/libs/blob/b38970e2a6f6d2620724c828808235be0445b799/cream/util/procname.py- #- # but I'm not quite clear on their implementation, and it only does targeted- # argument replacement (ie, replace argv[0], argv[1], etc but with a string- # the same size).-- _set_argv(process_name)-- if platform.system() == 'Linux':- _set_prctl_name(process_name)- elif platform.system() in ('Darwin', 'FreeBSD', 'OpenBSD'):- _set_proc_title(process_name)---def _set_argv(process_name):- """- Overwrites our argv in a similar fashion to how it's done in C with:- strcpy(argv[0], 'new_name');- """-- if Py_GetArgcArgv is None:- return-- global _PROCESS_NAME-- # both gets the current process name and initializes _MAX_NAME_LENGTH-- current_name = get_process_name()-- argv, argc = ctypes.c_int(0), argc_t()- Py_GetArgcArgv(argv, ctypes.pointer(argc))-- if len(process_name) > _MAX_NAME_LENGTH:- raise IOError("Can't rename process to something longer than our initial name (this would overwrite memory used for the env)")-- # space we need to clear- zero_size = max(len(current_name), len(process_name))-- ctypes.memset(argc.contents, 0, zero_size + 1) # null terminate the string's end- process_name_encoded = process_name.encode('utf8')- ctypes.memmove(argc.contents, process_name_encoded, len(process_name))- _PROCESS_NAME = process_name---def _set_prctl_name(process_name):- """- Sets the prctl name, which is used by top and killall. This appears to be- Linux specific and has the max of 15 characters.-- This is from...- http://stackoverflow.com/questions/564695/is-there-a-way-to-change-effective-process-name-in-python/923034#923034- """-- libc = ctypes.CDLL(ctypes.util.find_library('c'))- name_buffer = ctypes.create_string_buffer(len(process_name) + 1)- name_buffer.value = stem.util.str_tools._to_bytes(process_name)- libc.prctl(PR_SET_NAME, ctypes.byref(name_buffer), 0, 0, 0)---def _set_proc_title(process_name):- """- BSD specific calls (should be compataible with both FreeBSD and OpenBSD:- http://fxr.watson.org/fxr/source/gen/setproctitle.c?v=FREEBSD-LIBC- http://www.rootr.net/man/man/setproctitle/3- """-- libc = ctypes.CDLL(ctypes.util.find_library('c'))- name_buffer = ctypes.create_string_buffer(len(process_name) + 1)- name_buffer.value = process_name-- try:- libc.setproctitle(ctypes.byref(name_buffer))- except AttributeError:- # Possible issue (seen on OSX):- # AttributeError: dlsym(0x7fff6a41d1e0, setproctitle): symbol not found-- pass---# TODO: drop with stem 2.x-# We renamed our methods to drop a redundant 'get_*' prefix, so alias the old-# names for backward compatability.--get_name_by_pid = name_by_pid-get_pid_by_name = pid_by_name-get_pid_by_port = pid_by_port-get_pid_by_open_file = pid_by_open_file-get_cwd = cwd-get_user = user-get_start_time = start_time-get_bsd_jail_id = bsd_jail_id-get_bsd_jail_path = bsd_jail_pathdiff --git a/ext/stem/util/term.py b/ext/stem/util/term.pydeleted file mode 100644index bb110ea1..00000000--- a/ext/stem/util/term.py+++ /dev/null@@ -1,116 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Utilities for working with the terminal.--**Module Overview:**--::-- format - wrap text with ANSI for the given colors or attributes--.. data:: Color (enum)-.. data:: BgColor (enum)-- Enumerations for foreground or background terminal color.-- =========== ===========- Color Description- =========== ===========- **BLACK** black color- **BLUE** blue color- **CYAN** cyan color- **GREEN** green color- **MAGENTA** magenta color- **RED** red color- **WHITE** white color- **YELLOW** yellow color- =========== ===========--.. data:: Attr (enum)-- Enumerations of terminal text attributes.-- =================== ===========- Attr Description- =================== ===========- **BOLD** heavy typeface- **HILIGHT** inverted foreground and background- **UNDERLINE** underlined text- **READLINE_ESCAPE** wrap encodings in `RL_PROMPT_START_IGNORE and RL_PROMPT_END_IGNORE sequences <https://stackoverflow.com/questions/9468435/look-how-to-fix-column-calculation-in-python-readline-if-use-color-prompt>`_- =================== ===========-"""--import stem.util.enum-import stem.util.str_tools--TERM_COLORS = ('BLACK', 'RED', 'GREEN', 'YELLOW', 'BLUE', 'MAGENTA', 'CYAN', 'WHITE')--# DISABLE_COLOR_SUPPORT is *not* being vended to Stem users. This is likely to-# go away if I can think of a more graceful method for color toggling.--DISABLE_COLOR_SUPPORT = False--Color = stem.util.enum.Enum(*TERM_COLORS)-BgColor = stem.util.enum.Enum(*['BG_' + color for color in TERM_COLORS])-Attr = stem.util.enum.Enum('BOLD', 'UNDERLINE', 'HILIGHT', 'READLINE_ESCAPE')--# mappings of terminal attribute enums to their ANSI escape encoding-FG_ENCODING = dict([(list(Color)[i], str(30 + i)) for i in range(8)])-BG_ENCODING = dict([(list(BgColor)[i], str(40 + i)) for i in range(8)])-ATTR_ENCODING = {Attr.BOLD: '1', Attr.UNDERLINE: '4', Attr.HILIGHT: '7'}--CSI = '\x1B[%sm'-RESET = CSI % '0'---def format(msg, *attr):- """- Simple terminal text formatting using `ANSI escape sequences- <https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes>`_.- The following are some toolkits providing similar capabilities:-- * `django.utils.termcolors <https://github.com/django/django/blob/master/django/utils/termcolors.py>`_- * `termcolor <https://pypi.python.org/pypi/termcolor>`_- * `colorama <https://pypi.python.org/pypi/colorama>`_-- :param str msg: string to be formatted- :param str attr: text attributes, this can be :data:`~stem.util.term.Color`,- :data:`~stem.util.term.BgColor`, or :data:`~stem.util.term.Attr` enums- and are case insensitive (so strings like 'red' are fine)-- :returns: **str** wrapped with ANSI escape encodings, starting with the given- attributes and ending with a reset- """-- if DISABLE_COLOR_SUPPORT:- return msg-- # if we have reset sequences in the message then apply our attributes- # after each of them-- if RESET in msg:- return ''.join([format(comp, *attr) for comp in msg.split(RESET)])-- encodings = []-- for text_attr in attr:- text_attr, encoding = stem.util.str_tools._to_camel_case(text_attr), None- encoding = FG_ENCODING.get(text_attr, encoding)- encoding = BG_ENCODING.get(text_attr, encoding)- encoding = ATTR_ENCODING.get(text_attr, encoding)-- if encoding:- encodings.append(encoding)-- if encodings:- prefix, suffix = CSI % ';'.join(encodings), RESET-- if Attr.READLINE_ESCAPE in attr:- prefix = '\001%s\002' % prefix- suffix = '\001%s\002' % suffix-- return prefix + msg + suffix- else:- return msgdiff --git a/ext/stem/util/test_tools.py b/ext/stem/util/test_tools.pydeleted file mode 100644index d6a81c45..00000000--- a/ext/stem/util/test_tools.py+++ /dev/null@@ -1,341 +0,0 @@-# Copyright 2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Helper functions for testing.--.. versionadded:: 1.2.0--::-- clean_orphaned_pyc - delete *.pyc files without corresponding *.py-- is_pyflakes_available - checks if pyflakes is available- is_pep8_available - checks if pep8 is available-- stylistic_issues - checks for PEP8 and other stylistic issues- pyflakes_issues - static checks for problems via pyflakes-"""--import collections-import linecache-import os-import re--import stem.util.conf-import stem.util.system--CONFIG = stem.util.conf.config_dict('test', {- 'pep8.ignore': [],- 'pyflakes.ignore': [],- 'exclude_paths': [],-})--Issue = collections.namedtuple('Issue', [- 'line_number',- 'message',- 'line',-])---def clean_orphaned_pyc(paths):- """- Deletes any file with a *.pyc extention without a corresponding *.py. This- helps to address a common gotcha when deleting python files...-- * You delete module 'foo.py' and run the tests to ensure that you haven't- broken anything. They pass, however there *are* still some 'import foo'- statements that still work because the bytecode (foo.pyc) is still around.-- * You push your change.-- * Another developer clones our repository and is confused because we have a- bunch of ImportErrors.-- :param list paths: paths to search for orphaned pyc files-- :returns: list of absolute paths that were deleted- """-- orphaned_pyc = []-- for path in paths:- for pyc_path in stem.util.system.files_with_suffix(path, '.pyc'):- py_path = pyc_path[:-1]-- # If we're running python 3 then the *.pyc files are no longer bundled- # with the *.py. Rather, they're in a __pycache__ directory.-- pycache = '%s__pycache__%s' % (os.path.sep, os.path.sep)-- if pycache in pyc_path:- directory, pycache_filename = pyc_path.split(pycache, 1)-- if not pycache_filename.endswith('.pyc'):- continue # should look like 'test_tools.cpython-32.pyc'-- py_path = os.path.join(directory, pycache_filename.split('.')[0] + '.py')-- if not os.path.exists(py_path):- orphaned_pyc.append(pyc_path)- os.remove(pyc_path)-- return orphaned_pyc---def is_pyflakes_available():- """- Checks if pyflakes is availalbe.-- :returns: **True** if we can use pyflakes and **False** otherwise- """-- try:- import pyflakes.api- import pyflakes.reporter- return True- except ImportError:- return False---def is_pep8_available():- """- Checks if pep8 is availalbe.-- :returns: **True** if we can use pep8 and **False** otherwise- """-- try:- import pep8-- if not hasattr(pep8, 'BaseReport'):- raise ImportError()-- return True- except ImportError:- return False---def stylistic_issues(paths, check_two_space_indents = False, check_newlines = False, check_trailing_whitespace = False, check_exception_keyword = False, prefer_single_quotes = False):- """- Checks for stylistic issues that are an issue according to the parts of PEP8- we conform to. You can suppress PEP8 issues by making a 'test' configuration- that sets 'pep8.ignore'.-- For example, with a 'test/settings.cfg' of...-- ::-- # PEP8 compliance issues that we're ignoreing...- #- # * E111 and E121 four space indentations- # * E501 line is over 79 characters-- pep8.ignore E111- pep8.ignore E121- pep8.ignore E501-- ... you can then run tests with...-- ::-- import stem.util.conf-- test_config = stem.util.conf.get_config('test')- test_config.load('test/settings.cfg')-- issues = stylistic_issues('my_project')-- If a 'exclude_paths' was set in our test config then we exclude any absolute- paths matching those regexes.-- .. versionchanged:: 1.3.0- Renamed from get_stylistic_issues() to stylistic_issues(). The old name- still works as an alias, but will be dropped in Stem version 2.0.0.-- .. versionchanged:: 1.4.0- Changing tuples in return value to be namedtuple instances, and adding the- line that had the issue.-- .. versionchanged:: 1.4.0- Added the prefer_single_quotes option.-- :param list paths: paths to search for stylistic issues- :param bool check_two_space_indents: check for two space indentations and- that no tabs snuck in- :param bool check_newlines: check that we have standard newlines (\\n), not- windows (\\r\\n) nor classic mac (\\r)- :param bool check_trailing_whitespace: check that our lines don't end with- trailing whitespace- :param bool check_exception_keyword: checks that we're using 'as' for- exceptions rather than a comma- :param bool prefer_single_quotes: standardize on using single rather than- double quotes for strings, when reasonable-- :returns: **dict** of the form ``path => [(line_number, message)...]``- """-- issues = {}-- if is_pep8_available():- import pep8-- class StyleReport(pep8.BaseReport):- def __init__(self, options):- super(StyleReport, self).__init__(options)-- def error(self, line_number, offset, text, check):- code = super(StyleReport, self).error(line_number, offset, text, check)-- if code:- issues.setdefault(self.filename, []).append(Issue(line_number, '%s %s' % (code, text), text))-- style_checker = pep8.StyleGuide(ignore = CONFIG['pep8.ignore'], reporter = StyleReport)- style_checker.check_files(list(_python_files(paths)))-- if check_two_space_indents or check_newlines or check_trailing_whitespace or check_exception_keyword:- for path in _python_files(paths):- with open(path) as f:- file_contents = f.read()-- lines = file_contents.split('\n')- is_block_comment = False-- for index, line in enumerate(lines):- whitespace, content = re.match('^(\s*)(.*)$', line).groups()-- # TODO: This does not check that block indentations are two spaces- # because differentiating source from string blocks ("""foo""") is more- # of a pita than I want to deal with right now.-- if '"""' in content:- is_block_comment = not is_block_comment-- if check_two_space_indents and '\t' in whitespace:- issues.setdefault(path, []).append(Issue(index + 1, 'indentation has a tab', line))- elif check_newlines and '\r' in content:- issues.setdefault(path, []).append(Issue(index + 1, 'contains a windows newline', line))- elif check_trailing_whitespace and content != content.rstrip():- issues.setdefault(path, []).append(Issue(index + 1, 'line has trailing whitespace', line))- elif check_exception_keyword and content.lstrip().startswith('except') and content.endswith(', exc:'):- # Python 2.6 - 2.7 supports two forms for exceptions...- #- # except ValueError, exc:- # except ValueError as exc:- #- # The former is the old method and no longer supported in python 3- # going forward.-- # TODO: This check only works if the exception variable is called- # 'exc'. We should generalize this via a regex so other names work- # too.-- issues.setdefault(path, []).append(Issue(index + 1, "except clause should use 'as', not comma", line))-- if prefer_single_quotes and line and not is_block_comment:- content = line.strip().split('#', 1)[0]-- if '"' in content and "'" not in content and '"""' not in content and not content.endswith('\\'):- # Checking if the line already has any single quotes since that- # usually means double quotes are preferable for the content (for- # instance "I'm hungry"). Also checking for '\' at the end since- # that can indicate a multi-line string.-- issues.setdefault(path, []).append(Issue(index + 1, "use single rather than double quotes", line))-- return issues---def pyflakes_issues(paths):- """- Performs static checks via pyflakes. False positives can be ignored via- 'pyflakes.ignore' entries in our 'test' config. For instance...-- ::-- pyflakes.ignore stem/util/test_tools.py => 'pyflakes' imported but unused- pyflakes.ignore stem/util/test_tools.py => 'pep8' imported but unused-- If a 'exclude_paths' was set in our test config then we exclude any absolute- paths matching those regexes.-- .. versionchanged:: 1.3.0- Renamed from get_pyflakes_issues() to pyflakes_issues(). The old name- still works as an alias, but will be dropped in Stem version 2.0.0.-- .. versionchanged:: 1.4.0- Changing tuples in return value to be namedtuple instances, and adding the- line that had the issue.-- :param list paths: paths to search for problems-- :returns: dict of the form ``path => [(line_number, message)...]``- """-- issues = {}-- if is_pyflakes_available():- import pyflakes.api- import pyflakes.reporter-- class Reporter(pyflakes.reporter.Reporter):- def __init__(self):- self._ignored_issues = {}-- for line in CONFIG['pyflakes.ignore']:- path, issue = line.split('=>')- self._ignored_issues.setdefault(path.strip(), []).append(issue.strip())-- def unexpectedError(self, filename, msg):- self._register_issue(filename, None, msg, None)-- def syntaxError(self, filename, msg, lineno, offset, text):- self._register_issue(filename, lineno, msg, text)-- def flake(self, msg):- self._register_issue(msg.filename, msg.lineno, msg.message % msg.message_args, None)-- def _is_ignored(self, path, issue):- # Paths in pyflakes_ignore are relative, so we need to check to see if our- # path ends with any of them.-- for ignored_path, ignored_issues in self._ignored_issues.items():- if path.endswith(ignored_path) and issue in ignored_issues:- return True-- return False-- def _register_issue(self, path, line_number, issue, line):- if not self._is_ignored(path, issue):- if path and line_number and not line:- line = linecache.getline(path, line_number)-- issues.setdefault(path, []).append(Issue(line_number, issue, line))-- reporter = Reporter()-- for path in _python_files(paths):- pyflakes.api.checkPath(path, reporter)-- return issues---def _python_files(paths):- for path in paths:- for file_path in stem.util.system.files_with_suffix(path, '.py'):- skip = False-- for exclude_path in CONFIG['exclude_paths']:- if re.match(exclude_path, file_path):- skip = True- break-- if not skip:- yield file_path--# TODO: drop with stem 2.x-# We renamed our methods to drop a redundant 'get_*' prefix, so alias the old-# names for backward compatability.--get_stylistic_issues = stylistic_issues-get_pyflakes_issues = pyflakes_issuesdiff --git a/ext/stem/util/tor_tools.py b/ext/stem/util/tor_tools.pydeleted file mode 100644index 01c29eee..00000000--- a/ext/stem/util/tor_tools.py+++ /dev/null@@ -1,151 +0,0 @@-# Copyright 2012-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Miscellaneous utility functions for working with tor.--.. versionadded:: 1.2.0--**Module Overview:**--::-- is_valid_fingerprint - checks if a string is a valid tor relay fingerprint- is_valid_nickname - checks if a string is a valid tor relay nickname- is_valid_circuit_id - checks if a string is a valid tor circuit id- is_valid_stream_id - checks if a string is a valid tor stream id- is_valid_connection_id - checks if a string is a valid tor connection id- is_valid_hidden_service_address - checks if a string is a valid hidden service address- is_hex_digits - checks if a string is only made up of hex digits-"""--import re--# The control-spec defines the following as...-#-# Fingerprint = "$" 40*HEXDIG-# NicknameChar = "a"-"z" / "A"-"Z" / "0" - "9"-# Nickname = 1*19 NicknameChar-#-# CircuitID = 1*16 IDChar-# IDChar = ALPHA / DIGIT-#-# HEXDIG is defined in RFC 5234 as being uppercase and used in RFC 5987 as-# case insensitive. Tor doesn't define this in the spec so flipping a coin-# and going with case insensitive.--NICKNAME_PATTERN = re.compile('^[a-zA-Z0-9]{1,19}$')-CIRC_ID_PATTERN = re.compile('^[a-zA-Z0-9]{1,16}$')--# Hidden service addresses are sixteen base32 characters.--HS_ADDRESS_PATTERN = re.compile('^[a-z2-7]{16}$')---def is_valid_fingerprint(entry, check_prefix = False):- """- Checks if a string is a properly formatted relay fingerprint. This checks for- a '$' prefix if check_prefix is true, otherwise this only validates the hex- digits.-- :param str entry: string to be checked- :param bool check_prefix: checks for a '$' prefix-- :returns: **True** if the string could be a relay fingerprint, **False** otherwise- """-- try:- if check_prefix:- if not entry or entry[0] != '$':- return False-- entry = entry[1:]-- return is_hex_digits(entry, 40)- except TypeError:- return False---def is_valid_nickname(entry):- """- Checks if a string is a valid format for being a nickname.-- :param str entry: string to be checked-- :returns: **True** if the string could be a nickname, **False** otherwise- """-- try:- return bool(NICKNAME_PATTERN.match(entry))- except TypeError:- return False---def is_valid_circuit_id(entry):- """- Checks if a string is a valid format for being a circuit identifier.-- :returns: **True** if the string could be a circuit id, **False** otherwise- """-- try:- return bool(CIRC_ID_PATTERN.match(entry))- except TypeError:- return False---def is_valid_stream_id(entry):- """- Checks if a string is a valid format for being a stream identifier.- Currently, this is just an alias to :func:`~stem.util.tor_tools.is_valid_circuit_id`.-- :returns: **True** if the string could be a stream id, **False** otherwise- """-- return is_valid_circuit_id(entry)---def is_valid_connection_id(entry):- """- Checks if a string is a valid format for being a connection identifier.- Currently, this is just an alias to :func:`~stem.util.tor_tools.is_valid_circuit_id`.-- :returns: **True** if the string could be a connection id, **False** otherwise- """-- return is_valid_circuit_id(entry)---def is_valid_hidden_service_address(entry):- """- Checks if a string is a valid format for being a hidden service address (not- including the '.onion' suffix).-- :returns: **True** if the string could be a hidden service address, **False** otherwise- """-- try:- return bool(HS_ADDRESS_PATTERN.match(entry))- except TypeError:- return False---def is_hex_digits(entry, count):- """- Checks if a string is the given number of hex digits. Digits represented by- letters are case insensitive.-- :param str entry: string to be checked- :param int count: number of hex digits to be checked for-- :returns: **True** if the given number of hex digits, **False** otherwise- """-- try:- if len(entry) != count:- return False-- int(entry, 16) # attempt to convert it as hex- return True- except (ValueError, TypeError):- return Falsediff --git a/ext/stem/version.py b/ext/stem/version.pydeleted file mode 100644index 1182bfca..00000000--- a/ext/stem/version.py+++ /dev/null@@ -1,376 +0,0 @@-# Copyright 2011-2015, Damian Johnson and The Tor Project-# See LICENSE for licensing information--"""-Tor versioning information and requirements for its features. These can be-easily parsed and compared, for instance...--::-- >>> from stem.version import get_system_tor_version, Requirement- >>> my_version = get_system_tor_version()- >>> print(my_version)- 0.2.1.30- >>> my_version >= Requirement.TORRC_CONTROL_SOCKET- True--**Module Overview:**--::-- get_system_tor_version - gets the version of our system's tor installation-- Version - Tor versioning information--.. data:: Requirement (enum)-- Enumerations for the version requirements of features.-- ===================================== ===========- Requirement Description- ===================================== ===========- **AUTH_SAFECOOKIE** SAFECOOKIE authentication method- **DROPGUARDS** DROPGUARDS requests- **EVENT_AUTHDIR_NEWDESCS** AUTHDIR_NEWDESC events- **EVENT_BUILDTIMEOUT_SET** BUILDTIMEOUT_SET events- **EVENT_CIRC_MINOR** CIRC_MINOR events- **EVENT_CLIENTS_SEEN** CLIENTS_SEEN events- **EVENT_CONF_CHANGED** CONF_CHANGED events- **EVENT_DESCCHANGED** DESCCHANGED events- **EVENT_GUARD** GUARD events- **EVENT_HS_DESC_CONTENT** HS_DESC_CONTENT events- **EVENT_NEWCONSENSUS** NEWCONSENSUS events- **EVENT_NS** NS events- **EVENT_SIGNAL** SIGNAL events- **EVENT_STATUS** STATUS_GENERAL, STATUS_CLIENT, and STATUS_SERVER events- **EVENT_STREAM_BW** STREAM_BW events- **EVENT_TRANSPORT_LAUNCHED** TRANSPORT_LAUNCHED events- **EVENT_CONN_BW** CONN_BW events- **EVENT_CIRC_BW** CIRC_BW events- **EVENT_CELL_STATS** CELL_STATS events- **EVENT_TB_EMPTY** TB_EMPTY events- **EVENT_HS_DESC** HS_DESC events- **EXTENDCIRCUIT_PATH_OPTIONAL** EXTENDCIRCUIT queries can omit the path if the circuit is zero- **FEATURE_EXTENDED_EVENTS** 'EXTENDED_EVENTS' optional feature- **FEATURE_VERBOSE_NAMES** 'VERBOSE_NAMES' optional feature- **GETINFO_CONFIG_TEXT** 'GETINFO config-text' query- **HSFETCH** HSFETCH requests- **HSPOST** HSPOST requests- **ADD_ONION** ADD_ONION and DEL_ONION requests- **LOADCONF** LOADCONF requests- **MICRODESCRIPTOR_IS_DEFAULT** Tor gets microdescriptors by default rather than server descriptors- **TAKEOWNERSHIP** TAKEOWNERSHIP requests- **TORRC_CONTROL_SOCKET** 'ControlSocket <path>' config option- **TORRC_PORT_FORWARDING** 'PortForwarding' config option- **TORRC_DISABLE_DEBUGGER_ATTACHMENT** 'DisableDebuggerAttachment' config option- **TORRC_VIA_STDIN** Allow torrc options via 'tor -f -' (:trac:`13865`)- ===================================== ===========-"""--import os-import re--import stem.util.enum-import stem.util.system--try:- # added in python 3.2- from functools import lru_cache-except ImportError:- from stem.util.lru_cache import lru_cache--# cache for the get_system_tor_version function-VERSION_CACHE = {}---def get_system_tor_version(tor_cmd = 'tor'):- """- Queries tor for its version. This is os dependent, only working on linux,- osx, and bsd.-- :param str tor_cmd: command used to run tor-- :returns: :class:`~stem.version.Version` provided by the tor command-- :raises: **IOError** if unable to query or parse the version- """-- if tor_cmd not in VERSION_CACHE:- version_cmd = '%s --version' % tor_cmd-- try:- version_output = stem.util.system.call(version_cmd)- except OSError as exc:- # make the error message nicer if this is due to tor being unavialable-- if 'No such file or directory' in str(exc):- if os.path.isabs(tor_cmd):- exc = "Unable to check tor's version. '%s' doesn't exist." % tor_cmd- else:- exc = "Unable to run '%s'. Mabye tor isn't in your PATH?" % version_cmd-- raise IOError(exc)-- if version_output:- # output example:- # Oct 21 07:19:27.438 [notice] Tor v0.2.1.30. This is experimental software. Do not rely on it for strong anonymity. (Running on Linux i686)- # Tor version 0.2.1.30.-- last_line = version_output[-1]-- if last_line.startswith('Tor version ') and last_line.endswith('.'):- try:- version_str = last_line[12:-1]- VERSION_CACHE[tor_cmd] = Version(version_str)- except ValueError as exc:- raise IOError(exc)- else:- raise IOError("Unexpected response from '%s': %s" % (version_cmd, last_line))- else:- raise IOError("'%s' didn't have any output" % version_cmd)-- return VERSION_CACHE[tor_cmd]---@lru_cache()-def _get_version(version_str):- return Version(version_str)---class Version(object):- """- Comparable tor version. These are constructed from strings that conform to- the 'new' style in the `tor version-spec- <https://gitweb.torproject.org/torspec.git/tree/version-spec.txt>`_,- such as "0.1.4" or "0.2.2.23-alpha (git-7dcd105be34a4f44)".-- :var int major: major version- :var int minor: minor version- :var int micro: micro version- :var int patch: patch level (**None** if undefined)- :var str status: status tag such as 'alpha' or 'beta-dev' (**None** if undefined)- :var str extra: extra information without its parentheses such as- 'git-8be6058d8f31e578' (**None** if undefined)- :var str git_commit: git commit id (**None** if it wasn't provided)-- :param str version_str: version to be parsed-- :raises: **ValueError** if input isn't a valid tor version- """-- def __init__(self, version_str):- self.version_str = version_str- version_parts = re.match(r'^([0-9]+)\.([0-9]+)\.([0-9]+)(\.[0-9]+)?(-\S*)?( \(\S*\))?$', version_str)- self._hash = None-- if version_parts:- major, minor, micro, patch, status, extra = version_parts.groups()-- # The patch and status matches are optional (may be None) and have an extra- # proceeding period or dash if they exist. Stripping those off.-- if patch:- patch = int(patch[1:])-- if status:- status = status[1:]-- if extra:- extra = extra[2:-1]-- self.major = int(major)- self.minor = int(minor)- self.micro = int(micro)- self.patch = patch- self.status = status- self.extra = extra-- if extra and re.match('^git-[0-9a-f]{16}$', extra):- self.git_commit = extra[4:]- else:- self.git_commit = None- else:- raise ValueError("'%s' isn't a properly formatted tor version" % version_str)-- def __str__(self):- """- Provides the string used to construct the version.- """-- return self.version_str-- def _compare(self, other, method):- """- Compares version ordering according to the spec.- """-- if not isinstance(other, Version):- return False-- for attr in ('major', 'minor', 'micro', 'patch'):- my_version = getattr(self, attr)- other_version = getattr(other, attr)-- if my_version is None:- my_version = 0-- if other_version is None:- other_version = 0-- if my_version != other_version:- return method(my_version, other_version)-- # According to the version spec...- #- # If we *do* encounter two versions that differ only by status tag, we- # compare them lexically as ASCII byte strings.-- my_status = self.status if self.status else ''- other_status = other.status if other.status else ''-- return method(my_status, other_status)-- def __eq__(self, other):- return self._compare(other, lambda s, o: s == o)-- def __gt__(self, other):- """- Checks if this version meets the requirements for a given feature. We can- be compared to either a :class:`~stem.version.Version` or- :class:`~stem.version._VersionRequirements`.- """-- if isinstance(other, _VersionRequirements):- for rule in other.rules:- if rule(self):- return True-- return False-- return self._compare(other, lambda s, o: s > o)-- def __ge__(self, other):- if isinstance(other, _VersionRequirements):- for rule in other.rules:- if rule(self):- return True-- return False-- return self._compare(other, lambda s, o: s >= o)-- def __hash__(self):- if self._hash is None:- my_hash = 0-- for attr in ('major', 'minor', 'micro', 'patch', 'status'):- my_hash *= 1024-- attr_value = getattr(self, attr)-- if attr_value is not None:- my_hash += hash(attr_value)-- self._hash = my_hash-- return self._hash---class _VersionRequirements(object):- """- Series of version constraints that can be compared to. For instance, this- allows for comparisons like 'if I'm greater than version X in the 0.2.2- series, or greater than version Y in the 0.2.3 series'.-- This is a logical 'or' of the series of rules.- """-- def __init__(self):- self.rules = []-- def greater_than(self, version, inclusive = True):- """- Adds a constraint that we're greater than the given version.-- :param stem.version.Version version: version we're checking against- :param bool inclusive: if comparison is inclusive or not- """-- if inclusive:- self.rules.append(lambda v: version <= v)- else:- self.rules.append(lambda v: version < v)-- def less_than(self, version, inclusive = True):- """- Adds a constraint that we're less than the given version.-- :param stem.version.Version version: version we're checking against- :param bool inclusive: if comparison is inclusive or not- """-- if inclusive:- self.rules.append(lambda v: version >= v)- else:- self.rules.append(lambda v: version > v)-- def in_range(self, from_version, to_version, from_inclusive = True, to_inclusive = False):- """- Adds constraint that we're within the range from one version to another.-- :param stem.version.Version from_version: beginning of the comparison range- :param stem.version.Version to_version: end of the comparison range- :param bool from_inclusive: if comparison is inclusive with the starting version- :param bool to_inclusive: if comparison is inclusive with the ending version- """-- if from_inclusive and to_inclusive:- new_rule = lambda v: from_version <= v <= to_version- elif from_inclusive:- new_rule = lambda v: from_version <= v < to_version- else:- new_rule = lambda v: from_version < v < to_version-- self.rules.append(new_rule)--safecookie_req = _VersionRequirements()-safecookie_req.in_range(Version('0.2.2.36'), Version('0.2.3.0'))-safecookie_req.greater_than(Version('0.2.3.13'))--Requirement = stem.util.enum.Enum(- ('AUTH_SAFECOOKIE', safecookie_req),- ('DROPGUARDS', Version('0.2.5.1-alpha')),- ('EVENT_AUTHDIR_NEWDESCS', Version('0.1.1.10-alpha')),- ('EVENT_BUILDTIMEOUT_SET', Version('0.2.2.7-alpha')),- ('EVENT_CIRC_MINOR', Version('0.2.3.11-alpha')),- ('EVENT_CLIENTS_SEEN', Version('0.2.1.10-alpha')),- ('EVENT_CONF_CHANGED', Version('0.2.3.3-alpha')),- ('EVENT_DESCCHANGED', Version('0.1.2.2-alpha')),- ('EVENT_GUARD', Version('0.1.2.5-alpha')),- ('EVENT_HS_DESC_CONTENT', Version('0.2.7.1-alpha')),- ('EVENT_NS', Version('0.1.2.3-alpha')),- ('EVENT_NEWCONSENSUS', Version('0.2.1.13-alpha')),- ('EVENT_SIGNAL', Version('0.2.3.1-alpha')),- ('EVENT_STATUS', Version('0.1.2.3-alpha')),- ('EVENT_STREAM_BW', Version('0.1.2.8-beta')),- ('EVENT_TRANSPORT_LAUNCHED', Version('0.2.5.0-alpha')),- ('EVENT_CONN_BW', Version('0.2.5.2-alpha')),- ('EVENT_CIRC_BW', Version('0.2.5.2-alpha')),- ('EVENT_CELL_STATS', Version('0.2.5.2-alpha')),- ('EVENT_TB_EMPTY', Version('0.2.5.2-alpha')),- ('EVENT_HS_DESC', Version('0.2.5.2-alpha')),- ('EXTENDCIRCUIT_PATH_OPTIONAL', Version('0.2.2.9')),- ('FEATURE_EXTENDED_EVENTS', Version('0.2.2.1-alpha')),- ('FEATURE_VERBOSE_NAMES', Version('0.2.2.1-alpha')),- ('GETINFO_CONFIG_TEXT', Version('0.2.2.7-alpha')),- ('HSFETCH', Version('0.2.7.1-alpha')),- ('HSPOST', Version('0.2.7.1-alpha')),- ('ADD_ONION', Version('0.2.7.1-alpha')),- ('LOADCONF', Version('0.2.1.1')),- ('MICRODESCRIPTOR_IS_DEFAULT', Version('0.2.3.3')),- ('TAKEOWNERSHIP', Version('0.2.2.28-beta')),- ('TORRC_CONTROL_SOCKET', Version('0.2.0.30')),- ('TORRC_PORT_FORWARDING', Version('0.2.3.1-alpha')),- ('TORRC_DISABLE_DEBUGGER_ATTACHMENT', Version('0.2.3.9')),- ('TORRC_VIA_STDIN', Version('0.2.6.3-alpha')),-)diff --git a/ext/whois/__init__.py b/ext/whois/__init__.pydeleted file mode 100644index 1ae517af..00000000--- a/ext/whois/__init__.py+++ /dev/null@@ -1,101 +0,0 @@-# -*- coding: utf-8 -*---from __future__ import print_function-from __future__ import absolute_import-from __future__ import unicode_literals-from __future__ import division-from future import standard_library-standard_library.install_aliases()-from builtins import *-import re-import sys-import os-import subprocess-import socket-from .parser import WhoisEntry-from .whois import NICClient----def whois(url, command=False):- # clean domain to expose netloc- ip_match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", url)- if ip_match:- domain = url- try:- result = socket.gethostbyaddr(url)- except socket.herror as e:- pass- else:- domain = extract_domain(result[0])- else:- domain = extract_domain(url)- if command:- # try native whois command- r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)- text = r.stdout.read().decode()- else:- # try builtin client- nic_client = NICClient()- text = nic_client.whois_lookup(None, domain.encode('idna'), 0)- return WhoisEntry.load(domain, text)---suffixes = None-def extract_domain(url):- """Extract the domain from the given URL-- >>> print(extract_domain('http://www.google.com.au/tos.html'))- google.com.au- >>> print(extract_domain('abc.def.com'))- def.com- >>> print(extract_domain(u'www.公司.hk'))- 公司.hk- >>> print(extract_domain('chambagri.fr'))- chambagri.fr- >>> print(extract_domain('www.webscraping.com'))- webscraping.com- >>> print(extract_domain('198.252.206.140'))- stackoverflow.com- >>> print(extract_domain('102.112.2O7.net'))- 2o7.net- >>> print(extract_domain('globoesporte.globo.com'))- globo.com- >>> print(extract_domain('1-0-1-1-1-0-1-1-1-1-1-1-1-.0-0-0-0-0-0-0-0-0-0-0-0-0-10-0-0-0-0-0-0-0-0-0-0-0-0-0.info'))- 0-0-0-0-0-0-0-0-0-0-0-0-0-10-0-0-0-0-0-0-0-0-0-0-0-0-0.info- """- if re.match(r'\d+\.\d+\.\d+\.\d+', url):- # this is an IP address- return socket.gethostbyaddr(url)[0]-- # load known TLD suffixes- global suffixes- if not suffixes:- # downloaded from https://publicsuffix.org/list/public_suffix_list.dat- tlds_path = os.path.join(os.getcwd(), os.path.dirname(__file__), 'data', 'public_suffix_list.dat')- with open(tlds_path, encoding='utf-8') as tlds_fp:- suffixes = set(line.encode('utf-8') for line in tlds_fp.read().splitlines() if line and not line.startswith('//'))-- if not isinstance(url, str):- url = url.decode('utf-8')- url = re.sub('^.*://', '', url)- url = url.split('/')[0].lower()-- # find the longest suffix match- domain = b''- for section in reversed(url.split('.')):- if domain:- domain = b'.' + domain- domain = section.encode('utf-8') + domain- if domain not in suffixes:- break- return domain.decode('utf-8')---if __name__ == '__main__':- try:- url = sys.argv[1]- except IndexError:- print('Usage: %s url' % sys.argv[0])- else:- print(whois(url))diff --git a/ext/whois/data/public_suffix_list.dat b/ext/whois/data/public_suffix_list.datdeleted file mode 100644index 06e2fb06..00000000--- a/ext/whois/data/public_suffix_list.dat+++ /dev/null@@ -1,11855 +0,0 @@-// This Source Code Form is subject to the terms of the Mozilla Public-// License, v. 2.0. If a copy of the MPL was not distributed with this-// file, You can obtain one at https://mozilla.org/MPL/2.0/.--// Please pull this list from, and only from https://publicsuffix.org/list/public_suffix_list.dat,-// rather than any other VCS sites. Pulling from any other URL is not guaranteed to be supported.--// Instructions on pulling and using this list can be found at https://publicsuffix.org/list/.--// ===BEGIN ICANN DOMAINS===--// ac : https://en.wikipedia.org/wiki/.ac-ac-com.ac-edu.ac-gov.ac-net.ac-mil.ac-org.ac--// ad : https://en.wikipedia.org/wiki/.ad-ad-nom.ad--// ae : https://en.wikipedia.org/wiki/.ae-// see also: "Domain Name Eligibility Policy" at http://www.aeda.ae/eng/aepolicy.php-ae-co.ae-net.ae-org.ae-sch.ae-ac.ae-gov.ae-mil.ae--// aero : see https://www.information.aero/index.php?id=66-aero-accident-investigation.aero-accident-prevention.aero-aerobatic.aero-aeroclub.aero-aerodrome.aero-agents.aero-aircraft.aero-airline.aero-airport.aero-air-surveillance.aero-airtraffic.aero-air-traffic-control.aero-ambulance.aero-amusement.aero-association.aero-author.aero-ballooning.aero-broker.aero-caa.aero-cargo.aero-catering.aero-certification.aero-championship.aero-charter.aero-civilaviation.aero-club.aero-conference.aero-consultant.aero-consulting.aero-control.aero-council.aero-crew.aero-design.aero-dgca.aero-educator.aero-emergency.aero-engine.aero-engineer.aero-entertainment.aero-equipment.aero-exchange.aero-express.aero-federation.aero-flight.aero-freight.aero-fuel.aero-gliding.aero-government.aero-groundhandling.aero-group.aero-hanggliding.aero-homebuilt.aero-insurance.aero-journal.aero-journalist.aero-leasing.aero-logistics.aero-magazine.aero-maintenance.aero-media.aero-microlight.aero-modelling.aero-navigation.aero-parachuting.aero-paragliding.aero-passenger-association.aero-pilot.aero-press.aero-production.aero-recreation.aero-repbody.aero-res.aero-research.aero-rotorcraft.aero-safety.aero-scientist.aero-services.aero-show.aero-skydiving.aero-software.aero-student.aero-trader.aero-trading.aero-trainer.aero-union.aero-workinggroup.aero-works.aero--// af : http://www.nic.af/help.jsp-af-gov.af-com.af-org.af-net.af-edu.af--// ag : http://www.nic.ag/prices.htm-ag-com.ag-org.ag-net.ag-co.ag-nom.ag--// ai : http://nic.com.ai/-ai-off.ai-com.ai-net.ai-org.ai--// al : http://www.ert.gov.al/ert_alb/faq_det.html?Id=31-al-com.al-edu.al-gov.al-mil.al-net.al-org.al--// am : https://en.wikipedia.org/wiki/.am-am--// ao : https://en.wikipedia.org/wiki/.ao-// http://www.dns.ao/REGISTR.DOC-ao-ed.ao-gv.ao-og.ao-co.ao-pb.ao-it.ao--// aq : https://en.wikipedia.org/wiki/.aq-aq--// ar : https://nic.ar/normativa-vigente.xhtml-ar-com.ar-edu.ar-gob.ar-gov.ar-int.ar-mil.ar-net.ar-org.ar-tur.ar--// arpa : https://en.wikipedia.org/wiki/.arpa-// Confirmed by registry <[email protected]> 2008-06-18-arpa-e164.arpa-in-addr.arpa-ip6.arpa-iris.arpa-uri.arpa-urn.arpa--// as : https://en.wikipedia.org/wiki/.as-as-gov.as--// asia : https://en.wikipedia.org/wiki/.asia-asia--// at : https://en.wikipedia.org/wiki/.at-// Confirmed by registry <[email protected]> 2008-06-17-at-ac.at-co.at-gv.at-or.at--// au : https://en.wikipedia.org/wiki/.au-// http://www.auda.org.au/-au-// 2LDs-com.au-net.au-org.au-edu.au-gov.au-asn.au-id.au-// Historic 2LDs (closed to new registration, but sites still exist)-info.au-conf.au-oz.au-// CGDNs - http://www.cgdn.org.au/-act.au-nsw.au-nt.au-qld.au-sa.au-tas.au-vic.au-wa.au-// 3LDs-act.edu.au-nsw.edu.au-nt.edu.au-qld.edu.au-sa.edu.au-tas.edu.au-vic.edu.au-wa.edu.au-// act.gov.au Bug 984824 - Removed at request of Greg Tankard-// nsw.gov.au Bug 547985 - Removed at request of <[email protected]>-// nt.gov.au Bug 940478 - Removed at request of Greg Connors <[email protected]>-qld.gov.au-sa.gov.au-tas.gov.au-vic.gov.au-wa.gov.au--// aw : https://en.wikipedia.org/wiki/.aw-aw-com.aw--// ax : https://en.wikipedia.org/wiki/.ax-ax--// az : https://en.wikipedia.org/wiki/.az-az-com.az-net.az-int.az-gov.az-org.az-edu.az-info.az-pp.az-mil.az-name.az-pro.az-biz.az--// ba : http://nic.ba/users_data/files/pravilnik_o_registraciji.pdf-ba-com.ba-edu.ba-gov.ba-mil.ba-net.ba-org.ba--// bb : https://en.wikipedia.org/wiki/.bb-bb-biz.bb-co.bb-com.bb-edu.bb-gov.bb-info.bb-net.bb-org.bb-store.bb-tv.bb--// bd : https://en.wikipedia.org/wiki/.bd-*.bd--// be : https://en.wikipedia.org/wiki/.be-// Confirmed by registry <[email protected]> 2008-06-08-be-ac.be--// bf : https://en.wikipedia.org/wiki/.bf-bf-gov.bf--// bg : https://en.wikipedia.org/wiki/.bg-// https://www.register.bg/user/static/rules/en/index.html-bg-a.bg-b.bg-c.bg-d.bg-e.bg-f.bg-g.bg-h.bg-i.bg-j.bg-k.bg-l.bg-m.bg-n.bg-o.bg-p.bg-q.bg-r.bg-s.bg-t.bg-u.bg-v.bg-w.bg-x.bg-y.bg-z.bg-0.bg-1.bg-2.bg-3.bg-4.bg-5.bg-6.bg-7.bg-8.bg-9.bg--// bh : https://en.wikipedia.org/wiki/.bh-bh-com.bh-edu.bh-net.bh-org.bh-gov.bh--// bi : https://en.wikipedia.org/wiki/.bi-// http://whois.nic.bi/-bi-co.bi-com.bi-edu.bi-or.bi-org.bi--// biz : https://en.wikipedia.org/wiki/.biz-biz--// bj : https://en.wikipedia.org/wiki/.bj-bj-asso.bj-barreau.bj-gouv.bj--// bm : http://www.bermudanic.bm/dnr-text.txt-bm-com.bm-edu.bm-gov.bm-net.bm-org.bm--// bn : https://en.wikipedia.org/wiki/.bn-*.bn--// bo : http://www.nic.bo/-bo-com.bo-edu.bo-gov.bo-gob.bo-int.bo-org.bo-net.bo-mil.bo-tv.bo--// br : http://registro.br/dominio/categoria.html-// Submitted by registry <[email protected]>-br-adm.br-adv.br-agr.br-am.br-arq.br-art.br-ato.br-b.br-bio.br-blog.br-bmd.br-cim.br-cng.br-cnt.br-com.br-coop.br-ecn.br-eco.br-edu.br-emp.br-eng.br-esp.br-etc.br-eti.br-far.br-flog.br-fm.br-fnd.br-fot.br-fst.br-g12.br-ggf.br-gov.br-imb.br-ind.br-inf.br-jor.br-jus.br-leg.br-lel.br-mat.br-med.br-mil.br-mp.br-mus.br-net.br-*.nom.br-not.br-ntr.br-odo.br-org.br-ppg.br-pro.br-psc.br-psi.br-qsl.br-radio.br-rec.br-slg.br-srv.br-taxi.br-teo.br-tmp.br-trd.br-tur.br-tv.br-vet.br-vlog.br-wiki.br-zlg.br--// bs : http://www.nic.bs/rules.html-bs-com.bs-net.bs-org.bs-edu.bs-gov.bs--// bt : https://en.wikipedia.org/wiki/.bt-bt-com.bt-edu.bt-gov.bt-net.bt-org.bt--// bv : No registrations at this time.-// Submitted by registry <[email protected]>-bv--// bw : https://en.wikipedia.org/wiki/.bw-// http://www.gobin.info/domainname/bw.doc-// list of other 2nd level tlds ?-bw-co.bw-org.bw--// by : https://en.wikipedia.org/wiki/.by-// http://tld.by/rules_2006_en.html-// list of other 2nd level tlds ?-by-gov.by-mil.by-// Official information does not indicate that com.by is a reserved-// second-level domain, but it's being used as one (see www.google.com.by and-// www.yahoo.com.by, for example), so we list it here for safety's sake.-com.by--// http://hoster.by/-of.by--// bz : https://en.wikipedia.org/wiki/.bz-// http://www.belizenic.bz/-bz-com.bz-net.bz-org.bz-edu.bz-gov.bz--// ca : https://en.wikipedia.org/wiki/.ca-ca-// ca geographical names-ab.ca-bc.ca-mb.ca-nb.ca-nf.ca-nl.ca-ns.ca-nt.ca-nu.ca-on.ca-pe.ca-qc.ca-sk.ca-yk.ca-// gc.ca: https://en.wikipedia.org/wiki/.gc.ca-// see also: http://registry.gc.ca/en/SubdomainFAQ-gc.ca--// cat : https://en.wikipedia.org/wiki/.cat-cat--// cc : https://en.wikipedia.org/wiki/.cc-cc--// cd : https://en.wikipedia.org/wiki/.cd-// see also: https://www.nic.cd/domain/insertDomain_2.jsp?act=1-cd-gov.cd--// cf : https://en.wikipedia.org/wiki/.cf-cf--// cg : https://en.wikipedia.org/wiki/.cg-cg--// ch : https://en.wikipedia.org/wiki/.ch-ch--// ci : https://en.wikipedia.org/wiki/.ci-// http://www.nic.ci/index.php?page=charte-ci-org.ci-or.ci-com.ci-co.ci-edu.ci-ed.ci-ac.ci-net.ci-go.ci-asso.ci-aéroport.ci-int.ci-presse.ci-md.ci-gouv.ci--// ck : https://en.wikipedia.org/wiki/.ck-*.ck-!www.ck--// cl : https://en.wikipedia.org/wiki/.cl-cl-gov.cl-gob.cl-co.cl-mil.cl--// cm : https://en.wikipedia.org/wiki/.cm plus bug 981927-cm-co.cm-com.cm-gov.cm-net.cm--// cn : https://en.wikipedia.org/wiki/.cn-// Submitted by registry <[email protected]>-cn-ac.cn-com.cn-edu.cn-gov.cn-net.cn-org.cn-mil.cn-公司.cn-网络.cn-網絡.cn-// cn geographic names-ah.cn-bj.cn-cq.cn-fj.cn-gd.cn-gs.cn-gz.cn-gx.cn-ha.cn-hb.cn-he.cn-hi.cn-hl.cn-hn.cn-jl.cn-js.cn-jx.cn-ln.cn-nm.cn-nx.cn-qh.cn-sc.cn-sd.cn-sh.cn-sn.cn-sx.cn-tj.cn-xj.cn-xz.cn-yn.cn-zj.cn-hk.cn-mo.cn-tw.cn--// co : https://en.wikipedia.org/wiki/.co-// Submitted by registry <[email protected]>-co-arts.co-com.co-edu.co-firm.co-gov.co-info.co-int.co-mil.co-net.co-nom.co-org.co-rec.co-web.co--// com : https://en.wikipedia.org/wiki/.com-com--// coop : https://en.wikipedia.org/wiki/.coop-coop--// cr : http://www.nic.cr/niccr_publico/showRegistroDominiosScreen.do-cr-ac.cr-co.cr-ed.cr-fi.cr-go.cr-or.cr-sa.cr--// cu : https://en.wikipedia.org/wiki/.cu-cu-com.cu-edu.cu-org.cu-net.cu-gov.cu-inf.cu--// cv : https://en.wikipedia.org/wiki/.cv-cv--// cw : http://www.una.cw/cw_registry/-// Confirmed by registry <[email protected]> 2013-03-26-cw-com.cw-edu.cw-net.cw-org.cw--// cx : https://en.wikipedia.org/wiki/.cx-// list of other 2nd level tlds ?-cx-gov.cx--// cy : http://www.nic.cy/-// Submitted by registry Panayiotou Fotia <[email protected]>-cy-ac.cy-biz.cy-com.cy-ekloges.cy-gov.cy-ltd.cy-name.cy-net.cy-org.cy-parliament.cy-press.cy-pro.cy-tm.cy--// cz : https://en.wikipedia.org/wiki/.cz-cz--// de : https://en.wikipedia.org/wiki/.de-// Confirmed by registry <[email protected]> (with technical-// reservations) 2008-07-01-de--// dj : https://en.wikipedia.org/wiki/.dj-dj--// dk : https://en.wikipedia.org/wiki/.dk-// Confirmed by registry <[email protected]> 2008-06-17-dk--// dm : https://en.wikipedia.org/wiki/.dm-dm-com.dm-net.dm-org.dm-edu.dm-gov.dm--// do : https://en.wikipedia.org/wiki/.do-do-art.do-com.do-edu.do-gob.do-gov.do-mil.do-net.do-org.do-sld.do-web.do--// dz : https://en.wikipedia.org/wiki/.dz-dz-com.dz-org.dz-net.dz-gov.dz-edu.dz-asso.dz-pol.dz-art.dz--// ec : http://www.nic.ec/reg/paso1.asp-// Submitted by registry <[email protected]>-ec-com.ec-info.ec-net.ec-fin.ec-k12.ec-med.ec-pro.ec-org.ec-edu.ec-gov.ec-gob.ec-mil.ec--// edu : https://en.wikipedia.org/wiki/.edu-edu--// ee : http://www.eenet.ee/EENet/dom_reeglid.html#lisa_B-ee-edu.ee-gov.ee-riik.ee-lib.ee-med.ee-com.ee-pri.ee-aip.ee-org.ee-fie.ee--// eg : https://en.wikipedia.org/wiki/.eg-eg-com.eg-edu.eg-eun.eg-gov.eg-mil.eg-name.eg-net.eg-org.eg-sci.eg--// er : https://en.wikipedia.org/wiki/.er-*.er--// es : https://www.nic.es/site_ingles/ingles/dominios/index.html-es-com.es-nom.es-org.es-gob.es-edu.es--// et : https://en.wikipedia.org/wiki/.et-et-com.et-gov.et-org.et-edu.et-biz.et-name.et-info.et-net.et--// eu : https://en.wikipedia.org/wiki/.eu-eu--// fi : https://en.wikipedia.org/wiki/.fi-fi-// aland.fi : https://en.wikipedia.org/wiki/.ax-// This domain is being phased out in favor of .ax. As there are still many-// domains under aland.fi, we still keep it on the list until aland.fi is-// completely removed.-// TODO: Check for updates (expected to be phased out around Q1/2009)-aland.fi--// fj : https://en.wikipedia.org/wiki/.fj-*.fj--// fk : https://en.wikipedia.org/wiki/.fk-*.fk--// fm : https://en.wikipedia.org/wiki/.fm-fm--// fo : https://en.wikipedia.org/wiki/.fo-fo--// fr : http://www.afnic.fr/-// domaines descriptifs : http://www.afnic.fr/obtenir/chartes/nommage-fr/annexe-descriptifs-fr-com.fr-asso.fr-nom.fr-prd.fr-presse.fr-tm.fr-// domaines sectoriels : http://www.afnic.fr/obtenir/chartes/nommage-fr/annexe-sectoriels-aeroport.fr-assedic.fr-avocat.fr-avoues.fr-cci.fr-chambagri.fr-chirurgiens-dentistes.fr-experts-comptables.fr-geometre-expert.fr-gouv.fr-greta.fr-huissier-justice.fr-medecin.fr-notaires.fr-pharmacien.fr-port.fr-veterinaire.fr--// ga : https://en.wikipedia.org/wiki/.ga-ga--// gb : This registry is effectively dormant-// Submitted by registry <[email protected]>-gb--// gd : https://en.wikipedia.org/wiki/.gd-gd--// ge : http://www.nic.net.ge/policy_en.pdf-ge-com.ge-edu.ge-gov.ge-org.ge-mil.ge-net.ge-pvt.ge--// gf : https://en.wikipedia.org/wiki/.gf-gf--// gg : http://www.channelisles.net/register-domains/-// Confirmed by registry <[email protected]> 2013-11-28-gg-co.gg-net.gg-org.gg--// gh : https://en.wikipedia.org/wiki/.gh-// see also: http://www.nic.gh/reg_now.php-// Although domains directly at second level are not possible at the moment,-// they have been possible for some time and may come back.-gh-com.gh-edu.gh-gov.gh-org.gh-mil.gh--// gi : http://www.nic.gi/rules.html-gi-com.gi-ltd.gi-gov.gi-mod.gi-edu.gi-org.gi--// gl : https://en.wikipedia.org/wiki/.gl-// http://nic.gl-gl-co.gl-com.gl-edu.gl-net.gl-org.gl--// gm : http://www.nic.gm/htmlpages%5Cgm-policy.htm-gm--// gn : http://psg.com/dns/gn/gn.txt-// Submitted by registry <[email protected]>-gn-ac.gn-com.gn-edu.gn-gov.gn-org.gn-net.gn--// gov : https://en.wikipedia.org/wiki/.gov-gov--// gp : http://www.nic.gp/index.php?lang=en-gp-com.gp-net.gp-mobi.gp-edu.gp-org.gp-asso.gp--// gq : https://en.wikipedia.org/wiki/.gq-gq--// gr : https://grweb.ics.forth.gr/english/1617-B-2005.html-// Submitted by registry <[email protected]>-gr-com.gr-edu.gr-net.gr-org.gr-gov.gr--// gs : https://en.wikipedia.org/wiki/.gs-gs--// gt : http://www.gt/politicas_de_registro.html-gt-com.gt-edu.gt-gob.gt-ind.gt-mil.gt-net.gt-org.gt--// gu : http://gadao.gov.gu/registration.txt-*.gu--// gw : https://en.wikipedia.org/wiki/.gw-gw--// gy : https://en.wikipedia.org/wiki/.gy-// http://registry.gy/-gy-co.gy-com.gy-edu.gy-gov.gy-net.gy-org.gy--// hk : https://www.hkdnr.hk-// Submitted by registry <[email protected]>-hk-com.hk-edu.hk-gov.hk-idv.hk-net.hk-org.hk-公司.hk-教育.hk-敎育.hk-政府.hk-個人.hk-个人.hk-箇人.hk-網络.hk-网络.hk-组織.hk-網絡.hk-网絡.hk-组织.hk-組織.hk-組织.hk--// hm : https://en.wikipedia.org/wiki/.hm-hm--// hn : http://www.nic.hn/politicas/ps02,,05.html-hn-com.hn-edu.hn-org.hn-net.hn-mil.hn-gob.hn--// hr : http://www.dns.hr/documents/pdf/HRTLD-regulations.pdf-hr-iz.hr-from.hr-name.hr-com.hr--// ht : http://www.nic.ht/info/charte.cfm-ht-com.ht-shop.ht-firm.ht-info.ht-adult.ht-net.ht-pro.ht-org.ht-med.ht-art.ht-coop.ht-pol.ht-asso.ht-edu.ht-rel.ht-gouv.ht-perso.ht--// hu : http://www.domain.hu/domain/English/sld.html-// Confirmed by registry <[email protected]> 2008-06-12-hu-co.hu-info.hu-org.hu-priv.hu-sport.hu-tm.hu-2000.hu-agrar.hu-bolt.hu-casino.hu-city.hu-erotica.hu-erotika.hu-film.hu-forum.hu-games.hu-hotel.hu-ingatlan.hu-jogasz.hu-konyvelo.hu-lakas.hu-media.hu-news.hu-reklam.hu-sex.hu-shop.hu-suli.hu-szex.hu-tozsde.hu-utazas.hu-video.hu--// id : https://register.pandi.or.id/-id-ac.id-biz.id-co.id-desa.id-go.id-mil.id-my.id-net.id-or.id-sch.id-web.id--// ie : https://en.wikipedia.org/wiki/.ie-ie-gov.ie--// il : http://www.isoc.org.il/domains/-il-ac.il-co.il-gov.il-idf.il-k12.il-muni.il-net.il-org.il--// im : https://www.nic.im/-// Submitted by registry <[email protected]>-im-ac.im-co.im-com.im-ltd.co.im-net.im-org.im-plc.co.im-tt.im-tv.im--// in : https://en.wikipedia.org/wiki/.in-// see also: https://registry.in/Policies-// Please note, that nic.in is not an official eTLD, but used by most-// government institutions.-in-co.in-firm.in-net.in-org.in-gen.in-ind.in-nic.in-ac.in-edu.in-res.in-gov.in-mil.in--// info : https://en.wikipedia.org/wiki/.info-info--// int : https://en.wikipedia.org/wiki/.int-// Confirmed by registry <[email protected]> 2008-06-18-int-eu.int--// io : http://www.nic.io/rules.html-// list of other 2nd level tlds ?-io-com.io--// iq : http://www.cmc.iq/english/iq/iqregister1.htm-iq-gov.iq-edu.iq-mil.iq-com.iq-org.iq-net.iq--// ir : http://www.nic.ir/Terms_and_Conditions_ir,_Appendix_1_Domain_Rules-// Also see http://www.nic.ir/Internationalized_Domain_Names-// Two <iran>.ir entries added at request of <[email protected]>, 2010-04-16-ir-ac.ir-co.ir-gov.ir-id.ir-net.ir-org.ir-sch.ir-// xn--mgba3a4f16a.ir (<iran>.ir, Persian YEH)-ایران.ir-// xn--mgba3a4fra.ir (<iran>.ir, Arabic YEH)-ايران.ir--// is : http://www.isnic.is/domain/rules.php-// Confirmed by registry <[email protected]> 2008-12-06-is-net.is-com.is-edu.is-gov.is-org.is-int.is--// it : https://en.wikipedia.org/wiki/.it-it-gov.it-edu.it-// Reserved geo-names:-// http://www.nic.it/documenti/regolamenti-e-linee-guida/regolamento-assegnazione-versione-6.0.pdf-// There is also a list of reserved geo-names corresponding to Italian municipalities-// http://www.nic.it/documenti/appendice-c.pdf, but it is not included here.-// Regions-abr.it-abruzzo.it-aosta-valley.it-aostavalley.it-bas.it-basilicata.it-cal.it-calabria.it-cam.it-campania.it-emilia-romagna.it-emiliaromagna.it-emr.it-friuli-v-giulia.it-friuli-ve-giulia.it-friuli-vegiulia.it-friuli-venezia-giulia.it-friuli-veneziagiulia.it-friuli-vgiulia.it-friuliv-giulia.it-friulive-giulia.it-friulivegiulia.it-friulivenezia-giulia.it-friuliveneziagiulia.it-friulivgiulia.it-fvg.it-laz.it-lazio.it-lig.it-liguria.it-lom.it-lombardia.it-lombardy.it-lucania.it-mar.it-marche.it-mol.it-molise.it-piedmont.it-piemonte.it-pmn.it-pug.it-puglia.it-sar.it-sardegna.it-sardinia.it-sic.it-sicilia.it-sicily.it-taa.it-tos.it-toscana.it-trentino-a-adige.it-trentino-aadige.it-trentino-alto-adige.it-trentino-altoadige.it-trentino-s-tirol.it-trentino-stirol.it-trentino-sud-tirol.it-trentino-sudtirol.it-trentino-sued-tirol.it-trentino-suedtirol.it-trentinoa-adige.it-trentinoaadige.it-trentinoalto-adige.it-trentinoaltoadige.it-trentinos-tirol.it-trentinostirol.it-trentinosud-tirol.it-trentinosudtirol.it-trentinosued-tirol.it-trentinosuedtirol.it-tuscany.it-umb.it-umbria.it-val-d-aosta.it-val-daosta.it-vald-aosta.it-valdaosta.it-valle-aosta.it-valle-d-aosta.it-valle-daosta.it-valleaosta.it-valled-aosta.it-valledaosta.it-vallee-aoste.it-valleeaoste.it-vao.it-vda.it-ven.it-veneto.it-// Provinces-ag.it-agrigento.it-al.it-alessandria.it-alto-adige.it-altoadige.it-an.it-ancona.it-andria-barletta-trani.it-andria-trani-barletta.it-andriabarlettatrani.it-andriatranibarletta.it-ao.it-aosta.it-aoste.it-ap.it-aq.it-aquila.it-ar.it-arezzo.it-ascoli-piceno.it-ascolipiceno.it-asti.it-at.it-av.it-avellino.it-ba.it-balsan.it-bari.it-barletta-trani-andria.it-barlettatraniandria.it-belluno.it-benevento.it-bergamo.it-bg.it-bi.it-biella.it-bl.it-bn.it-bo.it-bologna.it-bolzano.it-bozen.it-br.it-brescia.it-brindisi.it-bs.it-bt.it-bz.it-ca.it-cagliari.it-caltanissetta.it-campidano-medio.it-campidanomedio.it-campobasso.it-carbonia-iglesias.it-carboniaiglesias.it-carrara-massa.it-carraramassa.it-caserta.it-catania.it-catanzaro.it-cb.it-ce.it-cesena-forli.it-cesenaforli.it-ch.it-chieti.it-ci.it-cl.it-cn.it-co.it-como.it-cosenza.it-cr.it-cremona.it-crotone.it-cs.it-ct.it-cuneo.it-cz.it-dell-ogliastra.it-dellogliastra.it-en.it-enna.it-fc.it-fe.it-fermo.it-ferrara.it-fg.it-fi.it-firenze.it-florence.it-fm.it-foggia.it-forli-cesena.it-forlicesena.it-fr.it-frosinone.it-ge.it-genoa.it-genova.it-go.it-gorizia.it-gr.it-grosseto.it-iglesias-carbonia.it-iglesiascarbonia.it-im.it-imperia.it-is.it-isernia.it-kr.it-la-spezia.it-laquila.it-laspezia.it-latina.it-lc.it-le.it-lecce.it-lecco.it-li.it-livorno.it-lo.it-lodi.it-lt.it-lu.it-lucca.it-macerata.it-mantova.it-massa-carrara.it-massacarrara.it-matera.it-mb.it-mc.it-me.it-medio-campidano.it-mediocampidano.it-messina.it-mi.it-milan.it-milano.it-mn.it-mo.it-modena.it-monza-brianza.it-monza-e-della-brianza.it-monza.it-monzabrianza.it-monzaebrianza.it-monzaedellabrianza.it-ms.it-mt.it-na.it-naples.it-napoli.it-no.it-novara.it-nu.it-nuoro.it-og.it-ogliastra.it-olbia-tempio.it-olbiatempio.it-or.it-oristano.it-ot.it-pa.it-padova.it-padua.it-palermo.it-parma.it-pavia.it-pc.it-pd.it-pe.it-perugia.it-pesaro-urbino.it-pesarourbino.it-pescara.it-pg.it-pi.it-piacenza.it-pisa.it-pistoia.it-pn.it-po.it-pordenone.it-potenza.it-pr.it-prato.it-pt.it-pu.it-pv.it-pz.it-ra.it-ragusa.it-ravenna.it-rc.it-re.it-reggio-calabria.it-reggio-emilia.it-reggiocalabria.it-reggioemilia.it-rg.it-ri.it-rieti.it-rimini.it-rm.it-rn.it-ro.it-roma.it-rome.it-rovigo.it-sa.it-salerno.it-sassari.it-savona.it-si.it-siena.it-siracusa.it-so.it-sondrio.it-sp.it-sr.it-ss.it-suedtirol.it-sv.it-ta.it-taranto.it-te.it-tempio-olbia.it-tempioolbia.it-teramo.it-terni.it-tn.it-to.it-torino.it-tp.it-tr.it-trani-andria-barletta.it-trani-barletta-andria.it-traniandriabarletta.it-tranibarlettaandria.it-trapani.it-trentino.it-trento.it-treviso.it-trieste.it-ts.it-turin.it-tv.it-ud.it-udine.it-urbino-pesaro.it-urbinopesaro.it-va.it-varese.it-vb.it-vc.it-ve.it-venezia.it-venice.it-verbania.it-vercelli.it-verona.it-vi.it-vibo-valentia.it-vibovalentia.it-vicenza.it-viterbo.it-vr.it-vs.it-vt.it-vv.it--// je : http://www.channelisles.net/register-domains/-// Confirmed by registry <[email protected]> 2013-11-28-je-co.je-net.je-org.je--// jm : http://www.com.jm/register.html-*.jm--// jo : http://www.dns.jo/Registration_policy.aspx-jo-com.jo-org.jo-net.jo-edu.jo-sch.jo-gov.jo-mil.jo-name.jo--// jobs : https://en.wikipedia.org/wiki/.jobs-jobs--// jp : https://en.wikipedia.org/wiki/.jp-// http://jprs.co.jp/en/jpdomain.html-// Submitted by registry <[email protected]>-jp-// jp organizational type names-ac.jp-ad.jp-co.jp-ed.jp-go.jp-gr.jp-lg.jp-ne.jp-or.jp-// jp prefecture type names-aichi.jp-akita.jp-aomori.jp-chiba.jp-ehime.jp-fukui.jp-fukuoka.jp-fukushima.jp-gifu.jp-gunma.jp-hiroshima.jp-hokkaido.jp-hyogo.jp-ibaraki.jp-ishikawa.jp-iwate.jp-kagawa.jp-kagoshima.jp-kanagawa.jp-kochi.jp-kumamoto.jp-kyoto.jp-mie.jp-miyagi.jp-miyazaki.jp-nagano.jp-nagasaki.jp-nara.jp-niigata.jp-oita.jp-okayama.jp-okinawa.jp-osaka.jp-saga.jp-saitama.jp-shiga.jp-shimane.jp-shizuoka.jp-tochigi.jp-tokushima.jp-tokyo.jp-tottori.jp-toyama.jp-wakayama.jp-yamagata.jp-yamaguchi.jp-yamanashi.jp-栃木.jp-愛知.jp-愛媛.jp-兵庫.jp-熊本.jp-茨城.jp-北海道.jp-千葉.jp-和歌山.jp-長崎.jp-長野.jp-新潟.jp-青森.jp-静岡.jp-東京.jp-石川.jp-埼玉.jp-三重.jp-京都.jp-佐賀.jp-大分.jp-大阪.jp-奈良.jp-宮城.jp-宮崎.jp-富山.jp-山口.jp-山形.jp-山梨.jp-岩手.jp-岐阜.jp-岡山.jp-島根.jp-広島.jp-徳島.jp-沖縄.jp-滋賀.jp-神奈川.jp-福井.jp-福岡.jp-福島.jp-秋田.jp-群馬.jp-香川.jp-高知.jp-鳥取.jp-鹿児島.jp-// jp geographic type names-// http://jprs.jp/doc/rule/saisoku-1.html-*.kawasaki.jp-*.kitakyushu.jp-*.kobe.jp-*.nagoya.jp-*.sapporo.jp-*.sendai.jp-*.yokohama.jp-!city.kawasaki.jp-!city.kitakyushu.jp-!city.kobe.jp-!city.nagoya.jp-!city.sapporo.jp-!city.sendai.jp-!city.yokohama.jp-// 4th level registration-aisai.aichi.jp-ama.aichi.jp-anjo.aichi.jp-asuke.aichi.jp-chiryu.aichi.jp-chita.aichi.jp-fuso.aichi.jp-gamagori.aichi.jp-handa.aichi.jp-hazu.aichi.jp-hekinan.aichi.jp-higashiura.aichi.jp-ichinomiya.aichi.jp-inazawa.aichi.jp-inuyama.aichi.jp-isshiki.aichi.jp-iwakura.aichi.jp-kanie.aichi.jp-kariya.aichi.jp-kasugai.aichi.jp-kira.aichi.jp-kiyosu.aichi.jp-komaki.aichi.jp-konan.aichi.jp-kota.aichi.jp-mihama.aichi.jp-miyoshi.aichi.jp-nishio.aichi.jp-nisshin.aichi.jp-obu.aichi.jp-oguchi.aichi.jp-oharu.aichi.jp-okazaki.aichi.jp-owariasahi.aichi.jp-seto.aichi.jp-shikatsu.aichi.jp-shinshiro.aichi.jp-shitara.aichi.jp-tahara.aichi.jp-takahama.aichi.jp-tobishima.aichi.jp-toei.aichi.jp-togo.aichi.jp-tokai.aichi.jp-tokoname.aichi.jp-toyoake.aichi.jp-toyohashi.aichi.jp-toyokawa.aichi.jp-toyone.aichi.jp-toyota.aichi.jp-tsushima.aichi.jp-yatomi.aichi.jp-akita.akita.jp-daisen.akita.jp-fujisato.akita.jp-gojome.akita.jp-hachirogata.akita.jp-happou.akita.jp-higashinaruse.akita.jp-honjo.akita.jp-honjyo.akita.jp-ikawa.akita.jp-kamikoani.akita.jp-kamioka.akita.jp-katagami.akita.jp-kazuno.akita.jp-kitaakita.akita.jp-kosaka.akita.jp-kyowa.akita.jp-misato.akita.jp-mitane.akita.jp-moriyoshi.akita.jp-nikaho.akita.jp-noshiro.akita.jp-odate.akita.jp-oga.akita.jp-ogata.akita.jp-semboku.akita.jp-yokote.akita.jp-yurihonjo.akita.jp-aomori.aomori.jp-gonohe.aomori.jp-hachinohe.aomori.jp-hashikami.aomori.jp-hiranai.aomori.jp-hirosaki.aomori.jp-itayanagi.aomori.jp-kuroishi.aomori.jp-misawa.aomori.jp-mutsu.aomori.jp-nakadomari.aomori.jp-noheji.aomori.jp-oirase.aomori.jp-owani.aomori.jp-rokunohe.aomori.jp-sannohe.aomori.jp-shichinohe.aomori.jp-shingo.aomori.jp-takko.aomori.jp-towada.aomori.jp-tsugaru.aomori.jp-tsuruta.aomori.jp-abiko.chiba.jp-asahi.chiba.jp-chonan.chiba.jp-chosei.chiba.jp-choshi.chiba.jp-chuo.chiba.jp-funabashi.chiba.jp-futtsu.chiba.jp-hanamigawa.chiba.jp-ichihara.chiba.jp-ichikawa.chiba.jp-ichinomiya.chiba.jp-inzai.chiba.jp-isumi.chiba.jp-kamagaya.chiba.jp-kamogawa.chiba.jp-kashiwa.chiba.jp-katori.chiba.jp-katsuura.chiba.jp-kimitsu.chiba.jp-kisarazu.chiba.jp-kozaki.chiba.jp-kujukuri.chiba.jp-kyonan.chiba.jp-matsudo.chiba.jp-midori.chiba.jp-mihama.chiba.jp-minamiboso.chiba.jp-mobara.chiba.jp-mutsuzawa.chiba.jp-nagara.chiba.jp-nagareyama.chiba.jp-narashino.chiba.jp-narita.chiba.jp-noda.chiba.jp-oamishirasato.chiba.jp-omigawa.chiba.jp-onjuku.chiba.jp-otaki.chiba.jp-sakae.chiba.jp-sakura.chiba.jp-shimofusa.chiba.jp-shirako.chiba.jp-shiroi.chiba.jp-shisui.chiba.jp-sodegaura.chiba.jp-sosa.chiba.jp-tako.chiba.jp-tateyama.chiba.jp-togane.chiba.jp-tohnosho.chiba.jp-tomisato.chiba.jp-urayasu.chiba.jp-yachimata.chiba.jp-yachiyo.chiba.jp-yokaichiba.chiba.jp-yokoshibahikari.chiba.jp-yotsukaido.chiba.jp-ainan.ehime.jp-honai.ehime.jp-ikata.ehime.jp-imabari.ehime.jp-iyo.ehime.jp-kamijima.ehime.jp-kihoku.ehime.jp-kumakogen.ehime.jp-masaki.ehime.jp-matsuno.ehime.jp-matsuyama.ehime.jp-namikata.ehime.jp-niihama.ehime.jp-ozu.ehime.jp-saijo.ehime.jp-seiyo.ehime.jp-shikokuchuo.ehime.jp-tobe.ehime.jp-toon.ehime.jp-uchiko.ehime.jp-uwajima.ehime.jp-yawatahama.ehime.jp-echizen.fukui.jp-eiheiji.fukui.jp-fukui.fukui.jp-ikeda.fukui.jp-katsuyama.fukui.jp-mihama.fukui.jp-minamiechizen.fukui.jp-obama.fukui.jp-ohi.fukui.jp-ono.fukui.jp-sabae.fukui.jp-sakai.fukui.jp-takahama.fukui.jp-tsuruga.fukui.jp-wakasa.fukui.jp-ashiya.fukuoka.jp-buzen.fukuoka.jp-chikugo.fukuoka.jp-chikuho.fukuoka.jp-chikujo.fukuoka.jp-chikushino.fukuoka.jp-chikuzen.fukuoka.jp-chuo.fukuoka.jp-dazaifu.fukuoka.jp-fukuchi.fukuoka.jp-hakata.fukuoka.jp-higashi.fukuoka.jp-hirokawa.fukuoka.jp-hisayama.fukuoka.jp-iizuka.fukuoka.jp-inatsuki.fukuoka.jp-kaho.fukuoka.jp-kasuga.fukuoka.jp-kasuya.fukuoka.jp-kawara.fukuoka.jp-keisen.fukuoka.jp-koga.fukuoka.jp-kurate.fukuoka.jp-kurogi.fukuoka.jp-kurume.fukuoka.jp-minami.fukuoka.jp-miyako.fukuoka.jp-miyama.fukuoka.jp-miyawaka.fukuoka.jp-mizumaki.fukuoka.jp-munakata.fukuoka.jp-nakagawa.fukuoka.jp-nakama.fukuoka.jp-nishi.fukuoka.jp-nogata.fukuoka.jp-ogori.fukuoka.jp-okagaki.fukuoka.jp-okawa.fukuoka.jp-oki.fukuoka.jp-omuta.fukuoka.jp-onga.fukuoka.jp-onojo.fukuoka.jp-oto.fukuoka.jp-saigawa.fukuoka.jp-sasaguri.fukuoka.jp-shingu.fukuoka.jp-shinyoshitomi.fukuoka.jp-shonai.fukuoka.jp-soeda.fukuoka.jp-sue.fukuoka.jp-tachiarai.fukuoka.jp-tagawa.fukuoka.jp-takata.fukuoka.jp-toho.fukuoka.jp-toyotsu.fukuoka.jp-tsuiki.fukuoka.jp-ukiha.fukuoka.jp-umi.fukuoka.jp-usui.fukuoka.jp-yamada.fukuoka.jp-yame.fukuoka.jp-yanagawa.fukuoka.jp-yukuhashi.fukuoka.jp-aizubange.fukushima.jp-aizumisato.fukushima.jp-aizuwakamatsu.fukushima.jp-asakawa.fukushima.jp-bandai.fukushima.jp-date.fukushima.jp-fukushima.fukushima.jp-furudono.fukushima.jp-futaba.fukushima.jp-hanawa.fukushima.jp-higashi.fukushima.jp-hirata.fukushima.jp-hirono.fukushima.jp-iitate.fukushima.jp-inawashiro.fukushima.jp-ishikawa.fukushima.jp-iwaki.fukushima.jp-izumizaki.fukushima.jp-kagamiishi.fukushima.jp-kaneyama.fukushima.jp-kawamata.fukushima.jp-kitakata.fukushima.jp-kitashiobara.fukushima.jp-koori.fukushima.jp-koriyama.fukushima.jp-kunimi.fukushima.jp-miharu.fukushima.jp-mishima.fukushima.jp-namie.fukushima.jp-nango.fukushima.jp-nishiaizu.fukushima.jp-nishigo.fukushima.jp-okuma.fukushima.jp-omotego.fukushima.jp-ono.fukushima.jp-otama.fukushima.jp-samegawa.fukushima.jp-shimogo.fukushima.jp-shirakawa.fukushima.jp-showa.fukushima.jp-soma.fukushima.jp-sukagawa.fukushima.jp-taishin.fukushima.jp-tamakawa.fukushima.jp-tanagura.fukushima.jp-tenei.fukushima.jp-yabuki.fukushima.jp-yamato.fukushima.jp-yamatsuri.fukushima.jp-yanaizu.fukushima.jp-yugawa.fukushima.jp-anpachi.gifu.jp-ena.gifu.jp-gifu.gifu.jp-ginan.gifu.jp-godo.gifu.jp-gujo.gifu.jp-hashima.gifu.jp-hichiso.gifu.jp-hida.gifu.jp-higashishirakawa.gifu.jp-ibigawa.gifu.jp-ikeda.gifu.jp-kakamigahara.gifu.jp-kani.gifu.jp-kasahara.gifu.jp-kasamatsu.gifu.jp-kawaue.gifu.jp-kitagata.gifu.jp-mino.gifu.jp-minokamo.gifu.jp-mitake.gifu.jp-mizunami.gifu.jp-motosu.gifu.jp-nakatsugawa.gifu.jp-ogaki.gifu.jp-sakahogi.gifu.jp-seki.gifu.jp-sekigahara.gifu.jp-shirakawa.gifu.jp-tajimi.gifu.jp-takayama.gifu.jp-tarui.gifu.jp-toki.gifu.jp-tomika.gifu.jp-wanouchi.gifu.jp-yamagata.gifu.jp-yaotsu.gifu.jp-yoro.gifu.jp-annaka.gunma.jp-chiyoda.gunma.jp-fujioka.gunma.jp-higashiagatsuma.gunma.jp-isesaki.gunma.jp-itakura.gunma.jp-kanna.gunma.jp-kanra.gunma.jp-katashina.gunma.jp-kawaba.gunma.jp-kiryu.gunma.jp-kusatsu.gunma.jp-maebashi.gunma.jp-meiwa.gunma.jp-midori.gunma.jp-minakami.gunma.jp-naganohara.gunma.jp-nakanojo.gunma.jp-nanmoku.gunma.jp-numata.gunma.jp-oizumi.gunma.jp-ora.gunma.jp-ota.gunma.jp-shibukawa.gunma.jp-shimonita.gunma.jp-shinto.gunma.jp-showa.gunma.jp-takasaki.gunma.jp-takayama.gunma.jp-tamamura.gunma.jp-tatebayashi.gunma.jp-tomioka.gunma.jp-tsukiyono.gunma.jp-tsumagoi.gunma.jp-ueno.gunma.jp-yoshioka.gunma.jp-asaminami.hiroshima.jp-daiwa.hiroshima.jp-etajima.hiroshima.jp-fuchu.hiroshima.jp-fukuyama.hiroshima.jp-hatsukaichi.hiroshima.jp-higashihiroshima.hiroshima.jp-hongo.hiroshima.jp-jinsekikogen.hiroshima.jp-kaita.hiroshima.jp-kui.hiroshima.jp-kumano.hiroshima.jp-kure.hiroshima.jp-mihara.hiroshima.jp-miyoshi.hiroshima.jp-naka.hiroshima.jp-onomichi.hiroshima.jp-osakikamijima.hiroshima.jp-otake.hiroshima.jp-saka.hiroshima.jp-sera.hiroshima.jp-seranishi.hiroshima.jp-shinichi.hiroshima.jp-shobara.hiroshima.jp-takehara.hiroshima.jp-abashiri.hokkaido.jp-abira.hokkaido.jp-aibetsu.hokkaido.jp-akabira.hokkaido.jp-akkeshi.hokkaido.jp-asahikawa.hokkaido.jp-ashibetsu.hokkaido.jp-ashoro.hokkaido.jp-assabu.hokkaido.jp-atsuma.hokkaido.jp-bibai.hokkaido.jp-biei.hokkaido.jp-bifuka.hokkaido.jp-bihoro.hokkaido.jp-biratori.hokkaido.jp-chippubetsu.hokkaido.jp-chitose.hokkaido.jp-date.hokkaido.jp-ebetsu.hokkaido.jp-embetsu.hokkaido.jp-eniwa.hokkaido.jp-erimo.hokkaido.jp-esan.hokkaido.jp-esashi.hokkaido.jp-fukagawa.hokkaido.jp-fukushima.hokkaido.jp-furano.hokkaido.jp-furubira.hokkaido.jp-haboro.hokkaido.jp-hakodate.hokkaido.jp-hamatonbetsu.hokkaido.jp-hidaka.hokkaido.jp-higashikagura.hokkaido.jp-higashikawa.hokkaido.jp-hiroo.hokkaido.jp-hokuryu.hokkaido.jp-hokuto.hokkaido.jp-honbetsu.hokkaido.jp-horokanai.hokkaido.jp-horonobe.hokkaido.jp-ikeda.hokkaido.jp-imakane.hokkaido.jp-ishikari.hokkaido.jp-iwamizawa.hokkaido.jp-iwanai.hokkaido.jp-kamifurano.hokkaido.jp-kamikawa.hokkaido.jp-kamishihoro.hokkaido.jp-kamisunagawa.hokkaido.jp-kamoenai.hokkaido.jp-kayabe.hokkaido.jp-kembuchi.hokkaido.jp-kikonai.hokkaido.jp-kimobetsu.hokkaido.jp-kitahiroshima.hokkaido.jp-kitami.hokkaido.jp-kiyosato.hokkaido.jp-koshimizu.hokkaido.jp-kunneppu.hokkaido.jp-kuriyama.hokkaido.jp-kuromatsunai.hokkaido.jp-kushiro.hokkaido.jp-kutchan.hokkaido.jp-kyowa.hokkaido.jp-mashike.hokkaido.jp-matsumae.hokkaido.jp-mikasa.hokkaido.jp-minamifurano.hokkaido.jp-mombetsu.hokkaido.jp-moseushi.hokkaido.jp-mukawa.hokkaido.jp-muroran.hokkaido.jp-naie.hokkaido.jp-nakagawa.hokkaido.jp-nakasatsunai.hokkaido.jp-nakatombetsu.hokkaido.jp-nanae.hokkaido.jp-nanporo.hokkaido.jp-nayoro.hokkaido.jp-nemuro.hokkaido.jp-niikappu.hokkaido.jp-niki.hokkaido.jp-nishiokoppe.hokkaido.jp-noboribetsu.hokkaido.jp-numata.hokkaido.jp-obihiro.hokkaido.jp-obira.hokkaido.jp-oketo.hokkaido.jp-okoppe.hokkaido.jp-otaru.hokkaido.jp-otobe.hokkaido.jp-otofuke.hokkaido.jp-otoineppu.hokkaido.jp-oumu.hokkaido.jp-ozora.hokkaido.jp-pippu.hokkaido.jp-rankoshi.hokkaido.jp-rebun.hokkaido.jp-rikubetsu.hokkaido.jp-rishiri.hokkaido.jp-rishirifuji.hokkaido.jp-saroma.hokkaido.jp-sarufutsu.hokkaido.jp-shakotan.hokkaido.jp-shari.hokkaido.jp-shibecha.hokkaido.jp-shibetsu.hokkaido.jp-shikabe.hokkaido.jp-shikaoi.hokkaido.jp-shimamaki.hokkaido.jp-shimizu.hokkaido.jp-shimokawa.hokkaido.jp-shinshinotsu.hokkaido.jp-shintoku.hokkaido.jp-shiranuka.hokkaido.jp-shiraoi.hokkaido.jp-shiriuchi.hokkaido.jp-sobetsu.hokkaido.jp-sunagawa.hokkaido.jp-taiki.hokkaido.jp-takasu.hokkaido.jp-takikawa.hokkaido.jp-takinoue.hokkaido.jp-teshikaga.hokkaido.jp-tobetsu.hokkaido.jp-tohma.hokkaido.jp-tomakomai.hokkaido.jp-tomari.hokkaido.jp-toya.hokkaido.jp-toyako.hokkaido.jp-toyotomi.hokkaido.jp-toyoura.hokkaido.jp-tsubetsu.hokkaido.jp-tsukigata.hokkaido.jp-urakawa.hokkaido.jp-urausu.hokkaido.jp-uryu.hokkaido.jp-utashinai.hokkaido.jp-wakkanai.hokkaido.jp-wassamu.hokkaido.jp-yakumo.hokkaido.jp-yoichi.hokkaido.jp-aioi.hyogo.jp-akashi.hyogo.jp-ako.hyogo.jp-amagasaki.hyogo.jp-aogaki.hyogo.jp-asago.hyogo.jp-ashiya.hyogo.jp-awaji.hyogo.jp-fukusaki.hyogo.jp-goshiki.hyogo.jp-harima.hyogo.jp-himeji.hyogo.jp-ichikawa.hyogo.jp-inagawa.hyogo.jp-itami.hyogo.jp-kakogawa.hyogo.jp-kamigori.hyogo.jp-kamikawa.hyogo.jp-kasai.hyogo.jp-kasuga.hyogo.jp-kawanishi.hyogo.jp-miki.hyogo.jp-minamiawaji.hyogo.jp-nishinomiya.hyogo.jp-nishiwaki.hyogo.jp-ono.hyogo.jp-sanda.hyogo.jp-sannan.hyogo.jp-sasayama.hyogo.jp-sayo.hyogo.jp-shingu.hyogo.jp-shinonsen.hyogo.jp-shiso.hyogo.jp-sumoto.hyogo.jp-taishi.hyogo.jp-taka.hyogo.jp-takarazuka.hyogo.jp-takasago.hyogo.jp-takino.hyogo.jp-tamba.hyogo.jp-tatsuno.hyogo.jp-toyooka.hyogo.jp-yabu.hyogo.jp-yashiro.hyogo.jp-yoka.hyogo.jp-yokawa.hyogo.jp-ami.ibaraki.jp-asahi.ibaraki.jp-bando.ibaraki.jp-chikusei.ibaraki.jp-daigo.ibaraki.jp-fujishiro.ibaraki.jp-hitachi.ibaraki.jp-hitachinaka.ibaraki.jp-hitachiomiya.ibaraki.jp-hitachiota.ibaraki.jp-ibaraki.ibaraki.jp-ina.ibaraki.jp-inashiki.ibaraki.jp-itako.ibaraki.jp-iwama.ibaraki.jp-joso.ibaraki.jp-kamisu.ibaraki.jp-kasama.ibaraki.jp-kashima.ibaraki.jp-kasumigaura.ibaraki.jp-koga.ibaraki.jp-miho.ibaraki.jp-mito.ibaraki.jp-moriya.ibaraki.jp-naka.ibaraki.jp-namegata.ibaraki.jp-oarai.ibaraki.jp-ogawa.ibaraki.jp-omitama.ibaraki.jp-ryugasaki.ibaraki.jp-sakai.ibaraki.jp-sakuragawa.ibaraki.jp-shimodate.ibaraki.jp-shimotsuma.ibaraki.jp-shirosato.ibaraki.jp-sowa.ibaraki.jp-suifu.ibaraki.jp-takahagi.ibaraki.jp-tamatsukuri.ibaraki.jp-tokai.ibaraki.jp-tomobe.ibaraki.jp-tone.ibaraki.jp-toride.ibaraki.jp-tsuchiura.ibaraki.jp-tsukuba.ibaraki.jp-uchihara.ibaraki.jp-ushiku.ibaraki.jp-yachiyo.ibaraki.jp-yamagata.ibaraki.jp-yawara.ibaraki.jp-yuki.ibaraki.jp-anamizu.ishikawa.jp-hakui.ishikawa.jp-hakusan.ishikawa.jp-kaga.ishikawa.jp-kahoku.ishikawa.jp-kanazawa.ishikawa.jp-kawakita.ishikawa.jp-komatsu.ishikawa.jp-nakanoto.ishikawa.jp-nanao.ishikawa.jp-nomi.ishikawa.jp-nonoichi.ishikawa.jp-noto.ishikawa.jp-shika.ishikawa.jp-suzu.ishikawa.jp-tsubata.ishikawa.jp-tsurugi.ishikawa.jp-uchinada.ishikawa.jp-wajima.ishikawa.jp-fudai.iwate.jp-fujisawa.iwate.jp-hanamaki.iwate.jp-hiraizumi.iwate.jp-hirono.iwate.jp-ichinohe.iwate.jp-ichinoseki.iwate.jp-iwaizumi.iwate.jp-iwate.iwate.jp-joboji.iwate.jp-kamaishi.iwate.jp-kanegasaki.iwate.jp-karumai.iwate.jp-kawai.iwate.jp-kitakami.iwate.jp-kuji.iwate.jp-kunohe.iwate.jp-kuzumaki.iwate.jp-miyako.iwate.jp-mizusawa.iwate.jp-morioka.iwate.jp-ninohe.iwate.jp-noda.iwate.jp-ofunato.iwate.jp-oshu.iwate.jp-otsuchi.iwate.jp-rikuzentakata.iwate.jp-shiwa.iwate.jp-shizukuishi.iwate.jp-sumita.iwate.jp-tanohata.iwate.jp-tono.iwate.jp-yahaba.iwate.jp-yamada.iwate.jp-ayagawa.kagawa.jp-higashikagawa.kagawa.jp-kanonji.kagawa.jp-kotohira.kagawa.jp-manno.kagawa.jp-marugame.kagawa.jp-mitoyo.kagawa.jp-naoshima.kagawa.jp-sanuki.kagawa.jp-tadotsu.kagawa.jp-takamatsu.kagawa.jp-tonosho.kagawa.jp-uchinomi.kagawa.jp-utazu.kagawa.jp-zentsuji.kagawa.jp-akune.kagoshima.jp-amami.kagoshima.jp-hioki.kagoshima.jp-isa.kagoshima.jp-isen.kagoshima.jp-izumi.kagoshima.jp-kagoshima.kagoshima.jp-kanoya.kagoshima.jp-kawanabe.kagoshima.jp-kinko.kagoshima.jp-kouyama.kagoshima.jp-makurazaki.kagoshima.jp-matsumoto.kagoshima.jp-minamitane.kagoshima.jp-nakatane.kagoshima.jp-nishinoomote.kagoshima.jp-satsumasendai.kagoshima.jp-soo.kagoshima.jp-tarumizu.kagoshima.jp-yusui.kagoshima.jp-aikawa.kanagawa.jp-atsugi.kanagawa.jp-ayase.kanagawa.jp-chigasaki.kanagawa.jp-ebina.kanagawa.jp-fujisawa.kanagawa.jp-hadano.kanagawa.jp-hakone.kanagawa.jp-hiratsuka.kanagawa.jp-isehara.kanagawa.jp-kaisei.kanagawa.jp-kamakura.kanagawa.jp-kiyokawa.kanagawa.jp-matsuda.kanagawa.jp-minamiashigara.kanagawa.jp-miura.kanagawa.jp-nakai.kanagawa.jp-ninomiya.kanagawa.jp-odawara.kanagawa.jp-oi.kanagawa.jp-oiso.kanagawa.jp-sagamihara.kanagawa.jp-samukawa.kanagawa.jp-tsukui.kanagawa.jp-yamakita.kanagawa.jp-yamato.kanagawa.jp-yokosuka.kanagawa.jp-yugawara.kanagawa.jp-zama.kanagawa.jp-zushi.kanagawa.jp-aki.kochi.jp-geisei.kochi.jp-hidaka.kochi.jp-higashitsuno.kochi.jp-ino.kochi.jp-kagami.kochi.jp-kami.kochi.jp-kitagawa.kochi.jp-kochi.kochi.jp-mihara.kochi.jp-motoyama.kochi.jp-muroto.kochi.jp-nahari.kochi.jp-nakamura.kochi.jp-nankoku.kochi.jp-nishitosa.kochi.jp-niyodogawa.kochi.jp-ochi.kochi.jp-okawa.kochi.jp-otoyo.kochi.jp-otsuki.kochi.jp-sakawa.kochi.jp-sukumo.kochi.jp-susaki.kochi.jp-tosa.kochi.jp-tosashimizu.kochi.jp-toyo.kochi.jp-tsuno.kochi.jp-umaji.kochi.jp-yasuda.kochi.jp-yusuhara.kochi.jp-amakusa.kumamoto.jp-arao.kumamoto.jp-aso.kumamoto.jp-choyo.kumamoto.jp-gyokuto.kumamoto.jp-kamiamakusa.kumamoto.jp-kikuchi.kumamoto.jp-kumamoto.kumamoto.jp-mashiki.kumamoto.jp-mifune.kumamoto.jp-minamata.kumamoto.jp-minamioguni.kumamoto.jp-nagasu.kumamoto.jp-nishihara.kumamoto.jp-oguni.kumamoto.jp-ozu.kumamoto.jp-sumoto.kumamoto.jp-takamori.kumamoto.jp-uki.kumamoto.jp-uto.kumamoto.jp-yamaga.kumamoto.jp-yamato.kumamoto.jp-yatsushiro.kumamoto.jp-ayabe.kyoto.jp-fukuchiyama.kyoto.jp-higashiyama.kyoto.jp-ide.kyoto.jp-ine.kyoto.jp-joyo.kyoto.jp-kameoka.kyoto.jp-kamo.kyoto.jp-kita.kyoto.jp-kizu.kyoto.jp-kumiyama.kyoto.jp-kyotamba.kyoto.jp-kyotanabe.kyoto.jp-kyotango.kyoto.jp-maizuru.kyoto.jp-minami.kyoto.jp-minamiyamashiro.kyoto.jp-miyazu.kyoto.jp-muko.kyoto.jp-nagaokakyo.kyoto.jp-nakagyo.kyoto.jp-nantan.kyoto.jp-oyamazaki.kyoto.jp-sakyo.kyoto.jp-seika.kyoto.jp-tanabe.kyoto.jp-uji.kyoto.jp-ujitawara.kyoto.jp-wazuka.kyoto.jp-yamashina.kyoto.jp-yawata.kyoto.jp-asahi.mie.jp-inabe.mie.jp-ise.mie.jp-kameyama.mie.jp-kawagoe.mie.jp-kiho.mie.jp-kisosaki.mie.jp-kiwa.mie.jp-komono.mie.jp-kumano.mie.jp-kuwana.mie.jp-matsusaka.mie.jp-meiwa.mie.jp-mihama.mie.jp-minamiise.mie.jp-misugi.mie.jp-miyama.mie.jp-nabari.mie.jp-shima.mie.jp-suzuka.mie.jp-tado.mie.jp-taiki.mie.jp-taki.mie.jp-tamaki.mie.jp-toba.mie.jp-tsu.mie.jp-udono.mie.jp-ureshino.mie.jp-watarai.mie.jp-yokkaichi.mie.jp-furukawa.miyagi.jp-higashimatsushima.miyagi.jp-ishinomaki.miyagi.jp-iwanuma.miyagi.jp-kakuda.miyagi.jp-kami.miyagi.jp-kawasaki.miyagi.jp-marumori.miyagi.jp-matsushima.miyagi.jp-minamisanriku.miyagi.jp-misato.miyagi.jp-murata.miyagi.jp-natori.miyagi.jp-ogawara.miyagi.jp-ohira.miyagi.jp-onagawa.miyagi.jp-osaki.miyagi.jp-rifu.miyagi.jp-semine.miyagi.jp-shibata.miyagi.jp-shichikashuku.miyagi.jp-shikama.miyagi.jp-shiogama.miyagi.jp-shiroishi.miyagi.jp-tagajo.miyagi.jp-taiwa.miyagi.jp-tome.miyagi.jp-tomiya.miyagi.jp-wakuya.miyagi.jp-watari.miyagi.jp-yamamoto.miyagi.jp-zao.miyagi.jp-aya.miyazaki.jp-ebino.miyazaki.jp-gokase.miyazaki.jp-hyuga.miyazaki.jp-kadogawa.miyazaki.jp-kawaminami.miyazaki.jp-kijo.miyazaki.jp-kitagawa.miyazaki.jp-kitakata.miyazaki.jp-kitaura.miyazaki.jp-kobayashi.miyazaki.jp-kunitomi.miyazaki.jp-kushima.miyazaki.jp-mimata.miyazaki.jp-miyakonojo.miyazaki.jp-miyazaki.miyazaki.jp-morotsuka.miyazaki.jp-nichinan.miyazaki.jp-nishimera.miyazaki.jp-nobeoka.miyazaki.jp-saito.miyazaki.jp-shiiba.miyazaki.jp-shintomi.miyazaki.jp-takaharu.miyazaki.jp-takanabe.miyazaki.jp-takazaki.miyazaki.jp-tsuno.miyazaki.jp-achi.nagano.jp-agematsu.nagano.jp-anan.nagano.jp-aoki.nagano.jp-asahi.nagano.jp-azumino.nagano.jp-chikuhoku.nagano.jp-chikuma.nagano.jp-chino.nagano.jp-fujimi.nagano.jp-hakuba.nagano.jp-hara.nagano.jp-hiraya.nagano.jp-iida.nagano.jp-iijima.nagano.jp-iiyama.nagano.jp-iizuna.nagano.jp-ikeda.nagano.jp-ikusaka.nagano.jp-ina.nagano.jp-karuizawa.nagano.jp-kawakami.nagano.jp-kiso.nagano.jp-kisofukushima.nagano.jp-kitaaiki.nagano.jp-komagane.nagano.jp-komoro.nagano.jp-matsukawa.nagano.jp-matsumoto.nagano.jp-miasa.nagano.jp-minamiaiki.nagano.jp-minamimaki.nagano.jp-minamiminowa.nagano.jp-minowa.nagano.jp-miyada.nagano.jp-miyota.nagano.jp-mochizuki.nagano.jp-nagano.nagano.jp-nagawa.nagano.jp-nagiso.nagano.jp-nakagawa.nagano.jp-nakano.nagano.jp-nozawaonsen.nagano.jp-obuse.nagano.jp-ogawa.nagano.jp-okaya.nagano.jp-omachi.nagano.jp-omi.nagano.jp-ookuwa.nagano.jp-ooshika.nagano.jp-otaki.nagano.jp-otari.nagano.jp-sakae.nagano.jp-sakaki.nagano.jp-saku.nagano.jp-sakuho.nagano.jp-shimosuwa.nagano.jp-shinanomachi.nagano.jp-shiojiri.nagano.jp-suwa.nagano.jp-suzaka.nagano.jp-takagi.nagano.jp-takamori.nagano.jp-takayama.nagano.jp-tateshina.nagano.jp-tatsuno.nagano.jp-togakushi.nagano.jp-togura.nagano.jp-tomi.nagano.jp-ueda.nagano.jp-wada.nagano.jp-yamagata.nagano.jp-yamanouchi.nagano.jp-yasaka.nagano.jp-yasuoka.nagano.jp-chijiwa.nagasaki.jp-futsu.nagasaki.jp-goto.nagasaki.jp-hasami.nagasaki.jp-hirado.nagasaki.jp-iki.nagasaki.jp-isahaya.nagasaki.jp-kawatana.nagasaki.jp-kuchinotsu.nagasaki.jp-matsuura.nagasaki.jp-nagasaki.nagasaki.jp-obama.nagasaki.jp-omura.nagasaki.jp-oseto.nagasaki.jp-saikai.nagasaki.jp-sasebo.nagasaki.jp-seihi.nagasaki.jp-shimabara.nagasaki.jp-shinkamigoto.nagasaki.jp-togitsu.nagasaki.jp-tsushima.nagasaki.jp-unzen.nagasaki.jp-ando.nara.jp-gose.nara.jp-heguri.nara.jp-higashiyoshino.nara.jp-ikaruga.nara.jp-ikoma.nara.jp-kamikitayama.nara.jp-kanmaki.nara.jp-kashiba.nara.jp-kashihara.nara.jp-katsuragi.nara.jp-kawai.nara.jp-kawakami.nara.jp-kawanishi.nara.jp-koryo.nara.jp-kurotaki.nara.jp-mitsue.nara.jp-miyake.nara.jp-nara.nara.jp-nosegawa.nara.jp-oji.nara.jp-ouda.nara.jp-oyodo.nara.jp-sakurai.nara.jp-sango.nara.jp-shimoichi.nara.jp-shimokitayama.nara.jp-shinjo.nara.jp-soni.nara.jp-takatori.nara.jp-tawaramoto.nara.jp-tenkawa.nara.jp-tenri.nara.jp-uda.nara.jp-yamatokoriyama.nara.jp-yamatotakada.nara.jp-yamazoe.nara.jp-yoshino.nara.jp-aga.niigata.jp-agano.niigata.jp-gosen.niigata.jp-itoigawa.niigata.jp-izumozaki.niigata.jp-joetsu.niigata.jp-kamo.niigata.jp-kariwa.niigata.jp-kashiwazaki.niigata.jp-minamiuonuma.niigata.jp-mitsuke.niigata.jp-muika.niigata.jp-murakami.niigata.jp-myoko.niigata.jp-nagaoka.niigata.jp-niigata.niigata.jp-ojiya.niigata.jp-omi.niigata.jp-sado.niigata.jp-sanjo.niigata.jp-seiro.niigata.jp-seirou.niigata.jp-sekikawa.niigata.jp-shibata.niigata.jp-tagami.niigata.jp-tainai.niigata.jp-tochio.niigata.jp-tokamachi.niigata.jp-tsubame.niigata.jp-tsunan.niigata.jp-uonuma.niigata.jp-yahiko.niigata.jp-yoita.niigata.jp-yuzawa.niigata.jp-beppu.oita.jp-bungoono.oita.jp-bungotakada.oita.jp-hasama.oita.jp-hiji.oita.jp-himeshima.oita.jp-hita.oita.jp-kamitsue.oita.jp-kokonoe.oita.jp-kuju.oita.jp-kunisaki.oita.jp-kusu.oita.jp-oita.oita.jp-saiki.oita.jp-taketa.oita.jp-tsukumi.oita.jp-usa.oita.jp-usuki.oita.jp-yufu.oita.jp-akaiwa.okayama.jp-asakuchi.okayama.jp-bizen.okayama.jp-hayashima.okayama.jp-ibara.okayama.jp-kagamino.okayama.jp-kasaoka.okayama.jp-kibichuo.okayama.jp-kumenan.okayama.jp-kurashiki.okayama.jp-maniwa.okayama.jp-misaki.okayama.jp-nagi.okayama.jp-niimi.okayama.jp-nishiawakura.okayama.jp-okayama.okayama.jp-satosho.okayama.jp-setouchi.okayama.jp-shinjo.okayama.jp-shoo.okayama.jp-soja.okayama.jp-takahashi.okayama.jp-tamano.okayama.jp-tsuyama.okayama.jp-wake.okayama.jp-yakage.okayama.jp-aguni.okinawa.jp-ginowan.okinawa.jp-ginoza.okinawa.jp-gushikami.okinawa.jp-haebaru.okinawa.jp-higashi.okinawa.jp-hirara.okinawa.jp-iheya.okinawa.jp-ishigaki.okinawa.jp-ishikawa.okinawa.jp-itoman.okinawa.jp-izena.okinawa.jp-kadena.okinawa.jp-kin.okinawa.jp-kitadaito.okinawa.jp-kitanakagusuku.okinawa.jp-kumejima.okinawa.jp-kunigami.okinawa.jp-minamidaito.okinawa.jp-motobu.okinawa.jp-nago.okinawa.jp-naha.okinawa.jp-nakagusuku.okinawa.jp-nakijin.okinawa.jp-nanjo.okinawa.jp-nishihara.okinawa.jp-ogimi.okinawa.jp-okinawa.okinawa.jp-onna.okinawa.jp-shimoji.okinawa.jp-taketomi.okinawa.jp-tarama.okinawa.jp-tokashiki.okinawa.jp-tomigusuku.okinawa.jp-tonaki.okinawa.jp-urasoe.okinawa.jp-uruma.okinawa.jp-yaese.okinawa.jp-yomitan.okinawa.jp-yonabaru.okinawa.jp-yonaguni.okinawa.jp-zamami.okinawa.jp-abeno.osaka.jp-chihayaakasaka.osaka.jp-chuo.osaka.jp-daito.osaka.jp-fujiidera.osaka.jp-habikino.osaka.jp-hannan.osaka.jp-higashiosaka.osaka.jp-higashisumiyoshi.osaka.jp-higashiyodogawa.osaka.jp-hirakata.osaka.jp-ibaraki.osaka.jp-ikeda.osaka.jp-izumi.osaka.jp-izumiotsu.osaka.jp-izumisano.osaka.jp-kadoma.osaka.jp-kaizuka.osaka.jp-kanan.osaka.jp-kashiwara.osaka.jp-katano.osaka.jp-kawachinagano.osaka.jp-kishiwada.osaka.jp-kita.osaka.jp-kumatori.osaka.jp-matsubara.osaka.jp-minato.osaka.jp-minoh.osaka.jp-misaki.osaka.jp-moriguchi.osaka.jp-neyagawa.osaka.jp-nishi.osaka.jp-nose.osaka.jp-osakasayama.osaka.jp-sakai.osaka.jp-sayama.osaka.jp-sennan.osaka.jp-settsu.osaka.jp-shijonawate.osaka.jp-shimamoto.osaka.jp-suita.osaka.jp-tadaoka.osaka.jp-taishi.osaka.jp-tajiri.osaka.jp-takaishi.osaka.jp-takatsuki.osaka.jp-tondabayashi.osaka.jp-toyonaka.osaka.jp-toyono.osaka.jp-yao.osaka.jp-ariake.saga.jp-arita.saga.jp-fukudomi.saga.jp-genkai.saga.jp-hamatama.saga.jp-hizen.saga.jp-imari.saga.jp-kamimine.saga.jp-kanzaki.saga.jp-karatsu.saga.jp-kashima.saga.jp-kitagata.saga.jp-kitahata.saga.jp-kiyama.saga.jp-kouhoku.saga.jp-kyuragi.saga.jp-nishiarita.saga.jp-ogi.saga.jp-omachi.saga.jp-ouchi.saga.jp-saga.saga.jp-shiroishi.saga.jp-taku.saga.jp-tara.saga.jp-tosu.saga.jp-yoshinogari.saga.jp-arakawa.saitama.jp-asaka.saitama.jp-chichibu.saitama.jp-fujimi.saitama.jp-fujimino.saitama.jp-fukaya.saitama.jp-hanno.saitama.jp-hanyu.saitama.jp-hasuda.saitama.jp-hatogaya.saitama.jp-hatoyama.saitama.jp-hidaka.saitama.jp-higashichichibu.saitama.jp-higashimatsuyama.saitama.jp-honjo.saitama.jp-ina.saitama.jp-iruma.saitama.jp-iwatsuki.saitama.jp-kamiizumi.saitama.jp-kamikawa.saitama.jp-kamisato.saitama.jp-kasukabe.saitama.jp-kawagoe.saitama.jp-kawaguchi.saitama.jp-kawajima.saitama.jp-kazo.saitama.jp-kitamoto.saitama.jp-koshigaya.saitama.jp-kounosu.saitama.jp-kuki.saitama.jp-kumagaya.saitama.jp-matsubushi.saitama.jp-minano.saitama.jp-misato.saitama.jp-miyashiro.saitama.jp-miyoshi.saitama.jp-moroyama.saitama.jp-nagatoro.saitama.jp-namegawa.saitama.jp-niiza.saitama.jp-ogano.saitama.jp-ogawa.saitama.jp-ogose.saitama.jp-okegawa.saitama.jp-omiya.saitama.jp-otaki.saitama.jp-ranzan.saitama.jp-ryokami.saitama.jp-saitama.saitama.jp-sakado.saitama.jp-satte.saitama.jp-sayama.saitama.jp-shiki.saitama.jp-shiraoka.saitama.jp-soka.saitama.jp-sugito.saitama.jp-toda.saitama.jp-tokigawa.saitama.jp-tokorozawa.saitama.jp-tsurugashima.saitama.jp-urawa.saitama.jp-warabi.saitama.jp-yashio.saitama.jp-yokoze.saitama.jp-yono.saitama.jp-yorii.saitama.jp-yoshida.saitama.jp-yoshikawa.saitama.jp-yoshimi.saitama.jp-aisho.shiga.jp-gamo.shiga.jp-higashiomi.shiga.jp-hikone.shiga.jp-koka.shiga.jp-konan.shiga.jp-kosei.shiga.jp-koto.shiga.jp-kusatsu.shiga.jp-maibara.shiga.jp-moriyama.shiga.jp-nagahama.shiga.jp-nishiazai.shiga.jp-notogawa.shiga.jp-omihachiman.shiga.jp-otsu.shiga.jp-ritto.shiga.jp-ryuoh.shiga.jp-takashima.shiga.jp-takatsuki.shiga.jp-torahime.shiga.jp-toyosato.shiga.jp-yasu.shiga.jp-akagi.shimane.jp-ama.shimane.jp-gotsu.shimane.jp-hamada.shimane.jp-higashiizumo.shimane.jp-hikawa.shimane.jp-hikimi.shimane.jp-izumo.shimane.jp-kakinoki.shimane.jp-masuda.shimane.jp-matsue.shimane.jp-misato.shimane.jp-nishinoshima.shimane.jp-ohda.shimane.jp-okinoshima.shimane.jp-okuizumo.shimane.jp-shimane.shimane.jp-tamayu.shimane.jp-tsuwano.shimane.jp-unnan.shimane.jp-yakumo.shimane.jp-yasugi.shimane.jp-yatsuka.shimane.jp-arai.shizuoka.jp-atami.shizuoka.jp-fuji.shizuoka.jp-fujieda.shizuoka.jp-fujikawa.shizuoka.jp-fujinomiya.shizuoka.jp-fukuroi.shizuoka.jp-gotemba.shizuoka.jp-haibara.shizuoka.jp-hamamatsu.shizuoka.jp-higashiizu.shizuoka.jp-ito.shizuoka.jp-iwata.shizuoka.jp-izu.shizuoka.jp-izunokuni.shizuoka.jp-kakegawa.shizuoka.jp-kannami.shizuoka.jp-kawanehon.shizuoka.jp-kawazu.shizuoka.jp-kikugawa.shizuoka.jp-kosai.shizuoka.jp-makinohara.shizuoka.jp-matsuzaki.shizuoka.jp-minamiizu.shizuoka.jp-mishima.shizuoka.jp-morimachi.shizuoka.jp-nishiizu.shizuoka.jp-numazu.shizuoka.jp-omaezaki.shizuoka.jp-shimada.shizuoka.jp-shimizu.shizuoka.jp-shimoda.shizuoka.jp-shizuoka.shizuoka.jp-susono.shizuoka.jp-yaizu.shizuoka.jp-yoshida.shizuoka.jp-ashikaga.tochigi.jp-bato.tochigi.jp-haga.tochigi.jp-ichikai.tochigi.jp-iwafune.tochigi.jp-kaminokawa.tochigi.jp-kanuma.tochigi.jp-karasuyama.tochigi.jp-kuroiso.tochigi.jp-mashiko.tochigi.jp-mibu.tochigi.jp-moka.tochigi.jp-motegi.tochigi.jp-nasu.tochigi.jp-nasushiobara.tochigi.jp-nikko.tochigi.jp-nishikata.tochigi.jp-nogi.tochigi.jp-ohira.tochigi.jp-ohtawara.tochigi.jp-oyama.tochigi.jp-sakura.tochigi.jp-sano.tochigi.jp-shimotsuke.tochigi.jp-shioya.tochigi.jp-takanezawa.tochigi.jp-tochigi.tochigi.jp-tsuga.tochigi.jp-ujiie.tochigi.jp-utsunomiya.tochigi.jp-yaita.tochigi.jp-aizumi.tokushima.jp-anan.tokushima.jp-ichiba.tokushima.jp-itano.tokushima.jp-kainan.tokushima.jp-komatsushima.tokushima.jp-matsushige.tokushima.jp-mima.tokushima.jp-minami.tokushima.jp-miyoshi.tokushima.jp-mugi.tokushima.jp-nakagawa.tokushima.jp-naruto.tokushima.jp-sanagochi.tokushima.jp-shishikui.tokushima.jp-tokushima.tokushima.jp-wajiki.tokushima.jp-adachi.tokyo.jp-akiruno.tokyo.jp-akishima.tokyo.jp-aogashima.tokyo.jp-arakawa.tokyo.jp-bunkyo.tokyo.jp-chiyoda.tokyo.jp-chofu.tokyo.jp-chuo.tokyo.jp-edogawa.tokyo.jp-fuchu.tokyo.jp-fussa.tokyo.jp-hachijo.tokyo.jp-hachioji.tokyo.jp-hamura.tokyo.jp-higashikurume.tokyo.jp-higashimurayama.tokyo.jp-higashiyamato.tokyo.jp-hino.tokyo.jp-hinode.tokyo.jp-hinohara.tokyo.jp-inagi.tokyo.jp-itabashi.tokyo.jp-katsushika.tokyo.jp-kita.tokyo.jp-kiyose.tokyo.jp-kodaira.tokyo.jp-koganei.tokyo.jp-kokubunji.tokyo.jp-komae.tokyo.jp-koto.tokyo.jp-kouzushima.tokyo.jp-kunitachi.tokyo.jp-machida.tokyo.jp-meguro.tokyo.jp-minato.tokyo.jp-mitaka.tokyo.jp-mizuho.tokyo.jp-musashimurayama.tokyo.jp-musashino.tokyo.jp-nakano.tokyo.jp-nerima.tokyo.jp-ogasawara.tokyo.jp-okutama.tokyo.jp-ome.tokyo.jp-oshima.tokyo.jp-ota.tokyo.jp-setagaya.tokyo.jp-shibuya.tokyo.jp-shinagawa.tokyo.jp-shinjuku.tokyo.jp-suginami.tokyo.jp-sumida.tokyo.jp-tachikawa.tokyo.jp-taito.tokyo.jp-tama.tokyo.jp-toshima.tokyo.jp-chizu.tottori.jp-hino.tottori.jp-kawahara.tottori.jp-koge.tottori.jp-kotoura.tottori.jp-misasa.tottori.jp-nanbu.tottori.jp-nichinan.tottori.jp-sakaiminato.tottori.jp-tottori.tottori.jp-wakasa.tottori.jp-yazu.tottori.jp-yonago.tottori.jp-asahi.toyama.jp-fuchu.toyama.jp-fukumitsu.toyama.jp-funahashi.toyama.jp-himi.toyama.jp-imizu.toyama.jp-inami.toyama.jp-johana.toyama.jp-kamiichi.toyama.jp-kurobe.toyama.jp-nakaniikawa.toyama.jp-namerikawa.toyama.jp-nanto.toyama.jp-nyuzen.toyama.jp-oyabe.toyama.jp-taira.toyama.jp-takaoka.toyama.jp-tateyama.toyama.jp-toga.toyama.jp-tonami.toyama.jp-toyama.toyama.jp-unazuki.toyama.jp-uozu.toyama.jp-yamada.toyama.jp-arida.wakayama.jp-aridagawa.wakayama.jp-gobo.wakayama.jp-hashimoto.wakayama.jp-hidaka.wakayama.jp-hirogawa.wakayama.jp-inami.wakayama.jp-iwade.wakayama.jp-kainan.wakayama.jp-kamitonda.wakayama.jp-katsuragi.wakayama.jp-kimino.wakayama.jp-kinokawa.wakayama.jp-kitayama.wakayama.jp-koya.wakayama.jp-koza.wakayama.jp-kozagawa.wakayama.jp-kudoyama.wakayama.jp-kushimoto.wakayama.jp-mihama.wakayama.jp-misato.wakayama.jp-nachikatsuura.wakayama.jp-shingu.wakayama.jp-shirahama.wakayama.jp-taiji.wakayama.jp-tanabe.wakayama.jp-wakayama.wakayama.jp-yuasa.wakayama.jp-yura.wakayama.jp-asahi.yamagata.jp-funagata.yamagata.jp-higashine.yamagata.jp-iide.yamagata.jp-kahoku.yamagata.jp-kaminoyama.yamagata.jp-kaneyama.yamagata.jp-kawanishi.yamagata.jp-mamurogawa.yamagata.jp-mikawa.yamagata.jp-murayama.yamagata.jp-nagai.yamagata.jp-nakayama.yamagata.jp-nanyo.yamagata.jp-nishikawa.yamagata.jp-obanazawa.yamagata.jp-oe.yamagata.jp-oguni.yamagata.jp-ohkura.yamagata.jp-oishida.yamagata.jp-sagae.yamagata.jp-sakata.yamagata.jp-sakegawa.yamagata.jp-shinjo.yamagata.jp-shirataka.yamagata.jp-shonai.yamagata.jp-takahata.yamagata.jp-tendo.yamagata.jp-tozawa.yamagata.jp-tsuruoka.yamagata.jp-yamagata.yamagata.jp-yamanobe.yamagata.jp-yonezawa.yamagata.jp-yuza.yamagata.jp-abu.yamaguchi.jp-hagi.yamaguchi.jp-hikari.yamaguchi.jp-hofu.yamaguchi.jp-iwakuni.yamaguchi.jp-kudamatsu.yamaguchi.jp-mitou.yamaguchi.jp-nagato.yamaguchi.jp-oshima.yamaguchi.jp-shimonoseki.yamaguchi.jp-shunan.yamaguchi.jp-tabuse.yamaguchi.jp-tokuyama.yamaguchi.jp-toyota.yamaguchi.jp-ube.yamaguchi.jp-yuu.yamaguchi.jp-chuo.yamanashi.jp-doshi.yamanashi.jp-fuefuki.yamanashi.jp-fujikawa.yamanashi.jp-fujikawaguchiko.yamanashi.jp-fujiyoshida.yamanashi.jp-hayakawa.yamanashi.jp-hokuto.yamanashi.jp-ichikawamisato.yamanashi.jp-kai.yamanashi.jp-kofu.yamanashi.jp-koshu.yamanashi.jp-kosuge.yamanashi.jp-minami-alps.yamanashi.jp-minobu.yamanashi.jp-nakamichi.yamanashi.jp-nanbu.yamanashi.jp-narusawa.yamanashi.jp-nirasaki.yamanashi.jp-nishikatsura.yamanashi.jp-oshino.yamanashi.jp-otsuki.yamanashi.jp-showa.yamanashi.jp-tabayama.yamanashi.jp-tsuru.yamanashi.jp-uenohara.yamanashi.jp-yamanakako.yamanashi.jp-yamanashi.yamanashi.jp--// ke : http://www.kenic.or.ke/index.php?option=com_content&task=view&id=117&Itemid=145-*.ke--// kg : http://www.domain.kg/dmn_n.html-kg-org.kg-net.kg-com.kg-edu.kg-gov.kg-mil.kg--// kh : http://www.mptc.gov.kh/dns_registration.htm-*.kh--// ki : http://www.ki/dns/index.html-ki-edu.ki-biz.ki-net.ki-org.ki-gov.ki-info.ki-com.ki--// km : https://en.wikipedia.org/wiki/.km-// http://www.domaine.km/documents/charte.doc-km-org.km-nom.km-gov.km-prd.km-tm.km-edu.km-mil.km-ass.km-com.km-// These are only mentioned as proposed suggestions at domaine.km, but-// https://en.wikipedia.org/wiki/.km says they're available for registration:-coop.km-asso.km-presse.km-medecin.km-notaires.km-pharmaciens.km-veterinaire.km-gouv.km--// kn : https://en.wikipedia.org/wiki/.kn-// http://www.dot.kn/domainRules.html-kn-net.kn-org.kn-edu.kn-gov.kn--// kp : http://www.kcce.kp/en_index.php-kp-com.kp-edu.kp-gov.kp-org.kp-rep.kp-tra.kp--// kr : https://en.wikipedia.org/wiki/.kr-// see also: http://domain.nida.or.kr/eng/registration.jsp-kr-ac.kr-co.kr-es.kr-go.kr-hs.kr-kg.kr-mil.kr-ms.kr-ne.kr-or.kr-pe.kr-re.kr-sc.kr-// kr geographical names-busan.kr-chungbuk.kr-chungnam.kr-daegu.kr-daejeon.kr-gangwon.kr-gwangju.kr-gyeongbuk.kr-gyeonggi.kr-gyeongnam.kr-incheon.kr-jeju.kr-jeonbuk.kr-jeonnam.kr-seoul.kr-ulsan.kr--// kw : https://en.wikipedia.org/wiki/.kw-*.kw--// ky : http://www.icta.ky/da_ky_reg_dom.php-// Confirmed by registry <[email protected]> 2008-06-17-ky-edu.ky-gov.ky-com.ky-org.ky-net.ky--// kz : https://en.wikipedia.org/wiki/.kz-// see also: http://www.nic.kz/rules/index.jsp-kz-org.kz-edu.kz-net.kz-gov.kz-mil.kz-com.kz--// la : https://en.wikipedia.org/wiki/.la-// Submitted by registry <[email protected]>-la-int.la-net.la-info.la-edu.la-gov.la-per.la-com.la-org.la--// lb : https://en.wikipedia.org/wiki/.lb-// Submitted by registry <[email protected]>-lb-com.lb-edu.lb-gov.lb-net.lb-org.lb--// lc : https://en.wikipedia.org/wiki/.lc-// see also: http://www.nic.lc/rules.htm-lc-com.lc-net.lc-co.lc-org.lc-edu.lc-gov.lc--// li : https://en.wikipedia.org/wiki/.li-li--// lk : http://www.nic.lk/seclevpr.html-lk-gov.lk-sch.lk-net.lk-int.lk-com.lk-org.lk-edu.lk-ngo.lk-soc.lk-web.lk-ltd.lk-assn.lk-grp.lk-hotel.lk-ac.lk--// lr : http://psg.com/dns/lr/lr.txt-// Submitted by registry <[email protected]>-lr-com.lr-edu.lr-gov.lr-org.lr-net.lr--// ls : https://en.wikipedia.org/wiki/.ls-ls-co.ls-org.ls--// lt : https://en.wikipedia.org/wiki/.lt-lt-// gov.lt : http://www.gov.lt/index_en.php-gov.lt--// lu : http://www.dns.lu/en/-lu--// lv : http://www.nic.lv/DNS/En/generic.php-lv-com.lv-edu.lv-gov.lv-org.lv-mil.lv-id.lv-net.lv-asn.lv-conf.lv--// ly : http://www.nic.ly/regulations.php-ly-com.ly-net.ly-gov.ly-plc.ly-edu.ly-sch.ly-med.ly-org.ly-id.ly--// ma : https://en.wikipedia.org/wiki/.ma-// http://www.anrt.ma/fr/admin/download/upload/file_fr782.pdf-ma-co.ma-net.ma-gov.ma-org.ma-ac.ma-press.ma--// mc : http://www.nic.mc/-mc-tm.mc-asso.mc--// md : https://en.wikipedia.org/wiki/.md-md--// me : https://en.wikipedia.org/wiki/.me-me-co.me-net.me-org.me-edu.me-ac.me-gov.me-its.me-priv.me--// mg : http://nic.mg/nicmg/?page_id=39-mg-org.mg-nom.mg-gov.mg-prd.mg-tm.mg-edu.mg-mil.mg-com.mg-co.mg--// mh : https://en.wikipedia.org/wiki/.mh-mh--// mil : https://en.wikipedia.org/wiki/.mil-mil--// mk : https://en.wikipedia.org/wiki/.mk-// see also: http://dns.marnet.net.mk/postapka.php-mk-com.mk-org.mk-net.mk-edu.mk-gov.mk-inf.mk-name.mk--// ml : http://www.gobin.info/domainname/ml-template.doc-// see also: https://en.wikipedia.org/wiki/.ml-ml-com.ml-edu.ml-gouv.ml-gov.ml-net.ml-org.ml-presse.ml--// mm : https://en.wikipedia.org/wiki/.mm-*.mm--// mn : https://en.wikipedia.org/wiki/.mn-mn-gov.mn-edu.mn-org.mn--// mo : http://www.monic.net.mo/-mo-com.mo-net.mo-org.mo-edu.mo-gov.mo--// mobi : https://en.wikipedia.org/wiki/.mobi-mobi--// mp : http://www.dot.mp/-// Confirmed by registry <[email protected]> 2008-06-17-mp--// mq : https://en.wikipedia.org/wiki/.mq-mq--// mr : https://en.wikipedia.org/wiki/.mr-mr-gov.mr--// ms : http://www.nic.ms/pdf/MS_Domain_Name_Rules.pdf-ms-com.ms-edu.ms-gov.ms-net.ms-org.ms--// mt : https://www.nic.org.mt/go/policy-// Submitted by registry <[email protected]>-mt-com.mt-edu.mt-net.mt-org.mt--// mu : https://en.wikipedia.org/wiki/.mu-mu-com.mu-net.mu-org.mu-gov.mu-ac.mu-co.mu-or.mu--// museum : http://about.museum/naming/-// http://index.museum/-museum-academy.museum-agriculture.museum-air.museum-airguard.museum-alabama.museum-alaska.museum-amber.museum-ambulance.museum-american.museum-americana.museum-americanantiques.museum-americanart.museum-amsterdam.museum-and.museum-annefrank.museum-anthro.museum-anthropology.museum-antiques.museum-aquarium.museum-arboretum.museum-archaeological.museum-archaeology.museum-architecture.museum-art.museum-artanddesign.museum-artcenter.museum-artdeco.museum-arteducation.museum-artgallery.museum-arts.museum-artsandcrafts.museum-asmatart.museum-assassination.museum-assisi.museum-association.museum-astronomy.museum-atlanta.museum-austin.museum-australia.museum-automotive.museum-aviation.museum-axis.museum-badajoz.museum-baghdad.museum-bahn.museum-bale.museum-baltimore.museum-barcelona.museum-baseball.museum-basel.museum-baths.museum-bauern.museum-beauxarts.museum-beeldengeluid.museum-bellevue.museum-bergbau.museum-berkeley.museum-berlin.museum-bern.museum-bible.museum-bilbao.museum-bill.museum-birdart.museum-birthplace.museum-bonn.museum-boston.museum-botanical.museum-botanicalgarden.museum-botanicgarden.museum-botany.museum-brandywinevalley.museum-brasil.museum-bristol.museum-british.museum-britishcolumbia.museum-broadcast.museum-brunel.museum-brussel.museum-brussels.museum-bruxelles.museum-building.museum-burghof.museum-bus.museum-bushey.museum-cadaques.museum-california.museum-cambridge.museum-can.museum-canada.museum-capebreton.museum-carrier.museum-cartoonart.museum-casadelamoneda.museum-castle.museum-castres.museum-celtic.museum-center.museum-chattanooga.museum-cheltenham.museum-chesapeakebay.museum-chicago.museum-children.museum-childrens.museum-childrensgarden.museum-chiropractic.museum-chocolate.museum-christiansburg.museum-cincinnati.museum-cinema.museum-circus.museum-civilisation.museum-civilization.museum-civilwar.museum-clinton.museum-clock.museum-coal.museum-coastaldefence.museum-cody.museum-coldwar.museum-collection.museum-colonialwilliamsburg.museum-coloradoplateau.museum-columbia.museum-columbus.museum-communication.museum-communications.museum-community.museum-computer.museum-computerhistory.museum-comunicações.museum-contemporary.museum-contemporaryart.museum-convent.museum-copenhagen.museum-corporation.museum-correios-e-telecomunicações.museum-corvette.museum-costume.museum-countryestate.museum-county.museum-crafts.museum-cranbrook.museum-creation.museum-cultural.museum-culturalcenter.museum-culture.museum-cyber.museum-cymru.museum-dali.museum-dallas.museum-database.museum-ddr.museum-decorativearts.museum-delaware.museum-delmenhorst.museum-denmark.museum-depot.museum-design.museum-detroit.museum-dinosaur.museum-discovery.museum-dolls.museum-donostia.museum-durham.museum-eastafrica.museum-eastcoast.museum-education.museum-educational.museum-egyptian.museum-eisenbahn.museum-elburg.museum-elvendrell.museum-embroidery.museum-encyclopedic.museum-england.museum-entomology.museum-environment.museum-environmentalconservation.museum-epilepsy.museum-essex.museum-estate.museum-ethnology.museum-exeter.museum-exhibition.museum-family.museum-farm.museum-farmequipment.museum-farmers.museum-farmstead.museum-field.museum-figueres.museum-filatelia.museum-film.museum-fineart.museum-finearts.museum-finland.museum-flanders.museum-florida.museum-force.museum-fortmissoula.museum-fortworth.museum-foundation.museum-francaise.museum-frankfurt.museum-franziskaner.museum-freemasonry.museum-freiburg.museum-fribourg.museum-frog.museum-fundacio.museum-furniture.museum-gallery.museum-garden.museum-gateway.museum-geelvinck.museum-gemological.museum-geology.museum-georgia.museum-giessen.museum-glas.museum-glass.museum-gorge.museum-grandrapids.museum-graz.museum-guernsey.museum-halloffame.museum-hamburg.museum-handson.museum-harvestcelebration.museum-hawaii.museum-health.museum-heimatunduhren.museum-hellas.museum-helsinki.museum-hembygdsforbund.museum-heritage.museum-histoire.museum-historical.museum-historicalsociety.museum-historichouses.museum-historisch.museum-historisches.museum-history.museum-historyofscience.museum-horology.museum-house.museum-humanities.museum-illustration.museum-imageandsound.museum-indian.museum-indiana.museum-indianapolis.museum-indianmarket.museum-intelligence.museum-interactive.museum-iraq.museum-iron.museum-isleofman.museum-jamison.museum-jefferson.museum-jerusalem.museum-jewelry.museum-jewish.museum-jewishart.museum-jfk.museum-journalism.museum-judaica.museum-judygarland.museum-juedisches.museum-juif.museum-karate.museum-karikatur.museum-kids.museum-koebenhavn.museum-koeln.museum-kunst.museum-kunstsammlung.museum-kunstunddesign.museum-labor.museum-labour.museum-lajolla.museum-lancashire.museum-landes.museum-lans.museum-läns.museum-larsson.museum-lewismiller.museum-lincoln.museum-linz.museum-living.museum-livinghistory.museum-localhistory.museum-london.museum-losangeles.museum-louvre.museum-loyalist.museum-lucerne.museum-luxembourg.museum-luzern.museum-mad.museum-madrid.museum-mallorca.museum-manchester.museum-mansion.museum-mansions.museum-manx.museum-marburg.museum-maritime.museum-maritimo.museum-maryland.museum-marylhurst.museum-media.museum-medical.museum-medizinhistorisches.museum-meeres.museum-memorial.museum-mesaverde.museum-michigan.museum-midatlantic.museum-military.museum-mill.museum-miners.museum-mining.museum-minnesota.museum-missile.museum-missoula.museum-modern.museum-moma.museum-money.museum-monmouth.museum-monticello.museum-montreal.museum-moscow.museum-motorcycle.museum-muenchen.museum-muenster.museum-mulhouse.museum-muncie.museum-museet.museum-museumcenter.museum-museumvereniging.museum-music.museum-national.museum-nationalfirearms.museum-nationalheritage.museum-nativeamerican.museum-naturalhistory.museum-naturalhistorymuseum.museum-naturalsciences.museum-nature.museum-naturhistorisches.museum-natuurwetenschappen.museum-naumburg.museum-naval.museum-nebraska.museum-neues.museum-newhampshire.museum-newjersey.museum-newmexico.museum-newport.museum-newspaper.museum-newyork.museum-niepce.museum-norfolk.museum-north.museum-nrw.museum-nuernberg.museum-nuremberg.museum-nyc.museum-nyny.museum-oceanographic.museum-oceanographique.museum-omaha.museum-online.museum-ontario.museum-openair.museum-oregon.museum-oregontrail.museum-otago.museum-oxford.museum-pacific.museum-paderborn.museum-palace.museum-paleo.museum-palmsprings.museum-panama.museum-paris.museum-pasadena.museum-pharmacy.museum-philadelphia.museum-philadelphiaarea.museum-philately.museum-phoenix.museum-photography.museum-pilots.museum-pittsburgh.museum-planetarium.museum-plantation.museum-plants.museum-plaza.museum-portal.museum-portland.museum-portlligat.museum-posts-and-telecommunications.museum-preservation.museum-presidio.museum-press.museum-project.museum-public.museum-pubol.museum-quebec.museum-railroad.museum-railway.museum-research.museum-resistance.museum-riodejaneiro.museum-rochester.museum-rockart.museum-roma.museum-russia.museum-saintlouis.museum-salem.museum-salvadordali.museum-salzburg.museum-sandiego.museum-sanfrancisco.museum-santabarbara.museum-santacruz.museum-santafe.museum-saskatchewan.museum-satx.museum-savannahga.museum-schlesisches.museum-schoenbrunn.museum-schokoladen.museum-school.museum-schweiz.museum-science.museum-scienceandhistory.museum-scienceandindustry.museum-sciencecenter.museum-sciencecenters.museum-science-fiction.museum-sciencehistory.museum-sciences.museum-sciencesnaturelles.museum-scotland.museum-seaport.museum-settlement.museum-settlers.museum-shell.museum-sherbrooke.museum-sibenik.museum-silk.museum-ski.museum-skole.museum-society.museum-sologne.museum-soundandvision.museum-southcarolina.museum-southwest.museum-space.museum-spy.museum-square.museum-stadt.museum-stalbans.museum-starnberg.museum-state.museum-stateofdelaware.museum-station.museum-steam.museum-steiermark.museum-stjohn.museum-stockholm.museum-stpetersburg.museum-stuttgart.museum-suisse.museum-surgeonshall.museum-surrey.museum-svizzera.museum-sweden.museum-sydney.museum-tank.museum-tcm.museum-technology.museum-telekommunikation.museum-television.museum-texas.museum-textile.museum-theater.museum-time.museum-timekeeping.museum-topology.museum-torino.museum-touch.museum-town.museum-transport.museum-tree.museum-trolley.museum-trust.museum-trustee.museum-uhren.museum-ulm.museum-undersea.museum-university.museum-usa.museum-usantiques.museum-usarts.museum-uscountryestate.museum-usculture.museum-usdecorativearts.museum-usgarden.museum-ushistory.museum-ushuaia.museum-uslivinghistory.museum-utah.museum-uvic.museum-valley.museum-vantaa.museum-versailles.museum-viking.museum-village.museum-virginia.museum-virtual.museum-virtuel.museum-vlaanderen.museum-volkenkunde.museum-wales.museum-wallonie.museum-war.museum-washingtondc.museum-watchandclock.museum-watch-and-clock.museum-western.museum-westfalen.museum-whaling.museum-wildlife.museum-williamsburg.museum-windmill.museum-workshop.museum-york.museum-yorkshire.museum-yosemite.museum-youth.museum-zoological.museum-zoology.museum-ירושלים.museum-иком.museum--// mv : https://en.wikipedia.org/wiki/.mv-// "mv" included because, contra Wikipedia, google.mv exists.-mv-aero.mv-biz.mv-com.mv-coop.mv-edu.mv-gov.mv-info.mv-int.mv-mil.mv-museum.mv-name.mv-net.mv-org.mv-pro.mv--// mw : http://www.registrar.mw/-mw-ac.mw-biz.mw-co.mw-com.mw-coop.mw-edu.mw-gov.mw-int.mw-museum.mw-net.mw-org.mw--// mx : http://www.nic.mx/-// Submitted by registry <[email protected]>-mx-com.mx-org.mx-gob.mx-edu.mx-net.mx--// my : http://www.mynic.net.my/-my-com.my-net.my-org.my-gov.my-edu.my-mil.my-name.my--// mz : http://www.uem.mz/-// Submitted by registry <[email protected]>-mz-ac.mz-adv.mz-co.mz-edu.mz-gov.mz-mil.mz-net.mz-org.mz--// na : http://www.na-nic.com.na/-// http://www.info.na/domain/-na-info.na-pro.na-name.na-school.na-or.na-dr.na-us.na-mx.na-ca.na-in.na-cc.na-tv.na-ws.na-mobi.na-co.na-com.na-org.na--// name : has 2nd-level tlds, but there's no list of them-name--// nc : http://www.cctld.nc/-nc-asso.nc--// ne : https://en.wikipedia.org/wiki/.ne-ne--// net : https://en.wikipedia.org/wiki/.net-net--// nf : https://en.wikipedia.org/wiki/.nf-nf-com.nf-net.nf-per.nf-rec.nf-web.nf-arts.nf-firm.nf-info.nf-other.nf-store.nf--// ng : http://www.nira.org.ng/index.php/join-us/register-ng-domain/189-nira-slds-ng-com.ng-edu.ng-gov.ng-i.ng-mil.ng-mobi.ng-name.ng-net.ng-org.ng-sch.ng--// ni : http://www.nic.ni/-ni-ac.ni-biz.ni-co.ni-com.ni-edu.ni-gob.ni-in.ni-info.ni-int.ni-mil.ni-net.ni-nom.ni-org.ni-web.ni--// nl : https://en.wikipedia.org/wiki/.nl-// https://www.sidn.nl/-// ccTLD for the Netherlands-nl--// BV.nl will be a registry for dutch BV's (besloten vennootschap)-bv.nl--// no : http://www.norid.no/regelverk/index.en.html-// The Norwegian registry has declined to notify us of updates. The web pages-// referenced below are the official source of the data. There is also an-// announce mailing list:-// https://postlister.uninett.no/sympa/info/norid-diskusjon-no-// Norid generic domains : http://www.norid.no/regelverk/vedlegg-c.en.html-fhs.no-vgs.no-fylkesbibl.no-folkebibl.no-museum.no-idrett.no-priv.no-// Non-Norid generic domains : http://www.norid.no/regelverk/vedlegg-d.en.html-mil.no-stat.no-dep.no-kommune.no-herad.no-// no geographical names : http://www.norid.no/regelverk/vedlegg-b.en.html-// counties-aa.no-ah.no-bu.no-fm.no-hl.no-hm.no-jan-mayen.no-mr.no-nl.no-nt.no-of.no-ol.no-oslo.no-rl.no-sf.no-st.no-svalbard.no-tm.no-tr.no-va.no-vf.no-// primary and lower secondary schools per county-gs.aa.no-gs.ah.no-gs.bu.no-gs.fm.no-gs.hl.no-gs.hm.no-gs.jan-mayen.no-gs.mr.no-gs.nl.no-gs.nt.no-gs.of.no-gs.ol.no-gs.oslo.no-gs.rl.no-gs.sf.no-gs.st.no-gs.svalbard.no-gs.tm.no-gs.tr.no-gs.va.no-gs.vf.no-// cities-akrehamn.no-åkrehamn.no-algard.no-ålgård.no-arna.no-brumunddal.no-bryne.no-bronnoysund.no-brønnøysund.no-drobak.no-drøbak.no-egersund.no-fetsund.no-floro.no-florø.no-fredrikstad.no-hokksund.no-honefoss.no-hønefoss.no-jessheim.no-jorpeland.no-jørpeland.no-kirkenes.no-kopervik.no-krokstadelva.no-langevag.no-langevåg.no-leirvik.no-mjondalen.no-mjøndalen.no-mo-i-rana.no-mosjoen.no-mosjøen.no-nesoddtangen.no-orkanger.no-osoyro.no-osøyro.no-raholt.no-råholt.no-sandnessjoen.no-sandnessjøen.no-skedsmokorset.no-slattum.no-spjelkavik.no-stathelle.no-stavern.no-stjordalshalsen.no-stjørdalshalsen.no-tananger.no-tranby.no-vossevangen.no-// communities-afjord.no-åfjord.no-agdenes.no-al.no-ål.no-alesund.no-ålesund.no-alstahaug.no-alta.no-áltá.no-alaheadju.no-álaheadju.no-alvdal.no-amli.no-åmli.no-amot.no-åmot.no-andebu.no-andoy.no-andøy.no-andasuolo.no-ardal.no-årdal.no-aremark.no-arendal.no-ås.no-aseral.no-åseral.no-asker.no-askim.no-askvoll.no-askoy.no-askøy.no-asnes.no-åsnes.no-audnedaln.no-aukra.no-aure.no-aurland.no-aurskog-holand.no-aurskog-høland.no-austevoll.no-austrheim.no-averoy.no-averøy.no-balestrand.no-ballangen.no-balat.no-bálát.no-balsfjord.no-bahccavuotna.no-báhccavuotna.no-bamble.no-bardu.no-beardu.no-beiarn.no-bajddar.no-bájddar.no-baidar.no-báidár.no-berg.no-bergen.no-berlevag.no-berlevåg.no-bearalvahki.no-bearalváhki.no-bindal.no-birkenes.no-bjarkoy.no-bjarkøy.no-bjerkreim.no-bjugn.no-bodo.no-bodø.no-badaddja.no-bådåddjå.no-budejju.no-bokn.no-bremanger.no-bronnoy.no-brønnøy.no-bygland.no-bykle.no-barum.no-bærum.no-bo.telemark.no-bø.telemark.no-bo.nordland.no-bø.nordland.no-bievat.no-bievát.no-bomlo.no-bømlo.no-batsfjord.no-båtsfjord.no-bahcavuotna.no-báhcavuotna.no-dovre.no-drammen.no-drangedal.no-dyroy.no-dyrøy.no-donna.no-dønna.no-eid.no-eidfjord.no-eidsberg.no-eidskog.no-eidsvoll.no-eigersund.no-elverum.no-enebakk.no-engerdal.no-etne.no-etnedal.no-evenes.no-evenassi.no-evenášši.no-evje-og-hornnes.no-farsund.no-fauske.no-fuossko.no-fuoisku.no-fedje.no-fet.no-finnoy.no-finnøy.no-fitjar.no-fjaler.no-fjell.no-flakstad.no-flatanger.no-flekkefjord.no-flesberg.no-flora.no-fla.no-flå.no-folldal.no-forsand.no-fosnes.no-frei.no-frogn.no-froland.no-frosta.no-frana.no-fræna.no-froya.no-frøya.no-fusa.no-fyresdal.no-forde.no-førde.no-gamvik.no-gangaviika.no-gáŋgaviika.no-gaular.no-gausdal.no-gildeskal.no-gildeskål.no-giske.no-gjemnes.no-gjerdrum.no-gjerstad.no-gjesdal.no-gjovik.no-gjøvik.no-gloppen.no-gol.no-gran.no-grane.no-granvin.no-gratangen.no-grimstad.no-grong.no-kraanghke.no-kråanghke.no-grue.no-gulen.no-hadsel.no-halden.no-halsa.no-hamar.no-hamaroy.no-habmer.no-hábmer.no-hapmir.no-hápmir.no-hammerfest.no-hammarfeasta.no-hámmárfeasta.no-haram.no-hareid.no-harstad.no-hasvik.no-aknoluokta.no-ákŋoluokta.no-hattfjelldal.no-aarborte.no-haugesund.no-hemne.no-hemnes.no-hemsedal.no-heroy.more-og-romsdal.no-herøy.møre-og-romsdal.no-heroy.nordland.no-herøy.nordland.no-hitra.no-hjartdal.no-hjelmeland.no-hobol.no-hobøl.no-hof.no-hol.no-hole.no-holmestrand.no-holtalen.no-holtålen.no-hornindal.no-horten.no-hurdal.no-hurum.no-hvaler.no-hyllestad.no-hagebostad.no-hægebostad.no-hoyanger.no-høyanger.no-hoylandet.no-høylandet.no-ha.no-hå.no-ibestad.no-inderoy.no-inderøy.no-iveland.no-jevnaker.no-jondal.no-jolster.no-jølster.no-karasjok.no-karasjohka.no-kárášjohka.no-karlsoy.no-galsa.no-gálsá.no-karmoy.no-karmøy.no-kautokeino.no-guovdageaidnu.no-klepp.no-klabu.no-klæbu.no-kongsberg.no-kongsvinger.no-kragero.no-kragerø.no-kristiansand.no-kristiansund.no-krodsherad.no-krødsherad.no-kvalsund.no-rahkkeravju.no-ráhkkerávju.no-kvam.no-kvinesdal.no-kvinnherad.no-kviteseid.no-kvitsoy.no-kvitsøy.no-kvafjord.no-kvæfjord.no-giehtavuoatna.no-kvanangen.no-kvænangen.no-navuotna.no-návuotna.no-kafjord.no-kåfjord.no-gaivuotna.no-gáivuotna.no-larvik.no-lavangen.no-lavagis.no-loabat.no-loabát.no-lebesby.no-davvesiida.no-leikanger.no-leirfjord.no-leka.no-leksvik.no-lenvik.no-leangaviika.no-leaŋgaviika.no-lesja.no-levanger.no-lier.no-lierne.no-lillehammer.no-lillesand.no-lindesnes.no-lindas.no-lindås.no-lom.no-loppa.no-lahppi.no-láhppi.no-lund.no-lunner.no-luroy.no-lurøy.no-luster.no-lyngdal.no-lyngen.no-ivgu.no-lardal.no-lerdal.no-lærdal.no-lodingen.no-lødingen.no-lorenskog.no-lørenskog.no-loten.no-løten.no-malvik.no-masoy.no-måsøy.no-muosat.no-muosát.no-mandal.no-marker.no-marnardal.no-masfjorden.no-meland.no-meldal.no-melhus.no-meloy.no-meløy.no-meraker.no-meråker.no-moareke.no-moåreke.no-midsund.no-midtre-gauldal.no-modalen.no-modum.no-molde.no-moskenes.no-moss.no-mosvik.no-malselv.no-målselv.no-malatvuopmi.no-málatvuopmi.no-namdalseid.no-aejrie.no-namsos.no-namsskogan.no-naamesjevuemie.no-nååmesjevuemie.no-laakesvuemie.no-nannestad.no-narvik.no-narviika.no-naustdal.no-nedre-eiker.no-nes.akershus.no-nes.buskerud.no-nesna.no-nesodden.no-nesseby.no-unjarga.no-unjárga.no-nesset.no-nissedal.no-nittedal.no-nord-aurdal.no-nord-fron.no-nord-odal.no-norddal.no-nordkapp.no-davvenjarga.no-davvenjárga.no-nordre-land.no-nordreisa.no-raisa.no-ráisa.no-nore-og-uvdal.no-notodden.no-naroy.no-nærøy.no-notteroy.no-nøtterøy.no-odda.no-oksnes.no-øksnes.no-oppdal.no-oppegard.no-oppegård.no-orkdal.no-orland.no-ørland.no-orskog.no-ørskog.no-orsta.no-ørsta.no-os.hedmark.no-os.hordaland.no-osen.no-osteroy.no-osterøy.no-ostre-toten.no-østre-toten.no-overhalla.no-ovre-eiker.no-øvre-eiker.no-oyer.no-øyer.no-oygarden.no-øygarden.no-oystre-slidre.no-øystre-slidre.no-porsanger.no-porsangu.no-porsáŋgu.no-porsgrunn.no-radoy.no-radøy.no-rakkestad.no-rana.no-ruovat.no-randaberg.no-rauma.no-rendalen.no-rennebu.no-rennesoy.no-rennesøy.no-rindal.no-ringebu.no-ringerike.no-ringsaker.no-rissa.no-risor.no-risør.no-roan.no-rollag.no-rygge.no-ralingen.no-rælingen.no-rodoy.no-rødøy.no-romskog.no-rømskog.no-roros.no-røros.no-rost.no-røst.no-royken.no-røyken.no-royrvik.no-røyrvik.no-rade.no-råde.no-salangen.no-siellak.no-saltdal.no-salat.no-sálát.no-sálat.no-samnanger.no-sande.more-og-romsdal.no-sande.møre-og-romsdal.no-sande.vestfold.no-sandefjord.no-sandnes.no-sandoy.no-sandøy.no-sarpsborg.no-sauda.no-sauherad.no-sel.no-selbu.no-selje.no-seljord.no-sigdal.no-siljan.no-sirdal.no-skaun.no-skedsmo.no-ski.no-skien.no-skiptvet.no-skjervoy.no-skjervøy.no-skierva.no-skiervá.no-skjak.no-skjåk.no-skodje.no-skanland.no-skånland.no-skanit.no-skánit.no-smola.no-smøla.no-snillfjord.no-snasa.no-snåsa.no-snoasa.no-snaase.no-snåase.no-sogndal.no-sokndal.no-sola.no-solund.no-songdalen.no-sortland.no-spydeberg.no-stange.no-stavanger.no-steigen.no-steinkjer.no-stjordal.no-stjørdal.no-stokke.no-stor-elvdal.no-stord.no-stordal.no-storfjord.no-omasvuotna.no-strand.no-stranda.no-stryn.no-sula.no-suldal.no-sund.no-sunndal.no-surnadal.no-sveio.no-svelvik.no-sykkylven.no-sogne.no-søgne.no-somna.no-sømna.no-sondre-land.no-søndre-land.no-sor-aurdal.no-sør-aurdal.no-sor-fron.no-sør-fron.no-sor-odal.no-sør-odal.no-sor-varanger.no-sør-varanger.no-matta-varjjat.no-mátta-várjjat.no-sorfold.no-sørfold.no-sorreisa.no-sørreisa.no-sorum.no-sørum.no-tana.no-deatnu.no-time.no-tingvoll.no-tinn.no-tjeldsund.no-dielddanuorri.no-tjome.no-tjøme.no-tokke.no-tolga.no-torsken.no-tranoy.no-tranøy.no-tromso.no-tromsø.no-tromsa.no-romsa.no-trondheim.no-troandin.no-trysil.no-trana.no-træna.no-trogstad.no-trøgstad.no-tvedestrand.no-tydal.no-tynset.no-tysfjord.no-divtasvuodna.no-divttasvuotna.no-tysnes.no-tysvar.no-tysvær.no-tonsberg.no-tønsberg.no-ullensaker.no-ullensvang.no-ulvik.no-utsira.no-vadso.no-vadsø.no-cahcesuolo.no-čáhcesuolo.no-vaksdal.no-valle.no-vang.no-vanylven.no-vardo.no-vardø.no-varggat.no-várggát.no-vefsn.no-vaapste.no-vega.no-vegarshei.no-vegårshei.no-vennesla.no-verdal.no-verran.no-vestby.no-vestnes.no-vestre-slidre.no-vestre-toten.no-vestvagoy.no-vestvågøy.no-vevelstad.no-vik.no-vikna.no-vindafjord.no-volda.no-voss.no-varoy.no-værøy.no-vagan.no-vågan.no-voagat.no-vagsoy.no-vågsøy.no-vaga.no-vågå.no-valer.ostfold.no-våler.østfold.no-valer.hedmark.no-våler.hedmark.no--// np : http://www.mos.com.np/register.html-*.np--// nr : http://cenpac.net.nr/dns/index.html-// Submitted by registry <[email protected]>-nr-biz.nr-info.nr-gov.nr-edu.nr-org.nr-net.nr-com.nr--// nu : https://en.wikipedia.org/wiki/.nu-nu--// nz : https://en.wikipedia.org/wiki/.nz-// Submitted by registry <[email protected]>-nz-ac.nz-co.nz-cri.nz-geek.nz-gen.nz-govt.nz-health.nz-iwi.nz-kiwi.nz-maori.nz-mil.nz-māori.nz-net.nz-org.nz-parliament.nz-school.nz--// om : https://en.wikipedia.org/wiki/.om-om-co.om-com.om-edu.om-gov.om-med.om-museum.om-net.om-org.om-pro.om--// onion : https://tools.ietf.org/html/rfc7686-onion--// org : https://en.wikipedia.org/wiki/.org-org--// pa : http://www.nic.pa/-// Some additional second level "domains" resolve directly as hostnames, such as-// pannet.pa, so we add a rule for "pa".-pa-ac.pa-gob.pa-com.pa-org.pa-sld.pa-edu.pa-net.pa-ing.pa-abo.pa-med.pa-nom.pa--// pe : https://www.nic.pe/InformeFinalComision.pdf-pe-edu.pe-gob.pe-nom.pe-mil.pe-org.pe-com.pe-net.pe--// pf : http://www.gobin.info/domainname/formulaire-pf.pdf-pf-com.pf-org.pf-edu.pf--// pg : https://en.wikipedia.org/wiki/.pg-*.pg--// ph : http://www.domains.ph/FAQ2.asp-// Submitted by registry <[email protected]>-ph-com.ph-net.ph-org.ph-gov.ph-edu.ph-ngo.ph-mil.ph-i.ph--// pk : http://pk5.pknic.net.pk/pk5/msgNamepk.PK-pk-com.pk-net.pk-edu.pk-org.pk-fam.pk-biz.pk-web.pk-gov.pk-gob.pk-gok.pk-gon.pk-gop.pk-gos.pk-info.pk--// pl http://www.dns.pl/english/index.html-// Submitted by registry-pl-com.pl-net.pl-org.pl-// pl functional domains (http://www.dns.pl/english/index.html)-aid.pl-agro.pl-atm.pl-auto.pl-biz.pl-edu.pl-gmina.pl-gsm.pl-info.pl-mail.pl-miasta.pl-media.pl-mil.pl-nieruchomosci.pl-nom.pl-pc.pl-powiat.pl-priv.pl-realestate.pl-rel.pl-sex.pl-shop.pl-sklep.pl-sos.pl-szkola.pl-targi.pl-tm.pl-tourism.pl-travel.pl-turystyka.pl-// Government domains-gov.pl-ap.gov.pl-ic.gov.pl-is.gov.pl-us.gov.pl-kmpsp.gov.pl-kppsp.gov.pl-kwpsp.gov.pl-psp.gov.pl-wskr.gov.pl-kwp.gov.pl-mw.gov.pl-ug.gov.pl-um.gov.pl-umig.gov.pl-ugim.gov.pl-upow.gov.pl-uw.gov.pl-starostwo.gov.pl-pa.gov.pl-po.gov.pl-psse.gov.pl-pup.gov.pl-rzgw.gov.pl-sa.gov.pl-so.gov.pl-sr.gov.pl-wsa.gov.pl-sko.gov.pl-uzs.gov.pl-wiih.gov.pl-winb.gov.pl-pinb.gov.pl-wios.gov.pl-witd.gov.pl-wzmiuw.gov.pl-piw.gov.pl-wiw.gov.pl-griw.gov.pl-wif.gov.pl-oum.gov.pl-sdn.gov.pl-zp.gov.pl-uppo.gov.pl-mup.gov.pl-wuoz.gov.pl-konsulat.gov.pl-oirm.gov.pl-// pl regional domains (http://www.dns.pl/english/index.html)-augustow.pl-babia-gora.pl-bedzin.pl-beskidy.pl-bialowieza.pl-bialystok.pl-bielawa.pl-bieszczady.pl-boleslawiec.pl-bydgoszcz.pl-bytom.pl-cieszyn.pl-czeladz.pl-czest.pl-dlugoleka.pl-elblag.pl-elk.pl-glogow.pl-gniezno.pl-gorlice.pl-grajewo.pl-ilawa.pl-jaworzno.pl-jelenia-gora.pl-jgora.pl-kalisz.pl-kazimierz-dolny.pl-karpacz.pl-kartuzy.pl-kaszuby.pl-katowice.pl-kepno.pl-ketrzyn.pl-klodzko.pl-kobierzyce.pl-kolobrzeg.pl-konin.pl-konskowola.pl-kutno.pl-lapy.pl-lebork.pl-legnica.pl-lezajsk.pl-limanowa.pl-lomza.pl-lowicz.pl-lubin.pl-lukow.pl-malbork.pl-malopolska.pl-mazowsze.pl-mazury.pl-mielec.pl-mielno.pl-mragowo.pl-naklo.pl-nowaruda.pl-nysa.pl-olawa.pl-olecko.pl-olkusz.pl-olsztyn.pl-opoczno.pl-opole.pl-ostroda.pl-ostroleka.pl-ostrowiec.pl-ostrowwlkp.pl-pila.pl-pisz.pl-podhale.pl-podlasie.pl-polkowice.pl-pomorze.pl-pomorskie.pl-prochowice.pl-pruszkow.pl-przeworsk.pl-pulawy.pl-radom.pl-rawa-maz.pl-rybnik.pl-rzeszow.pl-sanok.pl-sejny.pl-slask.pl-slupsk.pl-sosnowiec.pl-stalowa-wola.pl-skoczow.pl-starachowice.pl-stargard.pl-suwalki.pl-swidnica.pl-swiebodzin.pl-swinoujscie.pl-szczecin.pl-szczytno.pl-tarnobrzeg.pl-tgory.pl-turek.pl-tychy.pl-ustka.pl-walbrzych.pl-warmia.pl-warszawa.pl-waw.pl-wegrow.pl-wielun.pl-wlocl.pl-wloclawek.pl-wodzislaw.pl-wolomin.pl-wroclaw.pl-zachpomor.pl-zagan.pl-zarow.pl-zgora.pl-zgorzelec.pl--// pm : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf-pm--// pn : http://www.government.pn/PnRegistry/policies.htm-pn-gov.pn-co.pn-org.pn-edu.pn-net.pn--// post : https://en.wikipedia.org/wiki/.post-post--// pr : http://www.nic.pr/index.asp?f=1-pr-com.pr-net.pr-org.pr-gov.pr-edu.pr-isla.pr-pro.pr-biz.pr-info.pr-name.pr-// these aren't mentioned on nic.pr, but on https://en.wikipedia.org/wiki/.pr-est.pr-prof.pr-ac.pr--// pro : http://registry.pro/get-pro-pro-aaa.pro-aca.pro-acct.pro-avocat.pro-bar.pro-cpa.pro-eng.pro-jur.pro-law.pro-med.pro-recht.pro--// ps : https://en.wikipedia.org/wiki/.ps-// http://www.nic.ps/registration/policy.html#reg-ps-edu.ps-gov.ps-sec.ps-plo.ps-com.ps-org.ps-net.ps--// pt : http://online.dns.pt/dns/start_dns-pt-net.pt-gov.pt-org.pt-edu.pt-int.pt-publ.pt-com.pt-nome.pt--// pw : https://en.wikipedia.org/wiki/.pw-pw-co.pw-ne.pw-or.pw-ed.pw-go.pw-belau.pw--// py : http://www.nic.py/pautas.html#seccion_9-// Submitted by registry-py-com.py-coop.py-edu.py-gov.py-mil.py-net.py-org.py--// qa : http://domains.qa/en/-qa-com.qa-edu.qa-gov.qa-mil.qa-name.qa-net.qa-org.qa-sch.qa--// re : http://www.afnic.re/obtenir/chartes/nommage-re/annexe-descriptifs-re-asso.re-com.re-nom.re--// ro : http://www.rotld.ro/-ro-arts.ro-com.ro-firm.ro-info.ro-nom.ro-nt.ro-org.ro-rec.ro-store.ro-tm.ro-www.ro--// rs : https://www.rnids.rs/en/domains/national-domains-rs-ac.rs-co.rs-edu.rs-gov.rs-in.rs-org.rs--// ru : https://cctld.ru/en/domains/domens_ru/reserved/-ru-ac.ru-edu.ru-gov.ru-int.ru-mil.ru-test.ru--// rw : http://www.nic.rw/cgi-bin/policy.pl-rw-gov.rw-net.rw-edu.rw-ac.rw-com.rw-co.rw-int.rw-mil.rw-gouv.rw--// sa : http://www.nic.net.sa/-sa-com.sa-net.sa-org.sa-gov.sa-med.sa-pub.sa-edu.sa-sch.sa--// sb : http://www.sbnic.net.sb/-// Submitted by registry <[email protected]>-sb-com.sb-edu.sb-gov.sb-net.sb-org.sb--// sc : http://www.nic.sc/-sc-com.sc-gov.sc-net.sc-org.sc-edu.sc--// sd : http://www.isoc.sd/sudanic.isoc.sd/billing_pricing.htm-// Submitted by registry <[email protected]>-sd-com.sd-net.sd-org.sd-edu.sd-med.sd-tv.sd-gov.sd-info.sd--// se : https://en.wikipedia.org/wiki/.se-// Submitted by registry <[email protected]>-se-a.se-ac.se-b.se-bd.se-brand.se-c.se-d.se-e.se-f.se-fh.se-fhsk.se-fhv.se-g.se-h.se-i.se-k.se-komforb.se-kommunalforbund.se-komvux.se-l.se-lanbib.se-m.se-n.se-naturbruksgymn.se-o.se-org.se-p.se-parti.se-pp.se-press.se-r.se-s.se-t.se-tm.se-u.se-w.se-x.se-y.se-z.se--// sg : http://www.nic.net.sg/page/registration-policies-procedures-and-guidelines-sg-com.sg-net.sg-org.sg-gov.sg-edu.sg-per.sg--// sh : http://www.nic.sh/registrar.html-sh-com.sh-net.sh-gov.sh-org.sh-mil.sh--// si : https://en.wikipedia.org/wiki/.si-si--// sj : No registrations at this time.-// Submitted by registry <[email protected]>-sj--// sk : https://en.wikipedia.org/wiki/.sk-// list of 2nd level domains ?-sk--// sl : http://www.nic.sl-// Submitted by registry <[email protected]>-sl-com.sl-net.sl-edu.sl-gov.sl-org.sl--// sm : https://en.wikipedia.org/wiki/.sm-sm--// sn : https://en.wikipedia.org/wiki/.sn-sn-art.sn-com.sn-edu.sn-gouv.sn-org.sn-perso.sn-univ.sn--// so : http://www.soregistry.com/-so-com.so-net.so-org.so--// sr : https://en.wikipedia.org/wiki/.sr-sr--// st : http://www.nic.st/html/policyrules/-st-co.st-com.st-consulado.st-edu.st-embaixada.st-gov.st-mil.st-net.st-org.st-principe.st-saotome.st-store.st--// su : https://en.wikipedia.org/wiki/.su-su-adygeya.su-arkhangelsk.su-balashov.su-bashkiria.su-bryansk.su-dagestan.su-grozny.su-ivanovo.su-kalmykia.su-kaluga.su-karelia.su-khakassia.su-krasnodar.su-kurgan.su-lenug.su-mordovia.su-msk.su-murmansk.su-nalchik.su-nov.su-obninsk.su-penza.su-pokrovsk.su-sochi.su-spb.su-togliatti.su-troitsk.su-tula.su-tuva.su-vladikavkaz.su-vladimir.su-vologda.su--// sv : http://www.svnet.org.sv/niveldos.pdf-sv-com.sv-edu.sv-gob.sv-org.sv-red.sv--// sx : https://en.wikipedia.org/wiki/.sx-// Submitted by registry <[email protected]>-sx-gov.sx--// sy : https://en.wikipedia.org/wiki/.sy-// see also: http://www.gobin.info/domainname/sy.doc-sy-edu.sy-gov.sy-net.sy-mil.sy-com.sy-org.sy--// sz : https://en.wikipedia.org/wiki/.sz-// http://www.sispa.org.sz/-sz-co.sz-ac.sz-org.sz--// tc : https://en.wikipedia.org/wiki/.tc-tc--// td : https://en.wikipedia.org/wiki/.td-td--// tel: https://en.wikipedia.org/wiki/.tel-// http://www.telnic.org/-tel--// tf : https://en.wikipedia.org/wiki/.tf-tf--// tg : https://en.wikipedia.org/wiki/.tg-// http://www.nic.tg/-tg--// th : https://en.wikipedia.org/wiki/.th-// Submitted by registry <[email protected]>-th-ac.th-co.th-go.th-in.th-mi.th-net.th-or.th--// tj : http://www.nic.tj/policy.html-tj-ac.tj-biz.tj-co.tj-com.tj-edu.tj-go.tj-gov.tj-int.tj-mil.tj-name.tj-net.tj-nic.tj-org.tj-test.tj-web.tj--// tk : https://en.wikipedia.org/wiki/.tk-tk--// tl : https://en.wikipedia.org/wiki/.tl-tl-gov.tl--// tm : http://www.nic.tm/local.html-tm-com.tm-co.tm-org.tm-net.tm-nom.tm-gov.tm-mil.tm-edu.tm--// tn : https://en.wikipedia.org/wiki/.tn-// http://whois.ati.tn/-tn-com.tn-ens.tn-fin.tn-gov.tn-ind.tn-intl.tn-nat.tn-net.tn-org.tn-info.tn-perso.tn-tourism.tn-edunet.tn-rnrt.tn-rns.tn-rnu.tn-mincom.tn-agrinet.tn-defense.tn-turen.tn--// to : https://en.wikipedia.org/wiki/.to-// Submitted by registry <[email protected]>-to-com.to-gov.to-net.to-org.to-edu.to-mil.to--// subTLDs: https://www.nic.tr/forms/eng/policies.pdf-// and: https://www.nic.tr/forms/politikalar.pdf-// Submitted by <[email protected]>-tr-com.tr-info.tr-biz.tr-net.tr-org.tr-web.tr-gen.tr-tv.tr-av.tr-dr.tr-bbs.tr-name.tr-tel.tr-gov.tr-bel.tr-pol.tr-mil.tr-k12.tr-edu.tr-kep.tr--// Used by Northern Cyprus-nc.tr--// Used by government agencies of Northern Cyprus-gov.nc.tr--// travel : https://en.wikipedia.org/wiki/.travel-travel--// tt : http://www.nic.tt/-tt-co.tt-com.tt-org.tt-net.tt-biz.tt-info.tt-pro.tt-int.tt-coop.tt-jobs.tt-mobi.tt-travel.tt-museum.tt-aero.tt-name.tt-gov.tt-edu.tt--// tv : https://en.wikipedia.org/wiki/.tv-// Not listing any 2LDs as reserved since none seem to exist in practice,-// Wikipedia notwithstanding.-tv--// tw : https://en.wikipedia.org/wiki/.tw-tw-edu.tw-gov.tw-mil.tw-com.tw-net.tw-org.tw-idv.tw-game.tw-ebiz.tw-club.tw-網路.tw-組織.tw-商業.tw--// tz : http://www.tznic.or.tz/index.php/domains-// Submitted by registry <[email protected]>-tz-ac.tz-co.tz-go.tz-hotel.tz-info.tz-me.tz-mil.tz-mobi.tz-ne.tz-or.tz-sc.tz-tv.tz--// ua : https://hostmaster.ua/policy/?ua-// Submitted by registry <[email protected]>-ua-// ua 2LD-com.ua-edu.ua-gov.ua-in.ua-net.ua-org.ua-// ua geographic names-// https://hostmaster.ua/2ld/-cherkassy.ua-cherkasy.ua-chernigov.ua-chernihiv.ua-chernivtsi.ua-chernovtsy.ua-ck.ua-cn.ua-cr.ua-crimea.ua-cv.ua-dn.ua-dnepropetrovsk.ua-dnipropetrovsk.ua-dominic.ua-donetsk.ua-dp.ua-if.ua-ivano-frankivsk.ua-kh.ua-kharkiv.ua-kharkov.ua-kherson.ua-khmelnitskiy.ua-khmelnytskyi.ua-kiev.ua-kirovograd.ua-km.ua-kr.ua-krym.ua-ks.ua-kv.ua-kyiv.ua-lg.ua-lt.ua-lugansk.ua-lutsk.ua-lv.ua-lviv.ua-mk.ua-mykolaiv.ua-nikolaev.ua-od.ua-odesa.ua-odessa.ua-pl.ua-poltava.ua-rivne.ua-rovno.ua-rv.ua-sb.ua-sebastopol.ua-sevastopol.ua-sm.ua-sumy.ua-te.ua-ternopil.ua-uz.ua-uzhgorod.ua-vinnica.ua-vinnytsia.ua-vn.ua-volyn.ua-yalta.ua-zaporizhzhe.ua-zaporizhzhia.ua-zhitomir.ua-zhytomyr.ua-zp.ua-zt.ua--// ug : https://www.registry.co.ug/-ug-co.ug-or.ug-ac.ug-sc.ug-go.ug-ne.ug-com.ug-org.ug--// uk : https://en.wikipedia.org/wiki/.uk-// Submitted by registry <[email protected]>-uk-ac.uk-co.uk-gov.uk-ltd.uk-me.uk-net.uk-nhs.uk-org.uk-plc.uk-police.uk-*.sch.uk--// us : https://en.wikipedia.org/wiki/.us-us-dni.us-fed.us-isa.us-kids.us-nsn.us-// us geographic names-ak.us-al.us-ar.us-as.us-az.us-ca.us-co.us-ct.us-dc.us-de.us-fl.us-ga.us-gu.us-hi.us-ia.us-id.us-il.us-in.us-ks.us-ky.us-la.us-ma.us-md.us-me.us-mi.us-mn.us-mo.us-ms.us-mt.us-nc.us-nd.us-ne.us-nh.us-nj.us-nm.us-nv.us-ny.us-oh.us-ok.us-or.us-pa.us-pr.us-ri.us-sc.us-sd.us-tn.us-tx.us-ut.us-vi.us-vt.us-va.us-wa.us-wi.us-wv.us-wy.us-// The registrar notes several more specific domains available in each state,-// such as state.*.us, dst.*.us, etc., but resolution of these is somewhat-// haphazard; in some states these domains resolve as addresses, while in others-// only subdomains are available, or even nothing at all. We include the-// most common ones where it's clear that different sites are different-// entities.-k12.ak.us-k12.al.us-k12.ar.us-k12.as.us-k12.az.us-k12.ca.us-k12.co.us-k12.ct.us-k12.dc.us-k12.de.us-k12.fl.us-k12.ga.us-k12.gu.us-// k12.hi.us Bug 614565 - Hawaii has a state-wide DOE login-k12.ia.us-k12.id.us-k12.il.us-k12.in.us-k12.ks.us-k12.ky.us-k12.la.us-k12.ma.us-k12.md.us-k12.me.us-k12.mi.us-k12.mn.us-k12.mo.us-k12.ms.us-k12.mt.us-k12.nc.us-// k12.nd.us Bug 1028347 - Removed at request of Travis Rosso <[email protected]>-k12.ne.us-k12.nh.us-k12.nj.us-k12.nm.us-k12.nv.us-k12.ny.us-k12.oh.us-k12.ok.us-k12.or.us-k12.pa.us-k12.pr.us-k12.ri.us-k12.sc.us-// k12.sd.us Bug 934131 - Removed at request of James Booze <[email protected]>-k12.tn.us-k12.tx.us-k12.ut.us-k12.vi.us-k12.vt.us-k12.va.us-k12.wa.us-k12.wi.us-// k12.wv.us Bug 947705 - Removed at request of Verne Britton <[email protected]>-k12.wy.us-cc.ak.us-cc.al.us-cc.ar.us-cc.as.us-cc.az.us-cc.ca.us-cc.co.us-cc.ct.us-cc.dc.us-cc.de.us-cc.fl.us-cc.ga.us-cc.gu.us-cc.hi.us-cc.ia.us-cc.id.us-cc.il.us-cc.in.us-cc.ks.us-cc.ky.us-cc.la.us-cc.ma.us-cc.md.us-cc.me.us-cc.mi.us-cc.mn.us-cc.mo.us-cc.ms.us-cc.mt.us-cc.nc.us-cc.nd.us-cc.ne.us-cc.nh.us-cc.nj.us-cc.nm.us-cc.nv.us-cc.ny.us-cc.oh.us-cc.ok.us-cc.or.us-cc.pa.us-cc.pr.us-cc.ri.us-cc.sc.us-cc.sd.us-cc.tn.us-cc.tx.us-cc.ut.us-cc.vi.us-cc.vt.us-cc.va.us-cc.wa.us-cc.wi.us-cc.wv.us-cc.wy.us-lib.ak.us-lib.al.us-lib.ar.us-lib.as.us-lib.az.us-lib.ca.us-lib.co.us-lib.ct.us-lib.dc.us-// lib.de.us Issue #243 - Moved to Private section at request of Ed Moore <[email protected]>-lib.fl.us-lib.ga.us-lib.gu.us-lib.hi.us-lib.ia.us-lib.id.us-lib.il.us-lib.in.us-lib.ks.us-lib.ky.us-lib.la.us-lib.ma.us-lib.md.us-lib.me.us-lib.mi.us-lib.mn.us-lib.mo.us-lib.ms.us-lib.mt.us-lib.nc.us-lib.nd.us-lib.ne.us-lib.nh.us-lib.nj.us-lib.nm.us-lib.nv.us-lib.ny.us-lib.oh.us-lib.ok.us-lib.or.us-lib.pa.us-lib.pr.us-lib.ri.us-lib.sc.us-lib.sd.us-lib.tn.us-lib.tx.us-lib.ut.us-lib.vi.us-lib.vt.us-lib.va.us-lib.wa.us-lib.wi.us-// lib.wv.us Bug 941670 - Removed at request of Larry W Arnold <[email protected]>-lib.wy.us-// k12.ma.us contains school districts in Massachusetts. The 4LDs are-// managed independently except for private (PVT), charter (CHTR) and-// parochial (PAROCH) schools. Those are delegated directly to the-// 5LD operators. <k12-ma-hostmaster _ at _ rsuc.gweep.net>-pvt.k12.ma.us-chtr.k12.ma.us-paroch.k12.ma.us--// uy : http://www.nic.org.uy/-uy-com.uy-edu.uy-gub.uy-mil.uy-net.uy-org.uy--// uz : http://www.reg.uz/-uz-co.uz-com.uz-net.uz-org.uz--// va : https://en.wikipedia.org/wiki/.va-va--// vc : https://en.wikipedia.org/wiki/.vc-// Submitted by registry <[email protected]>-vc-com.vc-net.vc-org.vc-gov.vc-mil.vc-edu.vc--// ve : https://registro.nic.ve/-// Submitted by registry-ve-arts.ve-co.ve-com.ve-e12.ve-edu.ve-firm.ve-gob.ve-gov.ve-info.ve-int.ve-mil.ve-net.ve-org.ve-rec.ve-store.ve-tec.ve-web.ve--// vg : https://en.wikipedia.org/wiki/.vg-vg--// vi : http://www.nic.vi/newdomainform.htm-// http://www.nic.vi/Domain_Rules/body_domain_rules.html indicates some other-// TLDs are "reserved", such as edu.vi and gov.vi, but doesn't actually say they-// are available for registration (which they do not seem to be).-vi-co.vi-com.vi-k12.vi-net.vi-org.vi--// vn : https://www.dot.vn/vnnic/vnnic/domainregistration.jsp-vn-com.vn-net.vn-org.vn-edu.vn-gov.vn-int.vn-ac.vn-biz.vn-info.vn-name.vn-pro.vn-health.vn--// vu : https://en.wikipedia.org/wiki/.vu-// http://www.vunic.vu/-vu-com.vu-edu.vu-net.vu-org.vu--// wf : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf-wf--// ws : https://en.wikipedia.org/wiki/.ws-// http://samoanic.ws/index.dhtml-ws-com.ws-net.ws-org.ws-gov.ws-edu.ws--// yt : http://www.afnic.fr/medias/documents/AFNIC-naming-policy2012.pdf-yt--// IDN ccTLDs-// When submitting patches, please maintain a sort by ISO 3166 ccTLD, then-// U-label, and follow this format:-// // A-Label ("<Latin renderings>", <language name>[, variant info]) : <ISO 3166 ccTLD>-// // [sponsoring org]-// U-Label--// xn--mgbaam7a8h ("Emerat", Arabic) : AE-// http://nic.ae/english/arabicdomain/rules.jsp-امارات--// xn--y9a3aq ("hye", Armenian) : AM-// ISOC AM (operated by .am Registry)-հայ--// xn--54b7fta0cc ("Bangla", Bangla) : BD-বাংলা--// xn--90ais ("bel", Belarusian/Russian Cyrillic) : BY-// Operated by .by registry-бел--// xn--fiqs8s ("Zhongguo/China", Chinese, Simplified) : CN-// CNNIC-// http://cnnic.cn/html/Dir/2005/10/11/3218.htm-中国--// xn--fiqz9s ("Zhongguo/China", Chinese, Traditional) : CN-// CNNIC-// http://cnnic.cn/html/Dir/2005/10/11/3218.htm-中國--// xn--lgbbat1ad8j ("Algeria/Al Jazair", Arabic) : DZ-الجزائر--// xn--wgbh1c ("Egypt/Masr", Arabic) : EG-// http://www.dotmasr.eg/-مصر--// xn--e1a4c ("eu", Cyrillic) : EU-ею--// xn--node ("ge", Georgian Mkhedruli) : GE-გე--// xn--qxam ("el", Greek) : GR-// Hellenic Ministry of Infrastructure, Transport, and Networks-ελ--// xn--j6w193g ("Hong Kong", Chinese) : HK-// https://www2.hkirc.hk/register/rules.jsp-香港--// xn--h2brj9c ("Bharat", Devanagari) : IN-// India-भारत--// xn--mgbbh1a71e ("Bharat", Arabic) : IN-// India-بھارت--// xn--fpcrj9c3d ("Bharat", Telugu) : IN-// India-భారత్--// xn--gecrj9c ("Bharat", Gujarati) : IN-// India-ભારત--// xn--s9brj9c ("Bharat", Gurmukhi) : IN-// India-ਭਾਰਤ--// xn--45brj9c ("Bharat", Bengali) : IN-// India-ভারত--// xn--xkc2dl3a5ee0h ("India", Tamil) : IN-// India-இந்தியா--// xn--mgba3a4f16a ("Iran", Persian) : IR-ایران--// xn--mgba3a4fra ("Iran", Arabic) : IR-ايران--// xn--mgbtx2b ("Iraq", Arabic) : IQ-// Communications and Media Commission-عراق--// xn--mgbayh7gpa ("al-Ordon", Arabic) : JO-// National Information Technology Center (NITC)-// Royal Scientific Society, Al-Jubeiha-الاردن--// xn--3e0b707e ("Republic of Korea", Hangul) : KR-한국--// xn--80ao21a ("Kaz", Kazakh) : KZ-қаз--// xn--fzc2c9e2c ("Lanka", Sinhalese-Sinhala) : LK-// http://nic.lk-ලංකා--// xn--xkc2al3hye2a ("Ilangai", Tamil) : LK-// http://nic.lk-இலங்கை--// xn--mgbc0a9azcg ("Morocco/al-Maghrib", Arabic) : MA-المغرب--// xn--d1alf ("mkd", Macedonian) : MK-// MARnet-мкд--// xn--l1acc ("mon", Mongolian) : MN-мон--// xn--mix891f ("Macao", Chinese, Traditional) : MO-// MONIC / HNET Asia (Registry Operator for .mo)-澳門--// xn--mix082f ("Macao", Chinese, Simplified) : MO-澳门--// xn--mgbx4cd0ab ("Malaysia", Malay) : MY-مليسيا--// xn--mgb9awbf ("Oman", Arabic) : OM-عمان--// xn--mgbai9azgqp6j ("Pakistan", Urdu/Arabic) : PK-پاکستان--// xn--mgbai9a5eva00b ("Pakistan", Urdu/Arabic, variant) : PK-پاكستان--// xn--ygbi2ammx ("Falasteen", Arabic) : PS-// The Palestinian National Internet Naming Authority (PNINA)-// http://www.pnina.ps-فلسطين--// xn--90a3ac ("srb", Cyrillic) : RS-// https://www.rnids.rs/en/domains/national-domains-срб-пр.срб-орг.срб-обр.срб-од.срб-упр.срб-ак.срб--// xn--p1ai ("rf", Russian-Cyrillic) : RU-// http://www.cctld.ru/en/docs/rulesrf.php-рф--// xn--wgbl6a ("Qatar", Arabic) : QA-// http://www.ict.gov.qa/-قطر--// xn--mgberp4a5d4ar ("AlSaudiah", Arabic) : SA-// http://www.nic.net.sa/-السعودية--// xn--mgberp4a5d4a87g ("AlSaudiah", Arabic, variant) : SA-السعودیة--// xn--mgbqly7c0a67fbc ("AlSaudiah", Arabic, variant) : SA-السعودیۃ--// xn--mgbqly7cvafr ("AlSaudiah", Arabic, variant) : SA-السعوديه--// xn--mgbpl2fh ("sudan", Arabic) : SD-// Operated by .sd registry-سودان--// xn--yfro4i67o Singapore ("Singapore", Chinese) : SG-新加坡--// xn--clchc0ea0b2g2a9gcd ("Singapore", Tamil) : SG-சிங்கப்பூர்--// xn--ogbpf8fl ("Syria", Arabic) : SY-سورية--// xn--mgbtf8fl ("Syria", Arabic, variant) : SY-سوريا--// xn--o3cw4h ("Thai", Thai) : TH-// http://www.thnic.co.th-ไทย--// xn--pgbs0dh ("Tunisia", Arabic) : TN-// http://nic.tn-تونس--// xn--kpry57d ("Taiwan", Chinese, Traditional) : TW-// http://www.twnic.net/english/dn/dn_07a.htm-台灣--// xn--kprw13d ("Taiwan", Chinese, Simplified) : TW-// http://www.twnic.net/english/dn/dn_07a.htm-台湾--// xn--nnx388a ("Taiwan", Chinese, variant) : TW-臺灣--// xn--j1amh ("ukr", Cyrillic) : UA-укр--// xn--mgb2ddes ("AlYemen", Arabic) : YE-اليمن--// xxx : http://icmregistry.com-xxx--// ye : http://www.y.net.ye/services/domain_name.htm-*.ye--// za : http://www.zadna.org.za/content/page/domain-information-ac.za-agric.za-alt.za-co.za-edu.za-gov.za-grondar.za-law.za-mil.za-net.za-ngo.za-nis.za-nom.za-org.za-school.za-tm.za-web.za--// zm : https://zicta.zm/-// Submitted by registry <[email protected]>-zm-ac.zm-biz.zm-co.zm-com.zm-edu.zm-gov.zm-info.zm-mil.zm-net.zm-org.zm-sch.zm--// zw : https://en.wikipedia.org/wiki/.zw-*.zw---// List of new gTLDs imported from https://newgtlds.icann.org/newgtlds.csv on 2016-11-29T01:06:51Z--// aaa : 2015-02-26 American Automobile Association, Inc.-aaa--// aarp : 2015-05-21 AARP-aarp--// abarth : 2015-07-30 Fiat Chrysler Automobiles N.V.-abarth--// abb : 2014-10-24 ABB Ltd-abb--// abbott : 2014-07-24 Abbott Laboratories, Inc.-abbott--// abbvie : 2015-07-30 AbbVie Inc.-abbvie--// abc : 2015-07-30 Disney Enterprises, Inc.-abc--// able : 2015-06-25 Able Inc.-able--// abogado : 2014-04-24 Top Level Domain Holdings Limited-abogado--// abudhabi : 2015-07-30 Abu Dhabi Systems and Information Centre-abudhabi--// academy : 2013-11-07 Half Oaks, LLC-academy--// accenture : 2014-08-15 Accenture plc-accenture--// accountant : 2014-11-20 dot Accountant Limited-accountant--// accountants : 2014-03-20 Knob Town, LLC-accountants--// aco : 2015-01-08 ACO Severin Ahlmann GmbH & Co. KG-aco--// active : 2014-05-01 The Active Network, Inc-active--// actor : 2013-12-12 United TLD Holdco Ltd.-actor--// adac : 2015-07-16 Allgemeiner Deutscher Automobil-Club e.V. (ADAC)-adac--// ads : 2014-12-04 Charleston Road Registry Inc.-ads--// adult : 2014-10-16 ICM Registry AD LLC-adult--// aeg : 2015-03-19 Aktiebolaget Electrolux-aeg--// aetna : 2015-05-21 Aetna Life Insurance Company-aetna--// afamilycompany : 2015-07-23 Johnson Shareholdings, Inc.-afamilycompany--// afl : 2014-10-02 Australian Football League-afl--// africa : 2014-03-24 ZA Central Registry NPC trading as Registry.Africa-africa--// agakhan : 2015-04-23 Fondation Aga Khan (Aga Khan Foundation)-agakhan--// agency : 2013-11-14 Steel Falls, LLC-agency--// aig : 2014-12-18 American International Group, Inc.-aig--// aigo : 2015-08-06 aigo Digital Technology Co,Ltd.-aigo--// airbus : 2015-07-30 Airbus S.A.S.-airbus--// airforce : 2014-03-06 United TLD Holdco Ltd.-airforce--// airtel : 2014-10-24 Bharti Airtel Limited-airtel--// akdn : 2015-04-23 Fondation Aga Khan (Aga Khan Foundation)-akdn--// alfaromeo : 2015-07-31 Fiat Chrysler Automobiles N.V.-alfaromeo--// alibaba : 2015-01-15 Alibaba Group Holding Limited-alibaba--// alipay : 2015-01-15 Alibaba Group Holding Limited-alipay--// allfinanz : 2014-07-03 Allfinanz Deutsche Vermögensberatung Aktiengesellschaft-allfinanz--// allstate : 2015-07-31 Allstate Fire and Casualty Insurance Company-allstate--// ally : 2015-06-18 Ally Financial Inc.-ally--// alsace : 2014-07-02 REGION D ALSACE-alsace--// alstom : 2015-07-30 ALSTOM-alstom--// americanexpress : 2015-07-31 American Express Travel Related Services Company, Inc.-americanexpress--// americanfamily : 2015-07-23 AmFam, Inc.-americanfamily--// amex : 2015-07-31 American Express Travel Related Services Company, Inc.-amex--// amfam : 2015-07-23 AmFam, Inc.-amfam--// amica : 2015-05-28 Amica Mutual Insurance Company-amica--// amsterdam : 2014-07-24 Gemeente Amsterdam-amsterdam--// analytics : 2014-12-18 Campus IP LLC-analytics--// android : 2014-08-07 Charleston Road Registry Inc.-android--// anquan : 2015-01-08 QIHOO 360 TECHNOLOGY CO. LTD.-anquan--// anz : 2015-07-31 Australia and New Zealand Banking Group Limited-anz--// aol : 2015-09-17 AOL Inc.-aol--// apartments : 2014-12-11 June Maple, LLC-apartments--// app : 2015-05-14 Charleston Road Registry Inc.-app--// apple : 2015-05-14 Apple Inc.-apple--// aquarelle : 2014-07-24 Aquarelle.com-aquarelle--// arab : 2015-11-12 League of Arab States-arab--// aramco : 2014-11-20 Aramco Services Company-aramco--// archi : 2014-02-06 STARTING DOT LIMITED-archi--// army : 2014-03-06 United TLD Holdco Ltd.-army--// art : 2016-03-24 UK Creative Ideas Limited-art--// arte : 2014-12-11 Association Relative à la Télévision Européenne G.E.I.E.-arte--// asda : 2015-07-31 Wal-Mart Stores, Inc.-asda--// associates : 2014-03-06 Baxter Hill, LLC-associates--// athleta : 2015-07-30 The Gap, Inc.-athleta--// attorney : 2014-03-20-attorney--// auction : 2014-03-20-auction--// audi : 2015-05-21 AUDI Aktiengesellschaft-audi--// audible : 2015-06-25 Amazon EU S.à r.l.-audible--// audio : 2014-03-20 Uniregistry, Corp.-audio--// auspost : 2015-08-13 Australian Postal Corporation-auspost--// author : 2014-12-18 Amazon EU S.à r.l.-author--// auto : 2014-11-13-auto--// autos : 2014-01-09 DERAutos, LLC-autos--// avianca : 2015-01-08 Aerovias del Continente Americano S.A. Avianca-avianca--// aws : 2015-06-25 Amazon EU S.à r.l.-aws--// axa : 2013-12-19 AXA SA-axa--// azure : 2014-12-18 Microsoft Corporation-azure--// baby : 2015-04-09 Johnson & Johnson Services, Inc.-baby--// baidu : 2015-01-08 Baidu, Inc.-baidu--// banamex : 2015-07-30 Citigroup Inc.-banamex--// bananarepublic : 2015-07-31 The Gap, Inc.-bananarepublic--// band : 2014-06-12-band--// bank : 2014-09-25 fTLD Registry Services LLC-bank--// bar : 2013-12-12 Punto 2012 Sociedad Anonima Promotora de Inversion de Capital Variable-bar--// barcelona : 2014-07-24 Municipi de Barcelona-barcelona--// barclaycard : 2014-11-20 Barclays Bank PLC-barclaycard--// barclays : 2014-11-20 Barclays Bank PLC-barclays--// barefoot : 2015-06-11 Gallo Vineyards, Inc.-barefoot--// bargains : 2013-11-14 Half Hallow, LLC-bargains--// baseball : 2015-10-29 MLB Advanced Media DH, LLC-baseball--// basketball : 2015-08-20 Fédération Internationale de Basketball (FIBA)-basketball--// bauhaus : 2014-04-17 Werkhaus GmbH-bauhaus--// bayern : 2014-01-23 Bayern Connect GmbH-bayern--// bbc : 2014-12-18 British Broadcasting Corporation-bbc--// bbt : 2015-07-23 BB&T Corporation-bbt--// bbva : 2014-10-02 BANCO BILBAO VIZCAYA ARGENTARIA, S.A.-bbva--// bcg : 2015-04-02 The Boston Consulting Group, Inc.-bcg--// bcn : 2014-07-24 Municipi de Barcelona-bcn--// beats : 2015-05-14 Beats Electronics, LLC-beats--// beauty : 2015-12-03 L'Oréal-beauty--// beer : 2014-01-09 Top Level Domain Holdings Limited-beer--// bentley : 2014-12-18 Bentley Motors Limited-bentley--// berlin : 2013-10-31 dotBERLIN GmbH & Co. KG-berlin--// best : 2013-12-19 BestTLD Pty Ltd-best--// bestbuy : 2015-07-31 BBY Solutions, Inc.-bestbuy--// bet : 2015-05-07 Afilias plc-bet--// bharti : 2014-01-09 Bharti Enterprises (Holding) Private Limited-bharti--// bible : 2014-06-19 American Bible Society-bible--// bid : 2013-12-19 dot Bid Limited-bid--// bike : 2013-08-27 Grand Hollow, LLC-bike--// bing : 2014-12-18 Microsoft Corporation-bing--// bingo : 2014-12-04 Sand Cedar, LLC-bingo--// bio : 2014-03-06 STARTING DOT LIMITED-bio--// black : 2014-01-16 Afilias Limited-black--// blackfriday : 2014-01-16 Uniregistry, Corp.-blackfriday--// blanco : 2015-07-16 BLANCO GmbH + Co KG-blanco--// blockbuster : 2015-07-30 Dish DBS Corporation-blockbuster--// blog : 2015-05-14-blog--// bloomberg : 2014-07-17 Bloomberg IP Holdings LLC-bloomberg--// blue : 2013-11-07 Afilias Limited-blue--// bms : 2014-10-30 Bristol-Myers Squibb Company-bms--// bmw : 2014-01-09 Bayerische Motoren Werke Aktiengesellschaft-bmw--// bnl : 2014-07-24 Banca Nazionale del Lavoro-bnl--// bnpparibas : 2014-05-29 BNP Paribas-bnpparibas--// boats : 2014-12-04 DERBoats, LLC-boats--// boehringer : 2015-07-09 Boehringer Ingelheim International GmbH-boehringer--// bofa : 2015-07-31 NMS Services, Inc.-bofa--// bom : 2014-10-16 Núcleo de Informação e Coordenação do Ponto BR - NIC.br-bom--// bond : 2014-06-05 Bond University Limited-bond--// boo : 2014-01-30 Charleston Road Registry Inc.-boo--// book : 2015-08-27 Amazon EU S.à r.l.-book--// booking : 2015-07-16 Booking.com B.V.-booking--// boots : 2015-01-08 THE BOOTS COMPANY PLC-boots--// bosch : 2015-06-18 Robert Bosch GMBH-bosch--// bostik : 2015-05-28 Bostik SA-bostik--// boston : 2015-12-10-boston--// bot : 2014-12-18 Amazon EU S.à r.l.-bot--// boutique : 2013-11-14 Over Galley, LLC-boutique--// box : 2015-11-12 NS1 Limited-box--// bradesco : 2014-12-18 Banco Bradesco S.A.-bradesco--// bridgestone : 2014-12-18 Bridgestone Corporation-bridgestone--// broadway : 2014-12-22 Celebrate Broadway, Inc.-broadway--// broker : 2014-12-11 IG Group Holdings PLC-broker--// brother : 2015-01-29 Brother Industries, Ltd.-brother--// brussels : 2014-02-06 DNS.be vzw-brussels--// budapest : 2013-11-21 Top Level Domain Holdings Limited-budapest--// bugatti : 2015-07-23 Bugatti International SA-bugatti--// build : 2013-11-07 Plan Bee LLC-build--// builders : 2013-11-07 Atomic Madison, LLC-builders--// business : 2013-11-07 Spring Cross, LLC-business--// buy : 2014-12-18 Amazon EU S.à r.l.-buy--// buzz : 2013-10-02 DOTSTRATEGY CO.-buzz--// bzh : 2014-02-27 Association www.bzh-bzh--// cab : 2013-10-24 Half Sunset, LLC-cab--// cafe : 2015-02-11 Pioneer Canyon, LLC-cafe--// cal : 2014-07-24 Charleston Road Registry Inc.-cal--// call : 2014-12-18 Amazon EU S.à r.l.-call--// calvinklein : 2015-07-30 PVH gTLD Holdings LLC-calvinklein--// cam : 2016-04-21 AC Webconnecting Holding B.V.-cam--// camera : 2013-08-27 Atomic Maple, LLC-camera--// camp : 2013-11-07 Delta Dynamite, LLC-camp--// cancerresearch : 2014-05-15 Australian Cancer Research Foundation-cancerresearch--// canon : 2014-09-12 Canon Inc.-canon--// capetown : 2014-03-24 ZA Central Registry NPC trading as ZA Central Registry-capetown--// capital : 2014-03-06 Delta Mill, LLC-capital--// capitalone : 2015-08-06 Capital One Financial Corporation-capitalone--// car : 2015-01-22-car--// caravan : 2013-12-12 Caravan International, Inc.-caravan--// cards : 2013-12-05 Foggy Hollow, LLC-cards--// care : 2014-03-06 Goose Cross-care--// career : 2013-10-09 dotCareer LLC-career--// careers : 2013-10-02 Wild Corner, LLC-careers--// cars : 2014-11-13-cars--// cartier : 2014-06-23 Richemont DNS Inc.-cartier--// casa : 2013-11-21 Top Level Domain Holdings Limited-casa--// case : 2015-09-03 CNH Industrial N.V.-case--// caseih : 2015-09-03 CNH Industrial N.V.-caseih--// cash : 2014-03-06 Delta Lake, LLC-cash--// casino : 2014-12-18 Binky Sky, LLC-casino--// catering : 2013-12-05 New Falls. LLC-catering--// catholic : 2015-10-21 Pontificium Consilium de Comunicationibus Socialibus (PCCS) (Pontifical Council for Social Communication)-catholic--// cba : 2014-06-26 COMMONWEALTH BANK OF AUSTRALIA-cba--// cbn : 2014-08-22 The Christian Broadcasting Network, Inc.-cbn--// cbre : 2015-07-02 CBRE, Inc.-cbre--// cbs : 2015-08-06 CBS Domains Inc.-cbs--// ceb : 2015-04-09 The Corporate Executive Board Company-ceb--// center : 2013-11-07 Tin Mill, LLC-center--// ceo : 2013-11-07 CEOTLD Pty Ltd-ceo--// cern : 2014-06-05 European Organization for Nuclear Research ("CERN")-cern--// cfa : 2014-08-28 CFA Institute-cfa--// cfd : 2014-12-11 IG Group Holdings PLC-cfd--// chanel : 2015-04-09 Chanel International B.V.-chanel--// channel : 2014-05-08 Charleston Road Registry Inc.-channel--// chase : 2015-04-30 JPMorgan Chase & Co.-chase--// chat : 2014-12-04 Sand Fields, LLC-chat--// cheap : 2013-11-14 Sand Cover, LLC-cheap--// chintai : 2015-06-11 CHINTAI Corporation-chintai--// chloe : 2014-10-16 Richemont DNS Inc.-chloe--// christmas : 2013-11-21 Uniregistry, Corp.-christmas--// chrome : 2014-07-24 Charleston Road Registry Inc.-chrome--// chrysler : 2015-07-30 FCA US LLC.-chrysler--// church : 2014-02-06 Holly Fields, LLC-church--// cipriani : 2015-02-19 Hotel Cipriani Srl-cipriani--// circle : 2014-12-18 Amazon EU S.à r.l.-circle--// cisco : 2014-12-22 Cisco Technology, Inc.-cisco--// citadel : 2015-07-23 Citadel Domain LLC-citadel--// citi : 2015-07-30 Citigroup Inc.-citi--// citic : 2014-01-09 CITIC Group Corporation-citic--// city : 2014-05-29 Snow Sky, LLC-city--// cityeats : 2014-12-11 Lifestyle Domain Holdings, Inc.-cityeats--// claims : 2014-03-20 Black Corner, LLC-claims--// cleaning : 2013-12-05 Fox Shadow, LLC-cleaning--// click : 2014-06-05 Uniregistry, Corp.-click--// clinic : 2014-03-20 Goose Park, LLC-clinic--// clinique : 2015-10-01 The Estée Lauder Companies Inc.-clinique--// clothing : 2013-08-27 Steel Lake, LLC-clothing--// cloud : 2015-04-16 ARUBA S.p.A.-cloud--// club : 2013-11-08 .CLUB DOMAINS, LLC-club--// clubmed : 2015-06-25 Club Méditerranée S.A.-clubmed--// coach : 2014-10-09 Koko Island, LLC-coach--// codes : 2013-10-31 Puff Willow, LLC-codes--// coffee : 2013-10-17 Trixy Cover, LLC-coffee--// college : 2014-01-16 XYZ.COM LLC-college--// cologne : 2014-02-05 NetCologne Gesellschaft für Telekommunikation mbH-cologne--// comcast : 2015-07-23 Comcast IP Holdings I, LLC-comcast--// commbank : 2014-06-26 COMMONWEALTH BANK OF AUSTRALIA-commbank--// community : 2013-12-05 Fox Orchard, LLC-community--// company : 2013-11-07 Silver Avenue, LLC-company--// compare : 2015-10-08 iSelect Ltd-compare--// computer : 2013-10-24 Pine Mill, LLC-computer--// comsec : 2015-01-08 VeriSign, Inc.-comsec--// condos : 2013-12-05 Pine House, LLC-condos--// construction : 2013-09-16 Fox Dynamite, LLC-construction--// consulting : 2013-12-05-consulting--// contact : 2015-01-08 Top Level Spectrum, Inc.-contact--// contractors : 2013-09-10 Magic Woods, LLC-contractors--// cooking : 2013-11-21 Top Level Domain Holdings Limited-cooking--// cookingchannel : 2015-07-02 Lifestyle Domain Holdings, Inc.-cookingchannel--// cool : 2013-11-14 Koko Lake, LLC-cool--// corsica : 2014-09-25 Collectivité Territoriale de Corse-corsica--// country : 2013-12-19 Top Level Domain Holdings Limited-country--// coupon : 2015-02-26 Amazon EU S.à r.l.-coupon--// coupons : 2015-03-26 Black Island, LLC-coupons--// courses : 2014-12-04 OPEN UNIVERSITIES AUSTRALIA PTY LTD-courses--// credit : 2014-03-20 Snow Shadow, LLC-credit--// creditcard : 2014-03-20 Binky Frostbite, LLC-creditcard--// creditunion : 2015-01-22 CUNA Performance Resources, LLC-creditunion--// cricket : 2014-10-09 dot Cricket Limited-cricket--// crown : 2014-10-24 Crown Equipment Corporation-crown--// crs : 2014-04-03 Federated Co-operatives Limited-crs--// cruise : 2015-12-10 Viking River Cruises (Bermuda) Ltd.-cruise--// cruises : 2013-12-05 Spring Way, LLC-cruises--// csc : 2014-09-25 Alliance-One Services, Inc.-csc--// cuisinella : 2014-04-03 SALM S.A.S.-cuisinella--// cymru : 2014-05-08 Nominet UK-cymru--// cyou : 2015-01-22 Beijing Gamease Age Digital Technology Co., Ltd.-cyou--// dabur : 2014-02-06 Dabur India Limited-dabur--// dad : 2014-01-23 Charleston Road Registry Inc.-dad--// dance : 2013-10-24 United TLD Holdco Ltd.-dance--// data : 2016-06-02 Dish DBS Corporation-data--// date : 2014-11-20 dot Date Limited-date--// dating : 2013-12-05 Pine Fest, LLC-dating--// datsun : 2014-03-27 NISSAN MOTOR CO., LTD.-datsun--// day : 2014-01-30 Charleston Road Registry Inc.-day--// dclk : 2014-11-20 Charleston Road Registry Inc.-dclk--// dds : 2015-05-07 Top Level Domain Holdings Limited-dds--// deal : 2015-06-25 Amazon EU S.à r.l.-deal--// dealer : 2014-12-22 Dealer Dot Com, Inc.-dealer--// deals : 2014-05-22 Sand Sunset, LLC-deals--// degree : 2014-03-06-degree--// delivery : 2014-09-11 Steel Station, LLC-delivery--// dell : 2014-10-24 Dell Inc.-dell--// deloitte : 2015-07-31 Deloitte Touche Tohmatsu-deloitte--// delta : 2015-02-19 Delta Air Lines, Inc.-delta--// democrat : 2013-10-24 United TLD Holdco Ltd.-democrat--// dental : 2014-03-20 Tin Birch, LLC-dental--// dentist : 2014-03-20-dentist--// desi : 2013-11-14 Desi Networks LLC-desi--// design : 2014-11-07 Top Level Design, LLC-design--// dev : 2014-10-16 Charleston Road Registry Inc.-dev--// dhl : 2015-07-23 Deutsche Post AG-dhl--// diamonds : 2013-09-22 John Edge, LLC-diamonds--// diet : 2014-06-26 Uniregistry, Corp.-diet--// digital : 2014-03-06 Dash Park, LLC-digital--// direct : 2014-04-10 Half Trail, LLC-direct--// directory : 2013-09-20 Extra Madison, LLC-directory--// discount : 2014-03-06 Holly Hill, LLC-discount--// discover : 2015-07-23 Discover Financial Services-discover--// dish : 2015-07-30 Dish DBS Corporation-dish--// diy : 2015-11-05 Lifestyle Domain Holdings, Inc.-diy--// dnp : 2013-12-13 Dai Nippon Printing Co., Ltd.-dnp--// docs : 2014-10-16 Charleston Road Registry Inc.-docs--// doctor : 2016-06-02 Brice Trail, LLC-doctor--// dodge : 2015-07-30 FCA US LLC.-dodge--// dog : 2014-12-04 Koko Mill, LLC-dog--// doha : 2014-09-18 Communications Regulatory Authority (CRA)-doha--// domains : 2013-10-17 Sugar Cross, LLC-domains--// dot : 2015-05-21 Dish DBS Corporation-dot--// download : 2014-11-20 dot Support Limited-download--// drive : 2015-03-05 Charleston Road Registry Inc.-drive--// dtv : 2015-06-04 Dish DBS Corporation-dtv--// dubai : 2015-01-01 Dubai Smart Government Department-dubai--// duck : 2015-07-23 Johnson Shareholdings, Inc.-duck--// dunlop : 2015-07-02 The Goodyear Tire & Rubber Company-dunlop--// duns : 2015-08-06 The Dun & Bradstreet Corporation-duns--// dupont : 2015-06-25 E. I. du Pont de Nemours and Company-dupont--// durban : 2014-03-24 ZA Central Registry NPC trading as ZA Central Registry-durban--// dvag : 2014-06-23 Deutsche Vermögensberatung Aktiengesellschaft DVAG-dvag--// dvr : 2016-05-26 Hughes Satellite Systems Corporation-dvr--// dwg : 2015-07-23 Autodesk, Inc.-dwg--// earth : 2014-12-04 Interlink Co., Ltd.-earth--// eat : 2014-01-23 Charleston Road Registry Inc.-eat--// eco : 2016-07-08 Big Room Inc.-eco--// edeka : 2014-12-18 EDEKA Verband kaufmännischer Genossenschaften e.V.-edeka--// education : 2013-11-07 Brice Way, LLC-education--// email : 2013-10-31 Spring Madison, LLC--// emerck : 2014-04-03 Merck KGaA-emerck--// energy : 2014-09-11 Binky Birch, LLC-energy--// engineer : 2014-03-06 United TLD Holdco Ltd.-engineer--// engineering : 2014-03-06 Romeo Canyon-engineering--// enterprises : 2013-09-20 Snow Oaks, LLC-enterprises--// epost : 2015-07-23 Deutsche Post AG-epost--// epson : 2014-12-04 Seiko Epson Corporation-epson--// equipment : 2013-08-27 Corn Station, LLC-equipment--// ericsson : 2015-07-09 Telefonaktiebolaget L M Ericsson-ericsson--// erni : 2014-04-03 ERNI Group Holding AG-erni--// esq : 2014-05-08 Charleston Road Registry Inc.-esq--// estate : 2013-08-27 Trixy Park, LLC-estate--// esurance : 2015-07-23 Esurance Insurance Company-esurance--// etisalat : 2015-09-03 Emirates Telecommunications Corporation (trading as Etisalat)-etisalat--// eurovision : 2014-04-24 European Broadcasting Union (EBU)-eurovision--// eus : 2013-12-12 Puntueus Fundazioa-eus--// events : 2013-12-05 Pioneer Maple, LLC-events--// everbank : 2014-05-15 EverBank-everbank--// exchange : 2014-03-06 Spring Falls, LLC-exchange--// expert : 2013-11-21 Magic Pass, LLC-expert--// exposed : 2013-12-05 Victor Beach, LLC-exposed--// express : 2015-02-11 Sea Sunset, LLC-express--// extraspace : 2015-05-14 Extra Space Storage LLC-extraspace--// fage : 2014-12-18 Fage International S.A.-fage--// fail : 2014-03-06 Atomic Pipe, LLC-fail--// fairwinds : 2014-11-13 FairWinds Partners, LLC-fairwinds--// faith : 2014-11-20 dot Faith Limited-faith--// family : 2015-04-02-family--// fan : 2014-03-06-fan--// fans : 2014-11-07 Asiamix Digital Limited-fans--// farm : 2013-11-07 Just Maple, LLC-farm--// farmers : 2015-07-09 Farmers Insurance Exchange-farmers--// fashion : 2014-07-03 Top Level Domain Holdings Limited-fashion--// fast : 2014-12-18 Amazon EU S.à r.l.-fast--// fedex : 2015-08-06 Federal Express Corporation-fedex--// feedback : 2013-12-19 Top Level Spectrum, Inc.-feedback--// ferrari : 2015-07-31 Fiat Chrysler Automobiles N.V.-ferrari--// ferrero : 2014-12-18 Ferrero Trading Lux S.A.-ferrero--// fiat : 2015-07-31 Fiat Chrysler Automobiles N.V.-fiat--// fidelity : 2015-07-30 Fidelity Brokerage Services LLC-fidelity--// fido : 2015-08-06 Rogers Communications Partnership-fido--// film : 2015-01-08 Motion Picture Domain Registry Pty Ltd-film--// final : 2014-10-16 Núcleo de Informação e Coordenação do Ponto BR - NIC.br-final--// finance : 2014-03-20 Cotton Cypress, LLC-finance--// financial : 2014-03-06 Just Cover, LLC-financial--// fire : 2015-06-25 Amazon EU S.à r.l.-fire--// firestone : 2014-12-18 Bridgestone Corporation-firestone--// firmdale : 2014-03-27 Firmdale Holdings Limited-firmdale--// fish : 2013-12-12 Fox Woods, LLC-fish--// fishing : 2013-11-21 Top Level Domain Holdings Limited-fishing--// fit : 2014-11-07 Top Level Domain Holdings Limited-fit--// fitness : 2014-03-06 Brice Orchard, LLC-fitness--// flickr : 2015-04-02 Yahoo! Domain Services Inc.-flickr--// flights : 2013-12-05 Fox Station, LLC-flights--// flir : 2015-07-23 FLIR Systems, Inc.-flir--// florist : 2013-11-07 Half Cypress, LLC-florist--// flowers : 2014-10-09 Uniregistry, Corp.-flowers--// fly : 2014-05-08 Charleston Road Registry Inc.-fly--// foo : 2014-01-23 Charleston Road Registry Inc.-foo--// food : 2016-04-21 Lifestyle Domain Holdings, Inc.-food--// foodnetwork : 2015-07-02 Lifestyle Domain Holdings, Inc.-foodnetwork--// football : 2014-12-18 Foggy Farms, LLC-football--// ford : 2014-11-13 Ford Motor Company-ford--// forex : 2014-12-11 IG Group Holdings PLC-forex--// forsale : 2014-05-22-forsale--// forum : 2015-04-02 Fegistry, LLC-forum--// foundation : 2013-12-05 John Dale, LLC-foundation--// fox : 2015-09-11 FOX Registry, LLC-fox--// free : 2015-12-10 Amazon EU S.à r.l.-free--// fresenius : 2015-07-30 Fresenius Immobilien-Verwaltungs-GmbH-fresenius--// frl : 2014-05-15 FRLregistry B.V.-frl--// frogans : 2013-12-19 OP3FT-frogans--// frontdoor : 2015-07-02 Lifestyle Domain Holdings, Inc.-frontdoor--// frontier : 2015-02-05 Frontier Communications Corporation-frontier--// ftr : 2015-07-16 Frontier Communications Corporation-ftr--// fujitsu : 2015-07-30 Fujitsu Limited-fujitsu--// fujixerox : 2015-07-23 Xerox DNHC LLC-fujixerox--// fun : 2016-01-14-fun--// fund : 2014-03-20 John Castle, LLC-fund--// furniture : 2014-03-20 Lone Fields, LLC-furniture--// futbol : 2013-09-20-futbol--// fyi : 2015-04-02 Silver Tigers, LLC-fyi--// gal : 2013-11-07 Asociación puntoGAL-gal--// gallery : 2013-09-13 Sugar House, LLC-gallery--// gallo : 2015-06-11 Gallo Vineyards, Inc.-gallo--// gallup : 2015-02-19 Gallup, Inc.-gallup--// game : 2015-05-28 Uniregistry, Corp.-game--// games : 2015-05-28-games--// gap : 2015-07-31 The Gap, Inc.-gap--// garden : 2014-06-26 Top Level Domain Holdings Limited-garden--// gbiz : 2014-07-17 Charleston Road Registry Inc.-gbiz--// gdn : 2014-07-31 Joint Stock Company "Navigation-information systems"-gdn--// gea : 2014-12-04 GEA Group Aktiengesellschaft-gea--// gent : 2014-01-23 COMBELL GROUP NV/SA-gent--// genting : 2015-03-12 Resorts World Inc Pte. Ltd.-genting--// george : 2015-07-31 Wal-Mart Stores, Inc.-george--// ggee : 2014-01-09 GMO Internet, Inc.-ggee--// gift : 2013-10-17 Uniregistry, Corp.-gift--// gifts : 2014-07-03 Goose Sky, LLC-gifts--// gives : 2014-03-06 United TLD Holdco Ltd.-gives--// giving : 2014-11-13 Giving Limited-giving--// glade : 2015-07-23 Johnson Shareholdings, Inc.-glade--// glass : 2013-11-07 Black Cover, LLC-glass--// gle : 2014-07-24 Charleston Road Registry Inc.-gle--// global : 2014-04-17 Dot GLOBAL AS-global--// globo : 2013-12-19 Globo Comunicação e Participações S.A-globo--// gmail : 2014-05-01 Charleston Road Registry Inc.-gmail--// gmbh : 2016-01-29 Extra Dynamite, LLC-gmbh--// gmo : 2014-01-09 GMO Internet, Inc.-gmo--// gmx : 2014-04-24 1&1 Mail & Media GmbH-gmx--// godaddy : 2015-07-23 Go Daddy East, LLC-godaddy--// gold : 2015-01-22 June Edge, LLC-gold--// goldpoint : 2014-11-20 YODOBASHI CAMERA CO.,LTD.-goldpoint--// golf : 2014-12-18 Lone falls, LLC-golf--// goo : 2014-12-18 NTT Resonant Inc.-goo--// goodhands : 2015-07-31 Allstate Fire and Casualty Insurance Company-goodhands--// goodyear : 2015-07-02 The Goodyear Tire & Rubber Company-goodyear--// goog : 2014-11-20 Charleston Road Registry Inc.-goog--// google : 2014-07-24 Charleston Road Registry Inc.--// gop : 2014-01-16 Republican State Leadership Committee, Inc.-gop--// got : 2014-12-18 Amazon EU S.à r.l.-got--// grainger : 2015-05-07 Grainger Registry Services, LLC-grainger--// graphics : 2013-09-13 Over Madison, LLC-graphics--// gratis : 2014-03-20 Pioneer Tigers, LLC-gratis--// green : 2014-05-08 Afilias Limited-green--// gripe : 2014-03-06 Corn Sunset, LLC-gripe--// grocery : 2016-06-16 Wal-Mart Stores, Inc.-grocery--// group : 2014-08-15 Romeo Town, LLC-group--// guardian : 2015-07-30 The Guardian Life Insurance Company of America-guardian--// gucci : 2014-11-13 Guccio Gucci S.p.a.-gucci--// guge : 2014-08-28 Charleston Road Registry Inc.-guge--// guide : 2013-09-13 Snow Moon, LLC-guide--// guitars : 2013-11-14 Uniregistry, Corp.-guitars--// guru : 2013-08-27 Pioneer Cypress, LLC-guru--// hair : 2015-12-03 L'Oréal-hair--// hamburg : 2014-02-20 Hamburg Top-Level-Domain GmbH-hamburg--// hangout : 2014-11-13 Charleston Road Registry Inc.-hangout--// haus : 2013-12-05-haus--// hbo : 2015-07-30 HBO Registry Services, Inc.-hbo--// hdfc : 2015-07-30 HOUSING DEVELOPMENT FINANCE CORPORATION LIMITED-hdfc--// hdfcbank : 2015-02-12 HDFC Bank Limited-hdfcbank--// health : 2015-02-11 DotHealth, LLC-health--// healthcare : 2014-06-12 Silver Glen, LLC-healthcare--// help : 2014-06-26 Uniregistry, Corp.-help--// helsinki : 2015-02-05 City of Helsinki-helsinki--// here : 2014-02-06 Charleston Road Registry Inc.-here--// hermes : 2014-07-10 HERMES INTERNATIONAL-hermes--// hgtv : 2015-07-02 Lifestyle Domain Holdings, Inc.-hgtv--// hiphop : 2014-03-06 Uniregistry, Corp.-hiphop--// hisamitsu : 2015-07-16 Hisamitsu Pharmaceutical Co.,Inc.-hisamitsu--// hitachi : 2014-10-31 Hitachi, Ltd.-hitachi--// hiv : 2014-03-13-hiv--// hkt : 2015-05-14 PCCW-HKT DataCom Services Limited-hkt--// hockey : 2015-03-19 Half Willow, LLC-hockey--// holdings : 2013-08-27 John Madison, LLC-holdings--// holiday : 2013-11-07 Goose Woods, LLC-holiday--// homedepot : 2015-04-02 Homer TLC, Inc.-homedepot--// homegoods : 2015-07-16 The TJX Companies, Inc.-homegoods--// homes : 2014-01-09 DERHomes, LLC-homes--// homesense : 2015-07-16 The TJX Companies, Inc.-homesense--// honda : 2014-12-18 Honda Motor Co., Ltd.-honda--// honeywell : 2015-07-23 Honeywell GTLD LLC-honeywell--// horse : 2013-11-21 Top Level Domain Holdings Limited-horse--// hospital : 2016-10-20 Ruby Pike, LLC-hospital--// host : 2014-04-17 DotHost Inc.-host--// hosting : 2014-05-29 Uniregistry, Corp.-hosting--// hot : 2015-08-27 Amazon EU S.à r.l.-hot--// hoteles : 2015-03-05 Travel Reservations SRL-hoteles--// hotels : 2016-04-07 Booking.com B.V.-hotels--// hotmail : 2014-12-18 Microsoft Corporation-hotmail--// house : 2013-11-07 Sugar Park, LLC-house--// how : 2014-01-23 Charleston Road Registry Inc.-how--// hsbc : 2014-10-24 HSBC Holdings PLC-hsbc--// htc : 2015-04-02 HTC corporation-htc--// hughes : 2015-07-30 Hughes Satellite Systems Corporation-hughes--// hyatt : 2015-07-30 Hyatt GTLD, L.L.C.-hyatt--// hyundai : 2015-07-09 Hyundai Motor Company-hyundai--// ibm : 2014-07-31 International Business Machines Corporation-ibm--// icbc : 2015-02-19 Industrial and Commercial Bank of China Limited-icbc--// ice : 2014-10-30 IntercontinentalExchange, Inc.-ice--// icu : 2015-01-08 One.com A/S-icu--// ieee : 2015-07-23 IEEE Global LLC-ieee--// ifm : 2014-01-30 ifm electronic gmbh-ifm--// iinet : 2014-07-03 Connect West Pty. Ltd.-iinet--// ikano : 2015-07-09 Ikano S.A.-ikano--// imamat : 2015-08-06 Fondation Aga Khan (Aga Khan Foundation)-imamat--// imdb : 2015-06-25 Amazon EU S.à r.l.-imdb--// immo : 2014-07-10 Auburn Bloom, LLC-immo--// immobilien : 2013-11-07 United TLD Holdco Ltd.-immobilien--// industries : 2013-12-05 Outer House, LLC-industries--// infiniti : 2014-03-27 NISSAN MOTOR CO., LTD.-infiniti--// ing : 2014-01-23 Charleston Road Registry Inc.-ing--// ink : 2013-12-05 Top Level Design, LLC-ink--// institute : 2013-11-07 Outer Maple, LLC-institute--// insurance : 2015-02-19 fTLD Registry Services LLC-insurance--// insure : 2014-03-20 Pioneer Willow, LLC-insure--// intel : 2015-08-06 Intel Corporation-intel--// international : 2013-11-07 Wild Way, LLC-international--// intuit : 2015-07-30 Intuit Administrative Services, Inc.-intuit--// investments : 2014-03-20 Holly Glen, LLC-investments--// ipiranga : 2014-08-28 Ipiranga Produtos de Petroleo S.A.-ipiranga--// irish : 2014-08-07 Dot-Irish LLC-irish--// iselect : 2015-02-11 iSelect Ltd-iselect--// ismaili : 2015-08-06 Fondation Aga Khan (Aga Khan Foundation)-ismaili--// ist : 2014-08-28 Istanbul Metropolitan Municipality-ist--// istanbul : 2014-08-28 Istanbul Metropolitan Municipality-istanbul--// itau : 2014-10-02 Itau Unibanco Holding S.A.-itau--// itv : 2015-07-09 ITV Services Limited-itv--// iveco : 2015-09-03 CNH Industrial N.V.-iveco--// iwc : 2014-06-23 Richemont DNS Inc.-iwc--// jaguar : 2014-11-13 Jaguar Land Rover Ltd-jaguar--// java : 2014-06-19 Oracle Corporation-java--// jcb : 2014-11-20 JCB Co., Ltd.-jcb--// jcp : 2015-04-23 JCP Media, Inc.-jcp--// jeep : 2015-07-30 FCA US LLC.-jeep--// jetzt : 2014-01-09-jetzt--// jewelry : 2015-03-05 Wild Bloom, LLC-jewelry--// jio : 2015-04-02 Affinity Names, Inc.-jio--// jlc : 2014-12-04 Richemont DNS Inc.-jlc--// jll : 2015-04-02 Jones Lang LaSalle Incorporated-jll--// jmp : 2015-03-26 Matrix IP LLC-jmp--// jnj : 2015-06-18 Johnson & Johnson Services, Inc.-jnj--// joburg : 2014-03-24 ZA Central Registry NPC trading as ZA Central Registry-joburg--// jot : 2014-12-18 Amazon EU S.à r.l.-jot--// joy : 2014-12-18 Amazon EU S.à r.l.-joy--// jpmorgan : 2015-04-30 JPMorgan Chase & Co.-jpmorgan--// jprs : 2014-09-18 Japan Registry Services Co., Ltd.-jprs--// juegos : 2014-03-20 Uniregistry, Corp.-juegos--// juniper : 2015-07-30 JUNIPER NETWORKS, INC.-juniper--// kaufen : 2013-11-07 United TLD Holdco Ltd.-kaufen--// kddi : 2014-09-12 KDDI CORPORATION-kddi--// kerryhotels : 2015-04-30 Kerry Trading Co. Limited-kerryhotels--// kerrylogistics : 2015-04-09 Kerry Trading Co. Limited-kerrylogistics--// kerryproperties : 2015-04-09 Kerry Trading Co. Limited-kerryproperties--// kfh : 2014-12-04 Kuwait Finance House-kfh--// kia : 2015-07-09 KIA MOTORS CORPORATION-kia--// kim : 2013-09-23 Afilias Limited-kim--// kinder : 2014-11-07 Ferrero Trading Lux S.A.-kinder--// kindle : 2015-06-25 Amazon EU S.à r.l.-kindle--// kitchen : 2013-09-20 Just Goodbye, LLC-kitchen--// kiwi : 2013-09-20 DOT KIWI LIMITED-kiwi--// koeln : 2014-01-09 NetCologne Gesellschaft für Telekommunikation mbH-koeln--// komatsu : 2015-01-08 Komatsu Ltd.-komatsu--// kosher : 2015-08-20 Kosher Marketing Assets LLC-kosher--// kpmg : 2015-04-23 KPMG International Cooperative (KPMG International Genossenschaft)-kpmg--// kpn : 2015-01-08 Koninklijke KPN N.V.-kpn--// krd : 2013-12-05 KRG Department of Information Technology-krd--// kred : 2013-12-19 KredTLD Pty Ltd-kred--// kuokgroup : 2015-04-09 Kerry Trading Co. Limited-kuokgroup--// kyoto : 2014-11-07 Academic Institution: Kyoto Jyoho Gakuen-kyoto--// lacaixa : 2014-01-09 CAIXA D'ESTALVIS I PENSIONS DE BARCELONA-lacaixa--// ladbrokes : 2015-08-06 LADBROKES INTERNATIONAL PLC-ladbrokes--// lamborghini : 2015-06-04 Automobili Lamborghini S.p.A.-lamborghini--// lamer : 2015-10-01 The Estée Lauder Companies Inc.-lamer--// lancaster : 2015-02-12 LANCASTER-lancaster--// lancia : 2015-07-31 Fiat Chrysler Automobiles N.V.-lancia--// lancome : 2015-07-23 L'Oréal-lancome--// land : 2013-09-10 Pine Moon, LLC-land--// landrover : 2014-11-13 Jaguar Land Rover Ltd-landrover--// lanxess : 2015-07-30 LANXESS Corporation-lanxess--// lasalle : 2015-04-02 Jones Lang LaSalle Incorporated-lasalle--// lat : 2014-10-16 ECOM-LAC Federaciòn de Latinoamèrica y el Caribe para Internet y el Comercio Electrònico-lat--// latino : 2015-07-30 Dish DBS Corporation-latino--// latrobe : 2014-06-16 La Trobe University-latrobe--// law : 2015-01-22 Minds + Machines Group Limited-law--// lawyer : 2014-03-20-lawyer--// lds : 2014-03-20 IRI Domain Management, LLC ("Applicant")-lds--// lease : 2014-03-06 Victor Trail, LLC-lease--// leclerc : 2014-08-07 A.C.D. LEC Association des Centres Distributeurs Edouard Leclerc-leclerc--// lefrak : 2015-07-16 LeFrak Organization, Inc.-lefrak--// legal : 2014-10-16 Blue Falls, LLC-legal--// lego : 2015-07-16 LEGO Juris A/S-lego--// lexus : 2015-04-23 TOYOTA MOTOR CORPORATION-lexus--// lgbt : 2014-05-08 Afilias Limited-lgbt--// liaison : 2014-10-02 Liaison Technologies, Incorporated-liaison--// lidl : 2014-09-18 Schwarz Domains und Services GmbH & Co. KG-lidl--// life : 2014-02-06 Trixy Oaks, LLC-life--// lifeinsurance : 2015-01-15 American Council of Life Insurers-lifeinsurance--// lifestyle : 2014-12-11 Lifestyle Domain Holdings, Inc.-lifestyle--// lighting : 2013-08-27 John McCook, LLC-lighting--// like : 2014-12-18 Amazon EU S.à r.l.-like--// lilly : 2015-07-31 Eli Lilly and Company-lilly--// limited : 2014-03-06 Big Fest, LLC-limited--// limo : 2013-10-17 Hidden Frostbite, LLC-limo--// lincoln : 2014-11-13 Ford Motor Company-lincoln--// linde : 2014-12-04 Linde Aktiengesellschaft-linde--// link : 2013-11-14 Uniregistry, Corp.-link--// lipsy : 2015-06-25 Lipsy Ltd-lipsy--// live : 2014-12-04-live--// living : 2015-07-30 Lifestyle Domain Holdings, Inc.-living--// lixil : 2015-03-19 LIXIL Group Corporation-lixil--// loan : 2014-11-20 dot Loan Limited-loan--// loans : 2014-03-20 June Woods, LLC-loans--// locker : 2015-06-04 Dish DBS Corporation-locker--// locus : 2015-06-25 Locus Analytics LLC-locus--// loft : 2015-07-30 Annco, Inc.-loft--// lol : 2015-01-30 Uniregistry, Corp.-lol--// london : 2013-11-14 Dot London Domains Limited-london--// lotte : 2014-11-07 Lotte Holdings Co., Ltd.-lotte--// lotto : 2014-04-10 Afilias Limited-lotto--// love : 2014-12-22 Merchant Law Group LLP-love--// lpl : 2015-07-30 LPL Holdings, Inc.-lpl--// lplfinancial : 2015-07-30 LPL Holdings, Inc.-lplfinancial--// ltd : 2014-09-25 Over Corner, LLC-ltd--// ltda : 2014-04-17 DOMAIN ROBOT SERVICOS DE HOSPEDAGEM NA INTERNET LTDA-ltda--// lundbeck : 2015-08-06 H. Lundbeck A/S-lundbeck--// lupin : 2014-11-07 LUPIN LIMITED-lupin--// luxe : 2014-01-09 Top Level Domain Holdings Limited-luxe--// luxury : 2013-10-17 Luxury Partners, LLC-luxury--// macys : 2015-07-31 Macys, Inc.-macys--// madrid : 2014-05-01 Comunidad de Madrid-madrid--// maif : 2014-10-02 Mutuelle Assurance Instituteur France (MAIF)-maif--// maison : 2013-12-05 Victor Frostbite, LLC-maison--// makeup : 2015-01-15 L'Oréal-makeup--// man : 2014-12-04 MAN SE-man--// management : 2013-11-07 John Goodbye, LLC-management--// mango : 2013-10-24 PUNTO FA S.L.-mango--// map : 2016-06-09 Charleston Road Registry Inc.-map--// market : 2014-03-06-market--// marketing : 2013-11-07 Fern Pass, LLC-marketing--// markets : 2014-12-11 IG Group Holdings PLC-markets--// marriott : 2014-10-09 Marriott Worldwide Corporation-marriott--// marshalls : 2015-07-16 The TJX Companies, Inc.-marshalls--// maserati : 2015-07-31 Fiat Chrysler Automobiles N.V.-maserati--// mattel : 2015-08-06 Mattel Sites, Inc.-mattel--// mba : 2015-04-02 Lone Hollow, LLC-mba--// mcd : 2015-07-30 McDonald’s Corporation-mcd--// mcdonalds : 2015-07-30 McDonald’s Corporation-mcdonalds--// mckinsey : 2015-07-31 McKinsey Holdings, Inc.-mckinsey--// med : 2015-08-06 Medistry LLC-med--// media : 2014-03-06 Grand Glen, LLC-media--// meet : 2014-01-16-meet--// melbourne : 2014-05-29 The Crown in right of the State of Victoria, represented by its Department of State Development, Business and Innovation-melbourne--// meme : 2014-01-30 Charleston Road Registry Inc.-meme--// memorial : 2014-10-16 Dog Beach, LLC-memorial--// men : 2015-02-26 Exclusive Registry Limited-men--// menu : 2013-09-11 Wedding TLD2, LLC-menu--// meo : 2014-11-07 PT Comunicacoes S.A.-meo--// merckmsd : 2016-07-14 MSD Registry Holdings, Inc.-merckmsd--// metlife : 2015-05-07 MetLife Services and Solutions, LLC-metlife--// miami : 2013-12-19 Top Level Domain Holdings Limited-miami--// microsoft : 2014-12-18 Microsoft Corporation-microsoft--// mini : 2014-01-09 Bayerische Motoren Werke Aktiengesellschaft-mini--// mint : 2015-07-30 Intuit Administrative Services, Inc.-mint--// mit : 2015-07-02 Massachusetts Institute of Technology-mit--// mitsubishi : 2015-07-23 Mitsubishi Corporation-mitsubishi--// mlb : 2015-05-21 MLB Advanced Media DH, LLC-mlb--// mls : 2015-04-23 The Canadian Real Estate Association-mls--// mma : 2014-11-07 MMA IARD-mma--// mobile : 2016-06-02 Dish DBS Corporation-mobile--// mobily : 2014-12-18 GreenTech Consultancy Company W.L.L.-mobily--// moda : 2013-11-07 United TLD Holdco Ltd.-moda--// moe : 2013-11-13 Interlink Co., Ltd.-moe--// moi : 2014-12-18 Amazon EU S.à r.l.-moi--// mom : 2015-04-16 Uniregistry, Corp.-mom--// monash : 2013-09-30 Monash University-monash--// money : 2014-10-16 Outer McCook, LLC-money--// monster : 2015-09-11 Monster Worldwide, Inc.-monster--// montblanc : 2014-06-23 Richemont DNS Inc.-montblanc--// mopar : 2015-07-30 FCA US LLC.-mopar--// mormon : 2013-12-05 IRI Domain Management, LLC ("Applicant")-mormon--// mortgage : 2014-03-20-mortgage--// moscow : 2013-12-19 Foundation for Assistance for Internet Technologies and Infrastructure Development (FAITID)-moscow--// moto : 2015-06-04-moto--// motorcycles : 2014-01-09 DERMotorcycles, LLC-motorcycles--// mov : 2014-01-30 Charleston Road Registry Inc.-mov--// movie : 2015-02-05 New Frostbite, LLC-movie--// movistar : 2014-10-16 Telefónica S.A.-movistar--// msd : 2015-07-23 MSD Registry Holdings, Inc.-msd--// mtn : 2014-12-04 MTN Dubai Limited-mtn--// mtpc : 2014-11-20 Mitsubishi Tanabe Pharma Corporation-mtpc--// mtr : 2015-03-12 MTR Corporation Limited-mtr--// mutual : 2015-04-02 Northwestern Mutual MU TLD Registry, LLC-mutual--// mutuelle : 2015-06-18 Fédération Nationale de la Mutualité Française-mutuelle--// nab : 2015-08-20 National Australia Bank Limited-nab--// nadex : 2014-12-11 IG Group Holdings PLC-nadex--// nagoya : 2013-10-24 GMO Registry, Inc.-nagoya--// nationwide : 2015-07-23 Nationwide Mutual Insurance Company-nationwide--// natura : 2015-03-12 NATURA COSMÉTICOS S.A.-natura--// navy : 2014-03-06 United TLD Holdco Ltd.-navy--// nba : 2015-07-31 NBA REGISTRY, LLC-nba--// nec : 2015-01-08 NEC Corporation-nec--// netbank : 2014-06-26 COMMONWEALTH BANK OF AUSTRALIA-netbank--// netflix : 2015-06-18 Netflix, Inc.-netflix--// network : 2013-11-14 Trixy Manor, LLC-network--// neustar : 2013-12-05 NeuStar, Inc.-neustar--// new : 2014-01-30 Charleston Road Registry Inc.-new--// newholland : 2015-09-03 CNH Industrial N.V.-newholland--// news : 2014-12-18-news--// next : 2015-06-18 Next plc-next--// nextdirect : 2015-06-18 Next plc-nextdirect--// nexus : 2014-07-24 Charleston Road Registry Inc.-nexus--// nfl : 2015-07-23 NFL Reg Ops LLC-nfl--// ngo : 2014-03-06 Public Interest Registry-ngo--// nhk : 2014-02-13 Japan Broadcasting Corporation (NHK)-nhk--// nico : 2014-12-04 DWANGO Co., Ltd.-nico--// nike : 2015-07-23 NIKE, Inc.-nike--// nikon : 2015-05-21 NIKON CORPORATION-nikon--// ninja : 2013-11-07 United TLD Holdco Ltd.-ninja--// nissan : 2014-03-27 NISSAN MOTOR CO., LTD.-nissan--// nissay : 2015-10-29 Nippon Life Insurance Company-nissay--// nokia : 2015-01-08 Nokia Corporation-nokia--// northwesternmutual : 2015-06-18 Northwestern Mutual Registry, LLC-northwesternmutual--// norton : 2014-12-04 Symantec Corporation-norton--// now : 2015-06-25 Amazon EU S.à r.l.-now--// nowruz : 2014-09-04 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti.-nowruz--// nowtv : 2015-05-14 Starbucks (HK) Limited-nowtv--// nra : 2014-05-22 NRA Holdings Company, INC.-nra--// nrw : 2013-11-21 Minds + Machines GmbH-nrw--// ntt : 2014-10-31 NIPPON TELEGRAPH AND TELEPHONE CORPORATION-ntt--// nyc : 2014-01-23 The City of New York by and through the New York City Department of Information Technology & Telecommunications-nyc--// obi : 2014-09-25 OBI Group Holding SE & Co. KGaA-obi--// observer : 2015-04-30-observer--// off : 2015-07-23 Johnson Shareholdings, Inc.-off--// office : 2015-03-12 Microsoft Corporation-office--// okinawa : 2013-12-05 BusinessRalliart Inc.-okinawa--// olayan : 2015-05-14 Crescent Holding GmbH-olayan--// olayangroup : 2015-05-14 Crescent Holding GmbH-olayangroup--// oldnavy : 2015-07-31 The Gap, Inc.-oldnavy--// ollo : 2015-06-04 Dish DBS Corporation-ollo--// omega : 2015-01-08 The Swatch Group Ltd-omega--// one : 2014-11-07 One.com A/S-one--// ong : 2014-03-06 Public Interest Registry-ong--// onl : 2013-09-16 I-Registry Ltd.-onl--// online : 2015-01-15 DotOnline Inc.-online--// onyourside : 2015-07-23 Nationwide Mutual Insurance Company-onyourside--// ooo : 2014-01-09 INFIBEAM INCORPORATION LIMITED-ooo--// open : 2015-07-31 American Express Travel Related Services Company, Inc.-open--// oracle : 2014-06-19 Oracle Corporation-oracle--// orange : 2015-03-12 Orange Brand Services Limited-orange--// organic : 2014-03-27 Afilias Limited-organic--// orientexpress : 2015-02-05-orientexpress--// origins : 2015-10-01 The Estée Lauder Companies Inc.-origins--// osaka : 2014-09-04 Interlink Co., Ltd.-osaka--// otsuka : 2013-10-11 Otsuka Holdings Co., Ltd.-otsuka--// ott : 2015-06-04 Dish DBS Corporation-ott--// ovh : 2014-01-16 OVH SAS-ovh--// page : 2014-12-04 Charleston Road Registry Inc.-page--// pamperedchef : 2015-02-05 The Pampered Chef, Ltd.-pamperedchef--// panasonic : 2015-07-30 Panasonic Corporation-panasonic--// panerai : 2014-11-07 Richemont DNS Inc.-panerai--// paris : 2014-01-30 City of Paris-paris--// pars : 2014-09-04 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti.-pars--// partners : 2013-12-05 Magic Glen, LLC-partners--// parts : 2013-12-05 Sea Goodbye, LLC-parts--// party : 2014-09-11 Blue Sky Registry Limited-party--// passagens : 2015-03-05 Travel Reservations SRL-passagens--// pay : 2015-08-27 Amazon EU S.à r.l.-pay--// pccw : 2015-05-14 PCCW Enterprises Limited-pccw--// pet : 2015-05-07 Afilias plc-pet--// pfizer : 2015-09-11 Pfizer Inc.-pfizer--// pharmacy : 2014-06-19 National Association of Boards of Pharmacy-pharmacy--// phd : 2016-07-28 Charleston Road Registry Inc.-phd--// philips : 2014-11-07 Koninklijke Philips N.V.-philips--// phone : 2016-06-02 Dish DBS Corporation-phone--// photo : 2013-11-14 Uniregistry, Corp.-photo--// photography : 2013-09-20 Sugar Glen, LLC-photography--// photos : 2013-10-17 Sea Corner, LLC-photos--// physio : 2014-05-01 PhysBiz Pty Ltd-physio--// piaget : 2014-10-16 Richemont DNS Inc.-piaget--// pics : 2013-11-14 Uniregistry, Corp.-pics--// pictet : 2014-06-26 Pictet Europe S.A.-pictet--// pictures : 2014-03-06 Foggy Sky, LLC-pictures--// pid : 2015-01-08 Top Level Spectrum, Inc.-pid--// pin : 2014-12-18 Amazon EU S.à r.l.-pin--// ping : 2015-06-11 Ping Registry Provider, Inc.-ping--// pink : 2013-10-01 Afilias Limited-pink--// pioneer : 2015-07-16 Pioneer Corporation-pioneer--// pizza : 2014-06-26 Foggy Moon, LLC-pizza--// place : 2014-04-24 Snow Galley, LLC-place--// play : 2015-03-05 Charleston Road Registry Inc.-play--// playstation : 2015-07-02 Sony Computer Entertainment Inc.-playstation--// plumbing : 2013-09-10 Spring Tigers, LLC-plumbing--// plus : 2015-02-05 Sugar Mill, LLC-plus--// pnc : 2015-07-02 PNC Domain Co., LLC-pnc--// pohl : 2014-06-23 Deutsche Vermögensberatung Aktiengesellschaft DVAG-pohl--// poker : 2014-07-03 Afilias Domains No. 5 Limited-poker--// politie : 2015-08-20 Politie Nederland-politie--// porn : 2014-10-16 ICM Registry PN LLC-porn--// pramerica : 2015-07-30 Prudential Financial, Inc.-pramerica--// praxi : 2013-12-05 Praxi S.p.A.-praxi--// press : 2014-04-03 DotPress Inc.-press--// prime : 2015-06-25 Amazon EU S.à r.l.-prime--// prod : 2014-01-23 Charleston Road Registry Inc.-prod--// productions : 2013-12-05 Magic Birch, LLC-productions--// prof : 2014-07-24 Charleston Road Registry Inc.-prof--// progressive : 2015-07-23 Progressive Casualty Insurance Company-progressive--// promo : 2014-12-18-promo--// properties : 2013-12-05 Big Pass, LLC-properties--// property : 2014-05-22 Uniregistry, Corp.-property--// protection : 2015-04-23-protection--// pru : 2015-07-30 Prudential Financial, Inc.-pru--// prudential : 2015-07-30 Prudential Financial, Inc.-prudential--// pub : 2013-12-12 United TLD Holdco Ltd.-pub--// pwc : 2015-10-29 PricewaterhouseCoopers LLP-pwc--// qpon : 2013-11-14 dotCOOL, Inc.-qpon--// quebec : 2013-12-19 PointQuébec Inc-quebec--// quest : 2015-03-26 Quest ION Limited-quest--// qvc : 2015-07-30 QVC, Inc.-qvc--// racing : 2014-12-04 Premier Registry Limited-racing--// radio : 2016-07-21 European Broadcasting Union (EBU)-radio--// raid : 2015-07-23 Johnson Shareholdings, Inc.-raid--// read : 2014-12-18 Amazon EU S.à r.l.-read--// realestate : 2015-09-11 dotRealEstate LLC-realestate--// realtor : 2014-05-29 Real Estate Domains LLC-realtor--// realty : 2015-03-19 Fegistry, LLC-realty--// recipes : 2013-10-17 Grand Island, LLC-recipes--// red : 2013-11-07 Afilias Limited-red--// redstone : 2014-10-31 Redstone Haute Couture Co., Ltd.-redstone--// redumbrella : 2015-03-26 Travelers TLD, LLC-redumbrella--// rehab : 2014-03-06 United TLD Holdco Ltd.-rehab--// reise : 2014-03-13-reise--// reisen : 2014-03-06 New Cypress, LLC-reisen--// reit : 2014-09-04 National Association of Real Estate Investment Trusts, Inc.-reit--// reliance : 2015-04-02 Reliance Industries Limited-reliance--// ren : 2013-12-12 Beijing Qianxiang Wangjing Technology Development Co., Ltd.-ren--// rent : 2014-12-04 DERRent, LLC-rent--// rentals : 2013-12-05 Big Hollow,LLC-rentals--// repair : 2013-11-07 Lone Sunset, LLC-repair--// report : 2013-12-05 Binky Glen, LLC-report--// republican : 2014-03-20 United TLD Holdco Ltd.-republican--// rest : 2013-12-19 Punto 2012 Sociedad Anonima Promotora de Inversion de Capital Variable-rest--// restaurant : 2014-07-03 Snow Avenue, LLC-restaurant--// review : 2014-11-20 dot Review Limited-review--// reviews : 2013-09-13-reviews--// rexroth : 2015-06-18 Robert Bosch GMBH-rexroth--// rich : 2013-11-21 I-Registry Ltd.-rich--// richardli : 2015-05-14 Pacific Century Asset Management (HK) Limited-richardli--// ricoh : 2014-11-20 Ricoh Company, Ltd.-ricoh--// rightathome : 2015-07-23 Johnson Shareholdings, Inc.-rightathome--// ril : 2015-04-02 Reliance Industries Limited-ril--// rio : 2014-02-27 Empresa Municipal de Informática SA - IPLANRIO-rio--// rip : 2014-07-10 United TLD Holdco Ltd.-rip--// rmit : 2015-11-19 Royal Melbourne Institute of Technology-rmit--// rocher : 2014-12-18 Ferrero Trading Lux S.A.-rocher--// rocks : 2013-11-14-rocks--// rodeo : 2013-12-19 Top Level Domain Holdings Limited-rodeo--// rogers : 2015-08-06 Rogers Communications Partnership-rogers--// room : 2014-12-18 Amazon EU S.à r.l.-room--// rsvp : 2014-05-08 Charleston Road Registry Inc.-rsvp--// ruhr : 2013-10-02 regiodot GmbH & Co. KG-ruhr--// run : 2015-03-19 Snow Park, LLC-run--// rwe : 2015-04-02 RWE AG-rwe--// ryukyu : 2014-01-09 BusinessRalliart Inc.-ryukyu--// saarland : 2013-12-12 dotSaarland GmbH-saarland--// safe : 2014-12-18 Amazon EU S.à r.l.-safe--// safety : 2015-01-08 Safety Registry Services, LLC.-safety--// sakura : 2014-12-18 SAKURA Internet Inc.-sakura--// sale : 2014-10-16-sale--// salon : 2014-12-11 Outer Orchard, LLC-salon--// samsclub : 2015-07-31 Wal-Mart Stores, Inc.-samsclub--// samsung : 2014-04-03 SAMSUNG SDS CO., LTD-samsung--// sandvik : 2014-11-13 Sandvik AB-sandvik--// sandvikcoromant : 2014-11-07 Sandvik AB-sandvikcoromant--// sanofi : 2014-10-09 Sanofi-sanofi--// sap : 2014-03-27 SAP AG-sap--// sapo : 2014-11-07 PT Comunicacoes S.A.-sapo--// sarl : 2014-07-03 Delta Orchard, LLC-sarl--// sas : 2015-04-02 Research IP LLC-sas--// save : 2015-06-25 Amazon EU S.à r.l.-save--// saxo : 2014-10-31 Saxo Bank A/S-saxo--// sbi : 2015-03-12 STATE BANK OF INDIA-sbi--// sbs : 2014-11-07 SPECIAL BROADCASTING SERVICE CORPORATION-sbs--// sca : 2014-03-13 SVENSKA CELLULOSA AKTIEBOLAGET SCA (publ)-sca--// scb : 2014-02-20 The Siam Commercial Bank Public Company Limited ("SCB")-scb--// schaeffler : 2015-08-06 Schaeffler Technologies AG & Co. KG-schaeffler--// schmidt : 2014-04-03 SALM S.A.S.-schmidt--// scholarships : 2014-04-24 Scholarships.com, LLC-scholarships--// school : 2014-12-18 Little Galley, LLC-school--// schule : 2014-03-06 Outer Moon, LLC-schule--// schwarz : 2014-09-18 Schwarz Domains und Services GmbH & Co. KG-schwarz--// science : 2014-09-11 dot Science Limited-science--// scjohnson : 2015-07-23 Johnson Shareholdings, Inc.-scjohnson--// scor : 2014-10-31 SCOR SE-scor--// scot : 2014-01-23 Dot Scot Registry Limited-scot--// search : 2016-06-09 Charleston Road Registry Inc.-search--// seat : 2014-05-22 SEAT, S.A. (Sociedad Unipersonal)-seat--// secure : 2015-08-27 Amazon EU S.à r.l.-secure--// security : 2015-05-14-security--// seek : 2014-12-04 Seek Limited-seek--// select : 2015-10-08 iSelect Ltd-select--// sener : 2014-10-24 Sener Ingeniería y Sistemas, S.A.-sener--// services : 2014-02-27 Fox Castle, LLC-services--// ses : 2015-07-23 SES-ses--// seven : 2015-08-06 Seven West Media Ltd-seven--// sew : 2014-07-17 SEW-EURODRIVE GmbH & Co KG-sew--// sex : 2014-11-13 ICM Registry SX LLC-sex--// sexy : 2013-09-11 Uniregistry, Corp.-sexy--// sfr : 2015-08-13 Societe Francaise du Radiotelephone - SFR-sfr--// shangrila : 2015-09-03 Shangri‐La International Hotel Management Limited-shangrila--// sharp : 2014-05-01 Sharp Corporation-sharp--// shaw : 2015-04-23 Shaw Cablesystems G.P.-shaw--// shell : 2015-07-30 Shell Information Technology International Inc-shell--// shia : 2014-09-04 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti.-shia--// shiksha : 2013-11-14 Afilias Limited-shiksha--// shoes : 2013-10-02 Binky Galley, LLC-shoes--// shop : 2016-04-08 GMO Registry, Inc.-shop--// shopping : 2016-03-31-shopping--// shouji : 2015-01-08 QIHOO 360 TECHNOLOGY CO. LTD.-shouji--// show : 2015-03-05 Snow Beach, LLC-show--// showtime : 2015-08-06 CBS Domains Inc.-showtime--// shriram : 2014-01-23 Shriram Capital Ltd.-shriram--// silk : 2015-06-25 Amazon EU S.à r.l.-silk--// sina : 2015-03-12 Sina Corporation-sina--// singles : 2013-08-27 Fern Madison, LLC-singles--// site : 2015-01-15 DotSite Inc.-site--// ski : 2015-04-09 STARTING DOT LIMITED-ski--// skin : 2015-01-15 L'Oréal-skin--// sky : 2014-06-19 Sky IP International Ltd, a company incorporated in England and Wales, operating via its registered Swiss branch-sky--// skype : 2014-12-18 Microsoft Corporation-skype--// sling : 2015-07-30 Hughes Satellite Systems Corporation-sling--// smart : 2015-07-09 Smart Communications, Inc. (SMART)-smart--// smile : 2014-12-18 Amazon EU S.à r.l.-smile--// sncf : 2015-02-19 Société Nationale des Chemins de fer Francais S N C F-sncf--// soccer : 2015-03-26 Foggy Shadow, LLC-soccer--// social : 2013-11-07 United TLD Holdco Ltd.-social--// softbank : 2015-07-02 SoftBank Corp.-softbank--// software : 2014-03-20-software--// sohu : 2013-12-19 Sohu.com Limited-sohu--// solar : 2013-11-07 Ruby Town, LLC-solar--// solutions : 2013-11-07 Silver Cover, LLC-solutions--// song : 2015-02-26 Amazon EU S.à r.l.-song--// sony : 2015-01-08 Sony Corporation-sony--// soy : 2014-01-23 Charleston Road Registry Inc.-soy--// space : 2014-04-03 DotSpace Inc.-space--// spiegel : 2014-02-05 SPIEGEL-Verlag Rudolf Augstein GmbH & Co. KG-spiegel--// spot : 2015-02-26 Amazon EU S.à r.l.-spot--// spreadbetting : 2014-12-11 IG Group Holdings PLC-spreadbetting--// srl : 2015-05-07 mySRL GmbH-srl--// srt : 2015-07-30 FCA US LLC.-srt--// stada : 2014-11-13 STADA Arzneimittel AG-stada--// staples : 2015-07-30 Staples, Inc.-staples--// star : 2015-01-08 Star India Private Limited-star--// starhub : 2015-02-05 StarHub Ltd-starhub--// statebank : 2015-03-12 STATE BANK OF INDIA-statebank--// statefarm : 2015-07-30 State Farm Mutual Automobile Insurance Company-statefarm--// statoil : 2014-12-04 Statoil ASA-statoil--// stc : 2014-10-09 Saudi Telecom Company-stc--// stcgroup : 2014-10-09 Saudi Telecom Company-stcgroup--// stockholm : 2014-12-18 Stockholms kommun-stockholm--// storage : 2014-12-22 Self Storage Company LLC-storage--// store : 2015-04-09 DotStore Inc.-store--// stream : 2016-01-08 dot Stream Limited-stream--// studio : 2015-02-11-studio--// study : 2014-12-11 OPEN UNIVERSITIES AUSTRALIA PTY LTD-study--// style : 2014-12-04 Binky Moon, LLC-style--// sucks : 2014-12-22 Vox Populi Registry Inc.-sucks--// supplies : 2013-12-19 Atomic Fields, LLC-supplies--// supply : 2013-12-19 Half Falls, LLC-supply--// support : 2013-10-24 Grand Orchard, LLC-support--// surf : 2014-01-09 Top Level Domain Holdings Limited-surf--// surgery : 2014-03-20 Tin Avenue, LLC-surgery--// suzuki : 2014-02-20 SUZUKI MOTOR CORPORATION-suzuki--// swatch : 2015-01-08 The Swatch Group Ltd-swatch--// swiftcover : 2015-07-23 Swiftcover Insurance Services Limited-swiftcover--// swiss : 2014-10-16 Swiss Confederation-swiss--// sydney : 2014-09-18 State of New South Wales, Department of Premier and Cabinet-sydney--// symantec : 2014-12-04 Symantec Corporation-symantec--// systems : 2013-11-07 Dash Cypress, LLC-systems--// tab : 2014-12-04 Tabcorp Holdings Limited-tab--// taipei : 2014-07-10 Taipei City Government-taipei--// talk : 2015-04-09 Amazon EU S.à r.l.-talk--// taobao : 2015-01-15 Alibaba Group Holding Limited-taobao--// target : 2015-07-31 Target Domain Holdings, LLC-target--// tatamotors : 2015-03-12 Tata Motors Ltd-tatamotors--// tatar : 2014-04-24 Limited Liability Company "Coordination Center of Regional Domain of Tatarstan Republic"-tatar--// tattoo : 2013-08-30 Uniregistry, Corp.-tattoo--// tax : 2014-03-20 Storm Orchard, LLC-tax--// taxi : 2015-03-19 Pine Falls, LLC-taxi--// tci : 2014-09-12 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti.-tci--// tdk : 2015-06-11 TDK Corporation-tdk--// team : 2015-03-05 Atomic Lake, LLC-team--// tech : 2015-01-30 Dot Tech LLC-tech--// technology : 2013-09-13 Auburn Falls-technology--// telecity : 2015-02-19 TelecityGroup International Limited-telecity--// telefonica : 2014-10-16 Telefónica S.A.-telefonica--// temasek : 2014-08-07 Temasek Holdings (Private) Limited-temasek--// tennis : 2014-12-04 Cotton Bloom, LLC-tennis--// teva : 2015-07-02 Teva Pharmaceutical Industries Limited-teva--// thd : 2015-04-02 Homer TLC, Inc.-thd--// theater : 2015-03-19 Blue Tigers, LLC-theater--// theatre : 2015-05-07-theatre--// theguardian : 2015-04-30 Guardian News and Media Limited-theguardian--// tiaa : 2015-07-23 Teachers Insurance and Annuity Association of America-tiaa--// tickets : 2015-02-05 Accent Media Limited-tickets--// tienda : 2013-11-14 Victor Manor, LLC-tienda--// tiffany : 2015-01-30 Tiffany and Company-tiffany--// tips : 2013-09-20 Corn Willow, LLC-tips--// tires : 2014-11-07 Dog Edge, LLC-tires--// tirol : 2014-04-24 punkt Tirol GmbH-tirol--// tjmaxx : 2015-07-16 The TJX Companies, Inc.-tjmaxx--// tjx : 2015-07-16 The TJX Companies, Inc.-tjx--// tkmaxx : 2015-07-16 The TJX Companies, Inc.-tkmaxx--// tmall : 2015-01-15 Alibaba Group Holding Limited-tmall--// today : 2013-09-20 Pearl Woods, LLC-today--// tokyo : 2013-11-13 GMO Registry, Inc.-tokyo--// tools : 2013-11-21 Pioneer North, LLC-tools--// top : 2014-03-20 Jiangsu Bangning Science & Technology Co.,Ltd.-top--// toray : 2014-12-18 Toray Industries, Inc.-toray--// toshiba : 2014-04-10 TOSHIBA Corporation-toshiba--// total : 2015-08-06 Total SA-total--// tours : 2015-01-22 Sugar Station, LLC-tours--// town : 2014-03-06 Koko Moon, LLC-town--// toyota : 2015-04-23 TOYOTA MOTOR CORPORATION-toyota--// toys : 2014-03-06 Pioneer Orchard, LLC-toys--// trade : 2014-01-23 Elite Registry Limited-trade--// trading : 2014-12-11 IG Group Holdings PLC-trading--// training : 2013-11-07 Wild Willow, LLC-training--// travelchannel : 2015-07-02 Lifestyle Domain Holdings, Inc.-travelchannel--// travelers : 2015-03-26 Travelers TLD, LLC-travelers--// travelersinsurance : 2015-03-26 Travelers TLD, LLC-travelersinsurance--// trust : 2014-10-16-trust--// trv : 2015-03-26 Travelers TLD, LLC-trv--// tube : 2015-06-11 Latin American Telecom LLC-tube--// tui : 2014-07-03 TUI AG-tui--// tunes : 2015-02-26 Amazon EU S.à r.l.-tunes--// tushu : 2014-12-18 Amazon EU S.à r.l.-tushu--// tvs : 2015-02-19 T V SUNDRAM IYENGAR & SONS LIMITED-tvs--// ubank : 2015-08-20 National Australia Bank Limited-ubank--// ubs : 2014-12-11 UBS AG-ubs--// uconnect : 2015-07-30 FCA US LLC.-uconnect--// unicom : 2015-10-15 China United Network Communications Corporation Limited-unicom--// university : 2014-03-06 Little Station, LLC-university--// uno : 2013-09-11 Dot Latin LLC-uno--// uol : 2014-05-01 UBN INTERNET LTDA.-uol--// ups : 2015-06-25 UPS Market Driver, Inc.-ups--// vacations : 2013-12-05 Atomic Tigers, LLC-vacations--// vana : 2014-12-11 Lifestyle Domain Holdings, Inc.-vana--// vanguard : 2015-09-03 The Vanguard Group, Inc.-vanguard--// vegas : 2014-01-16 Dot Vegas, Inc.-vegas--// ventures : 2013-08-27 Binky Lake, LLC-ventures--// verisign : 2015-08-13 VeriSign, Inc.-verisign--// versicherung : 2014-03-20 dotversicherung-registry GmbH-versicherung--// vet : 2014-03-06-vet--// viajes : 2013-10-17 Black Madison, LLC-viajes--// video : 2014-10-16-video--// vig : 2015-05-14 VIENNA INSURANCE GROUP AG Wiener Versicherung Gruppe-vig--// viking : 2015-04-02 Viking River Cruises (Bermuda) Ltd.-viking--// villas : 2013-12-05 New Sky, LLC-villas--// vin : 2015-06-18 Holly Shadow, LLC-vin--// vip : 2015-01-22 Minds + Machines Group Limited-vip--// virgin : 2014-09-25 Virgin Enterprises Limited-virgin--// visa : 2015-07-30 Visa Worldwide Pte. Limited-visa--// vision : 2013-12-05 Koko Station, LLC-vision--// vista : 2014-09-18 Vistaprint Limited-vista--// vistaprint : 2014-09-18 Vistaprint Limited-vistaprint--// viva : 2014-11-07 Saudi Telecom Company-viva--// vivo : 2015-07-31 Telefonica Brasil S.A.-vivo--// vlaanderen : 2014-02-06 DNS.be vzw-vlaanderen--// vodka : 2013-12-19 Top Level Domain Holdings Limited-vodka--// volkswagen : 2015-05-14 Volkswagen Group of America Inc.-volkswagen--// volvo : 2015-11-12 Volvo Holding Sverige Aktiebolag-volvo--// vote : 2013-11-21 Monolith Registry LLC-vote--// voting : 2013-11-13 Valuetainment Corp.-voting--// voto : 2013-11-21 Monolith Registry LLC-voto--// voyage : 2013-08-27 Ruby House, LLC-voyage--// vuelos : 2015-03-05 Travel Reservations SRL-vuelos--// wales : 2014-05-08 Nominet UK-wales--// walmart : 2015-07-31 Wal-Mart Stores, Inc.-walmart--// walter : 2014-11-13 Sandvik AB-walter--// wang : 2013-10-24 Zodiac Leo Limited-wang--// wanggou : 2014-12-18 Amazon EU S.à r.l.-wanggou--// warman : 2015-06-18 Weir Group IP Limited-warman--// watch : 2013-11-14 Sand Shadow, LLC-watch--// watches : 2014-12-22 Richemont DNS Inc.-watches--// weather : 2015-01-08 The Weather Channel, LLC-weather--// weatherchannel : 2015-03-12 The Weather Channel, LLC-weatherchannel--// webcam : 2014-01-23 dot Webcam Limited-webcam--// weber : 2015-06-04 Saint-Gobain Weber SA-weber--// website : 2014-04-03 DotWebsite Inc.-website--// wed : 2013-10-01 Atgron, Inc.-wed--// wedding : 2014-04-24 Top Level Domain Holdings Limited-wedding--// weibo : 2015-03-05 Sina Corporation--// weir : 2015-01-29 Weir Group IP Limited-weir--// whoswho : 2014-02-20 Who's Who Registry-whoswho--// wien : 2013-10-28 punkt.wien GmbH-wien--// wiki : 2013-11-07 Top Level Design, LLC-wiki--// williamhill : 2014-03-13 William Hill Organization Limited-williamhill--// win : 2014-11-20 First Registry Limited-win--// windows : 2014-12-18 Microsoft Corporation-windows--// wine : 2015-06-18 June Station, LLC-wine--// winners : 2015-07-16 The TJX Companies, Inc.-winners--// wme : 2014-02-13 William Morris Endeavor Entertainment, LLC-wme--// wolterskluwer : 2015-08-06 Wolters Kluwer N.V.-wolterskluwer--// woodside : 2015-07-09 Woodside Petroleum Limited-woodside--// work : 2013-12-19 Top Level Domain Holdings Limited-work--// works : 2013-11-14 Little Dynamite, LLC-works--// world : 2014-06-12 Bitter Fields, LLC-world--// wow : 2015-10-08 Amazon EU S.à r.l.-wow--// wtc : 2013-12-19 World Trade Centers Association, Inc.-wtc--// wtf : 2014-03-06 Hidden Way, LLC-wtf--// xbox : 2014-12-18 Microsoft Corporation-xbox--// xerox : 2014-10-24 Xerox DNHC LLC-xerox--// xfinity : 2015-07-09 Comcast IP Holdings I, LLC-xfinity--// xihuan : 2015-01-08 QIHOO 360 TECHNOLOGY CO. LTD.-xihuan--// xin : 2014-12-11 Elegant Leader Limited-xin--// xn--11b4c3d : 2015-01-15 VeriSign Sarl-कॉम--// xn--1ck2e1b : 2015-02-26 Amazon EU S.à r.l.-セール--// xn--1qqw23a : 2014-01-09 Guangzhou YU Wei Information Technology Co., Ltd.-佛山--// xn--30rr7y : 2014-06-12 Excellent First Limited-慈善--// xn--3bst00m : 2013-09-13 Eagle Horizon Limited-集团--// xn--3ds443g : 2013-09-08 TLD REGISTRY LIMITED-在线--// xn--3oq18vl8pn36a : 2015-07-02 Volkswagen (China) Investment Co., Ltd.-大众汽车--// xn--3pxu8k : 2015-01-15 VeriSign Sarl-点看--// xn--42c2d9a : 2015-01-15 VeriSign Sarl-คอม--// xn--45q11c : 2013-11-21 Zodiac Scorpio Limited-八卦--// xn--4gbrim : 2013-10-04 Suhub Electronic Establishment-موقع--// xn--4gq48lf9j : 2015-07-31 Wal-Mart Stores, Inc.-一号店--// xn--55qw42g : 2013-11-08 China Organizational Name Administration Center-公益--// xn--55qx5d : 2013-11-14 Computer Network Information Center of Chinese Academy of Sciences (China Internet Network Information Center)-公司--// xn--5su34j936bgsg : 2015-09-03 Shangri‐La International Hotel Management Limited-香格里拉--// xn--5tzm5g : 2014-12-22 Global Website TLD Asia Limited-网站--// xn--6frz82g : 2013-09-23 Afilias Limited-移动--// xn--6qq986b3xl : 2013-09-13 Tycoon Treasure Limited-我爱你--// xn--80adxhks : 2013-12-19 Foundation for Assistance for Internet Technologies and Infrastructure Development (FAITID)-москва--// xn--80aqecdr1a : 2015-10-21 Pontificium Consilium de Comunicationibus Socialibus (PCCS) (Pontifical Council for Social Communication)-католик--// xn--80asehdb : 2013-07-14 CORE Association-онлайн--// xn--80aswg : 2013-07-14 CORE Association-сайт--// xn--8y0a063a : 2015-03-26 China United Network Communications Corporation Limited-联通--// xn--9dbq2a : 2015-01-15 VeriSign Sarl-קום--// xn--9et52u : 2014-06-12 RISE VICTORY LIMITED-时尚--// xn--9krt00a : 2015-03-12 Sina Corporation-微博--// xn--b4w605ferd : 2014-08-07 Temasek Holdings (Private) Limited-淡马锡--// xn--bck1b9a5dre4c : 2015-02-26 Amazon EU S.à r.l.-ファッション--// xn--c1avg : 2013-11-14 Public Interest Registry-орг--// xn--c2br7g : 2015-01-15 VeriSign Sarl-नेट--// xn--cck2b3b : 2015-02-26 Amazon EU S.à r.l.-ストア--// xn--cg4bki : 2013-09-27 SAMSUNG SDS CO., LTD-삼성--// xn--czr694b : 2014-01-16 Dot Trademark TLD Holding Company Limted-商标--// xn--czrs0t : 2013-12-19 Wild Island, LLC-商店--// xn--czru2d : 2013-11-21 Zodiac Capricorn Limited-商城--// xn--d1acj3b : 2013-11-20 The Foundation for Network Initiatives “The Smart Internet”-дети--// xn--eckvdtc9d : 2014-12-18 Amazon EU S.à r.l.-ポイント--// xn--efvy88h : 2014-08-22 Xinhua News Agency Guangdong Branch 新华通讯社广东分社-新闻--// xn--estv75g : 2015-02-19 Industrial and Commercial Bank of China Limited-工行--// xn--fct429k : 2015-04-09 Amazon EU S.à r.l.-家電--// xn--fhbei : 2015-01-15 VeriSign Sarl-كوم--// xn--fiq228c5hs : 2013-09-08 TLD REGISTRY LIMITED-中文网--// xn--fiq64b : 2013-10-14 CITIC Group Corporation-中信--// xn--fjq720a : 2014-05-22 Will Bloom, LLC-娱乐--// xn--flw351e : 2014-07-31 Charleston Road Registry Inc.-谷歌--// xn--fzys8d69uvgm : 2015-05-14 PCCW Enterprises Limited-電訊盈科--// xn--g2xx48c : 2015-01-30 Minds + Machines Group Limited-购物--// xn--gckr3f0f : 2015-02-26 Amazon EU S.à r.l.-クラウド--// xn--gk3at1e : 2015-10-08 Amazon EU S.à r.l.-通販--// xn--hxt814e : 2014-05-15 Zodiac Libra Limited-网店--// xn--i1b6b1a6a2e : 2013-11-14 Public Interest Registry-संगठन--// xn--imr513n : 2014-12-11 Dot Trademark TLD Holding Company Limted-餐厅--// xn--io0a7i : 2013-11-14 Computer Network Information Center of Chinese Academy of Sciences (China Internet Network Information Center)-网络--// xn--j1aef : 2015-01-15 VeriSign Sarl-ком--// xn--jlq61u9w7b : 2015-01-08 Nokia Corporation-诺基亚--// xn--jvr189m : 2015-02-26 Amazon EU S.à r.l.-食品--// xn--kcrx77d1x4a : 2014-11-07 Koninklijke Philips N.V.-飞利浦--// xn--kpu716f : 2014-12-22 Richemont DNS Inc.-手表--// xn--kput3i : 2014-02-13 Beijing RITT-Net Technology Development Co., Ltd-手机--// xn--mgba3a3ejt : 2014-11-20 Aramco Services Company-ارامكو--// xn--mgba7c0bbn0a : 2015-05-14 Crescent Holding GmbH-العليان--// xn--mgbaakc7dvf : 2015-09-03 Emirates Telecommunications Corporation (trading as Etisalat)-اتصالات--// xn--mgbab2bd : 2013-10-31 CORE Association-بازار--// xn--mgbb9fbpob : 2014-12-18 GreenTech Consultancy Company W.L.L.-موبايلي--// xn--mgbca7dzdo : 2015-07-30 Abu Dhabi Systems and Information Centre-ابوظبي--// xn--mgbi4ecexp : 2015-10-21 Pontificium Consilium de Comunicationibus Socialibus (PCCS) (Pontifical Council for Social Communication)-كاثوليك--// xn--mgbt3dhd : 2014-09-04 Asia Green IT System Bilgisayar San. ve Tic. Ltd. Sti.-همراه--// xn--mk1bu44c : 2015-01-15 VeriSign Sarl-닷컴--// xn--mxtq1m : 2014-03-06 Net-Chinese Co., Ltd.-政府--// xn--ngbc5azd : 2013-07-13 International Domain Registry Pty. Ltd.-شبكة--// xn--ngbe9e0a : 2014-12-04 Kuwait Finance House-بيتك--// xn--ngbrx : 2015-11-12 League of Arab States-عرب--// xn--nqv7f : 2013-11-14 Public Interest Registry-机构--// xn--nqv7fs00ema : 2013-11-14 Public Interest Registry-组织机构--// xn--nyqy26a : 2014-11-07 Stable Tone Limited-健康--// xn--p1acf : 2013-12-12 Rusnames Limited-рус--// xn--pbt977c : 2014-12-22 Richemont DNS Inc.-珠宝--// xn--pssy2u : 2015-01-15 VeriSign Sarl-大拿--// xn--q9jyb4c : 2013-09-17 Charleston Road Registry Inc.-みんな--// xn--qcka1pmc : 2014-07-31 Charleston Road Registry Inc.-グーグル--// xn--rhqv96g : 2013-09-11 Stable Tone Limited-世界--// xn--rovu88b : 2015-02-26 Amazon EU S.à r.l.-書籍--// xn--ses554g : 2014-01-16-网址--// xn--t60b56a : 2015-01-15 VeriSign Sarl-닷넷--// xn--tckwe : 2015-01-15 VeriSign Sarl-コム--// xn--tiq49xqyj : 2015-10-21 Pontificium Consilium de Comunicationibus Socialibus (PCCS) (Pontifical Council for Social Communication)-天主教--// xn--unup4y : 2013-07-14 Spring Fields, LLC-游戏--// xn--vermgensberater-ctb : 2014-06-23 Deutsche Vermögensberatung Aktiengesellschaft DVAG-vermögensberater--// xn--vermgensberatung-pwb : 2014-06-23 Deutsche Vermögensberatung Aktiengesellschaft DVAG-vermögensberatung--// xn--vhquv : 2013-08-27 Dash McCook, LLC-企业--// xn--vuq861b : 2014-10-16 Beijing Tele-info Network Technology Co., Ltd.-信息--// xn--w4r85el8fhu5dnra : 2015-04-30 Kerry Trading Co. Limited-嘉里大酒店--// xn--w4rs40l : 2015-07-30 Kerry Trading Co. Limited-嘉里--// xn--xhq521b : 2013-11-14 Guangzhou YU Wei Information Technology Co., Ltd.-广东--// xn--zfr164b : 2013-11-08 China Organizational Name Administration Center-政务--// xperia : 2015-05-14 Sony Mobile Communications AB-xperia--// xyz : 2013-12-05 XYZ.COM LLC-xyz--// yachts : 2014-01-09 DERYachts, LLC-yachts--// yahoo : 2015-04-02 Yahoo! Domain Services Inc.-yahoo--// yamaxun : 2014-12-18 Amazon EU S.à r.l.-yamaxun--// yandex : 2014-04-10 YANDEX, LLC-yandex--// yodobashi : 2014-11-20 YODOBASHI CAMERA CO.,LTD.-yodobashi--// yoga : 2014-05-29 Top Level Domain Holdings Limited-yoga--// yokohama : 2013-12-12 GMO Registry, Inc.-yokohama--// you : 2015-04-09 Amazon EU S.à r.l.-you--// youtube : 2014-05-01 Charleston Road Registry Inc.-youtube--// yun : 2015-01-08 QIHOO 360 TECHNOLOGY CO. LTD.-yun--// zappos : 2015-06-25 Amazon EU S.à r.l.-zappos--// zara : 2014-11-07 Industria de Diseño Textil, S.A. (INDITEX, S.A.)-zara--// zero : 2014-12-18 Amazon EU S.à r.l.-zero--// zip : 2014-05-08 Charleston Road Registry Inc.-zip--// zippo : 2015-07-02 Zadco Company-zippo--// zone : 2013-11-14 Outer Falls, LLC-zone--// zuerich : 2014-11-07 Kanton Zürich (Canton of Zurich)-zuerich---// ===END ICANN DOMAINS===-// ===BEGIN PRIVATE DOMAINS===-// (Note: these are in alphabetical order by company name)--// Agnat sp. z o.o. : https://domena.pl-// Submitted by Przemyslaw Plewa <[email protected]>-beep.pl--// Alces Software Ltd : http://alces-software.com-// Submitted by Mark J. Titorenko <[email protected]>-*.compute.estate-*.alces.network--// alwaysdata : https://www.alwaysdata.com-// Submitted by Cyril <[email protected]>-*.alwaysdata.net--// Amazon CloudFront : https://aws.amazon.com/cloudfront/-// Submitted by Donavan Miller <[email protected]>-cloudfront.net--// Amazon Elastic Compute Cloud: https://aws.amazon.com/ec2/-// Submitted by Luke Wells <[email protected]>-*.compute.amazonaws.com-*.compute-1.amazonaws.com-*.compute.amazonaws.com.cn-us-east-1.amazonaws.com--// Amazon Elastic Beanstalk : https://aws.amazon.com/elasticbeanstalk/-// Submitted by Luke Wells <[email protected]>-elasticbeanstalk.cn-north-1.amazonaws.com.cn-*.elasticbeanstalk.com--// Amazon Elastic Load Balancing : https://aws.amazon.com/elasticloadbalancing/-// Submitted by Luke Wells <[email protected]>-*.elb.amazonaws.com-*.elb.amazonaws.com.cn--// Amazon S3 : https://aws.amazon.com/s3/-// Submitted by Luke Wells <[email protected]>-*.s3.amazonaws.com-s3-ap-northeast-1.amazonaws.com-s3-ap-northeast-2.amazonaws.com-s3-ap-south-1.amazonaws.com-s3-ap-southeast-1.amazonaws.com-s3-ap-southeast-2.amazonaws.com-s3-ca-central-1.amazonaws.com-s3-eu-central-1.amazonaws.com-s3-eu-west-1.amazonaws.com-s3-external-1.amazonaws.com-s3-fips-us-gov-west-1.amazonaws.com-s3-sa-east-1.amazonaws.com-s3-us-gov-west-1.amazonaws.com-s3-us-east-2.amazonaws.com-s3-us-west-1.amazonaws.com-s3-us-west-2.amazonaws.com-s3.ap-northeast-2.amazonaws.com-s3.ap-south-1.amazonaws.com-s3.cn-north-1.amazonaws.com.cn-s3.ca-central-1.amazonaws.com-s3.eu-central-1.amazonaws.com-s3.us-east-2.amazonaws.com-s3.dualstack.ap-northeast-1.amazonaws.com-s3.dualstack.ap-northeast-2.amazonaws.com-s3.dualstack.ap-south-1.amazonaws.com-s3.dualstack.ap-southeast-1.amazonaws.com-s3.dualstack.ap-southeast-2.amazonaws.com-s3.dualstack.ca-central-1.amazonaws.com-s3.dualstack.eu-central-1.amazonaws.com-s3.dualstack.eu-west-1.amazonaws.com-s3.dualstack.sa-east-1.amazonaws.com-s3.dualstack.us-east-1.amazonaws.com-s3.dualstack.us-east-2.amazonaws.com-s3-website-us-east-1.amazonaws.com-s3-website-us-west-1.amazonaws.com-s3-website-us-west-2.amazonaws.com-s3-website-ap-northeast-1.amazonaws.com-s3-website-ap-southeast-1.amazonaws.com-s3-website-ap-southeast-2.amazonaws.com-s3-website-eu-west-1.amazonaws.com-s3-website-sa-east-1.amazonaws.com-s3-website.ap-northeast-2.amazonaws.com-s3-website.ap-south-1.amazonaws.com-s3-website.ca-central-1.amazonaws.com-s3-website.eu-central-1.amazonaws.com-s3-website.us-east-2.amazonaws.com--// Amune : https://amune.org/-// Submitted by Team Amune <[email protected]>-t3l3p0rt.net-tele.amune.org--// Aptible : https://www.aptible.com/-// Submitted by Thomas Orozco <[email protected]>-on-aptible.com--// Asociación Amigos de la Informática "Euskalamiga" : http://encounter.eus/-// Submitted by Hector Martin <[email protected]>-user.party.eus--// Association potager.org : https://potager.org/-// Submitted by Lunar <[email protected]>-pimienta.org-poivron.org-potager.org-sweetpepper.org--// ASUSTOR Inc. : http://www.asustor.com-// Submitted by Vincent Tseng <[email protected]>-myasustor.com--// AVM : https://avm.de-// Submitted by Andreas Weise <[email protected]>-myfritz.net--// backplane : https://www.backplane.io-// Submitted by Anthony Voutas <[email protected]>-backplaneapp.io--// BetaInABox-// Submitted by Adrian <[email protected]>-betainabox.com--// BinaryLane : http://www.binarylane.com-// Submitted by Nathan O'Sullivan <[email protected]>-bnr.la--// Boxfuse : https://boxfuse.com-// Submitted by Axel Fontaine <[email protected]>-boxfuse.io--// BrowserSafetyMark-// Submitted by Dave Tharp <[email protected]>-browsersafetymark.io--// callidomus: https://www.callidomus.com/-// Submitted by Marcus Popp <[email protected]>-mycd.eu--// CentralNic : http://www.centralnic.com/names/domains-// Submitted by registry <[email protected]>-ae.org-ar.com-br.com-cn.com-com.de-com.se-de.com-eu.com-gb.com-gb.net-hu.com-hu.net-jp.net-jpn.com-kr.com-mex.com-no.com-qc.com-ru.com-sa.com-se.com-se.net-uk.com-uk.net-us.com-uy.com-za.bz-za.com--// Africa.com Web Solutions Ltd : https://registry.africa.com-// Submitted by Gavin Brown <[email protected]>-africa.com--// iDOT Services Limited : http://www.domain.gr.com-// Submitted by Gavin Brown <[email protected]>-gr.com--// Radix FZC : http://domains.in.net-// Submitted by Gavin Brown <[email protected]>-in.net--// US REGISTRY LLC : http://us.org-// Submitted by Gavin Brown <[email protected]>-us.org--// co.com Registry, LLC : https://registry.co.com-// Submitted by Gavin Brown <[email protected]>-co.com--// c.la : http://www.c.la/-c.la--// certmgr.org : https://certmgr.org-// Submitted by B. Blechschmidt <[email protected]>-certmgr.org--// Citrix : https://citrix.com-// Submitted by Alex Stoddard <[email protected]>-xenapponazure.com--// ClearVox : http://www.clearvox.nl/-// Submitted by Leon Rowland <[email protected]>-virtueeldomein.nl--// cloudControl : https://www.cloudcontrol.com/-// Submitted by Tobias Wilken <[email protected]>-cloudcontrolled.com-cloudcontrolapp.com--// co.ca : http://registry.co.ca/-co.ca--// i-registry s.r.o. : http://www.i-registry.cz/-// Submitted by Martin Semrad <[email protected]>-co.cz--// CDN77.com : http://www.cdn77.com-// Submitted by Jan Krpes <[email protected]>-c.cdn77.org-cdn77-ssl.net-r.cdn77.net-rsc.cdn77.org-ssl.origin.cdn77-secure.org--// Cloud DNS Ltd : http://www.cloudns.net-// Submitted by Aleksander Hristov <[email protected]>-cloudns.asia-cloudns.biz-cloudns.club-cloudns.cc-cloudns.eu-cloudns.in-cloudns.info-cloudns.org-cloudns.pro-cloudns.pw-cloudns.us--// CoDNS B.V.-co.nl-co.no--// Commerce Guys, SAS-// Submitted by Damien Tournoud <[email protected]>-*.platform.sh--// COSIMO GmbH http://www.cosimo.de-// Submitted by Rene Marticke <[email protected]>-dyn.cosidns.de-dynamisches-dns.de-dnsupdater.de-internet-dns.de-l-o-g-i-n.de-dynamic-dns.info-feste-ip.net-knx-server.net-static-access.net--// Craynic, s.r.o. : http://www.craynic.com/-// Submitted by Ales Krajnik <[email protected]>-realm.cz--// Cryptonomic : https://cryptonomic.net/-// Submitted by Andrew Cady <[email protected]>-*.cryptonomic.net--// Cupcake : https://cupcake.io/-// Submitted by Jonathan Rudenberg <[email protected]>-cupcake.is--// cyon GmbH : https://www.cyon.ch/-// Submitted by Dominic Luechinger <[email protected]>-cyon.link-cyon.site--// Daplie, Inc : https://daplie.com-// Submitted by AJ ONeal <[email protected]>-daplie.me--// Dansk.net : http://www.dansk.net/-// Submitted by Anani Voule <[email protected]>-biz.dk-co.dk-firm.dk-reg.dk-store.dk--// deSEC : https://desec.io/-// Submitted by Peter Thomassen <[email protected]>-dedyn.io--// DNShome : https://www.dnshome.de/-// Submitted by Norbert Auler <[email protected]>-dnshome.de--// DreamHost : http://www.dreamhost.com/-// Submitted by Andrew Farmer <[email protected]>-dreamhosters.com--// Drobo : http://www.drobo.com/-// Submitted by Ricardo Padilha <[email protected]>-mydrobo.com--// Drud Holdings, LLC. : https://www.drud.com/-// Submitted by Kevin Bridges <[email protected]>-drud.io-drud.us--// DuckDNS : http://www.duckdns.org/-// Submitted by Richard Harper <[email protected]>-duckdns.org--// dy.fi : http://dy.fi/-// Submitted by Heikki Hannikainen <[email protected]>-dy.fi-tunk.org--// DynDNS.com : http://www.dyndns.com/services/dns/dyndns/-dyndns-at-home.com-dyndns-at-work.com-dyndns-blog.com-dyndns-free.com-dyndns-home.com-dyndns-ip.com-dyndns-mail.com-dyndns-office.com-dyndns-pics.com-dyndns-remote.com-dyndns-server.com-dyndns-web.com-dyndns-wiki.com-dyndns-work.com-dyndns.biz-dyndns.info-dyndns.org-dyndns.tv-at-band-camp.net-ath.cx-barrel-of-knowledge.info-barrell-of-knowledge.info-better-than.tv-blogdns.com-blogdns.net-blogdns.org-blogsite.org-boldlygoingnowhere.org-broke-it.net-buyshouses.net-cechire.com-dnsalias.com-dnsalias.net-dnsalias.org-dnsdojo.com-dnsdojo.net-dnsdojo.org-does-it.net-doesntexist.com-doesntexist.org-dontexist.com-dontexist.net-dontexist.org-doomdns.com-doomdns.org-dvrdns.org-dyn-o-saur.com-dynalias.com-dynalias.net-dynalias.org-dynathome.net-dyndns.ws-endofinternet.net-endofinternet.org-endoftheinternet.org-est-a-la-maison.com-est-a-la-masion.com-est-le-patron.com-est-mon-blogueur.com-for-better.biz-for-more.biz-for-our.info-for-some.biz-for-the.biz-forgot.her.name-forgot.his.name-from-ak.com-from-al.com-from-ar.com-from-az.net-from-ca.com-from-co.net-from-ct.com-from-dc.com-from-de.com-from-fl.com-from-ga.com-from-hi.com-from-ia.com-from-id.com-from-il.com-from-in.com-from-ks.com-from-ky.com-from-la.net-from-ma.com-from-md.com-from-me.org-from-mi.com-from-mn.com-from-mo.com-from-ms.com-from-mt.com-from-nc.com-from-nd.com-from-ne.com-from-nh.com-from-nj.com-from-nm.com-from-nv.com-from-ny.net-from-oh.com-from-ok.com-from-or.com-from-pa.com-from-pr.com-from-ri.com-from-sc.com-from-sd.com-from-tn.com-from-tx.com-from-ut.com-from-va.com-from-vt.com-from-wa.com-from-wi.com-from-wv.com-from-wy.com-ftpaccess.cc-fuettertdasnetz.de-game-host.org-game-server.cc-getmyip.com-gets-it.net-go.dyndns.org-gotdns.com-gotdns.org-groks-the.info-groks-this.info-ham-radio-op.net-here-for-more.info-hobby-site.com-hobby-site.org-home.dyndns.org-homedns.org-homeftp.net-homeftp.org-homeip.net-homelinux.com-homelinux.net-homelinux.org-homeunix.com-homeunix.net-homeunix.org-iamallama.com-in-the-band.net-is-a-anarchist.com-is-a-blogger.com-is-a-bookkeeper.com-is-a-bruinsfan.org-is-a-bulls-fan.com-is-a-candidate.org-is-a-caterer.com-is-a-celticsfan.org-is-a-chef.com-is-a-chef.net-is-a-chef.org-is-a-conservative.com-is-a-cpa.com-is-a-cubicle-slave.com-is-a-democrat.com-is-a-designer.com-is-a-doctor.com-is-a-financialadvisor.com-is-a-geek.com-is-a-geek.net-is-a-geek.org-is-a-green.com-is-a-guru.com-is-a-hard-worker.com-is-a-hunter.com-is-a-knight.org-is-a-landscaper.com-is-a-lawyer.com-is-a-liberal.com-is-a-libertarian.com-is-a-linux-user.org-is-a-llama.com-is-a-musician.com-is-a-nascarfan.com-is-a-nurse.com-is-a-painter.com-is-a-patsfan.org-is-a-personaltrainer.com-is-a-photographer.com-is-a-player.com-is-a-republican.com-is-a-rockstar.com-is-a-socialist.com-is-a-soxfan.org-is-a-student.com-is-a-teacher.com-is-a-techie.com-is-a-therapist.com-is-an-accountant.com-is-an-actor.com-is-an-actress.com-is-an-anarchist.com-is-an-artist.com-is-an-engineer.com-is-an-entertainer.com-is-by.us-is-certified.com-is-found.org-is-gone.com-is-into-anime.com-is-into-cars.com-is-into-cartoons.com-is-into-games.com-is-leet.com-is-lost.org-is-not-certified.com-is-saved.org-is-slick.com-is-uberleet.com-is-very-bad.org-is-very-evil.org-is-very-good.org-is-very-nice.org-is-very-sweet.org-is-with-theband.com-isa-geek.com-isa-geek.net-isa-geek.org-isa-hockeynut.com-issmarterthanyou.com-isteingeek.de-istmein.de-kicks-ass.net-kicks-ass.org-knowsitall.info-land-4-sale.us-lebtimnetz.de-leitungsen.de-likes-pie.com-likescandy.com-merseine.nu-mine.nu-misconfused.org-mypets.ws-myphotos.cc-neat-url.com-office-on-the.net-on-the-web.tv-podzone.net-podzone.org-readmyblog.org-saves-the-whales.com-scrapper-site.net-scrapping.cc-selfip.biz-selfip.com-selfip.info-selfip.net-selfip.org-sells-for-less.com-sells-for-u.com-sells-it.net-sellsyourhome.org-servebbs.com-servebbs.net-servebbs.org-serveftp.net-serveftp.org-servegame.org-shacknet.nu-simple-url.com-space-to-rent.com-stuff-4-sale.org-stuff-4-sale.us-teaches-yoga.com-thruhere.net-traeumtgerade.de-webhop.biz-webhop.info-webhop.net-webhop.org-worse-than.tv-writesthisblog.com--// ddnss.de : https://www.ddnss.de/-// Submitted by Robert Niedziela <[email protected]>-ddnss.de-dyn.ddnss.de-dyndns.ddnss.de-dyndns1.de-dyn-ip24.de-home-webserver.de-dyn.home-webserver.de-myhome-server.de-ddnss.org--// dynv6 : https://dynv6.com-// Submitted by Dominik Menke <[email protected]> 2016-01-18-dynv6.net--// E4YOU spol. s.r.o. : https://e4you.cz/-// Submitted by Vladimir Dudr <[email protected]>-e4.cz--// Enonic : http://enonic.com/-// Submitted by Erik Kaareng-Sunde <[email protected]>-enonic.io-customer.enonic.io--// EU.org https://eu.org/-// Submitted by Pierre Beyssac <[email protected]>-eu.org-al.eu.org-asso.eu.org-at.eu.org-au.eu.org-be.eu.org-bg.eu.org-ca.eu.org-cd.eu.org-ch.eu.org-cn.eu.org-cy.eu.org-cz.eu.org-de.eu.org-dk.eu.org-edu.eu.org-ee.eu.org-es.eu.org-fi.eu.org-fr.eu.org-gr.eu.org-hr.eu.org-hu.eu.org-ie.eu.org-il.eu.org-in.eu.org-int.eu.org-is.eu.org-it.eu.org-jp.eu.org-kr.eu.org-lt.eu.org-lu.eu.org-lv.eu.org-mc.eu.org-me.eu.org-mk.eu.org-mt.eu.org-my.eu.org-net.eu.org-ng.eu.org-nl.eu.org-no.eu.org-nz.eu.org-paris.eu.org-pl.eu.org-pt.eu.org-q-a.eu.org-ro.eu.org-ru.eu.org-se.eu.org-si.eu.org-sk.eu.org-tr.eu.org-uk.eu.org-us.eu.org--// Evennode : http://www.evennode.com/-// Submitted by Michal Kralik <[email protected]>-eu-1.evennode.com-eu-2.evennode.com-us-1.evennode.com-us-2.evennode.com--// Facebook, Inc.-// Submitted by Peter Ruibal <[email protected]>-apps.fbsbx.com--// Fastly Inc. : http://www.fastly.com/-// Submitted by Fastly Security <[email protected]>-map.fastly.net-a.prod.fastly.net-global.prod.fastly.net-a.ssl.fastly.net-b.ssl.fastly.net-global.ssl.fastly.net-fastlylb.net-map.fastlylb.net--// Featherhead : https://featherhead.xyz/-// Submitted by Simon Menke <[email protected]>-fhapp.xyz--// Firebase, Inc.-// Submitted by Chris Raynor <[email protected]>-firebaseapp.com--// Flynn : https://flynn.io-// Submitted by Jonathan Rudenberg <[email protected]>-flynnhub.com--// Freebox : http://www.freebox.fr-// Submitted by Romain Fliedel <[email protected]>-freebox-os.com-freeboxos.com-fbx-os.fr-fbxos.fr-freebox-os.fr-freeboxos.fr--// Fusion Intranet : https://www.fusion-intranet.com-// Submitted by Matthias Burtscher <[email protected]>-myfusion.cloud--// Futureweb OG : http://www.futureweb.at-// Submitted by Andreas Schnederle-Wagner <[email protected]>-futurehosting.at-futuremailing.at-*.ex.ortsinfo.at-*.kunden.ortsinfo.at-*.statics.cloud--// GDS : https://www.gov.uk/service-manual/operations/operating-servicegovuk-subdomains-// Submitted by David Illsley <[email protected]>-service.gov.uk--// GitHub, Inc.-// Submitted by Patrick Toomey <[email protected]>-github.io-githubusercontent.com-githubcloud.com-*.api.githubcloud.com-*.ext.githubcloud.com-gist.githubcloud.com-*.githubcloudusercontent.com--// GitLab, Inc.-// Submitted by Alex Hanselka <[email protected]>-gitlab.io--// UKHomeOffice : https://www.gov.uk/government/organisations/home-office-// Submitted by Jon Shanks <[email protected]>-homeoffice.gov.uk--// GlobeHosting, Inc.-// Submitted by Zoltan Egresi <[email protected]>-ro.im-shop.ro--// GoIP DNS Services : http://www.goip.de-// Submitted by Christian Poulter <[email protected]>-goip.de--// Google, Inc.-// Submitted by Eduardo Vela <[email protected]>-*.0emm.com-appspot.com-blogspot.ae-blogspot.al-blogspot.am-blogspot.ba-blogspot.be-blogspot.bg-blogspot.bj-blogspot.ca-blogspot.cf-blogspot.ch-blogspot.cl-blogspot.co.at-blogspot.co.id-blogspot.co.il-blogspot.co.ke-blogspot.co.nz-blogspot.co.uk-blogspot.co.za-blogspot.com-blogspot.com.ar-blogspot.com.au-blogspot.com.br-blogspot.com.by-blogspot.com.co-blogspot.com.cy-blogspot.com.ee-blogspot.com.eg-blogspot.com.es-blogspot.com.mt-blogspot.com.ng-blogspot.com.tr-blogspot.com.uy-blogspot.cv-blogspot.cz-blogspot.de-blogspot.dk-blogspot.fi-blogspot.fr-blogspot.gr-blogspot.hk-blogspot.hr-blogspot.hu-blogspot.ie-blogspot.in-blogspot.is-blogspot.it-blogspot.jp-blogspot.kr-blogspot.li-blogspot.lt-blogspot.lu-blogspot.md-blogspot.mk-blogspot.mr-blogspot.mx-blogspot.my-blogspot.nl-blogspot.no-blogspot.pe-blogspot.pt-blogspot.qa-blogspot.re-blogspot.ro-blogspot.rs-blogspot.ru-blogspot.se-blogspot.sg-blogspot.si-blogspot.sk-blogspot.sn-blogspot.td-blogspot.tw-blogspot.ug-blogspot.vn-cloudfunctions.net-codespot.com-googleapis.com-googlecode.com-pagespeedmobilizer.com-publishproxy.com-withgoogle.com-withyoutube.com--// Hashbang : https://hashbang.sh-hashbang.sh--// Hasura : https://hasura.io-// Submitted by Shahidh K Muhammed <[email protected]>-hasura-app.io--// Hepforge : https://www.hepforge.org-// Submitted by David Grellscheid <[email protected]>-hepforge.org--// Heroku : https://www.heroku.com/-// Submitted by Tom Maher <[email protected]>-herokuapp.com-herokussl.com--// iki.fi-// Submitted by Hannu Aronsson <[email protected]>-iki.fi--// info.at : http://www.info.at/-biz.at-info.at--// Interlegis : http://www.interlegis.leg.br-// Submitted by Gabriel Ferreira <[email protected]>-ac.leg.br-al.leg.br-am.leg.br-ap.leg.br-ba.leg.br-ce.leg.br-df.leg.br-es.leg.br-go.leg.br-ma.leg.br-mg.leg.br-ms.leg.br-mt.leg.br-pa.leg.br-pb.leg.br-pe.leg.br-pi.leg.br-pr.leg.br-rj.leg.br-rn.leg.br-ro.leg.br-rr.leg.br-rs.leg.br-sc.leg.br-se.leg.br-sp.leg.br-to.leg.br--// Joyent : https://www.joyent.com/-// Submitted by Brian Bennett <[email protected]>-*.triton.zone-*.cns.joyent.com--// JS.ORG : http://dns.js.org-// Submitted by Stefan Keim <[email protected]>-js.org--// Keyweb AG : https://www.keyweb.de-// Submitted by Martin Dannehl <[email protected]>-keymachine.de--// KnightPoint Systems, LLC : http://www.knightpoint.com/-// Submitted by Roy Keene <[email protected]>-knightpoint.systems--// .KRD : http://nic.krd/data/krd/Registration%20Policy.pdf-co.krd-edu.krd--// Magento Commerce-// Submitted by Damien Tournoud <[email protected]>-*.magentosite.cloud--// Meteor Development Group : https://www.meteor.com/hosting-// Submitted by Pierre Carrier <[email protected]>-meteorapp.com-eu.meteorapp.com--// Michau Enterprises Limited : http://www.co.pl/-co.pl--// Microsoft : http://microsoft.com-// Submitted by Barry Dorrans <[email protected]>-azurewebsites.net-azure-mobile.net-cloudapp.net--// Mozilla Foundation : https://mozilla.org/-// Submitted by glob <[email protected]>-bmoattachments.org--// Neustar Inc.-// Submitted by Trung Tran <[email protected]>-4u.com--// ngrok : https://ngrok.com/-// Submitted by Alan Shreve <[email protected]>-ngrok.io--// NFSN, Inc. : https://www.NearlyFreeSpeech.NET/-// Submitted by Jeff Wheelhouse <[email protected]>-nfshost.com--// nsupdate.info : https://www.nsupdate.info/-// Submitted by Thomas Waldmann <[email protected]>-nsupdate.info-nerdpol.ovh--// No-IP.com : https://noip.com/-// Submitted by Deven Reza <[email protected]>-blogsyte.com-brasilia.me-cable-modem.org-ciscofreak.com-collegefan.org-couchpotatofries.org-damnserver.com-ddns.me-ditchyourip.com-dnsfor.me-dnsiskinky.com-dvrcam.info-dynns.com-eating-organic.net-fantasyleague.cc-geekgalaxy.com-golffan.us-health-carereform.com-homesecuritymac.com-homesecuritypc.com-hopto.me-ilovecollege.info-loginto.me-mlbfan.org-mmafan.biz-myactivedirectory.com-mydissent.net-myeffect.net-mymediapc.net-mypsx.net-mysecuritycamera.com-mysecuritycamera.net-mysecuritycamera.org-net-freaks.com-nflfan.org-nhlfan.net-no-ip.ca-no-ip.co.uk-no-ip.net-noip.us-onthewifi.com-pgafan.net-point2this.com-pointto.us-privatizehealthinsurance.net-quicksytes.com-read-books.org-securitytactics.com-serveexchange.com-servehumour.com-servep2p.com-servesarcasm.com-stufftoread.com-ufcfan.org-unusualperson.com-workisboring.com-3utilities.com-bounceme.net-ddns.net-ddnsking.com-gotdns.ch-hopto.org-myftp.biz-myftp.org-myvnc.com-no-ip.biz-no-ip.info-no-ip.org-noip.me-redirectme.net-servebeer.com-serveblog.net-servecounterstrike.com-serveftp.com-servegame.com-servehalflife.com-servehttp.com-serveirc.com-serveminecraft.net-servemp3.com-servepics.com-servequake.com-sytes.net-webhop.me-zapto.org--// NYC.mn : http://www.information.nyc.mn-// Submitted by Matthew Brown <[email protected]>-nyc.mn--// One Fold Media : http://www.onefoldmedia.com/-// Submitted by Eddie Jones <[email protected]>-nid.io--// OpenCraft GmbH : http://opencraft.com/-// Submitted by Sven Marnach <[email protected]>-opencraft.hosting--// Opera Software, A.S.A.-// Submitted by Yngve Pettersen <[email protected]>-operaunite.com--// OutSystems-// Submitted by Duarte Santos <[email protected]>-outsystemscloud.com--// OwnProvider : http://www.ownprovider.com-// Submitted by Jan Moennich <[email protected]>-ownprovider.com--// oy.lc-// Submitted by Charly Coste <[email protected]>-oy.lc--// Pagefog : https://pagefog.com/-// Submitted by Derek Myers <[email protected]>-pgfog.com--// Pagefront : https://www.pagefronthq.com/-// Submitted by Jason Kriss <[email protected]>-pagefrontapp.com--// .pl domains (grandfathered)-art.pl-gliwice.pl-krakow.pl-poznan.pl-wroc.pl-zakopane.pl--// Pantheon Systems, Inc. : https://pantheon.io/-// Submitted by Gary Dylina <[email protected]>-pantheonsite.io-gotpantheon.com--// Peplink | Pepwave : http://peplink.com/-// Submitted by Steve Leung <[email protected]>-mypep.link--// Planet-Work : https://www.planet-work.com/-// Submitted by Frédéric VANNIÈRE <[email protected]>-on-web.fr--// prgmr.com : https://prgmr.com/-// Submitted by Sarah Newman <[email protected]>-xen.prgmr.com--// priv.at : http://www.nic.priv.at/-// Submitted by registry <[email protected]>-priv.at--// Protonet GmbH : http://protonet.io-// Submitted by Martin Meier <[email protected]>-protonet.io--// Publication Presse Communication SARL : https://ppcom.fr-// Submitted by Yaacov Akiba Slama <[email protected]>-chirurgiens-dentistes-en-france.fr--// QA2-// Submitted by Daniel Dent (https://www.danieldent.com/)-qa2.com--// QNAP System Inc : https://www.qnap.com-// Submitted by Nick Chang <[email protected]>-dev-myqnapcloud.com-alpha-myqnapcloud.com-myqnapcloud.com--// Rackmaze LLC : https://www.rackmaze.com-// Submitted by Kirill Pertsev <[email protected]>-rackmaze.com-rackmaze.net--// Red Hat, Inc. OpenShift : https://openshift.redhat.com/-// Submitted by Tim Kramer <[email protected]>-rhcloud.com--// RethinkDB : https://www.rethinkdb.com/-// Submitted by Chris Kastorff <[email protected]>-hzc.io--// Revitalised Limited : http://www.revitalised.co.uk-// Submitted by Jack Price <[email protected]>-wellbeingzone.eu-ptplus.fit-wellbeingzone.co.uk--// Sandstorm Development Group, Inc. : https://sandcats.io/-// Submitted by Asheesh Laroia <[email protected]>-sandcats.io--// SBE network solutions GmbH : https://www.sbe.de/-// Submitted by Norman Meilick <[email protected]>-logoip.de-logoip.com--// Securepoint GmbH : https://www.securepoint.de-// Submitted by Erik Anders <[email protected]>-firewall-gateway.com-firewall-gateway.de-my-gateway.de-my-router.de-spdns.de-spdns.eu-firewall-gateway.net-my-firewall.org-myfirewall.org-spdns.org--// Service Online LLC : http://drs.ua/-// Submitted by Serhii Bulakh <[email protected]>-biz.ua-co.ua-pp.ua--// ShiftEdit : https://shiftedit.net/-// Submitted by Adam Jimenez <[email protected]>-shiftedit.io--// Shopblocks : http://www.shopblocks.com/-// Submitted by Alex Bowers <[email protected]>-myshopblocks.com--// SinaAppEngine : http://sae.sina.com.cn/-// Submitted by SinaAppEngine <[email protected]>-1kapp.com-appchizi.com-applinzi.com-sinaapp.com-vipsinaapp.com--// Skyhat : http://www.skyhat.io-// Submitted by Shante Adam <[email protected]>-bounty-full.com-alpha.bounty-full.com-beta.bounty-full.com--// staticland : https://static.land-// Submitted by Seth Vincent <[email protected]>-static.land-dev.static.land-sites.static.land--// SourceLair PC : https://www.sourcelair.com-// Submitted by Antonis Kalipetis <[email protected]>-apps.lair.io-*.stolos.io--// SpaceKit : https://www.spacekit.io/-// Submitted by Reza Akhavan <[email protected]>-spacekit.io--// Stackspace : https://www.stackspace.io/-// Submitted by Lina He <[email protected]>-stackspace.space--// Synology, Inc. : https://www.synology.com/-// Submitted by Rony Weng <[email protected]>-diskstation.me-dscloud.biz-dscloud.me-dscloud.mobi-dsmynas.com-dsmynas.net-dsmynas.org-familyds.com-familyds.net-familyds.org-i234.me-myds.me-synology.me--// TAIFUN Software AG : http://taifun-software.de-// Submitted by Bjoern Henke <[email protected]>-taifun-dns.de--// TASK geographical domains (www.task.gda.pl/uslugi/dns)-gda.pl-gdansk.pl-gdynia.pl-med.pl-sopot.pl--// TownNews.com : http://www.townnews.com-// Submitted by Dustin Ward <[email protected]>-bloxcms.com-townnews-staging.com--// TransIP : htts://www.transip.nl-// Submitted by Rory Breuk <[email protected]>-*.transurl.be-*.transurl.eu-*.transurl.nl--// TuxFamily : http://tuxfamily.org-// Submitted by TuxFamily administrators <[email protected]>-tuxfamily.org--// TwoDNS : https://www.twodns.de/-// Submitted by TwoDNS-Support <[email protected]>-dd-dns.de-diskstation.eu-diskstation.org-dray-dns.de-draydns.de-dyn-vpn.de-dynvpn.de-mein-vigor.de-my-vigor.de-my-wan.de-syno-ds.de-synology-diskstation.de-synology-ds.de--// UDR Limited : http://www.udr.hk.com-// Submitted by registry <[email protected]>-hk.com-hk.org-ltd.hk-inc.hk--// .US-// Submitted by Ed Moore <[email protected]>-lib.de.us--// Viprinet Europe GmbH : http://www.viprinet.com-// Submitted by Simon Kissel <[email protected]>-router.management--// Western Digital Technologies, Inc : https://www.wdc.com-// Submitted by Jung Jin <[email protected]>-remotewd.com--// Wikimedia Labs : https://wikitech.wikimedia.org-// Submitted by Yuvi Panda <[email protected]>-wmflabs.org--// Yola : https://www.yola.com/-// Submitted by Stefano Rivera <[email protected]>-yolasite.com--// Yombo : https://yombo.net-// Submitted by Mitch Schwenk <[email protected]>-ybo.faith-yombo.me-homelink.one-ybo.party-ybo.review-ybo.science-ybo.trade--// ZaNiC : http://www.za.net/-// Submitted by registry <[email protected]>-za.net-za.org--// Zeit, Inc. : https://zeit.domains/-// Submitted by Olli Vanhoja <[email protected]>-now.sh--// 1GB LLC : https://www.1gb.ua/-// Submitted by 1GB LLC <[email protected]>-cc.ua-inf.ua-ltd.ua--// ===END PRIVATE DOMAINS===diff --git a/ext/whois/parser.py b/ext/whois/parser.pydeleted file mode 100644index 6de11146..00000000--- a/ext/whois/parser.py+++ /dev/null@@ -1,1584 +0,0 @@-# -*- coding: utf-8 -*---# parser.py - Module for parsing whois response data-# Copyright (c) 2008 Andrey Petrov-#-# This module is part of pywhois and is released under-# the MIT license: http://www.opensource.org/licenses/mit-license.php--from __future__ import absolute_import-from __future__ import unicode_literals-from __future__ import print_function-from __future__ import division-from future import standard_library-standard_library.install_aliases()-from builtins import *-from builtins import str-from past.builtins import basestring--import json-from datetime import datetime-import re-try:- import dateutil.parser as dp- from .time_zones import tz_data- DATEUTIL = True-except ImportError:- DATEUTIL = False--EMAIL_REGEX = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"--KNOWN_FORMATS = [- '%d-%b-%Y', # 02-jan-2000- '%d-%B-%Y', # 11-February-2000- '%d-%m-%Y', # 20-10-2000- '%Y-%m-%d', # 2000-01-02- '%d.%m.%Y', # 2.1.2000- '%Y.%m.%d', # 2000.01.02- '%Y/%m/%d', # 2000/01/02- '%Y%m%d', # 20170209- '%d/%m/%Y', # 02/01/2013- '%Y. %m. %d.', # 2000. 01. 02.- '%Y.%m.%d %H:%M:%S', # 2014.03.08 10:28:24- '%d-%b-%Y %H:%M:%S %Z', # 24-Jul-2009 13:20:03 UTC- '%a %b %d %H:%M:%S %Z %Y', # Tue Jun 21 23:59:59 GMT 2011- '%Y-%m-%dT%H:%M:%SZ', # 2007-01-26T19:10:31Z- '%Y-%m-%dT%H:%M:%S.%fZ', # 2018-12-01T16:17:30.568Z- '%Y-%m-%dT%H:%M:%S%z', # 2013-12-06T08:17:22-0800- '%Y-%m-%d %H:%M:%SZ', # 2000-08-22 18:55:20Z- '%Y-%m-%d %H:%M:%S', # 2000-08-22 18:55:20- '%d %b %Y %H:%M:%S', # 08 Apr 2013 05:44:00- '%d/%m/%Y %H:%M:%S', # 23/04/2015 12:00:07 EEST- '%d/%m/%Y %H:%M:%S %Z', # 23/04/2015 12:00:07 EEST- '%d/%m/%Y %H:%M:%S.%f %Z', # 23/04/2015 12:00:07.619546 EEST- '%B %d %Y', # August 14 2017- '%d.%m.%Y %H:%M:%S', # 08.03.2014 10:28:24-]---class PywhoisError(Exception):- pass---def datetime_parse(s):- for known_format in KNOWN_FORMATS:- try:- s = datetime.strptime(s, known_format)- break- except ValueError as e:- pass # Wrong format, keep trying- return s--def cast_date(s, dayfirst=False, yearfirst=False):- """Convert any date string found in WHOIS to a datetime object.- """- if DATEUTIL:- try:- return dp.parse(- s,- tzinfos=tz_data,- dayfirst=dayfirst,- yearfirst=yearfirst- ).replace(tzinfo=None)- except Exception:- return datetime_parse(s)- else:- return datetime_parse(s)---class WhoisEntry(dict):- """Base class for parsing a Whois entries.- """- # regular expressions to extract domain data from whois profile- # child classes will override this- _regex = {- 'domain_name': 'Domain Name: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'whois_server': 'Whois Server: *(.+)',- 'referral_url': 'Referral URL: *(.+)', # http url of whois_server- 'updated_date': 'Updated Date: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Expir\w+ Date: *(.+)',- 'name_servers': 'Name Server: *(.+)', # list of name servers- 'status': 'Status: *(.+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email s- 'dnssec': 'dnssec: *([\S]+)',- 'name': 'Registrant Name: *(.+)',- 'org': 'Registrant\s*Organization: *(.+)',- 'address': 'Registrant Street: *(.+)',- 'city': 'Registrant City: *(.+)',- 'state': 'Registrant State/Province: *(.+)',- 'zipcode': 'Registrant Postal Code: *(.+)',- 'country': 'Registrant Country: *(.+)',- }- dayfirst = False- yearfirst = False-- def __init__(self, domain, text, regex=None):- if 'This TLD has no whois server, but you can access the whois database at' in text:- raise PywhoisError(text)- else:- self.domain = domain- self.text = text- if regex is not None:- self._regex = regex- self.parse()-- def parse(self):- """The first time an attribute is called it will be calculated here.- The attribute is then set to be accessed directly by subsequent calls.- """- for attr, regex in list(self._regex.items()):- if regex:- values = []- for data in re.findall(regex, self.text, re.IGNORECASE):- matches = data if isinstance(data, tuple) else [data]- for value in matches:- value = self._preprocess(attr, value)- if value and value not in values:- # avoid duplicates- values.append(value)- if values and attr in ('registrar', 'whois_server', 'referral_url'):- values = values[-1] # ignore junk- if len(values) == 1:- values = values[0]- elif not values:- values = None-- self[attr] = values-- def _preprocess(self, attr, value):- value = value.strip()- if value and isinstance(value, basestring) and not value.isdigit() and '_date' in attr:- # try casting to date format- value = cast_date(- value,- dayfirst=self.dayfirst,- yearfirst=self.yearfirst)- return value-- def __setitem__(self, name, value):- super(WhoisEntry, self).__setitem__(name, value)--- def __getattr__(self, name):- return self.get(name)--- def __str__(self):- handler = lambda e: str(e)- return json.dumps(self, indent=2, default=handler)-- def __getstate__(self):- return self.__dict__-- def __setstate__(self, state):- self.__dict__ = state-- @staticmethod- def load(domain, text):- """Given whois output in ``text``, return an instance of ``WhoisEntry``- that represents its parsed contents.- """- if text.strip() == 'No whois server is known for this kind of object.':- raise PywhoisError(text)-- if domain.endswith('.com'):- return WhoisCom(domain, text)- elif domain.endswith('.net'):- return WhoisNet(domain, text)- elif domain.endswith('.org'):- return WhoisOrg(domain, text)- elif domain.endswith('.name'):- return WhoisName(domain, text)- elif domain.endswith('.me'):- return WhoisMe(domain, text)- elif domain.endswith('.au'):- return WhoisAU(domain, text)- elif domain.endswith('.ru'):- return WhoisRu(domain, text)- elif domain.endswith('.us'):- return WhoisUs(domain, text)- elif domain.endswith('.uk'):- return WhoisUk(domain, text)- elif domain.endswith('.fr'):- return WhoisFr(domain, text)- elif domain.endswith('.nl'):- return WhoisNl(domain, text)- elif domain.endswith('.fi'):- return WhoisFi(domain, text)- elif domain.endswith('.hr'):- return WhoisHr(domain, text)- elif domain.endswith('.jp'):- return WhoisJp(domain, text)- elif domain.endswith('.pl'):- return WhoisPl(domain, text)- elif domain.endswith('.br'):- return WhoisBr(domain, text)- elif domain.endswith('.eu'):- return WhoisEu(domain, text)- elif domain.endswith('.ee'):- return WhoisEe(domain, text)- elif domain.endswith('.kr'):- return WhoisKr(domain, text)- elif domain.endswith('.pt'):- return WhoisPt(domain, text)- elif domain.endswith('.bg'):- return WhoisBg(domain, text)- elif domain.endswith('.de'):- return WhoisDe(domain, text)- elif domain.endswith('.at'):- return WhoisAt(domain, text)- elif domain.endswith('.ca'):- return WhoisCa(domain, text)- elif domain.endswith('.be'):- return WhoisBe(domain, text)- elif domain.endswith('.рф'):- return WhoisRf(domain, text)- elif domain.endswith('.info'):- return WhoisInfo(domain, text)- elif domain.endswith('.su'):- return WhoisSu(domain, text)- elif domain.endswith('.kg'):- return WhoisKg(domain, text)- elif domain.endswith('.io'):- return WhoisIo(domain, text)- elif domain.endswith('.biz'):- return WhoisBiz(domain, text)- elif domain.endswith('.mobi'):- return WhoisMobi(domain, text)- elif domain.endswith('.ch'):- return WhoisChLi(domain, text)- elif domain.endswith('.li'):- return WhoisChLi(domain, text)- elif domain.endswith('.id'):- return WhoisID(domain, text)- elif domain.endswith('.sk'):- return WhoisSK(domain, text)- elif domain.endswith('.se'):- return WhoisSe(domain, text)- elif domain.endswith('.nu'):- return WhoisSe(domain, text)- elif domain.endswith('.is'):- return WhoisIs(domain, text)- elif domain.endswith('.dk'):- return WhoisDk(domain, text)- elif domain.endswith('.it'):- return WhoisIt(domain, text)- elif domain.endswith('.ai'):- return WhoisAi(domain, text)- elif domain.endswith('.il'):- return WhoisIl(domain, text)- elif domain.endswith('.in'):- return WhoisIn(domain, text)- elif domain.endswith('.cat'):- return WhoisCat(domain, text)- elif domain.endswith('.ie'):- return WhoisIe(domain, text)- elif domain.endswith('.nz'):- return WhoisNz(domain, text)- elif domain.endswith('.space'):- return WhoisSpace(domain, text)- elif domain.endswith('.lu'):- return WhoisLu(domain, text)- elif domain.endswith('.cz'):- return WhoisCz(domain, text)- elif domain.endswith('.online'):- return WhoisOnline(domain, text)- elif domain.endswith('.cn'):- return WhoisCn(domain, text)- elif domain.endswith('.app'):- return WhoisApp(domain, text)- else:- return WhoisEntry(domain, text)---class WhoisSpace(WhoisEntry):- """Whois parser for .space domains- """- def __init__(self, domain, text):- if 'No match for "' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text)---class WhoisCom(WhoisEntry):- """Whois parser for .com domains- """- def __init__(self, domain, text):- if 'No match for "' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text)---class WhoisNet(WhoisEntry):- """Whois parser for .net domains- """- def __init__(self, domain, text):- if 'No match for "' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text)---class WhoisOrg(WhoisEntry):- """Whois parser for .org domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'whois_server': 'Whois Server: *(.+)', # empty usually- 'referral_url': 'Referral URL: *(.+)', # http url of whois_server: empty usually- 'updated_date': 'Updated Date: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Registry Expiry Date: *(.+)',- 'name_servers': 'Name Server: *(.+)', # list of name servers- 'status': 'Status: *(.+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email addresses- }-- def __init__(self, domain, text):- if text.strip() == 'NOT FOUND':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text)---class WhoisRu(WhoisEntry):- """Whois parser for .ru domains- """- regex = {- 'domain_name': 'domain: *(.+)',- 'registrar': 'registrar: *(.+)',- 'creation_date': 'created: *(.+)',- 'expiration_date': 'paid-till: *(.+)',- 'updated_date': None,- 'name_servers': 'nserver: *(.+)', # list of name servers- 'status': 'state: *(.+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email addresses- 'org': 'org: *(.+)'- }-- def __init__(self, domain, text):- if text.strip() == 'No entries found':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisNl(WhoisEntry):- """Whois parser for .nl domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'expiration_date': None,- 'updated_date': None,- 'creation_date': None,- 'status': 'Status: *(.+)', # list of statuses- 'name': None,- 'address': None,- 'zip_code': None,- 'city': None,- 'country': None- }-- def __init__(self, domain, text):- if text.endswith('is free'):- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)-- match = re.compile('Registrar:(.*?)DNSSEC', re.DOTALL).search(text)- if match:- lines = [line.strip() for line in match.groups()[0].strip().splitlines()]- self['name'] = lines[0]- self['address'] = lines[1]- if len(lines) == 4:- self['zip_code'], _, self['city'] = lines[2].partition(' ')- self['country'] = lines[-1]---class WhoisName(WhoisEntry):- """Whois parser for .name domains- """- regex = {- 'domain_name_id': 'Domain Name ID: *(.+)',- 'domain_name': 'Domain Name: *(.+)',- 'registrar_id': 'Sponsoring Registrar ID: *(.+)',- 'registrar': 'Sponsoring Registrar: *(.+)',- 'registrant_id': 'Registrant ID: *(.+)',- 'admin_id': 'Admin ID: *(.+)',- 'technical_id': 'Tech ID: *(.+)',- 'billing_id': 'Billing ID: *(.+)',- 'creation_date': 'Created On: *(.+)',- 'expiration_date': 'Expires On: *(.+)',- 'updated_date': 'Updated On: *(.+)',- 'name_server_ids': 'Name Server ID: *(.+)', # list of name server ids- 'name_servers': 'Name Server: *(.+)', # list of name servers- 'status': 'Domain Status: *(.+)', # list of statuses- }-- def __init__(self, domain, text):- if 'No match for ' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisUs(WhoisEntry):- """Whois parser for .us domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'domain__id': 'Domain ID: *(.+)',- 'registrar': 'Sponsoring Registrar: *(.+)',- 'registrar_id': 'Sponsoring Registrar IANA ID: *(.+)',- 'registrar_url': 'Registrar URL \(registration services\): *(.+)',- 'status': 'Domain Status: *(.+)', # list of statuses- 'registrant_id': 'Registrant ID: *(.+)',- 'registrant_name': 'Registrant Name: *(.+)',- 'registrant_address1': 'Registrant Address1: *(.+)',- 'registrant_address2': 'Registrant Address2: *(.+)',- 'registrant_city': 'Registrant City: *(.+)',- 'registrant_state_province': 'Registrant State/Province: *(.+)',- 'registrant_postal_code': 'Registrant Postal Code: *(.+)',- 'registrant_country': 'Registrant Country: *(.+)',- 'registrant_country_code': 'Registrant Country Code: *(.+)',- 'registrant_phone_number': 'Registrant Phone Number: *(.+)',- 'registrant_email': 'Registrant Email: *(.+)',- 'registrant_application_purpose': 'Registrant Application Purpose: *(.+)',- 'registrant_nexus_category': 'Registrant Nexus Category: *(.+)',- 'admin_id': 'Administrative Contact ID: *(.+)',- 'admin_name': 'Administrative Contact Name: *(.+)',- 'admin_address1': 'Administrative Contact Address1: *(.+)',- 'admin_address2': 'Administrative Contact Address2: *(.+)',- 'admin_city': 'Administrative Contact City: *(.+)',- 'admin_state_province': 'Administrative Contact State/Province: *(.+)',- 'admin_postal_code': 'Administrative Contact Postal Code: *(.+)',- 'admin_country': 'Administrative Contact Country: *(.+)',- 'admin_country_code': 'Administrative Contact Country Code: *(.+)',- 'admin_phone_number': 'Administrative Contact Phone Number: *(.+)',- 'admin_email': 'Administrative Contact Email: *(.+)',- 'admin_application_purpose': 'Administrative Application Purpose: *(.+)',- 'admin_nexus_category': 'Administrative Nexus Category: *(.+)',- 'billing_id': 'Billing Contact ID: *(.+)',- 'billing_name': 'Billing Contact Name: *(.+)',- 'billing_address1': 'Billing Contact Address1: *(.+)',- 'billing_address2': 'Billing Contact Address2: *(.+)',- 'billing_city': 'Billing Contact City: *(.+)',- 'billing_state_province': 'Billing Contact State/Province: *(.+)',- 'billing_postal_code': 'Billing Contact Postal Code: *(.+)',- 'billing_country': 'Billing Contact Country: *(.+)',- 'billing_country_code': 'Billing Contact Country Code: *(.+)',- 'billing_phone_number': 'Billing Contact Phone Number: *(.+)',- 'billing_email': 'Billing Contact Email: *(.+)',- 'billing_application_purpose': 'Billing Application Purpose: *(.+)',- 'billing_nexus_category': 'Billing Nexus Category: *(.+)',- 'tech_id': 'Technical Contact ID: *(.+)',- 'tech_name': 'Technical Contact Name: *(.+)',- 'tech_address1': 'Technical Contact Address1: *(.+)',- 'tech_address2': 'Technical Contact Address2: *(.+)',- 'tech_city': 'Technical Contact City: *(.+)',- 'tech_state_province': 'Technical Contact State/Province: *(.+)',- 'tech_postal_code': 'Technical Contact Postal Code: *(.+)',- 'tech_country': 'Technical Contact Country: *(.+)',- 'tech_country_code': 'Technical Contact Country Code: *(.+)',- 'tech_phone_number': 'Technical Contact Phone Number: *(.+)',- 'tech_email': 'Technical Contact Email: *(.+)',- 'tech_application_purpose': 'Technical Application Purpose: *(.+)',- 'tech_nexus_category': 'Technical Nexus Category: *(.+)',- 'name_servers': 'Name Server: *(.+)', # list of name servers- 'created_by_registrar': 'Created by Registrar: *(.+)',- 'last_updated_by_registrar': 'Last Updated by Registrar: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Registry Expiry Date: *(.+)',- 'updated_date': 'Updated Date: *(.+)',- }-- def __init__(self, domain, text):- if 'Not found:' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisPl(WhoisEntry):- """Whois parser for .pl domains- """- regex = {- 'domain_name': 'DOMAIN NAME: *(.+)\n',- 'registrar': 'REGISTRAR:\n\s*(.+)',- 'registrar_url': 'URL: *(.+)', # not available- 'status': 'Registration status:\n\s*(.+)', # not available- 'registrant_name': 'Registrant:\n\s*(.+)', # not available- 'creation_date': 'created: *(.+)\n',- 'expiration_date': 'renewal date: *(.+)',- 'updated_date': 'last modified: *(.+)\n',- }-- def __init__(self, domain, text):- if 'No information available about domain name' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisCa(WhoisEntry):- """Whois parser for .ca domains- """- regex = {- 'domain_name': 'Domain name: *(.+)',- 'registrant_name': '(?<!Domain) Name: *(.+)',- 'registrant_number': 'Number: *(.+)\n',- 'domain_status': 'Domain status: *(.+)',- 'emails': 'Email: *(.+)',- 'updated_date': 'Updated Date: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Expiry Date: *(.+)',- 'phone': 'Phone: *(.+)',- 'fax': 'Fax: *(.+)',- 'dnssec': 'dnssec: *([\S]+)'- }-- def __init__(self, domain, text):- if 'Domain status: available' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisMe(WhoisEntry):- """Whois parser for .me domains- """- regex = {- 'domain_id': 'Registry Domain ID:(.+)',- 'domain_name': 'Domain Name:(.+)',- 'creation_date': 'Creation Date:(.+)',- 'updated_date': 'Updated Date:(.+)',- 'expiration_date': 'Registry Expiry Date: (.+)',- 'registrar': 'Registrar:(.+)',- 'status': 'Domain Status:(.+)', # list of statuses- 'registrant_id': 'Registrant ID:(.+)',- 'registrant_name': 'Registrant Name:(.+)',- 'registrant_org': 'Registrant Organization:(.+)',- 'registrant_address': 'Registrant Address:(.+)',- 'registrant_address2': 'Registrant Address2:(.+)',- 'registrant_address3': 'Registrant Address3:(.+)',- 'registrant_city': 'Registrant City:(.+)',- 'registrant_state_province': 'Registrant State/Province:(.+)',- 'registrant_country': 'Registrant Country/Economy:(.+)',- 'registrant_postal_code': 'Registrant Postal Code:(.+)',- 'registrant_phone': 'Registrant Phone:(.+)',- 'registrant_phone_ext': 'Registrant Phone Ext\.:(.+)',- 'registrant_fax': 'Registrant FAX:(.+)',- 'registrant_fax_ext': 'Registrant FAX Ext\.:(.+)',- 'registrant_email': 'Registrant E-mail:(.+)',- 'admin_id': 'Admin ID:(.+)',- 'admin_name': 'Admin Name:(.+)',- 'admin_org': 'Admin Organization:(.+)',- 'admin_address': 'Admin Address:(.+)',- 'admin_address2': 'Admin Address2:(.+)',- 'admin_address3': 'Admin Address3:(.+)',- 'admin_city': 'Admin City:(.+)',- 'admin_state_province': 'Admin State/Province:(.+)',- 'admin_country': 'Admin Country/Economy:(.+)',- 'admin_postal_code': 'Admin Postal Code:(.+)',- 'admin_phone': 'Admin Phone:(.+)',- 'admin_phone_ext': 'Admin Phone Ext\.:(.+)',- 'admin_fax': 'Admin FAX:(.+)',- 'admin_fax_ext': 'Admin FAX Ext\.:(.+)',- 'admin_email': 'Admin E-mail:(.+)',- 'tech_id': 'Tech ID:(.+)',- 'tech_name': 'Tech Name:(.+)',- 'tech_org': 'Tech Organization:(.+)',- 'tech_address': 'Tech Address:(.+)',- 'tech_address2': 'Tech Address2:(.+)',- 'tech_address3': 'Tech Address3:(.+)',- 'tech_city': 'Tech City:(.+)',- 'tech_state_province': 'Tech State/Province:(.+)',- 'tech_country': 'Tech Country/Economy:(.+)',- 'tech_postal_code': 'Tech Postal Code:(.+)',- 'tech_phone': 'Tech Phone:(.+)',- 'tech_phone_ext': 'Tech Phone Ext\.:(.+)',- 'tech_fax': 'Tech FAX:(.+)',- 'tech_fax_ext': 'Tech FAX Ext\.:(.+)',- 'tech_email': 'Tech E-mail:(.+)',- 'name_servers': 'Nameservers:(.+)', # list of name servers- }-- def __init__(self, domain, text):- if 'NOT FOUND' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisUk(WhoisEntry):- """Whois parser for .uk domains- """- regex = {- 'domain_name': 'Domain name:\s*(.+)',- 'registrar': 'Registrar:\s*(.+)',- 'registrar_url': 'URL:\s*(.+)',- 'status': 'Registration status:\s*(.+)', # list of statuses- 'registrant_name': 'Registrant:\s*(.+)',- 'creation_date': 'Registered on:\s*(.+)',- 'expiration_date': 'Expiry date:\s*(.+)',- 'updated_date': 'Last updated:\s*(.+)',- 'name_servers': 'Name servers:\s*(.+)',- }-- def __init__(self, domain, text):- if 'No match for ' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisFr(WhoisEntry):- """Whois parser for .fr domains- """- regex = {- 'domain_name': 'domain: *(.+)',- 'registrar': 'registrar: *(.+)',- 'creation_date': 'created: *(.+)',- 'expiration_date': 'Expir\w+ Date:\s?(.+)',- 'name_servers': 'nserver: *(.+)', # list of name servers- 'status': 'status: *(.+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email addresses- 'updated_date': 'last-update: *(.+)',- }-- def __init__(self, domain, text):- if 'No entries found' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisFi(WhoisEntry):- """Whois parser for .fi domains- """- regex = {- 'domain_name': 'domain\.*: *([\S]+)',- 'name': 'descr\.*: *([\S\ ]+)',- 'address': 'address\.*: *([\S\ ]+)',- 'phone': 'phone\.*: *([\S\ ]+)',- 'status': 'status\.*: *([\S]+)', # list of statuses- 'creation_date': 'created\.*: *([\S]+)',- 'updated_date': 'modified\.*: *([\S]+)',- 'expiration_date': 'expires\.*: *([\S]+)',- 'name_servers': 'nserver\.*: *([\S]+) \[\S+\]', # list of name servers- 'name_server_statuses': 'nserver\.*: *([\S]+) \[\S+\]', # list of name servers and statuses- 'dnssec': 'dnssec\.*: *([\S]+)',-- }-- def __init__(self, domain, text):- if 'Domain not ' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisJp(WhoisEntry):- """Whois parser for .jp domains- """- regex = {- 'domain_name': 'a\. \[Domain Name\]\s*(.+)',- 'registrant_org': 'g\. \[Organization\](.+)',- 'creation_date': r'\[Registered Date\]\s*(.+)',- 'name_servers': 'p\. \[Name Server\]\s*(.+)', # list of name servers- 'updated_date': '\[Last Update\]\s?(.+)',- 'status': '\[State\]\s*(.+)', # list of statuses- }-- def __init__(self, domain, text):- if 'No match!!' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisAU(WhoisEntry):- """Whois parser for .au domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)\n',- 'last_modified': 'Last Modified: *(.+)\n',- 'registrar': 'Registrar Name: *(.+)\n',- 'status': 'Status: *(.+)',- 'registrant_name': 'Registrant: *(.+)',- 'name_servers': 'Name Server: *(.+)',- }-- def __init__(self, domain, text):- if text.strip() == 'No Data Found':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisEu(WhoisEntry):- """Whois parser for .eu domains- """- regex = {- 'domain_name': r'Domain: *([^\n\r]+)',- 'tech_name': r'Technical: *Name: *([^\n\r]+)',- 'tech_org': r'Technical: *Name: *[^\n\r]+\s*Organisation: *([^\n\r]+)',- 'tech_phone': r'Technical: *Name: *[^\n\r]+\s*Organisation: *[^\n\r]+\s*Language: *[^\n\r]+\s*Phone: *([^\n\r]+)',- 'tech_fax': r'Technical: *Name: *[^\n\r]+\s*Organisation: *[^\n\r]+\s*Language: *[^\n\r]+\s*Phone: *[^\n\r]+\s*Fax: *([^\n\r]+)',- 'tech_email': r'Technical: *Name: *[^\n\r]+\s*Organisation: *[^\n\r]+\s*Language: *[^\n\r]+\s*Phone: *[^\n\r]+\s*Fax: *[^\n\r]+\s*Email: *([^\n\r]+)',- 'registrar': r'Registrar: *Name: *([^\n\r]+)',- 'name_servers': r'Name servers:\s*(.+)', # list of name servers- }-- def __init__(self, domain, text):- if text.strip() == 'Status: AVAILABLE':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisEe(WhoisEntry):- """Whois parser for .ee domains- """- regex = {- 'domain_name': r'Domain: *[\n\r]+\s*name: *([^\n\r]+)',- 'status': r'Domain: *[\n\r]+\s*name: *[^\n\r]+\sstatus: *([^\n\r]+)',- 'registered': r'Domain: *[\n\r]+\s*name: *[^\n\r]+\sstatus: *[^\n\r]+\sregistered: *([^\n\r]+)',- 'changed': r'Domain: *[\n\r]+\s*name: *[^\n\r]+\sstatus: *[^\n\r]+\sregistered: *[^\n\r]+\schanged: *([^\n\r]+)',- 'expire': r'Domain: *[\n\r]+\s*name: *[^\n\r]+\sstatus: *[^\n\r]+\sregistered: *[^\n\r]+\schanged: *[^\n\r]+\sexpire: *([^\n\r]+)',-- # 'tech_name': r'Technical: *Name: *([^\n\r]+)',- # 'tech_org': r'Technical: *Name: *[^\n\r]+\s*Organisation: *([^\n\r]+)',- # 'tech_phone': r'Technical: *Name: *[^\n\r]+\s*Organisation: *[^\n\r]+\s*Language: *[^\n\r]+\s*Phone: *([^\n\r]+)',- # 'tech_fax': r'Technical: *Name: *[^\n\r]+\s*Organisation: *[^\n\r]+\s*Language: *[^\n\r]+\s*Phone: *[^\n\r]+\s*Fax: *([^\n\r]+)',- # 'tech_email': r'Technical: *Name: *[^\n\r]+\s*Organisation: *[^\n\r]+\s*Language: *[^\n\r]+\s*Phone: *[^\n\r]+\s*Fax: *[^\n\r]+\s*Email: *([^\n\r]+)',- 'registrar': r'Registrar: *[\n\r]+\s*name: *([^\n\r]+)',- 'name_servers': r'nserver: *(.*)', # list of name servers- }-- def __init__(self, domain, text):- if text.strip() == 'Domain not found':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisBr(WhoisEntry):- """Whois parser for .br domains- """- regex = {- 'domain': 'domain: *(.+)\n',- 'owner': 'owner: *([\S ]+)',- 'ownerid': 'ownerid: *(.+)',- 'country': 'country: *(.+)',- 'owner_c': 'owner-c: *(.+)',- 'admin_c': 'admin-c: *(.+)',- 'tech_c': 'tech-c: *(.+)',- 'billing_c': 'billing-c: *(.+)',- 'nserver': 'nserver: *(.+)',- 'nsstat': 'nsstat: *(.+)',- 'nslastaa': 'nslastaa: *(.+)',- 'saci': 'saci: *(.+)',- 'created': 'created: *(.+)',- 'expires': 'expires: *(.+)',- 'changed': 'changed: *(.+)',- 'status': 'status: *(.+)',- 'nic_hdl_br': 'nic-hdl-br: *(.+)',- 'person': 'person: *([\S ]+)',- 'email': 'e-mail: *(.+)',- }-- def __init__(self, domain, text):-- if 'Not found:' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisKr(WhoisEntry):- """Whois parser for .kr domains- """- regex = {- 'domain_name': 'Domain Name\s*: *(.+)',- 'registrant_org': 'Registrant\s*: *(.+)',- 'registrant_address': 'Registrant Address\s*: *(.+)',- 'registrant_zip': 'Registrant Zip Code\s*: *(.+)',- 'admin_name': 'Administrative Contact\(AC\)\s*: *(.+)',- 'admin_email': 'AC E-Mail\s*: *(.+)',- 'admin_phone': 'AC Phone Number\s*: *(.+)',- 'creation_date': 'Registered Date\s*: *(.+)',- 'updated_date': 'Last updated Date\s*: *(.+)',- 'expiration_date': 'Expiration Date\s*: *(.+)',- 'registrar': 'Authorized Agency\s*: *(.+)',- 'name_servers': 'Host Name\s*: *(.+)', # list of name servers- }-- def __init__(self, domain, text):- if text.endswith(' no match'):- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisPt(WhoisEntry):- """Whois parser for .pt domains- """- regex = {- 'domain_name': 'domain name: *(.+)',- 'creation_date': 'creation date \(dd\/mm\/yyyy\): *(.+)',- 'expiration_date': 'expiration date \(dd\/mm\/yyyy\): *(.+)',- 'name_servers': '\tNS\t(.+).', # list of name servers- 'status': 'status: *(.+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email addresses- }-- def __init__(self, domain, text):- if text.strip() == 'No entries found':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisBg(WhoisEntry):- """Whois parser for .bg domains- """- regex = {- 'domain_name': 'DOMAIN NAME: *(.+)\n',- 'status': 'registration status: s*(.+)',- 'expiration_date': 'expires at: *(.+)',- }- dayfirst = True-- def __init__(self, domain, text):- if 'does not exist in database!' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisDe(WhoisEntry):- """Whois parser for .de domains- """- regex = {- 'domain_name': 'Domain: *(.+)',- 'status': 'Status: *(.+)',- 'name': 'name: *(.+)',- 'org': 'Organisation: *(.+)',- 'address': 'Address: *(.+)',- 'zipcode': 'PostalCode: *(.+)',- 'city': 'City: *(.+)',- 'country_code': 'CountryCode: *(.+)',- 'phone': 'Phone: *(.+)',- 'fax': 'Fax: *(.+)',- 'emails': EMAIL_REGEX # list of email addresses-- }-- def __init__(self, domain, text):- if 'Status: free' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)--class WhoisAt(WhoisEntry):- """Whois parser for .at domains- """- regex = {- 'domain_name': 'domain: *(.+)',- 'name': 'personname: *(.+)',- 'org': 'organization: *(.+)',- 'address': 'street address: *(.+)',- 'zipcode': 'postal code: *(.+)',- 'city': 'city: *(.+)',- 'country': 'country: *(.+)',- 'phone': 'phone: *(.+)',- 'fax': 'fax-no: *(.+)',- 'changed': 'changed: *(.+)',- }-- def __init__(self, domain, text):- if 'Status: free' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)--class WhoisBe(WhoisEntry):- """Whois parser for .be domains- """- regex = {- 'name': 'Name: *(.+)',- 'org': 'Organisation: *(.+)',- 'phone': 'Phone: *(.+)',- 'fax': 'Fax: *(.+)',- 'email': 'Email: *(.+)',- }-- def __init__(self, domain, text):- if 'Status: AVAILABLE' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)----class WhoisInfo(WhoisEntry):- """Whois parser for .info domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'whois_server': 'Whois Server: *(.+)', # empty usually- 'referral_url': 'Referral URL: *(.+)', # http url of whois_server: empty usually- 'updated_date': 'Updated Date: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Registry Expiry Date: *(.+)',- 'name_servers': 'Name Server: *(.+)', # list of name servers- 'status': 'Status: *(.+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email addresses- 'name': 'Registrant Name: *(.+)',- 'org': 'Registrant Organization: *(.+)',- 'address': 'Registrant Street: *(.+)',- 'city': 'Registrant City: *(.+)',- 'state': 'Registrant State/Province: *(.+)',- 'zipcode': 'Registrant Postal Code: *(.+)',- 'country': 'Registrant Country: *(.+)',- }-- def __init__(self, domain, text):- if text.strip() == 'NOT FOUND':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisRf(WhoisRu):- """Whois parser for .su domains- """- def __init__(self, domain, text):- WhoisRu.__init__(self, domain, text)---class WhoisSu(WhoisRu):- """Whois parser for .su domains- """- def __init__(self, domain, text):- WhoisRu.__init__(self, domain, text)---class WhoisClub(WhoisEntry):- """Whois parser for .us domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'domain__id': 'Domain ID: *(.+)',- 'registrar': 'Sponsoring Registrar: *(.+)',- 'registrar_id': 'Sponsoring Registrar IANA ID: *(.+)',- 'registrar_url': 'Registrar URL \(registration services\): *(.+)',- # list of statuses- 'status': 'Domain Status: *(.+)',- 'registrant_id': 'Registrant ID: *(.+)',- 'registrant_name': 'Registrant Name: *(.+)',- 'registrant_address1': 'Registrant Address1: *(.+)',- 'registrant_address2': 'Registrant Address2: *(.+)',- 'registrant_city': 'Registrant City: *(.+)',- 'registrant_state_province': 'Registrant State/Province: *(.+)',- 'registrant_postal_code': 'Registrant Postal Code: *(.+)',- 'registrant_country': 'Registrant Country: *(.+)',- 'registrant_country_code': 'Registrant Country Code: *(.+)',- 'registrant_phone_number': 'Registrant Phone Number: *(.+)',- 'registrant_email': 'Registrant Email: *(.+)',- 'registrant_application_purpose': 'Registrant Application Purpose: *(.+)',- 'registrant_nexus_category': 'Registrant Nexus Category: *(.+)',- 'admin_id': 'Administrative Contact ID: *(.+)',- 'admin_name': 'Administrative Contact Name: *(.+)',- 'admin_address1': 'Administrative Contact Address1: *(.+)',- 'admin_address2': 'Administrative Contact Address2: *(.+)',- 'admin_city': 'Administrative Contact City: *(.+)',- 'admin_state_province': 'Administrative Contact State/Province: *(.+)',- 'admin_postal_code': 'Administrative Contact Postal Code: *(.+)',- 'admin_country': 'Administrative Contact Country: *(.+)',- 'admin_country_code': 'Administrative Contact Country Code: *(.+)',- 'admin_phone_number': 'Administrative Contact Phone Number: *(.+)',- 'admin_email': 'Administrative Contact Email: *(.+)',- 'admin_application_purpose': 'Administrative Application Purpose: *(.+)',- 'admin_nexus_category': 'Administrative Nexus Category: *(.+)',- 'billing_id': 'Billing Contact ID: *(.+)',- 'billing_name': 'Billing Contact Name: *(.+)',- 'billing_address1': 'Billing Contact Address1: *(.+)',- 'billing_address2': 'Billing Contact Address2: *(.+)',- 'billing_city': 'Billing Contact City: *(.+)',- 'billing_state_province': 'Billing Contact State/Province: *(.+)',- 'billing_postal_code': 'Billing Contact Postal Code: *(.+)',- 'billing_country': 'Billing Contact Country: *(.+)',- 'billing_country_code': 'Billing Contact Country Code: *(.+)',- 'billing_phone_number': 'Billing Contact Phone Number: *(.+)',- 'billing_email': 'Billing Contact Email: *(.+)',- 'billing_application_purpose': 'Billing Application Purpose: *(.+)',- 'billing_nexus_category': 'Billing Nexus Category: *(.+)',- 'tech_id': 'Technical Contact ID: *(.+)',- 'tech_name': 'Technical Contact Name: *(.+)',- 'tech_address1': 'Technical Contact Address1: *(.+)',- 'tech_address2': 'Technical Contact Address2: *(.+)',- 'tech_city': 'Technical Contact City: *(.+)',- 'tech_state_province': 'Technical Contact State/Province: *(.+)',- 'tech_postal_code': 'Technical Contact Postal Code: *(.+)',- 'tech_country': 'Technical Contact Country: *(.+)',- 'tech_country_code': 'Technical Contact Country Code: *(.+)',- 'tech_phone_number': 'Technical Contact Phone Number: *(.+)',- 'tech_email': 'Technical Contact Email: *(.+)',- 'tech_application_purpose': 'Technical Application Purpose: *(.+)',- 'tech_nexus_category': 'Technical Nexus Category: *(.+)',- # list of name servers- 'name_servers': 'Name Server: *(.+)',- 'created_by_registrar': 'Created by Registrar: *(.+)',- 'last_updated_by_registrar': 'Last Updated by Registrar: *(.+)',- 'creation_date': 'Domain Registration Date: *(.+)',- 'expiration_date': 'Domain Expiration Date: *(.+)',- 'updated_date': 'Domain Last Updated Date: *(.+)',- }-- def __init__(self, domain, text):- if 'Not found:' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisIo(WhoisEntry):- """Whois parser for .io domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'domain__id': 'Registry Domain ID: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'registrar_id': 'Registrar IANA ID: *(.+)',- 'registrar_url': 'Registrar URL: *(.+)',- 'status': 'Domain Status: *(.+)',- 'registrant_name': 'Registrant Organization: *(.+)',- 'registrant_state_province': 'Registrant State/Province: *(.+)',- 'registrant_country': 'Registrant Country: *(.+)',- 'name_servers': 'Name Server: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Registry Expiry Date: *(.+)',- 'updated_date': 'Updated Date: *(.+)',- }-- def __init__(self, domain, text):- if 'is available for purchase' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisBiz(WhoisUs):- """Whois parser for .biz domains- """- def __init__(self, domain, text):- WhoisUs.__init__(self, domain, text)---class WhoisMobi(WhoisMe):- """Whois parser for .mobi domains- """- def __init__(self, domain, text):- WhoisMe.__init__(self, domain, text)---class WhoisKg(WhoisEntry):- """Whois parser for .kg domains- """- regex = {- 'domain_name': 'Domain\s*([\w]+\.[\w]{2,5})',- 'registrar': 'Domain support: \s*(.+)',- 'registrant_name': 'Name: *(.+)',- 'registrant_address1': 'Address: *(.+)',- 'registrant_phone_number': 'phone: *(.+)',- 'registrant_email': 'Email: *(.+)',- # # list of name servers- 'name_servers': 'Name servers in the listed order: *([\d\w\.\s]+)',- # 'name_servers': r'([\w]+\.[\w]+\.[\w]{2,5}\s*\d{1,3}\.\d]{1,3}\.[\d]{1-3}\.[\d]{1-3})',- 'creation_date': 'Record created: *(.+)',- 'expiration_date': 'Record expires on \s*(.+)',- 'updated_date': 'Record last updated on\s*(.+)',-- }- def __init__(self, domain, text):- if 'Data not found. This domain is available for registration' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisChLi(WhoisEntry):- """Whois Parser for .ch and .li domains- """- regex = {- 'domain_name': '\nDomain name:\n*(.+)',- 'registrant': 'Holder of domain name:\n*([\n\s\S]+)\nContractual Language:',- 'registrar': 'Registrar:\n*(.+)',- 'creation_date': 'First registration date:\n*(.+)',- 'dnssec': 'DNSSEC:*([\S]+)',- 'tech-c': 'Technical contact:\n*([\n\s\S]+)\nRegistrar:',- 'name_servers': 'Name servers:\n *([\n\S\s]+)'- }- def __init__(self,domain,text):- if 'We do not have an entry in our database matching your query.' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisID(WhoisEntry):- """Whois parser for .id domains- """- regex = {- 'domain_id': 'Domain ID:(.+)',- 'domain_name': 'Domain Name:(.+)',- 'creation_date': 'Created On:(.+)',- 'expiration_date': 'Expiration Date(.+)',- 'registrar': 'Sponsoring Registrar ID:(.+)',- 'status': 'Status:(.+)', # list of statuses- 'registrant_id': 'Registrant ID:(.+)',- 'registrant_name': 'Registrant Name:(.+)',- 'registrant_org': 'Registrant Organization:(.+)',- 'registrant_address': 'Registrant Street1:(.+)',- 'registrant_address2': 'Registrant Street2:(.+)',- 'registrant_address3': 'Registrant Street3:(.+)',- 'registrant_city': 'Registrant City:(.+)',- 'registrant_country': 'Registrant Country:(.+)',- 'registrant_postal_code': 'Registrant Postal Code:(.+)',- 'registrant_phone': 'Registrant Phone:(.+)',- 'registrant_fax': 'Registrant FAX:(.+)',- 'registrant_email': 'Registrant Email:(.+)',- 'name_servers': 'Name Server:(.+)', # list of name servers- }-- def __init__(self, domain, text):- if 'NOT FOUND' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisSK(WhoisEntry):- """- Whois parser for .sk domains- """- regex = {- 'domain_name': 'Domain-name *(.+)',- 'expiration_date': 'Valid-date *(.+)',- 'status': 'Domain-status *(.+)',- 'name_servers': 'dns_name *(.+)',- 'tech_id': 'Tech-id *(.+)',- 'tech_name': 'Tech-name *(.+)',- 'tech_org_id': 'Tech-org.-ID *(.+)',- 'tech_address': 'Tech-address *(.+)',- 'tech_email': 'Tech-email *(.+)',- 'admin_id': 'Admin-id *(.+)',- 'admin_name': 'Admin-name *(.+)',- 'admin_legal_form': 'Admin-legal-form (.+)',- 'admin_org_id': 'Admin-org.-ID *(.+)',- 'admin_address': 'Admin-address *(.+)',- 'admin_email': 'Admin-email *(.+)',- 'updated_date': 'Last-update *(.+)',- 'tech_phone': 'Tech-telephone *(.+)',- 'name_servers_ipv4': 'dns_IPv4 *(.+)',-- }-- def __init__(self, domain, text):- if 'Not found' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisSe(WhoisEntry):- """Whois parser for .se domains- """- regex = {- 'domain_name': 'domain\.*: *(.+)',- 'creation_date': 'created\.*: *(.+)',- 'updated_date': 'modified\.*: *(.+)',- 'expiration_date': 'expires\.*: *(.+)',- 'transfer_date': 'transferred\.*: *(.+)',- 'name_servers': 'nserver\.*: *(.+)', # list of name servers- 'dnssec': 'dnssec\.*: *(.+)',- 'status': 'status\.*: *(.+)', # list of statuses- 'registrar': 'registrar: *(.+)',- }-- def __init__(self, domain, text):- if 'not found.' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)--class WhoisIt(WhoisEntry):- """Whois parser for .it domains- """- regex = {- 'domain_name': 'Domain: *(.+)',- 'creation_date': '(?<! )Created: *(.+)',- 'updated_date': '(?<! )Last Update: *(.+)',- 'expiration_date': '(?<! )Expire Date: *(.+)',- 'status': 'Status: *(.+)', # list of statuses- }-- def __init__(self, domain, text):- if 'not found.' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisIs(WhoisEntry):- """Whois parser for .se domains- """- regex = {- 'domain_name': 'domain\.*: *(.+)',- 'name': 'person\.*: *(.+)',- 'address': 'address\.*: *(.+)',- 'creation_date': 'created\.*: *(.+)',- 'expiration_date': 'expires\.*: *(.+)',- 'name_servers': 'nserver\.*: *(.+)', # list of name servers- 'dnssec': 'dnssec\.*: *(.+)',- }-- def __init__(self, domain, text):- if 'No entries found' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)--class WhoisDk(WhoisEntry):- """Whois parser for .dk domains- """- regex = {- 'domain_name': 'Domain: *(.+)',- 'creation_date': 'Registered: *(.+)',- 'expiration_date': 'Expires: *(.+)',- 'dnssec': 'Dnssec: *(.+)',- 'status': 'Status: *(.+)',- 'name_servers': 'Nameservers\n *([\n\S\s]+)'- }-- def __init__(self, domain, text):- if 'No match for ' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)-- def _preprocess(self, attr, value):- if attr == 'name_servers':- return [- line.split(":")[-1].strip()- for line in value.split("\n")- if line.startswith("Hostname")- ]- return super(WhoisDk, self)._preprocess(attr, value)--class WhoisAi(WhoisEntry):- """Whois parser for .ai domains- """- regex = {- 'domain_name': 'Complete Domain Name\.*: *(.+)',- 'name': 'Name \(Last, First\)\.*: *(.+)',- 'org': 'Organization Name\.*: *(.+)',- 'address': 'Street Address\.*: *(.+)',- 'city': 'City\.*: *(.+)',- 'state': 'State\.*: *(.+)',- 'zipcode': 'Postal Code\.*: *(\d+)',- 'country': 'Country\.*: *(.+)',- 'name_servers': 'Server Hostname\.*: *(.+)',- }-- def __init__(self, domain, text):- if 'not registered' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)--class WhoisIl(WhoisEntry):- """Whois parser for .il domains- """- regex = {- 'domain_name': 'domain: *(.+)',- 'expiration_date': 'validity: *(.+)',- 'registrant_name': 'person: *(.+)',- 'dnssec': 'DNSSEC: *(.+)',- 'status': 'status: *(.+)',- 'name_servers': 'nserver: *(.+)',- 'emails': 'e-mail: *(.+)',- 'phone': 'phone: *(.+)',- 'name_servers': 'nserver: *(.+)',- 'registrar': 'registrar name: *(.+)',- 'referral_url': 'registrar info: *(.+)',- }- dayfirst = True-- def __init__(self, domain, text):- if 'No data was found' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)-- def _preprocess(self, attr, value):- if attr == 'emails':- value = value.replace(' AT ', '@')- return super(WhoisIl, self)._preprocess(attr, value)--class WhoisIn(WhoisEntry):- """Whois parser for .in domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'updated_date': 'Updated Date: *(.+)|Last Updated On: *(.+)',- 'creation_date': 'Creation Date: *(.+)|Created On: *(.+)',- 'expiration_date': 'Expiration Date: *(.+)|Registry Expiry Date: *(.+)',- 'name_servers': 'Name Server: *(.+)',- 'status': 'Status: *(.+)',- 'emails': EMAIL_REGEX,- }-- def __init__(self, domain, text):- if 'NOT FOUND' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)--class WhoisCat(WhoisEntry):- """Whois parser for .cat domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'updated_date': 'Updated Date: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Registry Expiry Date: *(.+)',- 'name_servers': 'Name Server: *(.+)',- 'status': 'Domain status: *(.+)',- 'emails': EMAIL_REGEX,- }-- def __init__(self, domain, text):- if 'no matching objects' in text:- raise PywhoisError(text)- else:- # Merge base class regex with specifics- self._regex.copy().update(self.regex)- self.regex = self._regex- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisIe(WhoisEntry):- """Whois parser for .ie domains- """- regex = {- 'domain_name': 'domain: *(.+)',- 'description': 'descr: *(.+)',- 'source': 'Source: *(.+)',- 'creation_date': 'registration: *(.+)',- 'expiration_date': 'renewal: *(.+)',- 'name_servers': 'nserver: *(.+)',- 'status': 'ren-status: *(.+)',- 'admin_id': 'admin-c: *(.+)',- 'tech_id': 'tech-c: *(.+)'- }-- def __init__(self, domain, text):- if 'no matching objects' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisNz(WhoisEntry):- """Whois parser for .nz domains- """- regex = {- 'domain_name': 'domain_name:\s*([^\n\r]+)',- 'registrar': 'registrar_name:\s*([^\n\r]+)',- 'updated_date': 'domain_datelastmodified:\s*([^\n\r]+)',- 'creation_date': 'domain_dateregistered:\s*([^\n\r]+)',- 'expiration_date': 'domain_datebilleduntil:\s*([^\n\r]+)',- 'name_servers': 'ns_name_\d*:\s*([^\n\r]+)', # list of name servers- 'status': 'status:\s*([^\n\r]+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email s- 'name': 'registrant_contact_name:\s*([^\n\r]+)',- 'address': 'registrant_contact_address\d*:\s*([^\n\r]+)',- 'city': 'registrant_contact_city:\s*([^\n\r]+)',- 'zipcode': 'registrant_contact_postalcode:\s*([^\n\r]+)',- 'country': 'registrant_contact_country:\s*([^\n\r]+)',- }-- def __init__(self, domain, text):- if 'no matching objects' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisLu(WhoisEntry):- """Whois parser for .lu domains- """- regex = {- 'domain_name': 'domainname: *(.+)',- 'creation_date': 'registered: *(.+)',- 'name_servers': 'nserver: *(.+)',- 'status': 'domaintype: *(.+)',- 'registrar': 'registrar-name: *(.+)',- 'registrant_name': 'org-name: *(.+)',- 'registrant_address': 'org-address: *(.+)',- 'registrant_postal_code': 'org-zipcode:*(.+)',- 'registrant_city': 'org-city: *(.+)',- 'registrant_country': 'org-country: *(.+)',- 'admin_name': 'adm-name: *(.+)',- 'admin_address': 'adm-address: *(.+)',- 'admin_postal_code': 'adm-zipcode: *(.+)',- 'admin_city': 'adm-city: *(.+)',- 'admin_country': 'adm-country: *(.+)',- 'admin_email': 'adm-email: *(.+)',- 'tech_name': 'tec-name: *(.+)',- 'tech_address': 'tec-address: *(.+)',- 'tech_postal_code': 'tec-zipcode: *(.+)',- 'tech_city': 'tec-city: *(.+)',- 'tech_country': 'tec-country: *(.+)',- 'tech_email': 'tec-email: *(.+)',- }-- def __init__(self, domain, text):- if 'No such domain' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisCz(WhoisEntry):- """Whois parser for .cz domains- """- regex = {- 'domain_name': 'domain: *(.+)',- 'registrant_name': 'registrant: *(.+)',- 'registrar': 'registrar: *(.+)',- 'creation_date': 'registered: *(.+)',- 'updated_date': 'changed: *(.+)',- 'expiration_date': 'expire: *(.+)',- 'name_servers': 'nserver: *(.+)',- }-- def __init__(self, domain, text):- if '% No entries found.' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisOnline(WhoisEntry):- """Whois parser for .online domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'domain__id': 'Domain ID: *(.+)',- 'whois_server': 'Registrar WHOIS Server: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'registrar_id': 'Registrar IANA ID: *(.+)',- 'registrar_url': 'Registrar URL: *(.+)',- 'status': 'Domain Status: *(.+)',- 'registrant_email': 'Registrant Email: *(.+)',- 'admin_email': 'Admin Email: *(.+)',- 'billing_email': 'Billing Email: *(.+)',- 'tech_email': 'Tech Email: *(.+)',- 'name_servers': 'Name Server: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Registry Expiry Date: *(.+)',- 'updated_date': 'Updated Date: *(.+)',- 'dnssec': 'DNSSEC: *([\S]+)',- }-- def __init__(self, domain, text):- if 'Not found:' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisHr(WhoisEntry):- """Whois parser for .hr domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'whois_server': 'Registrar WHOIS Server: *(.+)',- 'registrar_url': 'Registrar URL: *(.+)',- 'updated_date': 'Updated Date: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Registrar Registration Expiration Date: *(.+)',- 'name_servers': 'Name Server: *(.+)'- }-- def __init__(self, domain, text):- if 'ERROR: No entries found' in text:- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisCn(WhoisEntry):- """Whois parser for .cn domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'creation_date': 'Registration Time: *(.+)',- 'expiration_date': 'Expiration Time: *(.+)',- 'name_servers': 'Name Server: *(.+)', # list of name servers- 'status': 'Status: *(.+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email s- 'dnssec': 'dnssec: *([\S]+)',- }-- def __init__(self, domain, text):- if text.strip() == 'No matching record.':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)---class WhoisApp(WhoisEntry):- """Whois parser for .app domains- """- regex = {- 'domain_name': 'Domain Name: *(.+)',- 'registrar': 'Registrar: *(.+)',- 'whois_server': 'Whois Server: *(.+)',- 'updated_date': 'Updated Date: *(.+)',- 'creation_date': 'Creation Date: *(.+)',- 'expiration_date': 'Expir\w+ Date: *(.+)',- 'name_servers': 'Name Server: *(.+)', # list of name servers- 'status': 'Status: *(.+)', # list of statuses- 'emails': EMAIL_REGEX, # list of email s- 'registrant_email': 'Registrant Email: *(.+)', # registrant email- 'registrant_phone': 'Registrant Phone: *(.+)', # registrant phone- 'dnssec': 'dnssec: *([\S]+)',- 'name': 'Registrant Name: *(.+)',- 'org': 'Registrant\s*Organization: *(.+)',- 'address': 'Registrant Street: *(.+)',- 'city': 'Registrant City: *(.+)',- 'state': 'Registrant State/Province: *(.+)',- 'zipcode': 'Registrant Postal Code: *(.+)',- 'country': 'Registrant Country: *(.+)',- }-- def __init__(self, domain, text):- if text.strip() == 'Domain not found.':- raise PywhoisError(text)- else:- WhoisEntry.__init__(self, domain, text, self.regex)-diff --git a/ext/whois/time_zones.py b/ext/whois/time_zones.pydeleted file mode 100644index 1853b92c..00000000--- a/ext/whois/time_zones.py+++ /dev/null@@ -1,52 +0,0 @@-from __future__ import unicode_literals-from __future__ import print_function-from __future__ import division-from __future__ import absolute_import-from future import standard_library-standard_library.install_aliases()-from builtins import *-_tz_string = '''-12 Y--11 X NUT SST--10 W CKT HAST HST TAHT TKT--9 V AKST GAMT GIT HADT HNY--8 U AKDT CIST HAY HNP PST PT--7 T HAP HNR MST PDT--6 S CST EAST GALT HAR HNC MDT--5 R CDT COT EASST ECT EST ET HAC HNE PET--4 Q AST BOT CLT COST EDT FKT GYT HAE HNA PYT--3 P ADT ART BRT CLST FKST GFT HAA PMST PYST SRT UYT WGT--2 O BRST FNT PMDT UYST WGST--1 N AZOT CVT EGT-0 Z EGST GMT UTC WET WT-1 A CET DFT WAT WEDT WEST-2 B CAT CEDT CEST EET SAST WAST-3 C EAT EEDT EEST IDT MSK-4 D AMT AZT GET GST KUYT MSD MUT RET SAMT SCT-5 E AMST AQTT AZST HMT MAWT MVT PKT TFT TJT TMT UZT YEKT-6 F ALMT BIOT BTT IOT KGT NOVT OMST YEKST-7 G CXT DAVT HOVT ICT KRAT NOVST OMSST THA WIB-8 H ACT AWST BDT BNT CAST HKT IRKT KRAST MYT PHT SGT ULAT WITA WST-9 I AWDT IRKST JST KST PWT TLT WDT WIT YAKT-10 K AEST ChST PGT VLAT YAKST YAPT-11 L AEDT LHDT MAGT NCT PONT SBT VLAST VUT-12 M ANAST ANAT FJT GILT MAGST MHT NZST PETST PETT TVT WFT-13 FJST NZDT-11.5 NFT-10.5 ACDT LHST-9.5 ACST-6.5 CCT MMT-5.75 NPT-5.5 SLT-4.5 AFT IRDT-3.5 IRST--2.5 HAT NDT--3.5 HNT NST NT--4.5 HLV VET--9.5 MART MIT'''--tz_data = {}--for tz_descr in (tz_spec.split() for tz_spec in _tz_string.split('\n')):- tz_offset = int(float(tz_descr[0]) * 3600)- for tz_code in tz_descr[1:]:- tz_data[tz_code] = tz_offsetdiff --git a/ext/whois/whois.py b/ext/whois/whois.pydeleted file mode 100644index cb9f879c..00000000--- a/ext/whois/whois.py+++ /dev/null@@ -1,283 +0,0 @@-# -*- coding: utf-8 -*---"""-Whois client for python--transliteration of:-http://www.opensource.apple.com/source/adv_cmds/adv_cmds-138.1/whois/whois.c--Copyright (c) 2010 Chris Wolf--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in-all copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN-THE SOFTWARE.-"""-from __future__ import print_function-from __future__ import unicode_literals-from __future__ import division-from __future__ import absolute_import-from future import standard_library-standard_library.install_aliases()-from builtins import *-from builtins import object-import re-import sys-import socket-import optparse-import os--class NICClient(object):-- ABUSEHOST = "whois.abuse.net"- NICHOST = "whois.crsnic.net"- INICHOST = "whois.networksolutions.com"- DNICHOST = "whois.nic.mil"- GNICHOST = "whois.nic.gov"- ANICHOST = "whois.arin.net"- LNICHOST = "whois.lacnic.net"- RNICHOST = "whois.ripe.net"- PNICHOST = "whois.apnic.net"- MNICHOST = "whois.ra.net"- QNICHOST_TAIL = ".whois-servers.net"- SNICHOST = "whois.6bone.net"- BNICHOST = "whois.registro.br"- NORIDHOST = "whois.norid.no"- IANAHOST = "whois.iana.org"- PANDIHOST = "whois.pandi.or.id"- DENICHOST = "de.whois-servers.net"- AI_HOST = "whois.ai"- HR_HOST = "whois.dns.hr"- APP_HOST = "whois.nic.google"- DEFAULT_PORT = "nicname"-- WHOIS_RECURSE = 0x01- WHOIS_QUICK = 0x02-- ip_whois = [LNICHOST, RNICHOST, PNICHOST, BNICHOST,PANDIHOST]-- def __init__(self):- self.use_qnichost = False-- def findwhois_server(self, buf, hostname, query):- """Search the initial TLD lookup results for the regional-specifc- whois server for getting contact details.- """- nhost = None- match = re.compile('Domain Name: {}\s*.*?Whois Server: (.*?)\s'.format(query), flags=re.IGNORECASE|re.DOTALL).search(buf)- if match:- nhost = match.groups()[0]- # if the whois address is domain.tld/something then- # s.connect((hostname, 43)) does not work- if nhost.count('/') > 0:- nhost = None- elif hostname == NICClient.ANICHOST:- for nichost in NICClient.ip_whois:- if buf.find(nichost) != -1:- nhost = nichost- break- return nhost--- def whois(self, query, hostname, flags, many_results=False):- """Perform initial lookup with TLD whois server- then, if the quick flag is false, search that result- for the region-specifc whois server and do a lookup- there for contact details- """- response = b''- if "SOCKS" in os.environ:- try:- import socks- except ImportError as e:- print("You need to install the Python socks module. Install PIP (https://bootstrap.pypa.io/get-pip.py) and then 'pip install PySocks'")- raise e- socksproxy, port = os.environ["SOCKS"].split(":")- s = socks.socksocket()- s.set_proxy(socks.SOCKS5, socksproxy, int(port))- else:- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- s.settimeout(10)- s.connect((hostname, 43))-- try:- query = query.decode('utf-8')- except UnicodeEncodeError:- pass # Already Unicode (python2's error)- except AttributeError:- pass # Already Unicode (python3's error)-- if hostname == NICClient.DENICHOST:- query_bytes = "-T dn,ace -C UTF-8 " + query- elif hostname.endswith(NICClient.QNICHOST_TAIL) and many_results:- query_bytes = '=' + query- else:- query_bytes = query- s.send(bytes(query_bytes,'utf-8') + b"\r\n")- # recv returns bytes- while True:- d = s.recv(4096)- response += d- if not d:- break- s.close()-- nhost = None- response = response.decode('utf-8', 'replace')- if 'with "=xxx"' in response:- return self.whois(query, hostname, flags, True)- if flags & NICClient.WHOIS_RECURSE and nhost is None:- nhost = self.findwhois_server(response, hostname, query)- if nhost is not None:- response += self.whois(query, nhost, 0)- return response-- def choose_server(self, domain):- """Choose initial lookup NIC host"""- try:- domain = domain.encode('idna').decode('utf-8')- except TypeError:- domain = domain.decode('utf-8').encode('idna').decode('utf-8')- except AttributeError:- domain = domain.decode('utf-8').encode('idna').decode('utf-8')- if domain.endswith("-NORID"):- return NICClient.NORIDHOST- if domain.endswith("id"):- return NICClient.PANDIHOST- if domain.endswith("hr"):- return NICClient.HR_HOST-- domain = domain.split('.')- if len(domain) < 2:- return None- tld = domain[-1]- if tld[0].isdigit():- return NICClient.ANICHOST- elif tld == 'ai':- return NICClient.AI_HOST- elif tld == 'app':- return NICClient.APP_HOST- elif tld == 'online':- return 'whois.nic.online'- else:- return tld + NICClient.QNICHOST_TAIL-- def whois_lookup(self, options, query_arg, flags):- """Main entry point: Perform initial lookup on TLD whois server,- or other server to get region-specific whois server, then if quick- flag is false, perform a second lookup on the region-specific- server for contact records"""- nichost = None- # whoud happen when this function is called by other than main- if options is None:- options = {}-- if ('whoishost' not in options or options['whoishost'] is None) \- and ('country' not in options or options['country'] is None):- self.use_qnichost = True- options['whoishost'] = NICClient.NICHOST- if not (flags & NICClient.WHOIS_QUICK):- flags |= NICClient.WHOIS_RECURSE-- if 'country' in options and options['country'] is not None:- result = self.whois(- query_arg,- options['country'] + NICClient.QNICHOST_TAIL,- flags- )- elif self.use_qnichost:- nichost = self.choose_server(query_arg)- if nichost is not None:- result = self.whois(query_arg, nichost, flags)- else:- result = ''- else:- result = self.whois(query_arg, options['whoishost'], flags)- return result---def parse_command_line(argv):- """Options handling mostly follows the UNIX whois(1) man page, except- long-form options can also be used.- """- flags = 0-- usage = "usage: %prog [options] name"-- parser = optparse.OptionParser(add_help_option=False, usage=usage)- parser.add_option("-a", "--arin", action="store_const",- const=NICClient.ANICHOST, dest="whoishost",- help="Lookup using host " + NICClient.ANICHOST)- parser.add_option("-A", "--apnic", action="store_const",- const=NICClient.PNICHOST, dest="whoishost",- help="Lookup using host " + NICClient.PNICHOST)- parser.add_option("-b", "--abuse", action="store_const",- const=NICClient.ABUSEHOST, dest="whoishost",- help="Lookup using host " + NICClient.ABUSEHOST)- parser.add_option("-c", "--country", action="store",- type="string", dest="country",- help="Lookup using country-specific NIC")- parser.add_option("-d", "--mil", action="store_const",- const=NICClient.DNICHOST, dest="whoishost",- help="Lookup using host " + NICClient.DNICHOST)- parser.add_option("-g", "--gov", action="store_const",- const=NICClient.GNICHOST, dest="whoishost",- help="Lookup using host " + NICClient.GNICHOST)- parser.add_option("-h", "--host", action="store",- type="string", dest="whoishost",- help="Lookup using specified whois host")- parser.add_option("-i", "--nws", action="store_const",- const=NICClient.INICHOST, dest="whoishost",- help="Lookup using host " + NICClient.INICHOST)- parser.add_option("-I", "--iana", action="store_const",- const=NICClient.IANAHOST, dest="whoishost",- help="Lookup using host " + NICClient.IANAHOST)- parser.add_option("-l", "--lcanic", action="store_const",- const=NICClient.LNICHOST, dest="whoishost",- help="Lookup using host " + NICClient.LNICHOST)- parser.add_option("-m", "--ra", action="store_const",- const=NICClient.MNICHOST, dest="whoishost",- help="Lookup using host " + NICClient.MNICHOST)- parser.add_option("-p", "--port", action="store",- type="int", dest="port",- help="Lookup using specified tcp port")- parser.add_option("-Q", "--quick", action="store_true",- dest="b_quicklookup",- help="Perform quick lookup")- parser.add_option("-r", "--ripe", action="store_const",- const=NICClient.RNICHOST, dest="whoishost",- help="Lookup using host " + NICClient.RNICHOST)- parser.add_option("-R", "--ru", action="store_const",- const="ru", dest="country",- help="Lookup Russian NIC")- parser.add_option("-6", "--6bone", action="store_const",- const=NICClient.SNICHOST, dest="whoishost",- help="Lookup using host " + NICClient.SNICHOST)- parser.add_option("-n", "--ina", action="store_const",- const=NICClient.PANDIHOST, dest="whoishost",- help="Lookup using host " + NICClient.PANDIHOST)- parser.add_option("-?", "--help", action="help")-- return parser.parse_args(argv)---if __name__ == "__main__":- flags = 0- nic_client = NICClient()- options, args = parse_command_line(sys.argv)- if options.b_quicklookup:- flags = flags | NICClient.WHOIS_QUICK- print(nic_client.whois_lookup(options.__dict__, args[1], flags))diff --git a/modules/sfp_digitaloceanspace.py b/modules/sfp_digitaloceanspace.pyindex 234f6c9c..e79a1eec 100644--- a/modules/sfp_digitaloceanspace.py+++ b/modules/sfp_digitaloceanspace.py@@ -22,7 +22,7 @@ class sfp_digitaloceanspace(SpiderFootPlugin):# Default optionsopts = {"endpoints": "nyc3.digitaloceanspaces.com,sgp1.digitaloceanspaces.com,ams3.digitaloceanspaces.com",- "suffixes": "test,dev,web,beta,bucket,space,files,content,data,-test,-dev,-web,-beta,-bucket,-space,-files,-content,-data",+ "suffixes": "test,dev,web,beta,bucket,space,files,content,data,prod,staging,production,stage,app,media,development,-test,-dev,-web,-beta,-bucket,-space,-files,-content,-data,-prod,-staging,-production,-stage,-app,-media,-development","_maxthreads": 20}diff --git a/requirements.txt b/requirements.txtindex c064b222..f8423f60 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,3 +1,6 @@+adblockparser>=0.7+dnspython>=1.16.0+exifread>=2.1.2CherryPy>=14.0.0M2Crypto>=0.29.0Mako>=1.0.4@@ -8,4 +11,8 @@ requests>=2.20.0ipwhois==1.0.0ipaddr>=2.2.0phonenumbers>=8.10.2+pygexf>=0.2.2+PyPDF2>=1.26.0+stem>=1.7.1+python-whois>=0.7.1futurediff --git a/sf.py b/sf.pyindex 086cb37d..b85b06dd 100755--- a/sf.py+++ b/sf.py@@ -46,8 +46,12 @@ for mod in deps:for mod in deps:print(" - " + mod)print("")- print("If you are running on Windows and getting this error, please")- print("report this as a bug to [email protected].")+ print("****************************************************************")+ print("Please note that if you are seeing this after doing a git pull")+ print("then you just need to do a `pip install -r requirements.txt` as")+ print("dependencies previously bundled with SpiderFoot are now")+ print("unbundled.")+ print("****************************************************************")print("")sys.exit(-1)