2015-09-15 17:12:15 +00:00
|
|
|
from __future__ import absolute_import, print_function, division
|
2015-06-23 10:16:03 +00:00
|
|
|
import os.path
|
2015-08-05 19:32:53 +00:00
|
|
|
import re
|
2015-09-15 17:12:15 +00:00
|
|
|
import string
|
2015-09-12 15:03:09 +00:00
|
|
|
import unicodedata
|
2015-08-01 08:39:14 +00:00
|
|
|
|
2015-09-15 17:12:15 +00:00
|
|
|
import six
|
|
|
|
|
|
|
|
from six.moves import urllib
|
|
|
|
|
2012-09-23 23:21:48 +00:00
|
|
|
|
2015-09-20 22:44:17 +00:00
|
|
|
def always_bytes(unicode_or_bytes, *encode_args):
|
|
|
|
if isinstance(unicode_or_bytes, six.text_type):
|
|
|
|
return unicode_or_bytes.encode(*encode_args)
|
|
|
|
return unicode_or_bytes
|
|
|
|
|
|
|
|
|
|
|
|
def always_byte_args(*encode_args):
|
|
|
|
"""Decorator that transparently encodes all arguments passed as unicode"""
|
|
|
|
def decorator(fun):
|
|
|
|
def _fun(*args, **kwargs):
|
|
|
|
args = [always_bytes(arg, *encode_args) for arg in args]
|
|
|
|
kwargs = {k: always_bytes(v, *encode_args) for k, v in six.iteritems(kwargs)}
|
|
|
|
return fun(*args, **kwargs)
|
|
|
|
return _fun
|
|
|
|
return decorator
|
|
|
|
|
|
|
|
|
|
|
|
def native(s, encoding="latin-1"):
|
|
|
|
"""
|
|
|
|
Convert :py:class:`bytes` or :py:class:`unicode` to the native
|
|
|
|
:py:class:`str` type, using latin1 encoding if conversion is necessary.
|
|
|
|
|
|
|
|
https://www.python.org/dev/peps/pep-3333/#a-note-on-string-types
|
|
|
|
"""
|
|
|
|
if not isinstance(s, (six.binary_type, six.text_type)):
|
|
|
|
raise TypeError("%r is neither bytes nor unicode" % s)
|
|
|
|
if six.PY3:
|
|
|
|
if isinstance(s, six.binary_type):
|
|
|
|
return s.decode(encoding)
|
|
|
|
else:
|
|
|
|
if isinstance(s, six.text_type):
|
|
|
|
return s.encode(encoding)
|
|
|
|
return s
|
|
|
|
|
|
|
|
|
2015-09-15 17:12:15 +00:00
|
|
|
def isascii(bytes):
|
2013-03-03 08:36:19 +00:00
|
|
|
try:
|
2015-09-15 17:12:15 +00:00
|
|
|
bytes.decode("ascii")
|
2013-03-03 08:36:19 +00:00
|
|
|
except ValueError:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2015-04-20 23:19:00 +00:00
|
|
|
|
2015-09-12 15:03:09 +00:00
|
|
|
def clean_bin(s, keep_spacing=True):
|
2012-09-23 23:21:48 +00:00
|
|
|
"""
|
2015-09-12 15:03:09 +00:00
|
|
|
Cleans binary data to make it safe to display.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
keep_spacing: If False, tabs and newlines will also be replaced.
|
2012-09-23 23:21:48 +00:00
|
|
|
"""
|
2015-09-12 15:03:09 +00:00
|
|
|
if isinstance(s, six.text_type):
|
|
|
|
if keep_spacing:
|
|
|
|
keep = u" \n\r\t"
|
|
|
|
else:
|
|
|
|
keep = u" "
|
|
|
|
return u"".join(
|
|
|
|
ch if (unicodedata.category(ch)[0] not in "CZ" or ch in keep) else u"."
|
|
|
|
for ch in s
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
if keep_spacing:
|
2015-09-15 22:04:23 +00:00
|
|
|
keep = (9, 10, 13) # \t, \n, \r,
|
2012-09-23 23:21:48 +00:00
|
|
|
else:
|
2015-09-15 22:04:23 +00:00
|
|
|
keep = ()
|
2015-09-12 15:03:09 +00:00
|
|
|
return b"".join(
|
2015-09-15 17:12:15 +00:00
|
|
|
six.int2byte(ch) if (31 < ch < 127 or ch in keep) else b"."
|
|
|
|
for ch in six.iterbytes(s)
|
2015-09-12 15:03:09 +00:00
|
|
|
)
|
2012-09-23 23:21:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
def hexdump(s):
|
|
|
|
"""
|
2015-09-17 13:16:12 +00:00
|
|
|
Returns:
|
|
|
|
A generator of (offset, hex, str) tuples
|
2012-09-23 23:21:48 +00:00
|
|
|
"""
|
|
|
|
for i in range(0, len(s), 16):
|
2015-09-17 13:16:12 +00:00
|
|
|
offset = b"%.10x" % i
|
2014-06-25 18:31:10 +00:00
|
|
|
part = s[i:i + 16]
|
2015-09-17 13:16:12 +00:00
|
|
|
x = b" ".join(b"%.2x" % i for i in six.iterbytes(part))
|
|
|
|
x = x.ljust(47) # 16*2 + 15
|
|
|
|
yield (offset, x, clean_bin(part, False))
|
2015-04-24 03:09:21 +00:00
|
|
|
|
|
|
|
|
|
|
|
def setbit(byte, offset, value):
|
|
|
|
"""
|
|
|
|
Set a bit in a byte to 1 if value is truthy, 0 if not.
|
|
|
|
"""
|
|
|
|
if value:
|
|
|
|
return byte | (1 << offset)
|
|
|
|
else:
|
|
|
|
return byte & ~(1 << offset)
|
|
|
|
|
|
|
|
|
|
|
|
def getbit(byte, offset):
|
|
|
|
mask = 1 << offset
|
2015-09-17 13:16:12 +00:00
|
|
|
return bool(byte & mask)
|
2015-04-29 21:04:22 +00:00
|
|
|
|
|
|
|
|
2015-06-17 11:10:27 +00:00
|
|
|
class BiDi(object):
|
2015-05-27 09:18:54 +00:00
|
|
|
|
2015-04-29 21:04:22 +00:00
|
|
|
"""
|
|
|
|
A wee utility class for keeping bi-directional mappings, like field
|
2015-04-30 00:10:08 +00:00
|
|
|
constants in protocols. Names are attributes on the object, dict-like
|
|
|
|
access maps values to names:
|
2015-04-29 21:04:22 +00:00
|
|
|
|
|
|
|
CONST = BiDi(a=1, b=2)
|
|
|
|
assert CONST.a == 1
|
2015-04-30 00:10:08 +00:00
|
|
|
assert CONST.get_name(1) == "a"
|
2015-04-29 21:04:22 +00:00
|
|
|
"""
|
2015-05-27 09:18:54 +00:00
|
|
|
|
2015-04-29 21:04:22 +00:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
self.names = kwargs
|
|
|
|
self.values = {}
|
|
|
|
for k, v in kwargs.items():
|
|
|
|
self.values[v] = k
|
|
|
|
if len(self.names) != len(self.values):
|
|
|
|
raise ValueError("Duplicate values not allowed.")
|
|
|
|
|
|
|
|
def __getattr__(self, k):
|
|
|
|
if k in self.names:
|
|
|
|
return self.names[k]
|
|
|
|
raise AttributeError("No such attribute: %s", k)
|
|
|
|
|
2015-04-30 00:10:08 +00:00
|
|
|
def get_name(self, n, default=None):
|
|
|
|
return self.values.get(n, default)
|
|
|
|
|
|
|
|
|
|
|
|
def pretty_size(size):
|
|
|
|
suffixes = [
|
2015-05-27 09:18:54 +00:00
|
|
|
("B", 2 ** 10),
|
|
|
|
("kB", 2 ** 20),
|
|
|
|
("MB", 2 ** 30),
|
2015-04-30 00:10:08 +00:00
|
|
|
]
|
|
|
|
for suf, lim in suffixes:
|
|
|
|
if size >= lim:
|
|
|
|
continue
|
|
|
|
else:
|
2015-05-27 09:18:54 +00:00
|
|
|
x = round(size / float(lim / 2 ** 10), 2)
|
2015-04-30 00:10:08 +00:00
|
|
|
if x == int(x):
|
|
|
|
x = int(x)
|
|
|
|
return str(x) + suf
|
2015-06-23 10:16:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Data(object):
|
2015-08-10 18:44:36 +00:00
|
|
|
|
2015-06-23 10:16:03 +00:00
|
|
|
def __init__(self, name):
|
|
|
|
m = __import__(name)
|
|
|
|
dirname, _ = os.path.split(m.__file__)
|
|
|
|
self.dirname = os.path.abspath(dirname)
|
|
|
|
|
|
|
|
def path(self, path):
|
|
|
|
"""
|
|
|
|
Returns a path to the package data housed at 'path' under this
|
|
|
|
module.Path can be a path to a file, or to a directory.
|
|
|
|
|
|
|
|
This function will raise ValueError if the path does not exist.
|
|
|
|
"""
|
2015-08-01 12:49:15 +00:00
|
|
|
fullpath = os.path.join(self.dirname, '../test/', path)
|
2015-06-23 10:16:03 +00:00
|
|
|
if not os.path.exists(fullpath):
|
|
|
|
raise ValueError("dataPath: %s does not exist." % fullpath)
|
|
|
|
return fullpath
|
2015-07-29 09:27:43 +00:00
|
|
|
|
|
|
|
|
2015-09-15 17:12:15 +00:00
|
|
|
_label_valid = re.compile(b"(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
|
2015-08-01 08:39:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
def is_valid_host(host):
|
2015-09-20 17:40:09 +00:00
|
|
|
"""
|
|
|
|
Checks if a hostname is valid.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
host (bytes): The hostname
|
|
|
|
"""
|
2015-08-01 08:39:14 +00:00
|
|
|
try:
|
|
|
|
host.decode("idna")
|
|
|
|
except ValueError:
|
|
|
|
return False
|
2015-09-15 17:12:15 +00:00
|
|
|
if len(host) > 255:
|
|
|
|
return False
|
2015-09-17 13:16:12 +00:00
|
|
|
if host[-1] == b".":
|
2015-09-15 17:12:15 +00:00
|
|
|
host = host[:-1]
|
|
|
|
return all(_label_valid.match(x) for x in host.split(b"."))
|
|
|
|
|
|
|
|
|
|
|
|
def is_valid_port(port):
|
|
|
|
return 0 <= port <= 65535
|
|
|
|
|
|
|
|
|
|
|
|
# PY2 workaround
|
|
|
|
def decode_parse_result(result, enc):
|
|
|
|
if hasattr(result, "decode"):
|
|
|
|
return result.decode(enc)
|
|
|
|
else:
|
|
|
|
return urllib.parse.ParseResult(*[x.decode(enc) for x in result])
|
|
|
|
|
|
|
|
|
|
|
|
# PY2 workaround
|
|
|
|
def encode_parse_result(result, enc):
|
|
|
|
if hasattr(result, "encode"):
|
|
|
|
return result.encode(enc)
|
|
|
|
else:
|
|
|
|
return urllib.parse.ParseResult(*[x.encode(enc) for x in result])
|
2015-08-01 08:39:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
def parse_url(url):
|
|
|
|
"""
|
2015-09-15 17:12:15 +00:00
|
|
|
URL-parsing function that checks that
|
|
|
|
- port is an integer 0-65535
|
|
|
|
- host is a valid IDNA-encoded hostname with no null-bytes
|
|
|
|
- path is valid ASCII
|
2015-08-01 08:39:14 +00:00
|
|
|
|
2015-09-15 17:12:15 +00:00
|
|
|
Args:
|
|
|
|
A URL (as bytes or as unicode)
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A (scheme, host, port, path) tuple
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
ValueError, if the URL is not properly formatted.
|
2015-08-01 08:39:14 +00:00
|
|
|
"""
|
2015-09-15 17:12:15 +00:00
|
|
|
parsed = urllib.parse.urlparse(url)
|
|
|
|
|
|
|
|
if not parsed.hostname:
|
|
|
|
raise ValueError("No hostname given")
|
|
|
|
|
|
|
|
if isinstance(url, six.binary_type):
|
|
|
|
host = parsed.hostname
|
|
|
|
|
|
|
|
# this should not raise a ValueError
|
|
|
|
decode_parse_result(parsed, "ascii")
|
2015-08-01 08:39:14 +00:00
|
|
|
else:
|
2015-09-15 17:12:15 +00:00
|
|
|
host = parsed.hostname.encode("idna")
|
|
|
|
parsed = encode_parse_result(parsed, "ascii")
|
|
|
|
|
|
|
|
port = parsed.port
|
|
|
|
if not port:
|
|
|
|
port = 443 if parsed.scheme == b"https" else 80
|
|
|
|
|
|
|
|
full_path = urllib.parse.urlunparse(
|
|
|
|
(b"", b"", parsed.path, parsed.params, parsed.query, parsed.fragment)
|
|
|
|
)
|
|
|
|
if not full_path.startswith(b"/"):
|
|
|
|
full_path = b"/" + full_path
|
|
|
|
|
2015-08-01 08:39:14 +00:00
|
|
|
if not is_valid_host(host):
|
2015-09-15 17:12:15 +00:00
|
|
|
raise ValueError("Invalid Host")
|
2015-08-01 08:39:14 +00:00
|
|
|
if not is_valid_port(port):
|
2015-09-15 17:12:15 +00:00
|
|
|
raise ValueError("Invalid Port")
|
|
|
|
|
|
|
|
return parsed.scheme, host, port, full_path
|
2015-08-01 08:39:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
def get_header_tokens(headers, key):
|
|
|
|
"""
|
|
|
|
Retrieve all tokens for a header key. A number of different headers
|
|
|
|
follow a pattern where each header line can containe comma-separated
|
|
|
|
tokens, and headers can be set multiple times.
|
|
|
|
"""
|
2015-09-05 16:15:47 +00:00
|
|
|
if key not in headers:
|
|
|
|
return []
|
2015-09-15 17:12:15 +00:00
|
|
|
tokens = headers[key].split(b",")
|
2015-09-05 16:15:47 +00:00
|
|
|
return [token.strip() for token in tokens]
|
2015-08-01 08:39:14 +00:00
|
|
|
|
|
|
|
|
2015-09-20 22:44:17 +00:00
|
|
|
@always_byte_args()
|
2015-07-29 09:27:43 +00:00
|
|
|
def hostport(scheme, host, port):
|
|
|
|
"""
|
|
|
|
Returns the host component, with a port specifcation if needed.
|
|
|
|
"""
|
2015-09-17 13:16:12 +00:00
|
|
|
if (port, scheme) in [(80, b"http"), (443, b"https")]:
|
2015-07-29 09:27:43 +00:00
|
|
|
return host
|
|
|
|
else:
|
2015-09-15 22:04:23 +00:00
|
|
|
return b"%s:%d" % (host, port)
|
2015-08-01 08:39:14 +00:00
|
|
|
|
2015-08-10 18:44:36 +00:00
|
|
|
|
2015-08-01 08:39:14 +00:00
|
|
|
def unparse_url(scheme, host, port, path=""):
|
|
|
|
"""
|
|
|
|
Returns a URL string, constructed from the specified compnents.
|
|
|
|
"""
|
2015-09-17 14:31:50 +00:00
|
|
|
return b"%s://%s%s" % (scheme, hostport(scheme, host, port), path)
|
2015-08-01 08:39:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
def urlencode(s):
|
|
|
|
"""
|
|
|
|
Takes a list of (key, value) tuples and returns a urlencoded string.
|
|
|
|
"""
|
|
|
|
s = [tuple(i) for i in s]
|
2015-09-15 17:12:15 +00:00
|
|
|
return urllib.parse.urlencode(s, False)
|
2015-08-01 08:39:14 +00:00
|
|
|
|
2015-08-10 18:44:36 +00:00
|
|
|
|
2015-08-01 08:39:14 +00:00
|
|
|
def urldecode(s):
|
|
|
|
"""
|
|
|
|
Takes a urlencoded string and returns a list of (key, value) tuples.
|
|
|
|
"""
|
2015-09-15 17:12:15 +00:00
|
|
|
return urllib.parse.parse_qsl(s, keep_blank_values=True)
|
2015-08-05 19:32:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
def parse_content_type(c):
|
|
|
|
"""
|
|
|
|
A simple parser for content-type values. Returns a (type, subtype,
|
|
|
|
parameters) tuple, where type and subtype are strings, and parameters
|
|
|
|
is a dict. If the string could not be parsed, return None.
|
|
|
|
|
|
|
|
E.g. the following string:
|
|
|
|
|
|
|
|
text/html; charset=UTF-8
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
|
|
|
("text", "html", {"charset": "UTF-8"})
|
|
|
|
"""
|
2015-09-15 17:12:15 +00:00
|
|
|
parts = c.split(b";", 1)
|
|
|
|
ts = parts[0].split(b"/", 1)
|
2015-08-05 19:32:53 +00:00
|
|
|
if len(ts) != 2:
|
|
|
|
return None
|
|
|
|
d = {}
|
|
|
|
if len(parts) == 2:
|
2015-09-15 17:12:15 +00:00
|
|
|
for i in parts[1].split(b";"):
|
|
|
|
clause = i.split(b"=", 1)
|
2015-08-05 19:32:53 +00:00
|
|
|
if len(clause) == 2:
|
|
|
|
d[clause[0].strip()] = clause[1].strip()
|
|
|
|
return ts[0].lower(), ts[1].lower(), d
|
|
|
|
|
|
|
|
|
2015-09-05 16:15:47 +00:00
|
|
|
def multipartdecode(headers, content):
|
2015-08-05 19:32:53 +00:00
|
|
|
"""
|
|
|
|
Takes a multipart boundary encoded string and returns list of (key, value) tuples.
|
|
|
|
"""
|
2015-09-17 14:31:50 +00:00
|
|
|
v = headers.get(b"Content-Type")
|
2015-08-05 19:32:53 +00:00
|
|
|
if v:
|
|
|
|
v = parse_content_type(v)
|
|
|
|
if not v:
|
|
|
|
return []
|
2015-09-15 17:12:15 +00:00
|
|
|
boundary = v[2].get(b"boundary")
|
2015-08-05 19:32:53 +00:00
|
|
|
if not boundary:
|
|
|
|
return []
|
|
|
|
|
2015-09-17 14:31:50 +00:00
|
|
|
rx = re.compile(br'\bname="([^"]+)"')
|
2015-08-05 19:32:53 +00:00
|
|
|
r = []
|
|
|
|
|
2015-09-17 14:31:50 +00:00
|
|
|
for i in content.split(b"--" + boundary):
|
2015-08-05 19:32:53 +00:00
|
|
|
parts = i.splitlines()
|
2015-09-17 14:31:50 +00:00
|
|
|
if len(parts) > 1 and parts[0][0:2] != b"--":
|
2015-08-05 19:32:53 +00:00
|
|
|
match = rx.search(parts[1])
|
|
|
|
if match:
|
|
|
|
key = match.group(1)
|
2015-09-17 14:31:50 +00:00
|
|
|
value = b"".join(parts[3 + parts[2:].index(b""):])
|
2015-08-05 19:32:53 +00:00
|
|
|
r.append((key, value))
|
|
|
|
return r
|
|
|
|
return []
|