2016-05-19 05:50:19 +00:00
|
|
|
import collections
|
2016-07-08 08:46:29 +00:00
|
|
|
import email.utils
|
2015-07-14 21:02:14 +00:00
|
|
|
import re
|
2016-07-08 08:46:29 +00:00
|
|
|
import time
|
2015-07-14 21:02:14 +00:00
|
|
|
|
2016-05-31 23:12:10 +00:00
|
|
|
from netlib import multidict
|
2015-07-14 21:02:14 +00:00
|
|
|
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
|
|
|
A flexible module for cookie parsing and manipulation.
|
|
|
|
|
2015-04-21 01:39:00 +00:00
|
|
|
This module differs from usual standards-compliant cookie modules in a number
|
|
|
|
of ways. We try to be as permissive as possible, and to retain even mal-formed
|
2015-04-13 22:02:10 +00:00
|
|
|
information. Duplicate cookies are preserved in parsing, and can be set in
|
|
|
|
formatting. We do attempt to escape and quote values where needed, but will not
|
|
|
|
reject data that violate the specs.
|
|
|
|
|
|
|
|
Parsing accepts the formats in RFC6265 and partially RFC2109 and RFC2965. We do
|
2015-04-21 01:39:00 +00:00
|
|
|
not parse the comma-separated variant of Set-Cookie that allows multiple
|
|
|
|
cookies to be set in a single header. Technically this should be feasible, but
|
|
|
|
it turns out that violations of RFC6265 that makes the parsing problem
|
|
|
|
indeterminate are much more common than genuine occurences of the multi-cookie
|
|
|
|
variants. Serialization follows RFC6265.
|
2015-04-11 22:26:09 +00:00
|
|
|
|
|
|
|
http://tools.ietf.org/html/rfc6265
|
|
|
|
http://tools.ietf.org/html/rfc2109
|
2015-04-13 22:02:10 +00:00
|
|
|
http://tools.ietf.org/html/rfc2965
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
|
|
|
|
2015-08-16 18:02:18 +00:00
|
|
|
# TODO: Disallow LHS-only Cookie values
|
2015-04-13 22:02:10 +00:00
|
|
|
|
2016-05-28 20:17:02 +00:00
|
|
|
|
2015-04-11 22:26:09 +00:00
|
|
|
def _read_until(s, start, term):
|
|
|
|
"""
|
|
|
|
Read until one of the characters in term is reached.
|
|
|
|
"""
|
|
|
|
if start == len(s):
|
2015-04-21 01:39:00 +00:00
|
|
|
return "", start + 1
|
2015-04-11 22:26:09 +00:00
|
|
|
for i in range(start, len(s)):
|
|
|
|
if s[i] in term:
|
|
|
|
return s[start:i], i
|
2015-04-21 01:39:00 +00:00
|
|
|
return s[start:i + 1], i + 1
|
2015-04-11 22:26:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _read_token(s, start):
|
|
|
|
"""
|
|
|
|
Read a token - the LHS of a token/value pair in a cookie.
|
|
|
|
"""
|
|
|
|
return _read_until(s, start, ";=")
|
|
|
|
|
|
|
|
|
|
|
|
def _read_quoted_string(s, start):
|
|
|
|
"""
|
|
|
|
start: offset to the first quote of the string to be read
|
|
|
|
|
|
|
|
A sort of loose super-set of the various quoted string specifications.
|
|
|
|
|
|
|
|
RFC6265 disallows backslashes or double quotes within quoted strings.
|
|
|
|
Prior RFCs use backslashes to escape. This leaves us free to apply
|
|
|
|
backslash escaping by default and be compatible with everything.
|
|
|
|
"""
|
|
|
|
escaping = False
|
|
|
|
ret = []
|
|
|
|
# Skip the first quote
|
2015-09-26 22:49:41 +00:00
|
|
|
i = start # initialize in case the loop doesn't run.
|
2015-04-21 01:39:00 +00:00
|
|
|
for i in range(start + 1, len(s)):
|
2015-04-11 22:26:09 +00:00
|
|
|
if escaping:
|
|
|
|
ret.append(s[i])
|
|
|
|
escaping = False
|
|
|
|
elif s[i] == '"':
|
|
|
|
break
|
|
|
|
elif s[i] == "\\":
|
|
|
|
escaping = True
|
|
|
|
else:
|
|
|
|
ret.append(s[i])
|
2015-04-21 01:39:00 +00:00
|
|
|
return "".join(ret), i + 1
|
2015-04-11 22:26:09 +00:00
|
|
|
|
|
|
|
|
2015-04-13 22:02:10 +00:00
|
|
|
def _read_value(s, start, delims):
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
|
|
|
Reads a value - the RHS of a token/value pair in a cookie.
|
2015-04-11 23:26:02 +00:00
|
|
|
|
|
|
|
special: If the value is special, commas are premitted. Else comma
|
|
|
|
terminates. This helps us support old and new style values.
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
2015-04-11 23:26:02 +00:00
|
|
|
if start >= len(s):
|
|
|
|
return "", start
|
|
|
|
elif s[start] == '"':
|
2015-04-11 22:26:09 +00:00
|
|
|
return _read_quoted_string(s, start)
|
|
|
|
else:
|
2015-04-13 22:02:10 +00:00
|
|
|
return _read_until(s, start, delims)
|
2015-04-11 22:26:09 +00:00
|
|
|
|
|
|
|
|
2015-06-18 13:32:52 +00:00
|
|
|
def _read_pairs(s, off=0):
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
|
|
|
Read pairs of lhs=rhs values.
|
2015-04-11 23:26:02 +00:00
|
|
|
|
2015-04-13 22:02:10 +00:00
|
|
|
off: start offset
|
2015-04-13 22:13:03 +00:00
|
|
|
specials: a lower-cased list of keys that may contain commas
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
|
|
|
vals = []
|
2015-05-27 09:18:54 +00:00
|
|
|
while True:
|
2015-04-11 22:26:09 +00:00
|
|
|
lhs, off = _read_token(s, off)
|
2015-04-11 23:26:02 +00:00
|
|
|
lhs = lhs.lstrip()
|
2015-04-13 22:02:10 +00:00
|
|
|
if lhs:
|
|
|
|
rhs = None
|
|
|
|
if off < len(s):
|
|
|
|
if s[off] == "=":
|
2015-04-21 01:39:00 +00:00
|
|
|
rhs, off = _read_value(s, off + 1, ";")
|
2015-04-13 22:02:10 +00:00
|
|
|
vals.append([lhs, rhs])
|
2015-04-11 22:26:09 +00:00
|
|
|
off += 1
|
|
|
|
if not off < len(s):
|
|
|
|
break
|
|
|
|
return vals, off
|
|
|
|
|
|
|
|
|
2015-04-11 23:26:02 +00:00
|
|
|
def _has_special(s):
|
|
|
|
for i in s:
|
|
|
|
if i in '",;\\':
|
|
|
|
return True
|
|
|
|
o = ord(i)
|
|
|
|
if o < 0x21 or o > 0x7e:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2015-04-13 22:02:10 +00:00
|
|
|
ESCAPE = re.compile(r"([\"\\])")
|
|
|
|
|
|
|
|
|
2015-04-15 20:30:54 +00:00
|
|
|
def _format_pairs(lst, specials=(), sep="; "):
|
2015-04-11 23:26:02 +00:00
|
|
|
"""
|
|
|
|
specials: A lower-cased list of keys that will not be quoted.
|
|
|
|
"""
|
2015-04-11 22:26:09 +00:00
|
|
|
vals = []
|
|
|
|
for k, v in lst:
|
|
|
|
if v is None:
|
|
|
|
vals.append(k)
|
|
|
|
else:
|
2015-04-11 23:26:02 +00:00
|
|
|
if k.lower() not in specials and _has_special(v):
|
|
|
|
v = ESCAPE.sub(r"\\\1", v)
|
2015-05-27 09:18:54 +00:00
|
|
|
v = '"%s"' % v
|
|
|
|
vals.append("%s=%s" % (k, v))
|
2015-04-15 20:30:54 +00:00
|
|
|
return sep.join(vals)
|
2015-04-11 22:26:09 +00:00
|
|
|
|
|
|
|
|
2015-04-13 22:02:10 +00:00
|
|
|
def _format_set_cookie_pairs(lst):
|
|
|
|
return _format_pairs(
|
|
|
|
lst,
|
2015-05-27 09:18:54 +00:00
|
|
|
specials=("expires", "path")
|
2015-04-13 22:02:10 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_set_cookie_pairs(s):
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
2015-04-13 22:02:10 +00:00
|
|
|
For Set-Cookie, we support multiple cookies as described in RFC2109.
|
|
|
|
This function therefore returns a list of lists.
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
2015-06-18 13:32:52 +00:00
|
|
|
pairs, off_ = _read_pairs(s)
|
2015-04-13 22:02:10 +00:00
|
|
|
return pairs
|
2015-04-11 22:26:09 +00:00
|
|
|
|
|
|
|
|
2016-05-19 05:50:19 +00:00
|
|
|
def parse_set_cookie_headers(headers):
|
|
|
|
ret = []
|
|
|
|
for header in headers:
|
|
|
|
v = parse_set_cookie_header(header)
|
|
|
|
if v:
|
|
|
|
name, value, attrs = v
|
|
|
|
ret.append((name, SetCookie(value, attrs)))
|
|
|
|
return ret
|
|
|
|
|
|
|
|
|
2016-05-31 23:12:10 +00:00
|
|
|
class CookieAttrs(multidict.ImmutableMultiDict):
|
2016-05-19 05:50:19 +00:00
|
|
|
@staticmethod
|
2016-05-20 18:04:27 +00:00
|
|
|
def _kconv(key):
|
|
|
|
return key.lower()
|
2016-05-19 05:50:19 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _reduce_values(values):
|
|
|
|
# See the StickyCookieTest for a weird cookie that only makes sense
|
|
|
|
# if we take the last part.
|
|
|
|
return values[-1]
|
|
|
|
|
|
|
|
|
|
|
|
SetCookie = collections.namedtuple("SetCookie", ["value", "attrs"])
|
|
|
|
|
|
|
|
|
2015-06-17 11:10:27 +00:00
|
|
|
def parse_set_cookie_header(line):
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
2015-04-13 22:02:10 +00:00
|
|
|
Parse a Set-Cookie header value
|
|
|
|
|
|
|
|
Returns a (name, value, attrs) tuple, or None, where attrs is an
|
2016-05-19 05:50:19 +00:00
|
|
|
CookieAttrs dict of attributes. No attempt is made to parse attribute
|
2015-04-13 22:02:10 +00:00
|
|
|
values - they are treated purely as strings.
|
2015-04-11 22:26:09 +00:00
|
|
|
"""
|
2015-06-17 11:10:27 +00:00
|
|
|
pairs = _parse_set_cookie_pairs(line)
|
2015-04-13 22:02:10 +00:00
|
|
|
if pairs:
|
2016-05-19 05:50:19 +00:00
|
|
|
return pairs[0][0], pairs[0][1], CookieAttrs(tuple(x) for x in pairs[1:])
|
2015-04-13 22:02:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
def format_set_cookie_header(name, value, attrs):
|
|
|
|
"""
|
|
|
|
Formats a Set-Cookie header value.
|
|
|
|
"""
|
2016-05-19 05:50:19 +00:00
|
|
|
pairs = [(name, value)]
|
|
|
|
pairs.extend(
|
|
|
|
attrs.fields if hasattr(attrs, "fields") else attrs
|
|
|
|
)
|
2015-04-13 22:02:10 +00:00
|
|
|
return _format_set_cookie_pairs(pairs)
|
2015-04-11 22:26:09 +00:00
|
|
|
|
|
|
|
|
2016-05-19 01:46:42 +00:00
|
|
|
def parse_cookie_headers(cookie_headers):
|
|
|
|
cookie_list = []
|
|
|
|
for header in cookie_headers:
|
|
|
|
cookie_list.extend(parse_cookie_header(header))
|
|
|
|
return cookie_list
|
|
|
|
|
|
|
|
|
2015-06-17 11:10:27 +00:00
|
|
|
def parse_cookie_header(line):
|
2015-04-13 22:02:10 +00:00
|
|
|
"""
|
|
|
|
Parse a Cookie header value.
|
2016-05-19 01:46:42 +00:00
|
|
|
Returns a list of (lhs, rhs) tuples.
|
2015-04-13 22:02:10 +00:00
|
|
|
"""
|
2015-06-18 13:32:52 +00:00
|
|
|
pairs, off_ = _read_pairs(line)
|
2016-05-19 01:46:42 +00:00
|
|
|
return pairs
|
2015-04-11 22:26:09 +00:00
|
|
|
|
|
|
|
|
2016-05-19 01:46:42 +00:00
|
|
|
def format_cookie_header(lst):
|
2015-04-13 22:02:10 +00:00
|
|
|
"""
|
|
|
|
Formats a Cookie header value.
|
|
|
|
"""
|
2016-05-19 01:46:42 +00:00
|
|
|
return _format_pairs(lst)
|
2016-04-02 20:49:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
def refresh_set_cookie_header(c, delta):
|
|
|
|
"""
|
|
|
|
Args:
|
|
|
|
c: A Set-Cookie string
|
|
|
|
delta: Time delta in seconds
|
|
|
|
Returns:
|
|
|
|
A refreshed Set-Cookie string
|
|
|
|
"""
|
2016-05-08 18:13:48 +00:00
|
|
|
|
|
|
|
name, value, attrs = parse_set_cookie_header(c)
|
|
|
|
if not name or not value:
|
2016-04-02 20:49:05 +00:00
|
|
|
raise ValueError("Invalid Cookie")
|
2016-05-08 18:13:48 +00:00
|
|
|
|
|
|
|
if "expires" in attrs:
|
2016-05-31 23:12:10 +00:00
|
|
|
e = email.utils.parsedate_tz(attrs["expires"])
|
2016-05-08 18:13:48 +00:00
|
|
|
if e:
|
2016-05-31 23:12:10 +00:00
|
|
|
f = email.utils.mktime_tz(e) + delta
|
|
|
|
attrs = attrs.with_set_all("expires", [email.utils.formatdate(f)])
|
2016-05-08 18:13:48 +00:00
|
|
|
else:
|
|
|
|
# This can happen when the expires tag is invalid.
|
|
|
|
# reddit.com sends a an expires tag like this: "Thu, 31 Dec
|
|
|
|
# 2037 23:59:59 GMT", which is valid RFC 1123, but not
|
|
|
|
# strictly correct according to the cookie spec. Browsers
|
|
|
|
# appear to parse this tolerantly - maybe we should too.
|
|
|
|
# For now, we just ignore this.
|
2016-05-19 05:50:19 +00:00
|
|
|
attrs = attrs.with_delitem("expires")
|
2016-05-08 18:13:48 +00:00
|
|
|
|
|
|
|
ret = format_set_cookie_header(name, value, attrs)
|
2016-04-02 20:49:05 +00:00
|
|
|
if not ret:
|
|
|
|
raise ValueError("Invalid Cookie")
|
|
|
|
return ret
|
2016-07-08 08:46:29 +00:00
|
|
|
|
2016-07-09 19:36:50 +00:00
|
|
|
|
2016-07-08 08:46:29 +00:00
|
|
|
def is_expired(cookie_attrs):
|
|
|
|
"""
|
|
|
|
Determines whether a cookie has expired.
|
|
|
|
|
|
|
|
Returns: boolean
|
|
|
|
"""
|
|
|
|
|
|
|
|
# See if 'expires' time is in the past
|
2016-07-09 19:36:50 +00:00
|
|
|
expires = False
|
2016-07-08 08:46:29 +00:00
|
|
|
if 'expires' in cookie_attrs:
|
|
|
|
e = email.utils.parsedate_tz(cookie_attrs["expires"])
|
|
|
|
if e:
|
|
|
|
exp_ts = email.utils.mktime_tz(e)
|
|
|
|
now_ts = time.time()
|
2016-07-09 19:36:50 +00:00
|
|
|
expires = exp_ts < now_ts
|
2016-07-08 08:46:29 +00:00
|
|
|
|
|
|
|
# or if Max-Age is 0
|
2016-07-09 19:36:50 +00:00
|
|
|
max_age = False
|
|
|
|
try:
|
|
|
|
max_age = int(cookie_attrs.get('Max-Age', 1)) == 0
|
|
|
|
except ValueError:
|
|
|
|
pass
|
2016-07-08 08:46:29 +00:00
|
|
|
|
2016-07-09 19:36:50 +00:00
|
|
|
return expires or max_age
|