jpayne@68: r"""HTTP cookie handling for web clients. jpayne@68: jpayne@68: This module has (now fairly distant) origins in Gisle Aas' Perl module jpayne@68: HTTP::Cookies, from the libwww-perl library. jpayne@68: jpayne@68: Docstrings, comments and debug strings in this code refer to the jpayne@68: attributes of the HTTP cookie system as cookie-attributes, to distinguish jpayne@68: them clearly from Python attributes. jpayne@68: jpayne@68: Class diagram (note that BSDDBCookieJar and the MSIE* classes are not jpayne@68: distributed with the Python standard library, but are available from jpayne@68: http://wwwsearch.sf.net/): jpayne@68: jpayne@68: CookieJar____ jpayne@68: / \ \ jpayne@68: FileCookieJar \ \ jpayne@68: / | \ \ \ jpayne@68: MozillaCookieJar | LWPCookieJar \ \ jpayne@68: | | \ jpayne@68: | ---MSIEBase | \ jpayne@68: | / | | \ jpayne@68: | / MSIEDBCookieJar BSDDBCookieJar jpayne@68: |/ jpayne@68: MSIECookieJar jpayne@68: jpayne@68: """ jpayne@68: jpayne@68: __all__ = ['Cookie', 'CookieJar', 'CookiePolicy', 'DefaultCookiePolicy', jpayne@68: 'FileCookieJar', 'LWPCookieJar', 'LoadError', 'MozillaCookieJar'] jpayne@68: jpayne@68: import os jpayne@68: import copy jpayne@68: import datetime jpayne@68: import re jpayne@68: import time jpayne@68: import urllib.parse, urllib.request jpayne@68: import threading as _threading jpayne@68: import http.client # only for the default HTTP port jpayne@68: from calendar import timegm jpayne@68: jpayne@68: debug = False # set to True to enable debugging via the logging module jpayne@68: logger = None jpayne@68: jpayne@68: def _debug(*args): jpayne@68: if not debug: jpayne@68: return jpayne@68: global logger jpayne@68: if not logger: jpayne@68: import logging jpayne@68: logger = logging.getLogger("http.cookiejar") jpayne@68: return logger.debug(*args) jpayne@68: jpayne@68: jpayne@68: DEFAULT_HTTP_PORT = str(http.client.HTTP_PORT) jpayne@68: MISSING_FILENAME_TEXT = ("a filename was not supplied (nor was the CookieJar " jpayne@68: "instance initialised with one)") jpayne@68: jpayne@68: def _warn_unhandled_exception(): jpayne@68: # There are a few catch-all except: statements in this module, for jpayne@68: # catching input that's bad in unexpected ways. Warn if any jpayne@68: # exceptions are caught there. jpayne@68: import io, warnings, traceback jpayne@68: f = io.StringIO() jpayne@68: traceback.print_exc(None, f) jpayne@68: msg = f.getvalue() jpayne@68: warnings.warn("http.cookiejar bug!\n%s" % msg, stacklevel=2) jpayne@68: jpayne@68: jpayne@68: # Date/time conversion jpayne@68: # ----------------------------------------------------------------------------- jpayne@68: jpayne@68: EPOCH_YEAR = 1970 jpayne@68: def _timegm(tt): jpayne@68: year, month, mday, hour, min, sec = tt[:6] jpayne@68: if ((year >= EPOCH_YEAR) and (1 <= month <= 12) and (1 <= mday <= 31) and jpayne@68: (0 <= hour <= 24) and (0 <= min <= 59) and (0 <= sec <= 61)): jpayne@68: return timegm(tt) jpayne@68: else: jpayne@68: return None jpayne@68: jpayne@68: DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] jpayne@68: MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", jpayne@68: "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] jpayne@68: MONTHS_LOWER = [] jpayne@68: for month in MONTHS: MONTHS_LOWER.append(month.lower()) jpayne@68: jpayne@68: def time2isoz(t=None): jpayne@68: """Return a string representing time in seconds since epoch, t. jpayne@68: jpayne@68: If the function is called without an argument, it will use the current jpayne@68: time. jpayne@68: jpayne@68: The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ", jpayne@68: representing Universal Time (UTC, aka GMT). An example of this format is: jpayne@68: jpayne@68: 1994-11-24 08:49:37Z jpayne@68: jpayne@68: """ jpayne@68: if t is None: jpayne@68: dt = datetime.datetime.utcnow() jpayne@68: else: jpayne@68: dt = datetime.datetime.utcfromtimestamp(t) jpayne@68: return "%04d-%02d-%02d %02d:%02d:%02dZ" % ( jpayne@68: dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) jpayne@68: jpayne@68: def time2netscape(t=None): jpayne@68: """Return a string representing time in seconds since epoch, t. jpayne@68: jpayne@68: If the function is called without an argument, it will use the current jpayne@68: time. jpayne@68: jpayne@68: The format of the returned string is like this: jpayne@68: jpayne@68: Wed, DD-Mon-YYYY HH:MM:SS GMT jpayne@68: jpayne@68: """ jpayne@68: if t is None: jpayne@68: dt = datetime.datetime.utcnow() jpayne@68: else: jpayne@68: dt = datetime.datetime.utcfromtimestamp(t) jpayne@68: return "%s, %02d-%s-%04d %02d:%02d:%02d GMT" % ( jpayne@68: DAYS[dt.weekday()], dt.day, MONTHS[dt.month-1], jpayne@68: dt.year, dt.hour, dt.minute, dt.second) jpayne@68: jpayne@68: jpayne@68: UTC_ZONES = {"GMT": None, "UTC": None, "UT": None, "Z": None} jpayne@68: jpayne@68: TIMEZONE_RE = re.compile(r"^([-+])?(\d\d?):?(\d\d)?$", re.ASCII) jpayne@68: def offset_from_tz_string(tz): jpayne@68: offset = None jpayne@68: if tz in UTC_ZONES: jpayne@68: offset = 0 jpayne@68: else: jpayne@68: m = TIMEZONE_RE.search(tz) jpayne@68: if m: jpayne@68: offset = 3600 * int(m.group(2)) jpayne@68: if m.group(3): jpayne@68: offset = offset + 60 * int(m.group(3)) jpayne@68: if m.group(1) == '-': jpayne@68: offset = -offset jpayne@68: return offset jpayne@68: jpayne@68: def _str2time(day, mon, yr, hr, min, sec, tz): jpayne@68: yr = int(yr) jpayne@68: if yr > datetime.MAXYEAR: jpayne@68: return None jpayne@68: jpayne@68: # translate month name to number jpayne@68: # month numbers start with 1 (January) jpayne@68: try: jpayne@68: mon = MONTHS_LOWER.index(mon.lower())+1 jpayne@68: except ValueError: jpayne@68: # maybe it's already a number jpayne@68: try: jpayne@68: imon = int(mon) jpayne@68: except ValueError: jpayne@68: return None jpayne@68: if 1 <= imon <= 12: jpayne@68: mon = imon jpayne@68: else: jpayne@68: return None jpayne@68: jpayne@68: # make sure clock elements are defined jpayne@68: if hr is None: hr = 0 jpayne@68: if min is None: min = 0 jpayne@68: if sec is None: sec = 0 jpayne@68: jpayne@68: day = int(day) jpayne@68: hr = int(hr) jpayne@68: min = int(min) jpayne@68: sec = int(sec) jpayne@68: jpayne@68: if yr < 1000: jpayne@68: # find "obvious" year jpayne@68: cur_yr = time.localtime(time.time())[0] jpayne@68: m = cur_yr % 100 jpayne@68: tmp = yr jpayne@68: yr = yr + cur_yr - m jpayne@68: m = m - tmp jpayne@68: if abs(m) > 50: jpayne@68: if m > 0: yr = yr + 100 jpayne@68: else: yr = yr - 100 jpayne@68: jpayne@68: # convert UTC time tuple to seconds since epoch (not timezone-adjusted) jpayne@68: t = _timegm((yr, mon, day, hr, min, sec, tz)) jpayne@68: jpayne@68: if t is not None: jpayne@68: # adjust time using timezone string, to get absolute time since epoch jpayne@68: if tz is None: jpayne@68: tz = "UTC" jpayne@68: tz = tz.upper() jpayne@68: offset = offset_from_tz_string(tz) jpayne@68: if offset is None: jpayne@68: return None jpayne@68: t = t - offset jpayne@68: jpayne@68: return t jpayne@68: jpayne@68: STRICT_DATE_RE = re.compile( jpayne@68: r"^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) " jpayne@68: r"(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$", re.ASCII) jpayne@68: WEEKDAY_RE = re.compile( jpayne@68: r"^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*", re.I | re.ASCII) jpayne@68: LOOSE_HTTP_DATE_RE = re.compile( jpayne@68: r"""^ jpayne@68: (\d\d?) # day jpayne@68: (?:\s+|[-\/]) jpayne@68: (\w+) # month jpayne@68: (?:\s+|[-\/]) jpayne@68: (\d+) # year jpayne@68: (?: jpayne@68: (?:\s+|:) # separator before clock jpayne@68: (\d\d?):(\d\d) # hour:min jpayne@68: (?::(\d\d))? # optional seconds jpayne@68: )? # optional clock jpayne@68: \s* jpayne@68: (?: jpayne@68: ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+) # timezone jpayne@68: \s* jpayne@68: )? jpayne@68: (?: jpayne@68: \(\w+\) # ASCII representation of timezone in parens. jpayne@68: \s* jpayne@68: )?$""", re.X | re.ASCII) jpayne@68: def http2time(text): jpayne@68: """Returns time in seconds since epoch of time represented by a string. jpayne@68: jpayne@68: Return value is an integer. jpayne@68: jpayne@68: None is returned if the format of str is unrecognized, the time is outside jpayne@68: the representable range, or the timezone string is not recognized. If the jpayne@68: string contains no timezone, UTC is assumed. jpayne@68: jpayne@68: The timezone in the string may be numerical (like "-0800" or "+0100") or a jpayne@68: string timezone (like "UTC", "GMT", "BST" or "EST"). Currently, only the jpayne@68: timezone strings equivalent to UTC (zero offset) are known to the function. jpayne@68: jpayne@68: The function loosely parses the following formats: jpayne@68: jpayne@68: Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format jpayne@68: Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format jpayne@68: Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format jpayne@68: 09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday) jpayne@68: 08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday) jpayne@68: 08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday) jpayne@68: jpayne@68: The parser ignores leading and trailing whitespace. The time may be jpayne@68: absent. jpayne@68: jpayne@68: If the year is given with only 2 digits, the function will select the jpayne@68: century that makes the year closest to the current date. jpayne@68: jpayne@68: """ jpayne@68: # fast exit for strictly conforming string jpayne@68: m = STRICT_DATE_RE.search(text) jpayne@68: if m: jpayne@68: g = m.groups() jpayne@68: mon = MONTHS_LOWER.index(g[1].lower()) + 1 jpayne@68: tt = (int(g[2]), mon, int(g[0]), jpayne@68: int(g[3]), int(g[4]), float(g[5])) jpayne@68: return _timegm(tt) jpayne@68: jpayne@68: # No, we need some messy parsing... jpayne@68: jpayne@68: # clean up jpayne@68: text = text.lstrip() jpayne@68: text = WEEKDAY_RE.sub("", text, 1) # Useless weekday jpayne@68: jpayne@68: # tz is time zone specifier string jpayne@68: day, mon, yr, hr, min, sec, tz = [None]*7 jpayne@68: jpayne@68: # loose regexp parse jpayne@68: m = LOOSE_HTTP_DATE_RE.search(text) jpayne@68: if m is not None: jpayne@68: day, mon, yr, hr, min, sec, tz = m.groups() jpayne@68: else: jpayne@68: return None # bad format jpayne@68: jpayne@68: return _str2time(day, mon, yr, hr, min, sec, tz) jpayne@68: jpayne@68: ISO_DATE_RE = re.compile( jpayne@68: r"""^ jpayne@68: (\d{4}) # year jpayne@68: [-\/]? jpayne@68: (\d\d?) # numerical month jpayne@68: [-\/]? jpayne@68: (\d\d?) # day jpayne@68: (?: jpayne@68: (?:\s+|[-:Tt]) # separator before clock jpayne@68: (\d\d?):?(\d\d) # hour:min jpayne@68: (?::?(\d\d(?:\.\d*)?))? # optional seconds (and fractional) jpayne@68: )? # optional clock jpayne@68: \s* jpayne@68: (?: jpayne@68: ([-+]?\d\d?:?(:?\d\d)? jpayne@68: |Z|z) # timezone (Z is "zero meridian", i.e. GMT) jpayne@68: \s* jpayne@68: )?$""", re.X | re. ASCII) jpayne@68: def iso2time(text): jpayne@68: """ jpayne@68: As for http2time, but parses the ISO 8601 formats: jpayne@68: jpayne@68: 1994-02-03 14:15:29 -0100 -- ISO 8601 format jpayne@68: 1994-02-03 14:15:29 -- zone is optional jpayne@68: 1994-02-03 -- only date jpayne@68: 1994-02-03T14:15:29 -- Use T as separator jpayne@68: 19940203T141529Z -- ISO 8601 compact format jpayne@68: 19940203 -- only date jpayne@68: jpayne@68: """ jpayne@68: # clean up jpayne@68: text = text.lstrip() jpayne@68: jpayne@68: # tz is time zone specifier string jpayne@68: day, mon, yr, hr, min, sec, tz = [None]*7 jpayne@68: jpayne@68: # loose regexp parse jpayne@68: m = ISO_DATE_RE.search(text) jpayne@68: if m is not None: jpayne@68: # XXX there's an extra bit of the timezone I'm ignoring here: is jpayne@68: # this the right thing to do? jpayne@68: yr, mon, day, hr, min, sec, tz, _ = m.groups() jpayne@68: else: jpayne@68: return None # bad format jpayne@68: jpayne@68: return _str2time(day, mon, yr, hr, min, sec, tz) jpayne@68: jpayne@68: jpayne@68: # Header parsing jpayne@68: # ----------------------------------------------------------------------------- jpayne@68: jpayne@68: def unmatched(match): jpayne@68: """Return unmatched part of re.Match object.""" jpayne@68: start, end = match.span(0) jpayne@68: return match.string[:start]+match.string[end:] jpayne@68: jpayne@68: HEADER_TOKEN_RE = re.compile(r"^\s*([^=\s;,]+)") jpayne@68: HEADER_QUOTED_VALUE_RE = re.compile(r"^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"") jpayne@68: HEADER_VALUE_RE = re.compile(r"^\s*=\s*([^\s;,]*)") jpayne@68: HEADER_ESCAPE_RE = re.compile(r"\\(.)") jpayne@68: def split_header_words(header_values): jpayne@68: r"""Parse header values into a list of lists containing key,value pairs. jpayne@68: jpayne@68: The function knows how to deal with ",", ";" and "=" as well as quoted jpayne@68: values after "=". A list of space separated tokens are parsed as if they jpayne@68: were separated by ";". jpayne@68: jpayne@68: If the header_values passed as argument contains multiple values, then they jpayne@68: are treated as if they were a single value separated by comma ",". jpayne@68: jpayne@68: This means that this function is useful for parsing header fields that jpayne@68: follow this syntax (BNF as from the HTTP/1.1 specification, but we relax jpayne@68: the requirement for tokens). jpayne@68: jpayne@68: headers = #header jpayne@68: header = (token | parameter) *( [";"] (token | parameter)) jpayne@68: jpayne@68: token = 1* jpayne@68: separators = "(" | ")" | "<" | ">" | "@" jpayne@68: | "," | ";" | ":" | "\" | <"> jpayne@68: | "/" | "[" | "]" | "?" | "=" jpayne@68: | "{" | "}" | SP | HT jpayne@68: jpayne@68: quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) jpayne@68: qdtext = > jpayne@68: quoted-pair = "\" CHAR jpayne@68: jpayne@68: parameter = attribute "=" value jpayne@68: attribute = token jpayne@68: value = token | quoted-string jpayne@68: jpayne@68: Each header is represented by a list of key/value pairs. The value for a jpayne@68: simple token (not part of a parameter) is None. Syntactically incorrect jpayne@68: headers will not necessarily be parsed as you would want. jpayne@68: jpayne@68: This is easier to describe with some examples: jpayne@68: jpayne@68: >>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz']) jpayne@68: [[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]] jpayne@68: >>> split_header_words(['text/html; charset="iso-8859-1"']) jpayne@68: [[('text/html', None), ('charset', 'iso-8859-1')]] jpayne@68: >>> split_header_words([r'Basic realm="\"foo\bar\""']) jpayne@68: [[('Basic', None), ('realm', '"foobar"')]] jpayne@68: jpayne@68: """ jpayne@68: assert not isinstance(header_values, str) jpayne@68: result = [] jpayne@68: for text in header_values: jpayne@68: orig_text = text jpayne@68: pairs = [] jpayne@68: while text: jpayne@68: m = HEADER_TOKEN_RE.search(text) jpayne@68: if m: jpayne@68: text = unmatched(m) jpayne@68: name = m.group(1) jpayne@68: m = HEADER_QUOTED_VALUE_RE.search(text) jpayne@68: if m: # quoted value jpayne@68: text = unmatched(m) jpayne@68: value = m.group(1) jpayne@68: value = HEADER_ESCAPE_RE.sub(r"\1", value) jpayne@68: else: jpayne@68: m = HEADER_VALUE_RE.search(text) jpayne@68: if m: # unquoted value jpayne@68: text = unmatched(m) jpayne@68: value = m.group(1) jpayne@68: value = value.rstrip() jpayne@68: else: jpayne@68: # no value, a lone token jpayne@68: value = None jpayne@68: pairs.append((name, value)) jpayne@68: elif text.lstrip().startswith(","): jpayne@68: # concatenated headers, as per RFC 2616 section 4.2 jpayne@68: text = text.lstrip()[1:] jpayne@68: if pairs: result.append(pairs) jpayne@68: pairs = [] jpayne@68: else: jpayne@68: # skip junk jpayne@68: non_junk, nr_junk_chars = re.subn(r"^[=\s;]*", "", text) jpayne@68: assert nr_junk_chars > 0, ( jpayne@68: "split_header_words bug: '%s', '%s', %s" % jpayne@68: (orig_text, text, pairs)) jpayne@68: text = non_junk jpayne@68: if pairs: result.append(pairs) jpayne@68: return result jpayne@68: jpayne@68: HEADER_JOIN_ESCAPE_RE = re.compile(r"([\"\\])") jpayne@68: def join_header_words(lists): jpayne@68: """Do the inverse (almost) of the conversion done by split_header_words. jpayne@68: jpayne@68: Takes a list of lists of (key, value) pairs and produces a single header jpayne@68: value. Attribute values are quoted if needed. jpayne@68: jpayne@68: >>> join_header_words([[("text/plain", None), ("charset", "iso-8859-1")]]) jpayne@68: 'text/plain; charset="iso-8859-1"' jpayne@68: >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859-1")]]) jpayne@68: 'text/plain, charset="iso-8859-1"' jpayne@68: jpayne@68: """ jpayne@68: headers = [] jpayne@68: for pairs in lists: jpayne@68: attr = [] jpayne@68: for k, v in pairs: jpayne@68: if v is not None: jpayne@68: if not re.search(r"^\w+$", v): jpayne@68: v = HEADER_JOIN_ESCAPE_RE.sub(r"\\\1", v) # escape " and \ jpayne@68: v = '"%s"' % v jpayne@68: k = "%s=%s" % (k, v) jpayne@68: attr.append(k) jpayne@68: if attr: headers.append("; ".join(attr)) jpayne@68: return ", ".join(headers) jpayne@68: jpayne@68: def strip_quotes(text): jpayne@68: if text.startswith('"'): jpayne@68: text = text[1:] jpayne@68: if text.endswith('"'): jpayne@68: text = text[:-1] jpayne@68: return text jpayne@68: jpayne@68: def parse_ns_headers(ns_headers): jpayne@68: """Ad-hoc parser for Netscape protocol cookie-attributes. jpayne@68: jpayne@68: The old Netscape cookie format for Set-Cookie can for instance contain jpayne@68: an unquoted "," in the expires field, so we have to use this ad-hoc jpayne@68: parser instead of split_header_words. jpayne@68: jpayne@68: XXX This may not make the best possible effort to parse all the crap jpayne@68: that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient jpayne@68: parser is probably better, so could do worse than following that if jpayne@68: this ever gives any trouble. jpayne@68: jpayne@68: Currently, this is also used for parsing RFC 2109 cookies. jpayne@68: jpayne@68: """ jpayne@68: known_attrs = ("expires", "domain", "path", "secure", jpayne@68: # RFC 2109 attrs (may turn up in Netscape cookies, too) jpayne@68: "version", "port", "max-age") jpayne@68: jpayne@68: result = [] jpayne@68: for ns_header in ns_headers: jpayne@68: pairs = [] jpayne@68: version_set = False jpayne@68: jpayne@68: # XXX: The following does not strictly adhere to RFCs in that empty jpayne@68: # names and values are legal (the former will only appear once and will jpayne@68: # be overwritten if multiple occurrences are present). This is jpayne@68: # mostly to deal with backwards compatibility. jpayne@68: for ii, param in enumerate(ns_header.split(';')): jpayne@68: param = param.strip() jpayne@68: jpayne@68: key, sep, val = param.partition('=') jpayne@68: key = key.strip() jpayne@68: jpayne@68: if not key: jpayne@68: if ii == 0: jpayne@68: break jpayne@68: else: jpayne@68: continue jpayne@68: jpayne@68: # allow for a distinction between present and empty and missing jpayne@68: # altogether jpayne@68: val = val.strip() if sep else None jpayne@68: jpayne@68: if ii != 0: jpayne@68: lc = key.lower() jpayne@68: if lc in known_attrs: jpayne@68: key = lc jpayne@68: jpayne@68: if key == "version": jpayne@68: # This is an RFC 2109 cookie. jpayne@68: if val is not None: jpayne@68: val = strip_quotes(val) jpayne@68: version_set = True jpayne@68: elif key == "expires": jpayne@68: # convert expires date to seconds since epoch jpayne@68: if val is not None: jpayne@68: val = http2time(strip_quotes(val)) # None if invalid jpayne@68: pairs.append((key, val)) jpayne@68: jpayne@68: if pairs: jpayne@68: if not version_set: jpayne@68: pairs.append(("version", "0")) jpayne@68: result.append(pairs) jpayne@68: jpayne@68: return result jpayne@68: jpayne@68: jpayne@68: IPV4_RE = re.compile(r"\.\d+$", re.ASCII) jpayne@68: def is_HDN(text): jpayne@68: """Return True if text is a host domain name.""" jpayne@68: # XXX jpayne@68: # This may well be wrong. Which RFC is HDN defined in, if any (for jpayne@68: # the purposes of RFC 2965)? jpayne@68: # For the current implementation, what about IPv6? Remember to look jpayne@68: # at other uses of IPV4_RE also, if change this. jpayne@68: if IPV4_RE.search(text): jpayne@68: return False jpayne@68: if text == "": jpayne@68: return False jpayne@68: if text[0] == "." or text[-1] == ".": jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def domain_match(A, B): jpayne@68: """Return True if domain A domain-matches domain B, according to RFC 2965. jpayne@68: jpayne@68: A and B may be host domain names or IP addresses. jpayne@68: jpayne@68: RFC 2965, section 1: jpayne@68: jpayne@68: Host names can be specified either as an IP address or a HDN string. jpayne@68: Sometimes we compare one host name with another. (Such comparisons SHALL jpayne@68: be case-insensitive.) Host A's name domain-matches host B's if jpayne@68: jpayne@68: * their host name strings string-compare equal; or jpayne@68: jpayne@68: * A is a HDN string and has the form NB, where N is a non-empty jpayne@68: name string, B has the form .B', and B' is a HDN string. (So, jpayne@68: x.y.com domain-matches .Y.com but not Y.com.) jpayne@68: jpayne@68: Note that domain-match is not a commutative operation: a.b.c.com jpayne@68: domain-matches .c.com, but not the reverse. jpayne@68: jpayne@68: """ jpayne@68: # Note that, if A or B are IP addresses, the only relevant part of the jpayne@68: # definition of the domain-match algorithm is the direct string-compare. jpayne@68: A = A.lower() jpayne@68: B = B.lower() jpayne@68: if A == B: jpayne@68: return True jpayne@68: if not is_HDN(A): jpayne@68: return False jpayne@68: i = A.rfind(B) jpayne@68: if i == -1 or i == 0: jpayne@68: # A does not have form NB, or N is the empty string jpayne@68: return False jpayne@68: if not B.startswith("."): jpayne@68: return False jpayne@68: if not is_HDN(B[1:]): jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def liberal_is_HDN(text): jpayne@68: """Return True if text is a sort-of-like a host domain name. jpayne@68: jpayne@68: For accepting/blocking domains. jpayne@68: jpayne@68: """ jpayne@68: if IPV4_RE.search(text): jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def user_domain_match(A, B): jpayne@68: """For blocking/accepting domains. jpayne@68: jpayne@68: A and B may be host domain names or IP addresses. jpayne@68: jpayne@68: """ jpayne@68: A = A.lower() jpayne@68: B = B.lower() jpayne@68: if not (liberal_is_HDN(A) and liberal_is_HDN(B)): jpayne@68: if A == B: jpayne@68: # equal IP addresses jpayne@68: return True jpayne@68: return False jpayne@68: initial_dot = B.startswith(".") jpayne@68: if initial_dot and A.endswith(B): jpayne@68: return True jpayne@68: if not initial_dot and A == B: jpayne@68: return True jpayne@68: return False jpayne@68: jpayne@68: cut_port_re = re.compile(r":\d+$", re.ASCII) jpayne@68: def request_host(request): jpayne@68: """Return request-host, as defined by RFC 2965. jpayne@68: jpayne@68: Variation from RFC: returned value is lowercased, for convenient jpayne@68: comparison. jpayne@68: jpayne@68: """ jpayne@68: url = request.get_full_url() jpayne@68: host = urllib.parse.urlparse(url)[1] jpayne@68: if host == "": jpayne@68: host = request.get_header("Host", "") jpayne@68: jpayne@68: # remove port, if present jpayne@68: host = cut_port_re.sub("", host, 1) jpayne@68: return host.lower() jpayne@68: jpayne@68: def eff_request_host(request): jpayne@68: """Return a tuple (request-host, effective request-host name). jpayne@68: jpayne@68: As defined by RFC 2965, except both are lowercased. jpayne@68: jpayne@68: """ jpayne@68: erhn = req_host = request_host(request) jpayne@68: if req_host.find(".") == -1 and not IPV4_RE.search(req_host): jpayne@68: erhn = req_host + ".local" jpayne@68: return req_host, erhn jpayne@68: jpayne@68: def request_path(request): jpayne@68: """Path component of request-URI, as defined by RFC 2965.""" jpayne@68: url = request.get_full_url() jpayne@68: parts = urllib.parse.urlsplit(url) jpayne@68: path = escape_path(parts.path) jpayne@68: if not path.startswith("/"): jpayne@68: # fix bad RFC 2396 absoluteURI jpayne@68: path = "/" + path jpayne@68: return path jpayne@68: jpayne@68: def request_port(request): jpayne@68: host = request.host jpayne@68: i = host.find(':') jpayne@68: if i >= 0: jpayne@68: port = host[i+1:] jpayne@68: try: jpayne@68: int(port) jpayne@68: except ValueError: jpayne@68: _debug("nonnumeric port: '%s'", port) jpayne@68: return None jpayne@68: else: jpayne@68: port = DEFAULT_HTTP_PORT jpayne@68: return port jpayne@68: jpayne@68: # Characters in addition to A-Z, a-z, 0-9, '_', '.', and '-' that don't jpayne@68: # need to be escaped to form a valid HTTP URL (RFCs 2396 and 1738). jpayne@68: HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()" jpayne@68: ESCAPED_CHAR_RE = re.compile(r"%([0-9a-fA-F][0-9a-fA-F])") jpayne@68: def uppercase_escaped_char(match): jpayne@68: return "%%%s" % match.group(1).upper() jpayne@68: def escape_path(path): jpayne@68: """Escape any invalid characters in HTTP URL, and uppercase all escapes.""" jpayne@68: # There's no knowing what character encoding was used to create URLs jpayne@68: # containing %-escapes, but since we have to pick one to escape invalid jpayne@68: # path characters, we pick UTF-8, as recommended in the HTML 4.0 jpayne@68: # specification: jpayne@68: # http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1 jpayne@68: # And here, kind of: draft-fielding-uri-rfc2396bis-03 jpayne@68: # (And in draft IRI specification: draft-duerst-iri-05) jpayne@68: # (And here, for new URI schemes: RFC 2718) jpayne@68: path = urllib.parse.quote(path, HTTP_PATH_SAFE) jpayne@68: path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path) jpayne@68: return path jpayne@68: jpayne@68: def reach(h): jpayne@68: """Return reach of host h, as defined by RFC 2965, section 1. jpayne@68: jpayne@68: The reach R of a host name H is defined as follows: jpayne@68: jpayne@68: * If jpayne@68: jpayne@68: - H is the host domain name of a host; and, jpayne@68: jpayne@68: - H has the form A.B; and jpayne@68: jpayne@68: - A has no embedded (that is, interior) dots; and jpayne@68: jpayne@68: - B has at least one embedded dot, or B is the string "local". jpayne@68: then the reach of H is .B. jpayne@68: jpayne@68: * Otherwise, the reach of H is H. jpayne@68: jpayne@68: >>> reach("www.acme.com") jpayne@68: '.acme.com' jpayne@68: >>> reach("acme.com") jpayne@68: 'acme.com' jpayne@68: >>> reach("acme.local") jpayne@68: '.local' jpayne@68: jpayne@68: """ jpayne@68: i = h.find(".") jpayne@68: if i >= 0: jpayne@68: #a = h[:i] # this line is only here to show what a is jpayne@68: b = h[i+1:] jpayne@68: i = b.find(".") jpayne@68: if is_HDN(h) and (i >= 0 or b == "local"): jpayne@68: return "."+b jpayne@68: return h jpayne@68: jpayne@68: def is_third_party(request): jpayne@68: """ jpayne@68: jpayne@68: RFC 2965, section 3.3.6: jpayne@68: jpayne@68: An unverifiable transaction is to a third-party host if its request- jpayne@68: host U does not domain-match the reach R of the request-host O in the jpayne@68: origin transaction. jpayne@68: jpayne@68: """ jpayne@68: req_host = request_host(request) jpayne@68: if not domain_match(req_host, reach(request.origin_req_host)): jpayne@68: return True jpayne@68: else: jpayne@68: return False jpayne@68: jpayne@68: jpayne@68: class Cookie: jpayne@68: """HTTP Cookie. jpayne@68: jpayne@68: This class represents both Netscape and RFC 2965 cookies. jpayne@68: jpayne@68: This is deliberately a very simple class. It just holds attributes. It's jpayne@68: possible to construct Cookie instances that don't comply with the cookie jpayne@68: standards. CookieJar.make_cookies is the factory function for Cookie jpayne@68: objects -- it deals with cookie parsing, supplying defaults, and jpayne@68: normalising to the representation used in this class. CookiePolicy is jpayne@68: responsible for checking them to see whether they should be accepted from jpayne@68: and returned to the server. jpayne@68: jpayne@68: Note that the port may be present in the headers, but unspecified ("Port" jpayne@68: rather than"Port=80", for example); if this is the case, port is None. jpayne@68: jpayne@68: """ jpayne@68: jpayne@68: def __init__(self, version, name, value, jpayne@68: port, port_specified, jpayne@68: domain, domain_specified, domain_initial_dot, jpayne@68: path, path_specified, jpayne@68: secure, jpayne@68: expires, jpayne@68: discard, jpayne@68: comment, jpayne@68: comment_url, jpayne@68: rest, jpayne@68: rfc2109=False, jpayne@68: ): jpayne@68: jpayne@68: if version is not None: version = int(version) jpayne@68: if expires is not None: expires = int(float(expires)) jpayne@68: if port is None and port_specified is True: jpayne@68: raise ValueError("if port is None, port_specified must be false") jpayne@68: jpayne@68: self.version = version jpayne@68: self.name = name jpayne@68: self.value = value jpayne@68: self.port = port jpayne@68: self.port_specified = port_specified jpayne@68: # normalise case, as per RFC 2965 section 3.3.3 jpayne@68: self.domain = domain.lower() jpayne@68: self.domain_specified = domain_specified jpayne@68: # Sigh. We need to know whether the domain given in the jpayne@68: # cookie-attribute had an initial dot, in order to follow RFC 2965 jpayne@68: # (as clarified in draft errata). Needed for the returned $Domain jpayne@68: # value. jpayne@68: self.domain_initial_dot = domain_initial_dot jpayne@68: self.path = path jpayne@68: self.path_specified = path_specified jpayne@68: self.secure = secure jpayne@68: self.expires = expires jpayne@68: self.discard = discard jpayne@68: self.comment = comment jpayne@68: self.comment_url = comment_url jpayne@68: self.rfc2109 = rfc2109 jpayne@68: jpayne@68: self._rest = copy.copy(rest) jpayne@68: jpayne@68: def has_nonstandard_attr(self, name): jpayne@68: return name in self._rest jpayne@68: def get_nonstandard_attr(self, name, default=None): jpayne@68: return self._rest.get(name, default) jpayne@68: def set_nonstandard_attr(self, name, value): jpayne@68: self._rest[name] = value jpayne@68: jpayne@68: def is_expired(self, now=None): jpayne@68: if now is None: now = time.time() jpayne@68: if (self.expires is not None) and (self.expires <= now): jpayne@68: return True jpayne@68: return False jpayne@68: jpayne@68: def __str__(self): jpayne@68: if self.port is None: p = "" jpayne@68: else: p = ":"+self.port jpayne@68: limit = self.domain + p + self.path jpayne@68: if self.value is not None: jpayne@68: namevalue = "%s=%s" % (self.name, self.value) jpayne@68: else: jpayne@68: namevalue = self.name jpayne@68: return "" % (namevalue, limit) jpayne@68: jpayne@68: def __repr__(self): jpayne@68: args = [] jpayne@68: for name in ("version", "name", "value", jpayne@68: "port", "port_specified", jpayne@68: "domain", "domain_specified", "domain_initial_dot", jpayne@68: "path", "path_specified", jpayne@68: "secure", "expires", "discard", "comment", "comment_url", jpayne@68: ): jpayne@68: attr = getattr(self, name) jpayne@68: args.append("%s=%s" % (name, repr(attr))) jpayne@68: args.append("rest=%s" % repr(self._rest)) jpayne@68: args.append("rfc2109=%s" % repr(self.rfc2109)) jpayne@68: return "%s(%s)" % (self.__class__.__name__, ", ".join(args)) jpayne@68: jpayne@68: jpayne@68: class CookiePolicy: jpayne@68: """Defines which cookies get accepted from and returned to server. jpayne@68: jpayne@68: May also modify cookies, though this is probably a bad idea. jpayne@68: jpayne@68: The subclass DefaultCookiePolicy defines the standard rules for Netscape jpayne@68: and RFC 2965 cookies -- override that if you want a customized policy. jpayne@68: jpayne@68: """ jpayne@68: def set_ok(self, cookie, request): jpayne@68: """Return true if (and only if) cookie should be accepted from server. jpayne@68: jpayne@68: Currently, pre-expired cookies never get this far -- the CookieJar jpayne@68: class deletes such cookies itself. jpayne@68: jpayne@68: """ jpayne@68: raise NotImplementedError() jpayne@68: jpayne@68: def return_ok(self, cookie, request): jpayne@68: """Return true if (and only if) cookie should be returned to server.""" jpayne@68: raise NotImplementedError() jpayne@68: jpayne@68: def domain_return_ok(self, domain, request): jpayne@68: """Return false if cookies should not be returned, given cookie domain. jpayne@68: """ jpayne@68: return True jpayne@68: jpayne@68: def path_return_ok(self, path, request): jpayne@68: """Return false if cookies should not be returned, given cookie path. jpayne@68: """ jpayne@68: return True jpayne@68: jpayne@68: jpayne@68: class DefaultCookiePolicy(CookiePolicy): jpayne@68: """Implements the standard rules for accepting and returning cookies.""" jpayne@68: jpayne@68: DomainStrictNoDots = 1 jpayne@68: DomainStrictNonDomain = 2 jpayne@68: DomainRFC2965Match = 4 jpayne@68: jpayne@68: DomainLiberal = 0 jpayne@68: DomainStrict = DomainStrictNoDots|DomainStrictNonDomain jpayne@68: jpayne@68: def __init__(self, jpayne@68: blocked_domains=None, allowed_domains=None, jpayne@68: netscape=True, rfc2965=False, jpayne@68: rfc2109_as_netscape=None, jpayne@68: hide_cookie2=False, jpayne@68: strict_domain=False, jpayne@68: strict_rfc2965_unverifiable=True, jpayne@68: strict_ns_unverifiable=False, jpayne@68: strict_ns_domain=DomainLiberal, jpayne@68: strict_ns_set_initial_dollar=False, jpayne@68: strict_ns_set_path=False, jpayne@68: secure_protocols=("https", "wss") jpayne@68: ): jpayne@68: """Constructor arguments should be passed as keyword arguments only.""" jpayne@68: self.netscape = netscape jpayne@68: self.rfc2965 = rfc2965 jpayne@68: self.rfc2109_as_netscape = rfc2109_as_netscape jpayne@68: self.hide_cookie2 = hide_cookie2 jpayne@68: self.strict_domain = strict_domain jpayne@68: self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable jpayne@68: self.strict_ns_unverifiable = strict_ns_unverifiable jpayne@68: self.strict_ns_domain = strict_ns_domain jpayne@68: self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar jpayne@68: self.strict_ns_set_path = strict_ns_set_path jpayne@68: self.secure_protocols = secure_protocols jpayne@68: jpayne@68: if blocked_domains is not None: jpayne@68: self._blocked_domains = tuple(blocked_domains) jpayne@68: else: jpayne@68: self._blocked_domains = () jpayne@68: jpayne@68: if allowed_domains is not None: jpayne@68: allowed_domains = tuple(allowed_domains) jpayne@68: self._allowed_domains = allowed_domains jpayne@68: jpayne@68: def blocked_domains(self): jpayne@68: """Return the sequence of blocked domains (as a tuple).""" jpayne@68: return self._blocked_domains jpayne@68: def set_blocked_domains(self, blocked_domains): jpayne@68: """Set the sequence of blocked domains.""" jpayne@68: self._blocked_domains = tuple(blocked_domains) jpayne@68: jpayne@68: def is_blocked(self, domain): jpayne@68: for blocked_domain in self._blocked_domains: jpayne@68: if user_domain_match(domain, blocked_domain): jpayne@68: return True jpayne@68: return False jpayne@68: jpayne@68: def allowed_domains(self): jpayne@68: """Return None, or the sequence of allowed domains (as a tuple).""" jpayne@68: return self._allowed_domains jpayne@68: def set_allowed_domains(self, allowed_domains): jpayne@68: """Set the sequence of allowed domains, or None.""" jpayne@68: if allowed_domains is not None: jpayne@68: allowed_domains = tuple(allowed_domains) jpayne@68: self._allowed_domains = allowed_domains jpayne@68: jpayne@68: def is_not_allowed(self, domain): jpayne@68: if self._allowed_domains is None: jpayne@68: return False jpayne@68: for allowed_domain in self._allowed_domains: jpayne@68: if user_domain_match(domain, allowed_domain): jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def set_ok(self, cookie, request): jpayne@68: """ jpayne@68: If you override .set_ok(), be sure to call this method. If it returns jpayne@68: false, so should your subclass (assuming your subclass wants to be more jpayne@68: strict about which cookies to accept). jpayne@68: jpayne@68: """ jpayne@68: _debug(" - checking cookie %s=%s", cookie.name, cookie.value) jpayne@68: jpayne@68: assert cookie.name is not None jpayne@68: jpayne@68: for n in "version", "verifiability", "name", "path", "domain", "port": jpayne@68: fn_name = "set_ok_"+n jpayne@68: fn = getattr(self, fn_name) jpayne@68: if not fn(cookie, request): jpayne@68: return False jpayne@68: jpayne@68: return True jpayne@68: jpayne@68: def set_ok_version(self, cookie, request): jpayne@68: if cookie.version is None: jpayne@68: # Version is always set to 0 by parse_ns_headers if it's a Netscape jpayne@68: # cookie, so this must be an invalid RFC 2965 cookie. jpayne@68: _debug(" Set-Cookie2 without version attribute (%s=%s)", jpayne@68: cookie.name, cookie.value) jpayne@68: return False jpayne@68: if cookie.version > 0 and not self.rfc2965: jpayne@68: _debug(" RFC 2965 cookies are switched off") jpayne@68: return False jpayne@68: elif cookie.version == 0 and not self.netscape: jpayne@68: _debug(" Netscape cookies are switched off") jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def set_ok_verifiability(self, cookie, request): jpayne@68: if request.unverifiable and is_third_party(request): jpayne@68: if cookie.version > 0 and self.strict_rfc2965_unverifiable: jpayne@68: _debug(" third-party RFC 2965 cookie during " jpayne@68: "unverifiable transaction") jpayne@68: return False jpayne@68: elif cookie.version == 0 and self.strict_ns_unverifiable: jpayne@68: _debug(" third-party Netscape cookie during " jpayne@68: "unverifiable transaction") jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def set_ok_name(self, cookie, request): jpayne@68: # Try and stop servers setting V0 cookies designed to hack other jpayne@68: # servers that know both V0 and V1 protocols. jpayne@68: if (cookie.version == 0 and self.strict_ns_set_initial_dollar and jpayne@68: cookie.name.startswith("$")): jpayne@68: _debug(" illegal name (starts with '$'): '%s'", cookie.name) jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def set_ok_path(self, cookie, request): jpayne@68: if cookie.path_specified: jpayne@68: req_path = request_path(request) jpayne@68: if ((cookie.version > 0 or jpayne@68: (cookie.version == 0 and self.strict_ns_set_path)) and jpayne@68: not self.path_return_ok(cookie.path, request)): jpayne@68: _debug(" path attribute %s is not a prefix of request " jpayne@68: "path %s", cookie.path, req_path) jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def set_ok_domain(self, cookie, request): jpayne@68: if self.is_blocked(cookie.domain): jpayne@68: _debug(" domain %s is in user block-list", cookie.domain) jpayne@68: return False jpayne@68: if self.is_not_allowed(cookie.domain): jpayne@68: _debug(" domain %s is not in user allow-list", cookie.domain) jpayne@68: return False jpayne@68: if cookie.domain_specified: jpayne@68: req_host, erhn = eff_request_host(request) jpayne@68: domain = cookie.domain jpayne@68: if self.strict_domain and (domain.count(".") >= 2): jpayne@68: # XXX This should probably be compared with the Konqueror jpayne@68: # (kcookiejar.cpp) and Mozilla implementations, but it's a jpayne@68: # losing battle. jpayne@68: i = domain.rfind(".") jpayne@68: j = domain.rfind(".", 0, i) jpayne@68: if j == 0: # domain like .foo.bar jpayne@68: tld = domain[i+1:] jpayne@68: sld = domain[j+1:i] jpayne@68: if sld.lower() in ("co", "ac", "com", "edu", "org", "net", jpayne@68: "gov", "mil", "int", "aero", "biz", "cat", "coop", jpayne@68: "info", "jobs", "mobi", "museum", "name", "pro", jpayne@68: "travel", "eu") and len(tld) == 2: jpayne@68: # domain like .co.uk jpayne@68: _debug(" country-code second level domain %s", domain) jpayne@68: return False jpayne@68: if domain.startswith("."): jpayne@68: undotted_domain = domain[1:] jpayne@68: else: jpayne@68: undotted_domain = domain jpayne@68: embedded_dots = (undotted_domain.find(".") >= 0) jpayne@68: if not embedded_dots and domain != ".local": jpayne@68: _debug(" non-local domain %s contains no embedded dot", jpayne@68: domain) jpayne@68: return False jpayne@68: if cookie.version == 0: jpayne@68: if (not erhn.endswith(domain) and jpayne@68: (not erhn.startswith(".") and jpayne@68: not ("."+erhn).endswith(domain))): jpayne@68: _debug(" effective request-host %s (even with added " jpayne@68: "initial dot) does not end with %s", jpayne@68: erhn, domain) jpayne@68: return False jpayne@68: if (cookie.version > 0 or jpayne@68: (self.strict_ns_domain & self.DomainRFC2965Match)): jpayne@68: if not domain_match(erhn, domain): jpayne@68: _debug(" effective request-host %s does not domain-match " jpayne@68: "%s", erhn, domain) jpayne@68: return False jpayne@68: if (cookie.version > 0 or jpayne@68: (self.strict_ns_domain & self.DomainStrictNoDots)): jpayne@68: host_prefix = req_host[:-len(domain)] jpayne@68: if (host_prefix.find(".") >= 0 and jpayne@68: not IPV4_RE.search(req_host)): jpayne@68: _debug(" host prefix %s for domain %s contains a dot", jpayne@68: host_prefix, domain) jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def set_ok_port(self, cookie, request): jpayne@68: if cookie.port_specified: jpayne@68: req_port = request_port(request) jpayne@68: if req_port is None: jpayne@68: req_port = "80" jpayne@68: else: jpayne@68: req_port = str(req_port) jpayne@68: for p in cookie.port.split(","): jpayne@68: try: jpayne@68: int(p) jpayne@68: except ValueError: jpayne@68: _debug(" bad port %s (not numeric)", p) jpayne@68: return False jpayne@68: if p == req_port: jpayne@68: break jpayne@68: else: jpayne@68: _debug(" request port (%s) not found in %s", jpayne@68: req_port, cookie.port) jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def return_ok(self, cookie, request): jpayne@68: """ jpayne@68: If you override .return_ok(), be sure to call this method. If it jpayne@68: returns false, so should your subclass (assuming your subclass wants to jpayne@68: be more strict about which cookies to return). jpayne@68: jpayne@68: """ jpayne@68: # Path has already been checked by .path_return_ok(), and domain jpayne@68: # blocking done by .domain_return_ok(). jpayne@68: _debug(" - checking cookie %s=%s", cookie.name, cookie.value) jpayne@68: jpayne@68: for n in "version", "verifiability", "secure", "expires", "port", "domain": jpayne@68: fn_name = "return_ok_"+n jpayne@68: fn = getattr(self, fn_name) jpayne@68: if not fn(cookie, request): jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def return_ok_version(self, cookie, request): jpayne@68: if cookie.version > 0 and not self.rfc2965: jpayne@68: _debug(" RFC 2965 cookies are switched off") jpayne@68: return False jpayne@68: elif cookie.version == 0 and not self.netscape: jpayne@68: _debug(" Netscape cookies are switched off") jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def return_ok_verifiability(self, cookie, request): jpayne@68: if request.unverifiable and is_third_party(request): jpayne@68: if cookie.version > 0 and self.strict_rfc2965_unverifiable: jpayne@68: _debug(" third-party RFC 2965 cookie during unverifiable " jpayne@68: "transaction") jpayne@68: return False jpayne@68: elif cookie.version == 0 and self.strict_ns_unverifiable: jpayne@68: _debug(" third-party Netscape cookie during unverifiable " jpayne@68: "transaction") jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def return_ok_secure(self, cookie, request): jpayne@68: if cookie.secure and request.type not in self.secure_protocols: jpayne@68: _debug(" secure cookie with non-secure request") jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def return_ok_expires(self, cookie, request): jpayne@68: if cookie.is_expired(self._now): jpayne@68: _debug(" cookie expired") jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def return_ok_port(self, cookie, request): jpayne@68: if cookie.port: jpayne@68: req_port = request_port(request) jpayne@68: if req_port is None: jpayne@68: req_port = "80" jpayne@68: for p in cookie.port.split(","): jpayne@68: if p == req_port: jpayne@68: break jpayne@68: else: jpayne@68: _debug(" request port %s does not match cookie port %s", jpayne@68: req_port, cookie.port) jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def return_ok_domain(self, cookie, request): jpayne@68: req_host, erhn = eff_request_host(request) jpayne@68: domain = cookie.domain jpayne@68: jpayne@68: if domain and not domain.startswith("."): jpayne@68: dotdomain = "." + domain jpayne@68: else: jpayne@68: dotdomain = domain jpayne@68: jpayne@68: # strict check of non-domain cookies: Mozilla does this, MSIE5 doesn't jpayne@68: if (cookie.version == 0 and jpayne@68: (self.strict_ns_domain & self.DomainStrictNonDomain) and jpayne@68: not cookie.domain_specified and domain != erhn): jpayne@68: _debug(" cookie with unspecified domain does not string-compare " jpayne@68: "equal to request domain") jpayne@68: return False jpayne@68: jpayne@68: if cookie.version > 0 and not domain_match(erhn, domain): jpayne@68: _debug(" effective request-host name %s does not domain-match " jpayne@68: "RFC 2965 cookie domain %s", erhn, domain) jpayne@68: return False jpayne@68: if cookie.version == 0 and not ("."+erhn).endswith(dotdomain): jpayne@68: _debug(" request-host %s does not match Netscape cookie domain " jpayne@68: "%s", req_host, domain) jpayne@68: return False jpayne@68: return True jpayne@68: jpayne@68: def domain_return_ok(self, domain, request): jpayne@68: # Liberal check of. This is here as an optimization to avoid jpayne@68: # having to load lots of MSIE cookie files unless necessary. jpayne@68: req_host, erhn = eff_request_host(request) jpayne@68: if not req_host.startswith("."): jpayne@68: req_host = "."+req_host jpayne@68: if not erhn.startswith("."): jpayne@68: erhn = "."+erhn jpayne@68: if domain and not domain.startswith("."): jpayne@68: dotdomain = "." + domain jpayne@68: else: jpayne@68: dotdomain = domain jpayne@68: if not (req_host.endswith(dotdomain) or erhn.endswith(dotdomain)): jpayne@68: #_debug(" request domain %s does not match cookie domain %s", jpayne@68: # req_host, domain) jpayne@68: return False jpayne@68: jpayne@68: if self.is_blocked(domain): jpayne@68: _debug(" domain %s is in user block-list", domain) jpayne@68: return False jpayne@68: if self.is_not_allowed(domain): jpayne@68: _debug(" domain %s is not in user allow-list", domain) jpayne@68: return False jpayne@68: jpayne@68: return True jpayne@68: jpayne@68: def path_return_ok(self, path, request): jpayne@68: _debug("- checking cookie path=%s", path) jpayne@68: req_path = request_path(request) jpayne@68: pathlen = len(path) jpayne@68: if req_path == path: jpayne@68: return True jpayne@68: elif (req_path.startswith(path) and jpayne@68: (path.endswith("/") or req_path[pathlen:pathlen+1] == "/")): jpayne@68: return True jpayne@68: jpayne@68: _debug(" %s does not path-match %s", req_path, path) jpayne@68: return False jpayne@68: jpayne@68: def vals_sorted_by_key(adict): jpayne@68: keys = sorted(adict.keys()) jpayne@68: return map(adict.get, keys) jpayne@68: jpayne@68: def deepvalues(mapping): jpayne@68: """Iterates over nested mapping, depth-first, in sorted order by key.""" jpayne@68: values = vals_sorted_by_key(mapping) jpayne@68: for obj in values: jpayne@68: mapping = False jpayne@68: try: jpayne@68: obj.items jpayne@68: except AttributeError: jpayne@68: pass jpayne@68: else: jpayne@68: mapping = True jpayne@68: yield from deepvalues(obj) jpayne@68: if not mapping: jpayne@68: yield obj jpayne@68: jpayne@68: jpayne@68: # Used as second parameter to dict.get() method, to distinguish absent jpayne@68: # dict key from one with a None value. jpayne@68: class Absent: pass jpayne@68: jpayne@68: class CookieJar: jpayne@68: """Collection of HTTP cookies. jpayne@68: jpayne@68: You may not need to know about this class: try jpayne@68: urllib.request.build_opener(HTTPCookieProcessor).open(url). jpayne@68: """ jpayne@68: jpayne@68: non_word_re = re.compile(r"\W") jpayne@68: quote_re = re.compile(r"([\"\\])") jpayne@68: strict_domain_re = re.compile(r"\.?[^.]*") jpayne@68: domain_re = re.compile(r"[^.]*") jpayne@68: dots_re = re.compile(r"^\.+") jpayne@68: jpayne@68: magic_re = re.compile(r"^\#LWP-Cookies-(\d+\.\d+)", re.ASCII) jpayne@68: jpayne@68: def __init__(self, policy=None): jpayne@68: if policy is None: jpayne@68: policy = DefaultCookiePolicy() jpayne@68: self._policy = policy jpayne@68: jpayne@68: self._cookies_lock = _threading.RLock() jpayne@68: self._cookies = {} jpayne@68: jpayne@68: def set_policy(self, policy): jpayne@68: self._policy = policy jpayne@68: jpayne@68: def _cookies_for_domain(self, domain, request): jpayne@68: cookies = [] jpayne@68: if not self._policy.domain_return_ok(domain, request): jpayne@68: return [] jpayne@68: _debug("Checking %s for cookies to return", domain) jpayne@68: cookies_by_path = self._cookies[domain] jpayne@68: for path in cookies_by_path.keys(): jpayne@68: if not self._policy.path_return_ok(path, request): jpayne@68: continue jpayne@68: cookies_by_name = cookies_by_path[path] jpayne@68: for cookie in cookies_by_name.values(): jpayne@68: if not self._policy.return_ok(cookie, request): jpayne@68: _debug(" not returning cookie") jpayne@68: continue jpayne@68: _debug(" it's a match") jpayne@68: cookies.append(cookie) jpayne@68: return cookies jpayne@68: jpayne@68: def _cookies_for_request(self, request): jpayne@68: """Return a list of cookies to be returned to server.""" jpayne@68: cookies = [] jpayne@68: for domain in self._cookies.keys(): jpayne@68: cookies.extend(self._cookies_for_domain(domain, request)) jpayne@68: return cookies jpayne@68: jpayne@68: def _cookie_attrs(self, cookies): jpayne@68: """Return a list of cookie-attributes to be returned to server. jpayne@68: jpayne@68: like ['foo="bar"; $Path="/"', ...] jpayne@68: jpayne@68: The $Version attribute is also added when appropriate (currently only jpayne@68: once per request). jpayne@68: jpayne@68: """ jpayne@68: # add cookies in order of most specific (ie. longest) path first jpayne@68: cookies.sort(key=lambda a: len(a.path), reverse=True) jpayne@68: jpayne@68: version_set = False jpayne@68: jpayne@68: attrs = [] jpayne@68: for cookie in cookies: jpayne@68: # set version of Cookie header jpayne@68: # XXX jpayne@68: # What should it be if multiple matching Set-Cookie headers have jpayne@68: # different versions themselves? jpayne@68: # Answer: there is no answer; was supposed to be settled by jpayne@68: # RFC 2965 errata, but that may never appear... jpayne@68: version = cookie.version jpayne@68: if not version_set: jpayne@68: version_set = True jpayne@68: if version > 0: jpayne@68: attrs.append("$Version=%s" % version) jpayne@68: jpayne@68: # quote cookie value if necessary jpayne@68: # (not for Netscape protocol, which already has any quotes jpayne@68: # intact, due to the poorly-specified Netscape Cookie: syntax) jpayne@68: if ((cookie.value is not None) and jpayne@68: self.non_word_re.search(cookie.value) and version > 0): jpayne@68: value = self.quote_re.sub(r"\\\1", cookie.value) jpayne@68: else: jpayne@68: value = cookie.value jpayne@68: jpayne@68: # add cookie-attributes to be returned in Cookie header jpayne@68: if cookie.value is None: jpayne@68: attrs.append(cookie.name) jpayne@68: else: jpayne@68: attrs.append("%s=%s" % (cookie.name, value)) jpayne@68: if version > 0: jpayne@68: if cookie.path_specified: jpayne@68: attrs.append('$Path="%s"' % cookie.path) jpayne@68: if cookie.domain.startswith("."): jpayne@68: domain = cookie.domain jpayne@68: if (not cookie.domain_initial_dot and jpayne@68: domain.startswith(".")): jpayne@68: domain = domain[1:] jpayne@68: attrs.append('$Domain="%s"' % domain) jpayne@68: if cookie.port is not None: jpayne@68: p = "$Port" jpayne@68: if cookie.port_specified: jpayne@68: p = p + ('="%s"' % cookie.port) jpayne@68: attrs.append(p) jpayne@68: jpayne@68: return attrs jpayne@68: jpayne@68: def add_cookie_header(self, request): jpayne@68: """Add correct Cookie: header to request (urllib.request.Request object). jpayne@68: jpayne@68: The Cookie2 header is also added unless policy.hide_cookie2 is true. jpayne@68: jpayne@68: """ jpayne@68: _debug("add_cookie_header") jpayne@68: self._cookies_lock.acquire() jpayne@68: try: jpayne@68: jpayne@68: self._policy._now = self._now = int(time.time()) jpayne@68: jpayne@68: cookies = self._cookies_for_request(request) jpayne@68: jpayne@68: attrs = self._cookie_attrs(cookies) jpayne@68: if attrs: jpayne@68: if not request.has_header("Cookie"): jpayne@68: request.add_unredirected_header( jpayne@68: "Cookie", "; ".join(attrs)) jpayne@68: jpayne@68: # if necessary, advertise that we know RFC 2965 jpayne@68: if (self._policy.rfc2965 and not self._policy.hide_cookie2 and jpayne@68: not request.has_header("Cookie2")): jpayne@68: for cookie in cookies: jpayne@68: if cookie.version != 1: jpayne@68: request.add_unredirected_header("Cookie2", '$Version="1"') jpayne@68: break jpayne@68: jpayne@68: finally: jpayne@68: self._cookies_lock.release() jpayne@68: jpayne@68: self.clear_expired_cookies() jpayne@68: jpayne@68: def _normalized_cookie_tuples(self, attrs_set): jpayne@68: """Return list of tuples containing normalised cookie information. jpayne@68: jpayne@68: attrs_set is the list of lists of key,value pairs extracted from jpayne@68: the Set-Cookie or Set-Cookie2 headers. jpayne@68: jpayne@68: Tuples are name, value, standard, rest, where name and value are the jpayne@68: cookie name and value, standard is a dictionary containing the standard jpayne@68: cookie-attributes (discard, secure, version, expires or max-age, jpayne@68: domain, path and port) and rest is a dictionary containing the rest of jpayne@68: the cookie-attributes. jpayne@68: jpayne@68: """ jpayne@68: cookie_tuples = [] jpayne@68: jpayne@68: boolean_attrs = "discard", "secure" jpayne@68: value_attrs = ("version", jpayne@68: "expires", "max-age", jpayne@68: "domain", "path", "port", jpayne@68: "comment", "commenturl") jpayne@68: jpayne@68: for cookie_attrs in attrs_set: jpayne@68: name, value = cookie_attrs[0] jpayne@68: jpayne@68: # Build dictionary of standard cookie-attributes (standard) and jpayne@68: # dictionary of other cookie-attributes (rest). jpayne@68: jpayne@68: # Note: expiry time is normalised to seconds since epoch. V0 jpayne@68: # cookies should have the Expires cookie-attribute, and V1 cookies jpayne@68: # should have Max-Age, but since V1 includes RFC 2109 cookies (and jpayne@68: # since V0 cookies may be a mish-mash of Netscape and RFC 2109), we jpayne@68: # accept either (but prefer Max-Age). jpayne@68: max_age_set = False jpayne@68: jpayne@68: bad_cookie = False jpayne@68: jpayne@68: standard = {} jpayne@68: rest = {} jpayne@68: for k, v in cookie_attrs[1:]: jpayne@68: lc = k.lower() jpayne@68: # don't lose case distinction for unknown fields jpayne@68: if lc in value_attrs or lc in boolean_attrs: jpayne@68: k = lc jpayne@68: if k in boolean_attrs and v is None: jpayne@68: # boolean cookie-attribute is present, but has no value jpayne@68: # (like "discard", rather than "port=80") jpayne@68: v = True jpayne@68: if k in standard: jpayne@68: # only first value is significant jpayne@68: continue jpayne@68: if k == "domain": jpayne@68: if v is None: jpayne@68: _debug(" missing value for domain attribute") jpayne@68: bad_cookie = True jpayne@68: break jpayne@68: # RFC 2965 section 3.3.3 jpayne@68: v = v.lower() jpayne@68: if k == "expires": jpayne@68: if max_age_set: jpayne@68: # Prefer max-age to expires (like Mozilla) jpayne@68: continue jpayne@68: if v is None: jpayne@68: _debug(" missing or invalid value for expires " jpayne@68: "attribute: treating as session cookie") jpayne@68: continue jpayne@68: if k == "max-age": jpayne@68: max_age_set = True jpayne@68: try: jpayne@68: v = int(v) jpayne@68: except ValueError: jpayne@68: _debug(" missing or invalid (non-numeric) value for " jpayne@68: "max-age attribute") jpayne@68: bad_cookie = True jpayne@68: break jpayne@68: # convert RFC 2965 Max-Age to seconds since epoch jpayne@68: # XXX Strictly you're supposed to follow RFC 2616 jpayne@68: # age-calculation rules. Remember that zero Max-Age jpayne@68: # is a request to discard (old and new) cookie, though. jpayne@68: k = "expires" jpayne@68: v = self._now + v jpayne@68: if (k in value_attrs) or (k in boolean_attrs): jpayne@68: if (v is None and jpayne@68: k not in ("port", "comment", "commenturl")): jpayne@68: _debug(" missing value for %s attribute" % k) jpayne@68: bad_cookie = True jpayne@68: break jpayne@68: standard[k] = v jpayne@68: else: jpayne@68: rest[k] = v jpayne@68: jpayne@68: if bad_cookie: jpayne@68: continue jpayne@68: jpayne@68: cookie_tuples.append((name, value, standard, rest)) jpayne@68: jpayne@68: return cookie_tuples jpayne@68: jpayne@68: def _cookie_from_cookie_tuple(self, tup, request): jpayne@68: # standard is dict of standard cookie-attributes, rest is dict of the jpayne@68: # rest of them jpayne@68: name, value, standard, rest = tup jpayne@68: jpayne@68: domain = standard.get("domain", Absent) jpayne@68: path = standard.get("path", Absent) jpayne@68: port = standard.get("port", Absent) jpayne@68: expires = standard.get("expires", Absent) jpayne@68: jpayne@68: # set the easy defaults jpayne@68: version = standard.get("version", None) jpayne@68: if version is not None: jpayne@68: try: jpayne@68: version = int(version) jpayne@68: except ValueError: jpayne@68: return None # invalid version, ignore cookie jpayne@68: secure = standard.get("secure", False) jpayne@68: # (discard is also set if expires is Absent) jpayne@68: discard = standard.get("discard", False) jpayne@68: comment = standard.get("comment", None) jpayne@68: comment_url = standard.get("commenturl", None) jpayne@68: jpayne@68: # set default path jpayne@68: if path is not Absent and path != "": jpayne@68: path_specified = True jpayne@68: path = escape_path(path) jpayne@68: else: jpayne@68: path_specified = False jpayne@68: path = request_path(request) jpayne@68: i = path.rfind("/") jpayne@68: if i != -1: jpayne@68: if version == 0: jpayne@68: # Netscape spec parts company from reality here jpayne@68: path = path[:i] jpayne@68: else: jpayne@68: path = path[:i+1] jpayne@68: if len(path) == 0: path = "/" jpayne@68: jpayne@68: # set default domain jpayne@68: domain_specified = domain is not Absent jpayne@68: # but first we have to remember whether it starts with a dot jpayne@68: domain_initial_dot = False jpayne@68: if domain_specified: jpayne@68: domain_initial_dot = bool(domain.startswith(".")) jpayne@68: if domain is Absent: jpayne@68: req_host, erhn = eff_request_host(request) jpayne@68: domain = erhn jpayne@68: elif not domain.startswith("."): jpayne@68: domain = "."+domain jpayne@68: jpayne@68: # set default port jpayne@68: port_specified = False jpayne@68: if port is not Absent: jpayne@68: if port is None: jpayne@68: # Port attr present, but has no value: default to request port. jpayne@68: # Cookie should then only be sent back on that port. jpayne@68: port = request_port(request) jpayne@68: else: jpayne@68: port_specified = True jpayne@68: port = re.sub(r"\s+", "", port) jpayne@68: else: jpayne@68: # No port attr present. Cookie can be sent back on any port. jpayne@68: port = None jpayne@68: jpayne@68: # set default expires and discard jpayne@68: if expires is Absent: jpayne@68: expires = None jpayne@68: discard = True jpayne@68: elif expires <= self._now: jpayne@68: # Expiry date in past is request to delete cookie. This can't be jpayne@68: # in DefaultCookiePolicy, because can't delete cookies there. jpayne@68: try: jpayne@68: self.clear(domain, path, name) jpayne@68: except KeyError: jpayne@68: pass jpayne@68: _debug("Expiring cookie, domain='%s', path='%s', name='%s'", jpayne@68: domain, path, name) jpayne@68: return None jpayne@68: jpayne@68: return Cookie(version, jpayne@68: name, value, jpayne@68: port, port_specified, jpayne@68: domain, domain_specified, domain_initial_dot, jpayne@68: path, path_specified, jpayne@68: secure, jpayne@68: expires, jpayne@68: discard, jpayne@68: comment, jpayne@68: comment_url, jpayne@68: rest) jpayne@68: jpayne@68: def _cookies_from_attrs_set(self, attrs_set, request): jpayne@68: cookie_tuples = self._normalized_cookie_tuples(attrs_set) jpayne@68: jpayne@68: cookies = [] jpayne@68: for tup in cookie_tuples: jpayne@68: cookie = self._cookie_from_cookie_tuple(tup, request) jpayne@68: if cookie: cookies.append(cookie) jpayne@68: return cookies jpayne@68: jpayne@68: def _process_rfc2109_cookies(self, cookies): jpayne@68: rfc2109_as_ns = getattr(self._policy, 'rfc2109_as_netscape', None) jpayne@68: if rfc2109_as_ns is None: jpayne@68: rfc2109_as_ns = not self._policy.rfc2965 jpayne@68: for cookie in cookies: jpayne@68: if cookie.version == 1: jpayne@68: cookie.rfc2109 = True jpayne@68: if rfc2109_as_ns: jpayne@68: # treat 2109 cookies as Netscape cookies rather than jpayne@68: # as RFC2965 cookies jpayne@68: cookie.version = 0 jpayne@68: jpayne@68: def make_cookies(self, response, request): jpayne@68: """Return sequence of Cookie objects extracted from response object.""" jpayne@68: # get cookie-attributes for RFC 2965 and Netscape protocols jpayne@68: headers = response.info() jpayne@68: rfc2965_hdrs = headers.get_all("Set-Cookie2", []) jpayne@68: ns_hdrs = headers.get_all("Set-Cookie", []) jpayne@68: self._policy._now = self._now = int(time.time()) jpayne@68: jpayne@68: rfc2965 = self._policy.rfc2965 jpayne@68: netscape = self._policy.netscape jpayne@68: jpayne@68: if ((not rfc2965_hdrs and not ns_hdrs) or jpayne@68: (not ns_hdrs and not rfc2965) or jpayne@68: (not rfc2965_hdrs and not netscape) or jpayne@68: (not netscape and not rfc2965)): jpayne@68: return [] # no relevant cookie headers: quick exit jpayne@68: jpayne@68: try: jpayne@68: cookies = self._cookies_from_attrs_set( jpayne@68: split_header_words(rfc2965_hdrs), request) jpayne@68: except Exception: jpayne@68: _warn_unhandled_exception() jpayne@68: cookies = [] jpayne@68: jpayne@68: if ns_hdrs and netscape: jpayne@68: try: jpayne@68: # RFC 2109 and Netscape cookies jpayne@68: ns_cookies = self._cookies_from_attrs_set( jpayne@68: parse_ns_headers(ns_hdrs), request) jpayne@68: except Exception: jpayne@68: _warn_unhandled_exception() jpayne@68: ns_cookies = [] jpayne@68: self._process_rfc2109_cookies(ns_cookies) jpayne@68: jpayne@68: # Look for Netscape cookies (from Set-Cookie headers) that match jpayne@68: # corresponding RFC 2965 cookies (from Set-Cookie2 headers). jpayne@68: # For each match, keep the RFC 2965 cookie and ignore the Netscape jpayne@68: # cookie (RFC 2965 section 9.1). Actually, RFC 2109 cookies are jpayne@68: # bundled in with the Netscape cookies for this purpose, which is jpayne@68: # reasonable behaviour. jpayne@68: if rfc2965: jpayne@68: lookup = {} jpayne@68: for cookie in cookies: jpayne@68: lookup[(cookie.domain, cookie.path, cookie.name)] = None jpayne@68: jpayne@68: def no_matching_rfc2965(ns_cookie, lookup=lookup): jpayne@68: key = ns_cookie.domain, ns_cookie.path, ns_cookie.name jpayne@68: return key not in lookup jpayne@68: ns_cookies = filter(no_matching_rfc2965, ns_cookies) jpayne@68: jpayne@68: if ns_cookies: jpayne@68: cookies.extend(ns_cookies) jpayne@68: jpayne@68: return cookies jpayne@68: jpayne@68: def set_cookie_if_ok(self, cookie, request): jpayne@68: """Set a cookie if policy says it's OK to do so.""" jpayne@68: self._cookies_lock.acquire() jpayne@68: try: jpayne@68: self._policy._now = self._now = int(time.time()) jpayne@68: jpayne@68: if self._policy.set_ok(cookie, request): jpayne@68: self.set_cookie(cookie) jpayne@68: jpayne@68: jpayne@68: finally: jpayne@68: self._cookies_lock.release() jpayne@68: jpayne@68: def set_cookie(self, cookie): jpayne@68: """Set a cookie, without checking whether or not it should be set.""" jpayne@68: c = self._cookies jpayne@68: self._cookies_lock.acquire() jpayne@68: try: jpayne@68: if cookie.domain not in c: c[cookie.domain] = {} jpayne@68: c2 = c[cookie.domain] jpayne@68: if cookie.path not in c2: c2[cookie.path] = {} jpayne@68: c3 = c2[cookie.path] jpayne@68: c3[cookie.name] = cookie jpayne@68: finally: jpayne@68: self._cookies_lock.release() jpayne@68: jpayne@68: def extract_cookies(self, response, request): jpayne@68: """Extract cookies from response, where allowable given the request.""" jpayne@68: _debug("extract_cookies: %s", response.info()) jpayne@68: self._cookies_lock.acquire() jpayne@68: try: jpayne@68: for cookie in self.make_cookies(response, request): jpayne@68: if self._policy.set_ok(cookie, request): jpayne@68: _debug(" setting cookie: %s", cookie) jpayne@68: self.set_cookie(cookie) jpayne@68: finally: jpayne@68: self._cookies_lock.release() jpayne@68: jpayne@68: def clear(self, domain=None, path=None, name=None): jpayne@68: """Clear some cookies. jpayne@68: jpayne@68: Invoking this method without arguments will clear all cookies. If jpayne@68: given a single argument, only cookies belonging to that domain will be jpayne@68: removed. If given two arguments, cookies belonging to the specified jpayne@68: path within that domain are removed. If given three arguments, then jpayne@68: the cookie with the specified name, path and domain is removed. jpayne@68: jpayne@68: Raises KeyError if no matching cookie exists. jpayne@68: jpayne@68: """ jpayne@68: if name is not None: jpayne@68: if (domain is None) or (path is None): jpayne@68: raise ValueError( jpayne@68: "domain and path must be given to remove a cookie by name") jpayne@68: del self._cookies[domain][path][name] jpayne@68: elif path is not None: jpayne@68: if domain is None: jpayne@68: raise ValueError( jpayne@68: "domain must be given to remove cookies by path") jpayne@68: del self._cookies[domain][path] jpayne@68: elif domain is not None: jpayne@68: del self._cookies[domain] jpayne@68: else: jpayne@68: self._cookies = {} jpayne@68: jpayne@68: def clear_session_cookies(self): jpayne@68: """Discard all session cookies. jpayne@68: jpayne@68: Note that the .save() method won't save session cookies anyway, unless jpayne@68: you ask otherwise by passing a true ignore_discard argument. jpayne@68: jpayne@68: """ jpayne@68: self._cookies_lock.acquire() jpayne@68: try: jpayne@68: for cookie in self: jpayne@68: if cookie.discard: jpayne@68: self.clear(cookie.domain, cookie.path, cookie.name) jpayne@68: finally: jpayne@68: self._cookies_lock.release() jpayne@68: jpayne@68: def clear_expired_cookies(self): jpayne@68: """Discard all expired cookies. jpayne@68: jpayne@68: You probably don't need to call this method: expired cookies are never jpayne@68: sent back to the server (provided you're using DefaultCookiePolicy), jpayne@68: this method is called by CookieJar itself every so often, and the jpayne@68: .save() method won't save expired cookies anyway (unless you ask jpayne@68: otherwise by passing a true ignore_expires argument). jpayne@68: jpayne@68: """ jpayne@68: self._cookies_lock.acquire() jpayne@68: try: jpayne@68: now = time.time() jpayne@68: for cookie in self: jpayne@68: if cookie.is_expired(now): jpayne@68: self.clear(cookie.domain, cookie.path, cookie.name) jpayne@68: finally: jpayne@68: self._cookies_lock.release() jpayne@68: jpayne@68: def __iter__(self): jpayne@68: return deepvalues(self._cookies) jpayne@68: jpayne@68: def __len__(self): jpayne@68: """Return number of contained cookies.""" jpayne@68: i = 0 jpayne@68: for cookie in self: i = i + 1 jpayne@68: return i jpayne@68: jpayne@68: def __repr__(self): jpayne@68: r = [] jpayne@68: for cookie in self: r.append(repr(cookie)) jpayne@68: return "<%s[%s]>" % (self.__class__.__name__, ", ".join(r)) jpayne@68: jpayne@68: def __str__(self): jpayne@68: r = [] jpayne@68: for cookie in self: r.append(str(cookie)) jpayne@68: return "<%s[%s]>" % (self.__class__.__name__, ", ".join(r)) jpayne@68: jpayne@68: jpayne@68: # derives from OSError for backwards-compatibility with Python 2.4.0 jpayne@68: class LoadError(OSError): pass jpayne@68: jpayne@68: class FileCookieJar(CookieJar): jpayne@68: """CookieJar that can be loaded from and saved to a file.""" jpayne@68: jpayne@68: def __init__(self, filename=None, delayload=False, policy=None): jpayne@68: """ jpayne@68: Cookies are NOT loaded from the named file until either the .load() or jpayne@68: .revert() method is called. jpayne@68: jpayne@68: """ jpayne@68: CookieJar.__init__(self, policy) jpayne@68: if filename is not None: jpayne@68: filename = os.fspath(filename) jpayne@68: self.filename = filename jpayne@68: self.delayload = bool(delayload) jpayne@68: jpayne@68: def save(self, filename=None, ignore_discard=False, ignore_expires=False): jpayne@68: """Save cookies to a file.""" jpayne@68: raise NotImplementedError() jpayne@68: jpayne@68: def load(self, filename=None, ignore_discard=False, ignore_expires=False): jpayne@68: """Load cookies from a file.""" jpayne@68: if filename is None: jpayne@68: if self.filename is not None: filename = self.filename jpayne@68: else: raise ValueError(MISSING_FILENAME_TEXT) jpayne@68: jpayne@68: with open(filename) as f: jpayne@68: self._really_load(f, filename, ignore_discard, ignore_expires) jpayne@68: jpayne@68: def revert(self, filename=None, jpayne@68: ignore_discard=False, ignore_expires=False): jpayne@68: """Clear all cookies and reload cookies from a saved file. jpayne@68: jpayne@68: Raises LoadError (or OSError) if reversion is not successful; the jpayne@68: object's state will not be altered if this happens. jpayne@68: jpayne@68: """ jpayne@68: if filename is None: jpayne@68: if self.filename is not None: filename = self.filename jpayne@68: else: raise ValueError(MISSING_FILENAME_TEXT) jpayne@68: jpayne@68: self._cookies_lock.acquire() jpayne@68: try: jpayne@68: jpayne@68: old_state = copy.deepcopy(self._cookies) jpayne@68: self._cookies = {} jpayne@68: try: jpayne@68: self.load(filename, ignore_discard, ignore_expires) jpayne@68: except OSError: jpayne@68: self._cookies = old_state jpayne@68: raise jpayne@68: jpayne@68: finally: jpayne@68: self._cookies_lock.release() jpayne@68: jpayne@68: jpayne@68: def lwp_cookie_str(cookie): jpayne@68: """Return string representation of Cookie in the LWP cookie file format. jpayne@68: jpayne@68: Actually, the format is extended a bit -- see module docstring. jpayne@68: jpayne@68: """ jpayne@68: h = [(cookie.name, cookie.value), jpayne@68: ("path", cookie.path), jpayne@68: ("domain", cookie.domain)] jpayne@68: if cookie.port is not None: h.append(("port", cookie.port)) jpayne@68: if cookie.path_specified: h.append(("path_spec", None)) jpayne@68: if cookie.port_specified: h.append(("port_spec", None)) jpayne@68: if cookie.domain_initial_dot: h.append(("domain_dot", None)) jpayne@68: if cookie.secure: h.append(("secure", None)) jpayne@68: if cookie.expires: h.append(("expires", jpayne@68: time2isoz(float(cookie.expires)))) jpayne@68: if cookie.discard: h.append(("discard", None)) jpayne@68: if cookie.comment: h.append(("comment", cookie.comment)) jpayne@68: if cookie.comment_url: h.append(("commenturl", cookie.comment_url)) jpayne@68: jpayne@68: keys = sorted(cookie._rest.keys()) jpayne@68: for k in keys: jpayne@68: h.append((k, str(cookie._rest[k]))) jpayne@68: jpayne@68: h.append(("version", str(cookie.version))) jpayne@68: jpayne@68: return join_header_words([h]) jpayne@68: jpayne@68: class LWPCookieJar(FileCookieJar): jpayne@68: """ jpayne@68: The LWPCookieJar saves a sequence of "Set-Cookie3" lines. jpayne@68: "Set-Cookie3" is the format used by the libwww-perl library, not known jpayne@68: to be compatible with any browser, but which is easy to read and jpayne@68: doesn't lose information about RFC 2965 cookies. jpayne@68: jpayne@68: Additional methods jpayne@68: jpayne@68: as_lwp_str(ignore_discard=True, ignore_expired=True) jpayne@68: jpayne@68: """ jpayne@68: jpayne@68: def as_lwp_str(self, ignore_discard=True, ignore_expires=True): jpayne@68: """Return cookies as a string of "\\n"-separated "Set-Cookie3" headers. jpayne@68: jpayne@68: ignore_discard and ignore_expires: see docstring for FileCookieJar.save jpayne@68: jpayne@68: """ jpayne@68: now = time.time() jpayne@68: r = [] jpayne@68: for cookie in self: jpayne@68: if not ignore_discard and cookie.discard: jpayne@68: continue jpayne@68: if not ignore_expires and cookie.is_expired(now): jpayne@68: continue jpayne@68: r.append("Set-Cookie3: %s" % lwp_cookie_str(cookie)) jpayne@68: return "\n".join(r+[""]) jpayne@68: jpayne@68: def save(self, filename=None, ignore_discard=False, ignore_expires=False): jpayne@68: if filename is None: jpayne@68: if self.filename is not None: filename = self.filename jpayne@68: else: raise ValueError(MISSING_FILENAME_TEXT) jpayne@68: jpayne@68: with open(filename, "w") as f: jpayne@68: # There really isn't an LWP Cookies 2.0 format, but this indicates jpayne@68: # that there is extra information in here (domain_dot and jpayne@68: # port_spec) while still being compatible with libwww-perl, I hope. jpayne@68: f.write("#LWP-Cookies-2.0\n") jpayne@68: f.write(self.as_lwp_str(ignore_discard, ignore_expires)) jpayne@68: jpayne@68: def _really_load(self, f, filename, ignore_discard, ignore_expires): jpayne@68: magic = f.readline() jpayne@68: if not self.magic_re.search(magic): jpayne@68: msg = ("%r does not look like a Set-Cookie3 (LWP) format " jpayne@68: "file" % filename) jpayne@68: raise LoadError(msg) jpayne@68: jpayne@68: now = time.time() jpayne@68: jpayne@68: header = "Set-Cookie3:" jpayne@68: boolean_attrs = ("port_spec", "path_spec", "domain_dot", jpayne@68: "secure", "discard") jpayne@68: value_attrs = ("version", jpayne@68: "port", "path", "domain", jpayne@68: "expires", jpayne@68: "comment", "commenturl") jpayne@68: jpayne@68: try: jpayne@68: while 1: jpayne@68: line = f.readline() jpayne@68: if line == "": break jpayne@68: if not line.startswith(header): jpayne@68: continue jpayne@68: line = line[len(header):].strip() jpayne@68: jpayne@68: for data in split_header_words([line]): jpayne@68: name, value = data[0] jpayne@68: standard = {} jpayne@68: rest = {} jpayne@68: for k in boolean_attrs: jpayne@68: standard[k] = False jpayne@68: for k, v in data[1:]: jpayne@68: if k is not None: jpayne@68: lc = k.lower() jpayne@68: else: jpayne@68: lc = None jpayne@68: # don't lose case distinction for unknown fields jpayne@68: if (lc in value_attrs) or (lc in boolean_attrs): jpayne@68: k = lc jpayne@68: if k in boolean_attrs: jpayne@68: if v is None: v = True jpayne@68: standard[k] = v jpayne@68: elif k in value_attrs: jpayne@68: standard[k] = v jpayne@68: else: jpayne@68: rest[k] = v jpayne@68: jpayne@68: h = standard.get jpayne@68: expires = h("expires") jpayne@68: discard = h("discard") jpayne@68: if expires is not None: jpayne@68: expires = iso2time(expires) jpayne@68: if expires is None: jpayne@68: discard = True jpayne@68: domain = h("domain") jpayne@68: domain_specified = domain.startswith(".") jpayne@68: c = Cookie(h("version"), name, value, jpayne@68: h("port"), h("port_spec"), jpayne@68: domain, domain_specified, h("domain_dot"), jpayne@68: h("path"), h("path_spec"), jpayne@68: h("secure"), jpayne@68: expires, jpayne@68: discard, jpayne@68: h("comment"), jpayne@68: h("commenturl"), jpayne@68: rest) jpayne@68: if not ignore_discard and c.discard: jpayne@68: continue jpayne@68: if not ignore_expires and c.is_expired(now): jpayne@68: continue jpayne@68: self.set_cookie(c) jpayne@68: except OSError: jpayne@68: raise jpayne@68: except Exception: jpayne@68: _warn_unhandled_exception() jpayne@68: raise LoadError("invalid Set-Cookie3 format file %r: %r" % jpayne@68: (filename, line)) jpayne@68: jpayne@68: jpayne@68: class MozillaCookieJar(FileCookieJar): jpayne@68: """ jpayne@68: jpayne@68: WARNING: you may want to backup your browser's cookies file if you use jpayne@68: this class to save cookies. I *think* it works, but there have been jpayne@68: bugs in the past! jpayne@68: jpayne@68: This class differs from CookieJar only in the format it uses to save and jpayne@68: load cookies to and from a file. This class uses the Mozilla/Netscape jpayne@68: `cookies.txt' format. lynx uses this file format, too. jpayne@68: jpayne@68: Don't expect cookies saved while the browser is running to be noticed by jpayne@68: the browser (in fact, Mozilla on unix will overwrite your saved cookies if jpayne@68: you change them on disk while it's running; on Windows, you probably can't jpayne@68: save at all while the browser is running). jpayne@68: jpayne@68: Note that the Mozilla/Netscape format will downgrade RFC2965 cookies to jpayne@68: Netscape cookies on saving. jpayne@68: jpayne@68: In particular, the cookie version and port number information is lost, jpayne@68: together with information about whether or not Path, Port and Discard were jpayne@68: specified by the Set-Cookie2 (or Set-Cookie) header, and whether or not the jpayne@68: domain as set in the HTTP header started with a dot (yes, I'm aware some jpayne@68: domains in Netscape files start with a dot and some don't -- trust me, you jpayne@68: really don't want to know any more about this). jpayne@68: jpayne@68: Note that though Mozilla and Netscape use the same format, they use jpayne@68: slightly different headers. The class saves cookies using the Netscape jpayne@68: header by default (Mozilla can cope with that). jpayne@68: jpayne@68: """ jpayne@68: magic_re = re.compile("#( Netscape)? HTTP Cookie File") jpayne@68: header = """\ jpayne@68: # Netscape HTTP Cookie File jpayne@68: # http://curl.haxx.se/rfc/cookie_spec.html jpayne@68: # This is a generated file! Do not edit. jpayne@68: jpayne@68: """ jpayne@68: jpayne@68: def _really_load(self, f, filename, ignore_discard, ignore_expires): jpayne@68: now = time.time() jpayne@68: jpayne@68: magic = f.readline() jpayne@68: if not self.magic_re.search(magic): jpayne@68: raise LoadError( jpayne@68: "%r does not look like a Netscape format cookies file" % jpayne@68: filename) jpayne@68: jpayne@68: try: jpayne@68: while 1: jpayne@68: line = f.readline() jpayne@68: if line == "": break jpayne@68: jpayne@68: # last field may be absent, so keep any trailing tab jpayne@68: if line.endswith("\n"): line = line[:-1] jpayne@68: jpayne@68: # skip comments and blank lines XXX what is $ for? jpayne@68: if (line.strip().startswith(("#", "$")) or jpayne@68: line.strip() == ""): jpayne@68: continue jpayne@68: jpayne@68: domain, domain_specified, path, secure, expires, name, value = \ jpayne@68: line.split("\t") jpayne@68: secure = (secure == "TRUE") jpayne@68: domain_specified = (domain_specified == "TRUE") jpayne@68: if name == "": jpayne@68: # cookies.txt regards 'Set-Cookie: foo' as a cookie jpayne@68: # with no name, whereas http.cookiejar regards it as a jpayne@68: # cookie with no value. jpayne@68: name = value jpayne@68: value = None jpayne@68: jpayne@68: initial_dot = domain.startswith(".") jpayne@68: assert domain_specified == initial_dot jpayne@68: jpayne@68: discard = False jpayne@68: if expires == "": jpayne@68: expires = None jpayne@68: discard = True jpayne@68: jpayne@68: # assume path_specified is false jpayne@68: c = Cookie(0, name, value, jpayne@68: None, False, jpayne@68: domain, domain_specified, initial_dot, jpayne@68: path, False, jpayne@68: secure, jpayne@68: expires, jpayne@68: discard, jpayne@68: None, jpayne@68: None, jpayne@68: {}) jpayne@68: if not ignore_discard and c.discard: jpayne@68: continue jpayne@68: if not ignore_expires and c.is_expired(now): jpayne@68: continue jpayne@68: self.set_cookie(c) jpayne@68: jpayne@68: except OSError: jpayne@68: raise jpayne@68: except Exception: jpayne@68: _warn_unhandled_exception() jpayne@68: raise LoadError("invalid Netscape format cookies file %r: %r" % jpayne@68: (filename, line)) jpayne@68: jpayne@68: def save(self, filename=None, ignore_discard=False, ignore_expires=False): jpayne@68: if filename is None: jpayne@68: if self.filename is not None: filename = self.filename jpayne@68: else: raise ValueError(MISSING_FILENAME_TEXT) jpayne@68: jpayne@68: with open(filename, "w") as f: jpayne@68: f.write(self.header) jpayne@68: now = time.time() jpayne@68: for cookie in self: jpayne@68: if not ignore_discard and cookie.discard: jpayne@68: continue jpayne@68: if not ignore_expires and cookie.is_expired(now): jpayne@68: continue jpayne@68: if cookie.secure: secure = "TRUE" jpayne@68: else: secure = "FALSE" jpayne@68: if cookie.domain.startswith("."): initial_dot = "TRUE" jpayne@68: else: initial_dot = "FALSE" jpayne@68: if cookie.expires is not None: jpayne@68: expires = str(cookie.expires) jpayne@68: else: jpayne@68: expires = "" jpayne@68: if cookie.value is None: jpayne@68: # cookies.txt regards 'Set-Cookie: foo' as a cookie jpayne@68: # with no name, whereas http.cookiejar regards it as a jpayne@68: # cookie with no value. jpayne@68: name = "" jpayne@68: value = cookie.name jpayne@68: else: jpayne@68: name = cookie.name jpayne@68: value = cookie.value jpayne@68: f.write( jpayne@68: "\t".join([cookie.domain, initial_dot, cookie.path, jpayne@68: secure, expires, name, value])+ jpayne@68: "\n")