PageRenderTime 63ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/cookielib.py

https://bitbucket.org/krono/pypy
Python | 1810 lines | 1734 code | 25 blank | 51 comment | 58 complexity | 0ee65256e5c872efca5e062803ac7a09 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. r"""HTTP cookie handling for web clients.
  2. This module has (now fairly distant) origins in Gisle Aas' Perl module
  3. HTTP::Cookies, from the libwww-perl library.
  4. Docstrings, comments and debug strings in this code refer to the
  5. attributes of the HTTP cookie system as cookie-attributes, to distinguish
  6. them clearly from Python attributes.
  7. Class diagram (note that BSDDBCookieJar and the MSIE* classes are not
  8. distributed with the Python standard library, but are available from
  9. http://wwwsearch.sf.net/):
  10. CookieJar____
  11. / \ \
  12. FileCookieJar \ \
  13. / | \ \ \
  14. MozillaCookieJar | LWPCookieJar \ \
  15. | | \
  16. | ---MSIEBase | \
  17. | / | | \
  18. | / MSIEDBCookieJar BSDDBCookieJar
  19. |/
  20. MSIECookieJar
  21. """
  22. __all__ = ['Cookie', 'CookieJar', 'CookiePolicy', 'DefaultCookiePolicy',
  23. 'FileCookieJar', 'LWPCookieJar', 'lwp_cookie_str', 'LoadError',
  24. 'MozillaCookieJar']
  25. import re, urlparse, copy, time, urllib
  26. try:
  27. import threading as _threading
  28. except ImportError:
  29. import dummy_threading as _threading
  30. import httplib # only for the default HTTP port
  31. from calendar import timegm
  32. debug = False # set to True to enable debugging via the logging module
  33. logger = None
  34. def _debug(*args):
  35. if not debug:
  36. return
  37. global logger
  38. if not logger:
  39. import logging
  40. logger = logging.getLogger("cookielib")
  41. return logger.debug(*args)
  42. DEFAULT_HTTP_PORT = str(httplib.HTTP_PORT)
  43. MISSING_FILENAME_TEXT = ("a filename was not supplied (nor was the CookieJar "
  44. "instance initialised with one)")
  45. def _warn_unhandled_exception():
  46. # There are a few catch-all except: statements in this module, for
  47. # catching input that's bad in unexpected ways. Warn if any
  48. # exceptions are caught there.
  49. import warnings, traceback, StringIO
  50. f = StringIO.StringIO()
  51. traceback.print_exc(None, f)
  52. msg = f.getvalue()
  53. warnings.warn("cookielib bug!\n%s" % msg, stacklevel=2)
  54. # Date/time conversion
  55. # -----------------------------------------------------------------------------
  56. EPOCH_YEAR = 1970
  57. def _timegm(tt):
  58. year, month, mday, hour, min, sec = tt[:6]
  59. if ((year >= EPOCH_YEAR) and (1 <= month <= 12) and (1 <= mday <= 31) and
  60. (0 <= hour <= 24) and (0 <= min <= 59) and (0 <= sec <= 61)):
  61. return timegm(tt)
  62. else:
  63. return None
  64. DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  65. MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  66. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  67. MONTHS_LOWER = []
  68. for month in MONTHS: MONTHS_LOWER.append(month.lower())
  69. def time2isoz(t=None):
  70. """Return a string representing time in seconds since epoch, t.
  71. If the function is called without an argument, it will use the current
  72. time.
  73. The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
  74. representing Universal Time (UTC, aka GMT). An example of this format is:
  75. 1994-11-24 08:49:37Z
  76. """
  77. if t is None: t = time.time()
  78. year, mon, mday, hour, min, sec = time.gmtime(t)[:6]
  79. return "%04d-%02d-%02d %02d:%02d:%02dZ" % (
  80. year, mon, mday, hour, min, sec)
  81. def time2netscape(t=None):
  82. """Return a string representing time in seconds since epoch, t.
  83. If the function is called without an argument, it will use the current
  84. time.
  85. The format of the returned string is like this:
  86. Wed, DD-Mon-YYYY HH:MM:SS GMT
  87. """
  88. if t is None: t = time.time()
  89. year, mon, mday, hour, min, sec, wday = time.gmtime(t)[:7]
  90. return "%s %02d-%s-%04d %02d:%02d:%02d GMT" % (
  91. DAYS[wday], mday, MONTHS[mon-1], year, hour, min, sec)
  92. UTC_ZONES = {"GMT": None, "UTC": None, "UT": None, "Z": None}
  93. TIMEZONE_RE = re.compile(r"^([-+])?(\d\d?):?(\d\d)?$")
  94. def offset_from_tz_string(tz):
  95. offset = None
  96. if tz in UTC_ZONES:
  97. offset = 0
  98. else:
  99. m = TIMEZONE_RE.search(tz)
  100. if m:
  101. offset = 3600 * int(m.group(2))
  102. if m.group(3):
  103. offset = offset + 60 * int(m.group(3))
  104. if m.group(1) == '-':
  105. offset = -offset
  106. return offset
  107. def _str2time(day, mon, yr, hr, min, sec, tz):
  108. # translate month name to number
  109. # month numbers start with 1 (January)
  110. try:
  111. mon = MONTHS_LOWER.index(mon.lower())+1
  112. except ValueError:
  113. # maybe it's already a number
  114. try:
  115. imon = int(mon)
  116. except ValueError:
  117. return None
  118. if 1 <= imon <= 12:
  119. mon = imon
  120. else:
  121. return None
  122. # make sure clock elements are defined
  123. if hr is None: hr = 0
  124. if min is None: min = 0
  125. if sec is None: sec = 0
  126. yr = int(yr)
  127. day = int(day)
  128. hr = int(hr)
  129. min = int(min)
  130. sec = int(sec)
  131. if yr < 1000:
  132. # find "obvious" year
  133. cur_yr = time.localtime(time.time())[0]
  134. m = cur_yr % 100
  135. tmp = yr
  136. yr = yr + cur_yr - m
  137. m = m - tmp
  138. if abs(m) > 50:
  139. if m > 0: yr = yr + 100
  140. else: yr = yr - 100
  141. # convert UTC time tuple to seconds since epoch (not timezone-adjusted)
  142. t = _timegm((yr, mon, day, hr, min, sec, tz))
  143. if t is not None:
  144. # adjust time using timezone string, to get absolute time since epoch
  145. if tz is None:
  146. tz = "UTC"
  147. tz = tz.upper()
  148. offset = offset_from_tz_string(tz)
  149. if offset is None:
  150. return None
  151. t = t - offset
  152. return t
  153. STRICT_DATE_RE = re.compile(
  154. r"^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) "
  155. "(\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$")
  156. WEEKDAY_RE = re.compile(
  157. r"^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*", re.I)
  158. LOOSE_HTTP_DATE_RE = re.compile(
  159. r"""^
  160. (\d\d?) # day
  161. (?:\s+|[-\/])
  162. (\w+) # month
  163. (?:\s+|[-\/])
  164. (\d+) # year
  165. (?:
  166. (?:\s+|:) # separator before clock
  167. (\d\d?):(\d\d) # hour:min
  168. (?::(\d\d))? # optional seconds
  169. )? # optional clock
  170. \s*
  171. ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+)? # timezone
  172. \s*
  173. (?:\(\w+\))? # ASCII representation of timezone in parens.
  174. \s*$""", re.X)
  175. def http2time(text):
  176. """Returns time in seconds since epoch of time represented by a string.
  177. Return value is an integer.
  178. None is returned if the format of str is unrecognized, the time is outside
  179. the representable range, or the timezone string is not recognized. If the
  180. string contains no timezone, UTC is assumed.
  181. The timezone in the string may be numerical (like "-0800" or "+0100") or a
  182. string timezone (like "UTC", "GMT", "BST" or "EST"). Currently, only the
  183. timezone strings equivalent to UTC (zero offset) are known to the function.
  184. The function loosely parses the following formats:
  185. Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format
  186. Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format
  187. Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format
  188. 09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday)
  189. 08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday)
  190. 08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday)
  191. The parser ignores leading and trailing whitespace. The time may be
  192. absent.
  193. If the year is given with only 2 digits, the function will select the
  194. century that makes the year closest to the current date.
  195. """
  196. # fast exit for strictly conforming string
  197. m = STRICT_DATE_RE.search(text)
  198. if m:
  199. g = m.groups()
  200. mon = MONTHS_LOWER.index(g[1].lower()) + 1
  201. tt = (int(g[2]), mon, int(g[0]),
  202. int(g[3]), int(g[4]), float(g[5]))
  203. return _timegm(tt)
  204. # No, we need some messy parsing...
  205. # clean up
  206. text = text.lstrip()
  207. text = WEEKDAY_RE.sub("", text, 1) # Useless weekday
  208. # tz is time zone specifier string
  209. day, mon, yr, hr, min, sec, tz = [None]*7
  210. # loose regexp parse
  211. m = LOOSE_HTTP_DATE_RE.search(text)
  212. if m is not None:
  213. day, mon, yr, hr, min, sec, tz = m.groups()
  214. else:
  215. return None # bad format
  216. return _str2time(day, mon, yr, hr, min, sec, tz)
  217. ISO_DATE_RE = re.compile(
  218. """^
  219. (\d{4}) # year
  220. [-\/]?
  221. (\d\d?) # numerical month
  222. [-\/]?
  223. (\d\d?) # day
  224. (?:
  225. (?:\s+|[-:Tt]) # separator before clock
  226. (\d\d?):?(\d\d) # hour:min
  227. (?::?(\d\d(?:\.\d*)?))? # optional seconds (and fractional)
  228. )? # optional clock
  229. \s*
  230. ([-+]?\d\d?:?(:?\d\d)?
  231. |Z|z)? # timezone (Z is "zero meridian", i.e. GMT)
  232. \s*$""", re.X)
  233. def iso2time(text):
  234. """
  235. As for http2time, but parses the ISO 8601 formats:
  236. 1994-02-03 14:15:29 -0100 -- ISO 8601 format
  237. 1994-02-03 14:15:29 -- zone is optional
  238. 1994-02-03 -- only date
  239. 1994-02-03T14:15:29 -- Use T as separator
  240. 19940203T141529Z -- ISO 8601 compact format
  241. 19940203 -- only date
  242. """
  243. # clean up
  244. text = text.lstrip()
  245. # tz is time zone specifier string
  246. day, mon, yr, hr, min, sec, tz = [None]*7
  247. # loose regexp parse
  248. m = ISO_DATE_RE.search(text)
  249. if m is not None:
  250. # XXX there's an extra bit of the timezone I'm ignoring here: is
  251. # this the right thing to do?
  252. yr, mon, day, hr, min, sec, tz, _ = m.groups()
  253. else:
  254. return None # bad format
  255. return _str2time(day, mon, yr, hr, min, sec, tz)
  256. # Header parsing
  257. # -----------------------------------------------------------------------------
  258. def unmatched(match):
  259. """Return unmatched part of re.Match object."""
  260. start, end = match.span(0)
  261. return match.string[:start]+match.string[end:]
  262. HEADER_TOKEN_RE = re.compile(r"^\s*([^=\s;,]+)")
  263. HEADER_QUOTED_VALUE_RE = re.compile(r"^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"")
  264. HEADER_VALUE_RE = re.compile(r"^\s*=\s*([^\s;,]*)")
  265. HEADER_ESCAPE_RE = re.compile(r"\\(.)")
  266. def split_header_words(header_values):
  267. r"""Parse header values into a list of lists containing key,value pairs.
  268. The function knows how to deal with ",", ";" and "=" as well as quoted
  269. values after "=". A list of space separated tokens are parsed as if they
  270. were separated by ";".
  271. If the header_values passed as argument contains multiple values, then they
  272. are treated as if they were a single value separated by comma ",".
  273. This means that this function is useful for parsing header fields that
  274. follow this syntax (BNF as from the HTTP/1.1 specification, but we relax
  275. the requirement for tokens).
  276. headers = #header
  277. header = (token | parameter) *( [";"] (token | parameter))
  278. token = 1*<any CHAR except CTLs or separators>
  279. separators = "(" | ")" | "<" | ">" | "@"
  280. | "," | ";" | ":" | "\" | <">
  281. | "/" | "[" | "]" | "?" | "="
  282. | "{" | "}" | SP | HT
  283. quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
  284. qdtext = <any TEXT except <">>
  285. quoted-pair = "\" CHAR
  286. parameter = attribute "=" value
  287. attribute = token
  288. value = token | quoted-string
  289. Each header is represented by a list of key/value pairs. The value for a
  290. simple token (not part of a parameter) is None. Syntactically incorrect
  291. headers will not necessarily be parsed as you would want.
  292. This is easier to describe with some examples:
  293. >>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz'])
  294. [[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]]
  295. >>> split_header_words(['text/html; charset="iso-8859-1"'])
  296. [[('text/html', None), ('charset', 'iso-8859-1')]]
  297. >>> split_header_words([r'Basic realm="\"foo\bar\""'])
  298. [[('Basic', None), ('realm', '"foobar"')]]
  299. """
  300. assert not isinstance(header_values, basestring)
  301. result = []
  302. for text in header_values:
  303. orig_text = text
  304. pairs = []
  305. while text:
  306. m = HEADER_TOKEN_RE.search(text)
  307. if m:
  308. text = unmatched(m)
  309. name = m.group(1)
  310. m = HEADER_QUOTED_VALUE_RE.search(text)
  311. if m: # quoted value
  312. text = unmatched(m)
  313. value = m.group(1)
  314. value = HEADER_ESCAPE_RE.sub(r"\1", value)
  315. else:
  316. m = HEADER_VALUE_RE.search(text)
  317. if m: # unquoted value
  318. text = unmatched(m)
  319. value = m.group(1)
  320. value = value.rstrip()
  321. else:
  322. # no value, a lone token
  323. value = None
  324. pairs.append((name, value))
  325. elif text.lstrip().startswith(","):
  326. # concatenated headers, as per RFC 2616 section 4.2
  327. text = text.lstrip()[1:]
  328. if pairs: result.append(pairs)
  329. pairs = []
  330. else:
  331. # skip junk
  332. non_junk, nr_junk_chars = re.subn("^[=\s;]*", "", text)
  333. assert nr_junk_chars > 0, (
  334. "split_header_words bug: '%s', '%s', %s" %
  335. (orig_text, text, pairs))
  336. text = non_junk
  337. if pairs: result.append(pairs)
  338. return result
  339. HEADER_JOIN_ESCAPE_RE = re.compile(r"([\"\\])")
  340. def join_header_words(lists):
  341. """Do the inverse (almost) of the conversion done by split_header_words.
  342. Takes a list of lists of (key, value) pairs and produces a single header
  343. value. Attribute values are quoted if needed.
  344. >>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]])
  345. 'text/plain; charset="iso-8859/1"'
  346. >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]])
  347. 'text/plain, charset="iso-8859/1"'
  348. """
  349. headers = []
  350. for pairs in lists:
  351. attr = []
  352. for k, v in pairs:
  353. if v is not None:
  354. if not re.search(r"^\w+$", v):
  355. v = HEADER_JOIN_ESCAPE_RE.sub(r"\\\1", v) # escape " and \
  356. v = '"%s"' % v
  357. k = "%s=%s" % (k, v)
  358. attr.append(k)
  359. if attr: headers.append("; ".join(attr))
  360. return ", ".join(headers)
  361. def _strip_quotes(text):
  362. if text.startswith('"'):
  363. text = text[1:]
  364. if text.endswith('"'):
  365. text = text[:-1]
  366. return text
  367. def parse_ns_headers(ns_headers):
  368. """Ad-hoc parser for Netscape protocol cookie-attributes.
  369. The old Netscape cookie format for Set-Cookie can for instance contain
  370. an unquoted "," in the expires field, so we have to use this ad-hoc
  371. parser instead of split_header_words.
  372. XXX This may not make the best possible effort to parse all the crap
  373. that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient
  374. parser is probably better, so could do worse than following that if
  375. this ever gives any trouble.
  376. Currently, this is also used for parsing RFC 2109 cookies.
  377. """
  378. known_attrs = ("expires", "domain", "path", "secure",
  379. # RFC 2109 attrs (may turn up in Netscape cookies, too)
  380. "version", "port", "max-age")
  381. result = []
  382. for ns_header in ns_headers:
  383. pairs = []
  384. version_set = False
  385. # XXX: The following does not strictly adhere to RFCs in that empty
  386. # names and values are legal (the former will only appear once and will
  387. # be overwritten if multiple occurrences are present). This is
  388. # mostly to deal with backwards compatibility.
  389. for ii, param in enumerate(ns_header.split(';')):
  390. param = param.strip()
  391. key, sep, val = param.partition('=')
  392. key = key.strip()
  393. if not key:
  394. if ii == 0:
  395. break
  396. else:
  397. continue
  398. # allow for a distinction between present and empty and missing
  399. # altogether
  400. val = val.strip() if sep else None
  401. if ii != 0:
  402. lc = key.lower()
  403. if lc in known_attrs:
  404. key = lc
  405. if key == "version":
  406. # This is an RFC 2109 cookie.
  407. if val is not None:
  408. val = _strip_quotes(val)
  409. version_set = True
  410. elif key == "expires":
  411. # convert expires date to seconds since epoch
  412. if val is not None:
  413. val = http2time(_strip_quotes(val)) # None if invalid
  414. pairs.append((key, val))
  415. if pairs:
  416. if not version_set:
  417. pairs.append(("version", "0"))
  418. result.append(pairs)
  419. return result
  420. IPV4_RE = re.compile(r"\.\d+$")
  421. def is_HDN(text):
  422. """Return True if text is a host domain name."""
  423. # XXX
  424. # This may well be wrong. Which RFC is HDN defined in, if any (for
  425. # the purposes of RFC 2965)?
  426. # For the current implementation, what about IPv6? Remember to look
  427. # at other uses of IPV4_RE also, if change this.
  428. if IPV4_RE.search(text):
  429. return False
  430. if text == "":
  431. return False
  432. if text[0] == "." or text[-1] == ".":
  433. return False
  434. return True
  435. def domain_match(A, B):
  436. """Return True if domain A domain-matches domain B, according to RFC 2965.
  437. A and B may be host domain names or IP addresses.
  438. RFC 2965, section 1:
  439. Host names can be specified either as an IP address or a HDN string.
  440. Sometimes we compare one host name with another. (Such comparisons SHALL
  441. be case-insensitive.) Host A's name domain-matches host B's if
  442. * their host name strings string-compare equal; or
  443. * A is a HDN string and has the form NB, where N is a non-empty
  444. name string, B has the form .B', and B' is a HDN string. (So,
  445. x.y.com domain-matches .Y.com but not Y.com.)
  446. Note that domain-match is not a commutative operation: a.b.c.com
  447. domain-matches .c.com, but not the reverse.
  448. """
  449. # Note that, if A or B are IP addresses, the only relevant part of the
  450. # definition of the domain-match algorithm is the direct string-compare.
  451. A = A.lower()
  452. B = B.lower()
  453. if A == B:
  454. return True
  455. if not is_HDN(A):
  456. return False
  457. i = A.rfind(B)
  458. if i == -1 or i == 0:
  459. # A does not have form NB, or N is the empty string
  460. return False
  461. if not B.startswith("."):
  462. return False
  463. if not is_HDN(B[1:]):
  464. return False
  465. return True
  466. def liberal_is_HDN(text):
  467. """Return True if text is a sort-of-like a host domain name.
  468. For accepting/blocking domains.
  469. """
  470. if IPV4_RE.search(text):
  471. return False
  472. return True
  473. def user_domain_match(A, B):
  474. """For blocking/accepting domains.
  475. A and B may be host domain names or IP addresses.
  476. """
  477. A = A.lower()
  478. B = B.lower()
  479. if not (liberal_is_HDN(A) and liberal_is_HDN(B)):
  480. if A == B:
  481. # equal IP addresses
  482. return True
  483. return False
  484. initial_dot = B.startswith(".")
  485. if initial_dot and A.endswith(B):
  486. return True
  487. if not initial_dot and A == B:
  488. return True
  489. return False
  490. cut_port_re = re.compile(r":\d+$")
  491. def request_host(request):
  492. """Return request-host, as defined by RFC 2965.
  493. Variation from RFC: returned value is lowercased, for convenient
  494. comparison.
  495. """
  496. url = request.get_full_url()
  497. host = urlparse.urlparse(url)[1]
  498. if host == "":
  499. host = request.get_header("Host", "")
  500. # remove port, if present
  501. host = cut_port_re.sub("", host, 1)
  502. return host.lower()
  503. def eff_request_host(request):
  504. """Return a tuple (request-host, effective request-host name).
  505. As defined by RFC 2965, except both are lowercased.
  506. """
  507. erhn = req_host = request_host(request)
  508. if req_host.find(".") == -1 and not IPV4_RE.search(req_host):
  509. erhn = req_host + ".local"
  510. return req_host, erhn
  511. def request_path(request):
  512. """Path component of request-URI, as defined by RFC 2965."""
  513. url = request.get_full_url()
  514. parts = urlparse.urlsplit(url)
  515. path = escape_path(parts.path)
  516. if not path.startswith("/"):
  517. # fix bad RFC 2396 absoluteURI
  518. path = "/" + path
  519. return path
  520. def request_port(request):
  521. host = request.get_host()
  522. i = host.find(':')
  523. if i >= 0:
  524. port = host[i+1:]
  525. try:
  526. int(port)
  527. except ValueError:
  528. _debug("nonnumeric port: '%s'", port)
  529. return None
  530. else:
  531. port = DEFAULT_HTTP_PORT
  532. return port
  533. # Characters in addition to A-Z, a-z, 0-9, '_', '.', and '-' that don't
  534. # need to be escaped to form a valid HTTP URL (RFCs 2396 and 1738).
  535. HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()"
  536. ESCAPED_CHAR_RE = re.compile(r"%([0-9a-fA-F][0-9a-fA-F])")
  537. def uppercase_escaped_char(match):
  538. return "%%%s" % match.group(1).upper()
  539. def escape_path(path):
  540. """Escape any invalid characters in HTTP URL, and uppercase all escapes."""
  541. # There's no knowing what character encoding was used to create URLs
  542. # containing %-escapes, but since we have to pick one to escape invalid
  543. # path characters, we pick UTF-8, as recommended in the HTML 4.0
  544. # specification:
  545. # http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1
  546. # And here, kind of: draft-fielding-uri-rfc2396bis-03
  547. # (And in draft IRI specification: draft-duerst-iri-05)
  548. # (And here, for new URI schemes: RFC 2718)
  549. if isinstance(path, unicode):
  550. path = path.encode("utf-8")
  551. path = urllib.quote(path, HTTP_PATH_SAFE)
  552. path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)
  553. return path
  554. def reach(h):
  555. """Return reach of host h, as defined by RFC 2965, section 1.
  556. The reach R of a host name H is defined as follows:
  557. * If
  558. - H is the host domain name of a host; and,
  559. - H has the form A.B; and
  560. - A has no embedded (that is, interior) dots; and
  561. - B has at least one embedded dot, or B is the string "local".
  562. then the reach of H is .B.
  563. * Otherwise, the reach of H is H.
  564. >>> reach("www.acme.com")
  565. '.acme.com'
  566. >>> reach("acme.com")
  567. 'acme.com'
  568. >>> reach("acme.local")
  569. '.local'
  570. """
  571. i = h.find(".")
  572. if i >= 0:
  573. #a = h[:i] # this line is only here to show what a is
  574. b = h[i+1:]
  575. i = b.find(".")
  576. if is_HDN(h) and (i >= 0 or b == "local"):
  577. return "."+b
  578. return h
  579. def is_third_party(request):
  580. """
  581. RFC 2965, section 3.3.6:
  582. An unverifiable transaction is to a third-party host if its request-
  583. host U does not domain-match the reach R of the request-host O in the
  584. origin transaction.
  585. """
  586. req_host = request_host(request)
  587. if not domain_match(req_host, reach(request.get_origin_req_host())):
  588. return True
  589. else:
  590. return False
  591. class Cookie:
  592. """HTTP Cookie.
  593. This class represents both Netscape and RFC 2965 cookies.
  594. This is deliberately a very simple class. It just holds attributes. It's
  595. possible to construct Cookie instances that don't comply with the cookie
  596. standards. CookieJar.make_cookies is the factory function for Cookie
  597. objects -- it deals with cookie parsing, supplying defaults, and
  598. normalising to the representation used in this class. CookiePolicy is
  599. responsible for checking them to see whether they should be accepted from
  600. and returned to the server.
  601. Note that the port may be present in the headers, but unspecified ("Port"
  602. rather than"Port=80", for example); if this is the case, port is None.
  603. """
  604. def __init__(self, version, name, value,
  605. port, port_specified,
  606. domain, domain_specified, domain_initial_dot,
  607. path, path_specified,
  608. secure,
  609. expires,
  610. discard,
  611. comment,
  612. comment_url,
  613. rest,
  614. rfc2109=False,
  615. ):
  616. if version is not None: version = int(version)
  617. if expires is not None: expires = int(expires)
  618. if port is None and port_specified is True:
  619. raise ValueError("if port is None, port_specified must be false")
  620. self.version = version
  621. self.name = name
  622. self.value = value
  623. self.port = port
  624. self.port_specified = port_specified
  625. # normalise case, as per RFC 2965 section 3.3.3
  626. self.domain = domain.lower()
  627. self.domain_specified = domain_specified
  628. # Sigh. We need to know whether the domain given in the
  629. # cookie-attribute had an initial dot, in order to follow RFC 2965
  630. # (as clarified in draft errata). Needed for the returned $Domain
  631. # value.
  632. self.domain_initial_dot = domain_initial_dot
  633. self.path = path
  634. self.path_specified = path_specified
  635. self.secure = secure
  636. self.expires = expires
  637. self.discard = discard
  638. self.comment = comment
  639. self.comment_url = comment_url
  640. self.rfc2109 = rfc2109
  641. self._rest = copy.copy(rest)
  642. def has_nonstandard_attr(self, name):
  643. return name in self._rest
  644. def get_nonstandard_attr(self, name, default=None):
  645. return self._rest.get(name, default)
  646. def set_nonstandard_attr(self, name, value):
  647. self._rest[name] = value
  648. def is_expired(self, now=None):
  649. if now is None: now = time.time()
  650. if (self.expires is not None) and (self.expires <= now):
  651. return True
  652. return False
  653. def __str__(self):
  654. if self.port is None: p = ""
  655. else: p = ":"+self.port
  656. limit = self.domain + p + self.path
  657. if self.value is not None:
  658. namevalue = "%s=%s" % (self.name, self.value)
  659. else:
  660. namevalue = self.name
  661. return "<Cookie %s for %s>" % (namevalue, limit)
  662. def __repr__(self):
  663. args = []
  664. for name in ("version", "name", "value",
  665. "port", "port_specified",
  666. "domain", "domain_specified", "domain_initial_dot",
  667. "path", "path_specified",
  668. "secure", "expires", "discard", "comment", "comment_url",
  669. ):
  670. attr = getattr(self, name)
  671. args.append("%s=%s" % (name, repr(attr)))
  672. args.append("rest=%s" % repr(self._rest))
  673. args.append("rfc2109=%s" % repr(self.rfc2109))
  674. return "Cookie(%s)" % ", ".join(args)
  675. class CookiePolicy:
  676. """Defines which cookies get accepted from and returned to server.
  677. May also modify cookies, though this is probably a bad idea.
  678. The subclass DefaultCookiePolicy defines the standard rules for Netscape
  679. and RFC 2965 cookies -- override that if you want a customised policy.
  680. """
  681. def set_ok(self, cookie, request):
  682. """Return true if (and only if) cookie should be accepted from server.
  683. Currently, pre-expired cookies never get this far -- the CookieJar
  684. class deletes such cookies itself.
  685. """
  686. raise NotImplementedError()
  687. def return_ok(self, cookie, request):
  688. """Return true if (and only if) cookie should be returned to server."""
  689. raise NotImplementedError()
  690. def domain_return_ok(self, domain, request):
  691. """Return false if cookies should not be returned, given cookie domain.
  692. """
  693. return True
  694. def path_return_ok(self, path, request):
  695. """Return false if cookies should not be returned, given cookie path.
  696. """
  697. return True
  698. class DefaultCookiePolicy(CookiePolicy):
  699. """Implements the standard rules for accepting and returning cookies."""
  700. DomainStrictNoDots = 1
  701. DomainStrictNonDomain = 2
  702. DomainRFC2965Match = 4
  703. DomainLiberal = 0
  704. DomainStrict = DomainStrictNoDots|DomainStrictNonDomain
  705. def __init__(self,
  706. blocked_domains=None, allowed_domains=None,
  707. netscape=True, rfc2965=False,
  708. rfc2109_as_netscape=None,
  709. hide_cookie2=False,
  710. strict_domain=False,
  711. strict_rfc2965_unverifiable=True,
  712. strict_ns_unverifiable=False,
  713. strict_ns_domain=DomainLiberal,
  714. strict_ns_set_initial_dollar=False,
  715. strict_ns_set_path=False,
  716. ):
  717. """Constructor arguments should be passed as keyword arguments only."""
  718. self.netscape = netscape
  719. self.rfc2965 = rfc2965
  720. self.rfc2109_as_netscape = rfc2109_as_netscape
  721. self.hide_cookie2 = hide_cookie2
  722. self.strict_domain = strict_domain
  723. self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable
  724. self.strict_ns_unverifiable = strict_ns_unverifiable
  725. self.strict_ns_domain = strict_ns_domain
  726. self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar
  727. self.strict_ns_set_path = strict_ns_set_path
  728. if blocked_domains is not None:
  729. self._blocked_domains = tuple(blocked_domains)
  730. else:
  731. self._blocked_domains = ()
  732. if allowed_domains is not None:
  733. allowed_domains = tuple(allowed_domains)
  734. self._allowed_domains = allowed_domains
  735. def blocked_domains(self):
  736. """Return the sequence of blocked domains (as a tuple)."""
  737. return self._blocked_domains
  738. def set_blocked_domains(self, blocked_domains):
  739. """Set the sequence of blocked domains."""
  740. self._blocked_domains = tuple(blocked_domains)
  741. def is_blocked(self, domain):
  742. for blocked_domain in self._blocked_domains:
  743. if user_domain_match(domain, blocked_domain):
  744. return True
  745. return False
  746. def allowed_domains(self):
  747. """Return None, or the sequence of allowed domains (as a tuple)."""
  748. return self._allowed_domains
  749. def set_allowed_domains(self, allowed_domains):
  750. """Set the sequence of allowed domains, or None."""
  751. if allowed_domains is not None:
  752. allowed_domains = tuple(allowed_domains)
  753. self._allowed_domains = allowed_domains
  754. def is_not_allowed(self, domain):
  755. if self._allowed_domains is None:
  756. return False
  757. for allowed_domain in self._allowed_domains:
  758. if user_domain_match(domain, allowed_domain):
  759. return False
  760. return True
  761. def set_ok(self, cookie, request):
  762. """
  763. If you override .set_ok(), be sure to call this method. If it returns
  764. false, so should your subclass (assuming your subclass wants to be more
  765. strict about which cookies to accept).
  766. """
  767. _debug(" - checking cookie %s=%s", cookie.name, cookie.value)
  768. assert cookie.name is not None
  769. for n in "version", "verifiability", "name", "path", "domain", "port":
  770. fn_name = "set_ok_"+n
  771. fn = getattr(self, fn_name)
  772. if not fn(cookie, request):
  773. return False
  774. return True
  775. def set_ok_version(self, cookie, request):
  776. if cookie.version is None:
  777. # Version is always set to 0 by parse_ns_headers if it's a Netscape
  778. # cookie, so this must be an invalid RFC 2965 cookie.
  779. _debug(" Set-Cookie2 without version attribute (%s=%s)",
  780. cookie.name, cookie.value)
  781. return False
  782. if cookie.version > 0 and not self.rfc2965:
  783. _debug(" RFC 2965 cookies are switched off")
  784. return False
  785. elif cookie.version == 0 and not self.netscape:
  786. _debug(" Netscape cookies are switched off")
  787. return False
  788. return True
  789. def set_ok_verifiability(self, cookie, request):
  790. if request.is_unverifiable() and is_third_party(request):
  791. if cookie.version > 0 and self.strict_rfc2965_unverifiable:
  792. _debug(" third-party RFC 2965 cookie during "
  793. "unverifiable transaction")
  794. return False
  795. elif cookie.version == 0 and self.strict_ns_unverifiable:
  796. _debug(" third-party Netscape cookie during "
  797. "unverifiable transaction")
  798. return False
  799. return True
  800. def set_ok_name(self, cookie, request):
  801. # Try and stop servers setting V0 cookies designed to hack other
  802. # servers that know both V0 and V1 protocols.
  803. if (cookie.version == 0 and self.strict_ns_set_initial_dollar and
  804. cookie.name.startswith("$")):
  805. _debug(" illegal name (starts with '$'): '%s'", cookie.name)
  806. return False
  807. return True
  808. def set_ok_path(self, cookie, request):
  809. if cookie.path_specified:
  810. req_path = request_path(request)
  811. if ((cookie.version > 0 or
  812. (cookie.version == 0 and self.strict_ns_set_path)) and
  813. not req_path.startswith(cookie.path)):
  814. _debug(" path attribute %s is not a prefix of request "
  815. "path %s", cookie.path, req_path)
  816. return False
  817. return True
  818. def set_ok_domain(self, cookie, request):
  819. if self.is_blocked(cookie.domain):
  820. _debug(" domain %s is in user block-list", cookie.domain)
  821. return False
  822. if self.is_not_allowed(cookie.domain):
  823. _debug(" domain %s is not in user allow-list", cookie.domain)
  824. return False
  825. if cookie.domain_specified:
  826. req_host, erhn = eff_request_host(request)
  827. domain = cookie.domain
  828. if self.strict_domain and (domain.count(".") >= 2):
  829. # XXX This should probably be compared with the Konqueror
  830. # (kcookiejar.cpp) and Mozilla implementations, but it's a
  831. # losing battle.
  832. i = domain.rfind(".")
  833. j = domain.rfind(".", 0, i)
  834. if j == 0: # domain like .foo.bar
  835. tld = domain[i+1:]
  836. sld = domain[j+1:i]
  837. if sld.lower() in ("co", "ac", "com", "edu", "org", "net",
  838. "gov", "mil", "int", "aero", "biz", "cat", "coop",
  839. "info", "jobs", "mobi", "museum", "name", "pro",
  840. "travel", "eu") and len(tld) == 2:
  841. # domain like .co.uk
  842. _debug(" country-code second level domain %s", domain)
  843. return False
  844. if domain.startswith("."):
  845. undotted_domain = domain[1:]
  846. else:
  847. undotted_domain = domain
  848. embedded_dots = (undotted_domain.find(".") >= 0)
  849. if not embedded_dots and domain != ".local":
  850. _debug(" non-local domain %s contains no embedded dot",
  851. domain)
  852. return False
  853. if cookie.version == 0:
  854. if (not erhn.endswith(domain) and
  855. (not erhn.startswith(".") and
  856. not ("."+erhn).endswith(domain))):
  857. _debug(" effective request-host %s (even with added "
  858. "initial dot) does not end with %s",
  859. erhn, domain)
  860. return False
  861. if (cookie.version > 0 or
  862. (self.strict_ns_domain & self.DomainRFC2965Match)):
  863. if not domain_match(erhn, domain):
  864. _debug(" effective request-host %s does not domain-match "
  865. "%s", erhn, domain)
  866. return False
  867. if (cookie.version > 0 or
  868. (self.strict_ns_domain & self.DomainStrictNoDots)):
  869. host_prefix = req_host[:-len(domain)]
  870. if (host_prefix.find(".") >= 0 and
  871. not IPV4_RE.search(req_host)):
  872. _debug(" host prefix %s for domain %s contains a dot",
  873. host_prefix, domain)
  874. return False
  875. return True
  876. def set_ok_port(self, cookie, request):
  877. if cookie.port_specified:
  878. req_port = request_port(request)
  879. if req_port is None:
  880. req_port = "80"
  881. else:
  882. req_port = str(req_port)
  883. for p in cookie.port.split(","):
  884. try:
  885. int(p)
  886. except ValueError:
  887. _debug(" bad port %s (not numeric)", p)
  888. return False
  889. if p == req_port:
  890. break
  891. else:
  892. _debug(" request port (%s) not found in %s",
  893. req_port, cookie.port)
  894. return False
  895. return True
  896. def return_ok(self, cookie, request):
  897. """
  898. If you override .return_ok(), be sure to call this method. If it
  899. returns false, so should your subclass (assuming your subclass wants to
  900. be more strict about which cookies to return).
  901. """
  902. # Path has already been checked by .path_return_ok(), and domain
  903. # blocking done by .domain_return_ok().
  904. _debug(" - checking cookie %s=%s", cookie.name, cookie.value)
  905. for n in "version", "verifiability", "secure", "expires", "port", "domain":
  906. fn_name = "return_ok_"+n
  907. fn = getattr(self, fn_name)
  908. if not fn(cookie, request):
  909. return False
  910. return True
  911. def return_ok_version(self, cookie, request):
  912. if cookie.version > 0 and not self.rfc2965:
  913. _debug(" RFC 2965 cookies are switched off")
  914. return False
  915. elif cookie.version == 0 and not self.netscape:
  916. _debug(" Netscape cookies are switched off")
  917. return False
  918. return True
  919. def return_ok_verifiability(self, cookie, request):
  920. if request.is_unverifiable() and is_third_party(request):
  921. if cookie.version > 0 and self.strict_rfc2965_unverifiable:
  922. _debug(" third-party RFC 2965 cookie during unverifiable "
  923. "transaction")
  924. return False
  925. elif cookie.version == 0 and self.strict_ns_unverifiable:
  926. _debug(" third-party Netscape cookie during unverifiable "
  927. "transaction")
  928. return False
  929. return True
  930. def return_ok_secure(self, cookie, request):
  931. if cookie.secure and request.get_type() != "https":
  932. _debug(" secure cookie with non-secure request")
  933. return False
  934. return True
  935. def return_ok_expires(self, cookie, request):
  936. if cookie.is_expired(self._now):
  937. _debug(" cookie expired")
  938. return False
  939. return True
  940. def return_ok_port(self, cookie, request):
  941. if cookie.port:
  942. req_port = request_port(request)
  943. if req_port is None:
  944. req_port = "80"
  945. for p in cookie.port.split(","):
  946. if p == req_port:
  947. break
  948. else:
  949. _debug(" request port %s does not match cookie port %s",
  950. req_port, cookie.port)
  951. return False
  952. return True
  953. def return_ok_domain(self, cookie, request):
  954. req_host, erhn = eff_request_host(request)
  955. domain = cookie.domain
  956. # strict check of non-domain cookies: Mozilla does this, MSIE5 doesn't
  957. if (cookie.version == 0 and
  958. (self.strict_ns_domain & self.DomainStrictNonDomain) and
  959. not cookie.domain_specified and domain != erhn):
  960. _debug(" cookie with unspecified domain does not string-compare "
  961. "equal to request domain")
  962. return False
  963. if cookie.version > 0 and not domain_match(erhn, domain):
  964. _debug(" effective request-host name %s does not domain-match "
  965. "RFC 2965 cookie domain %s", erhn, domain)
  966. return False
  967. if cookie.version == 0 and not ("."+erhn).endswith(domain):
  968. _debug(" request-host %s does not match Netscape cookie domain "
  969. "%s", req_host, domain)
  970. return False
  971. return True
  972. def domain_return_ok(self, domain, request):
  973. # Liberal check of. This is here as an optimization to avoid
  974. # having to load lots of MSIE cookie files unless necessary.
  975. req_host, erhn = eff_request_host(request)
  976. if not req_host.startswith("."):
  977. req_host = "."+req_host
  978. if not erhn.startswith("."):
  979. erhn = "."+erhn
  980. if not (req_host.endswith(domain) or erhn.endswith(domain)):
  981. #_debug(" request domain %s does not match cookie domain %s",
  982. # req_host, domain)
  983. return False
  984. if self.is_blocked(domain):
  985. _debug(" domain %s is in user block-list", domain)
  986. return False
  987. if self.is_not_allowed(domain):
  988. _debug(" domain %s is not in user allow-list", domain)
  989. return False
  990. return True
  991. def path_return_ok(self, path, request):
  992. _debug("- checking cookie path=%s", path)
  993. req_path = request_path(request)
  994. if not req_path.startswith(path):
  995. _debug(" %s does not path-match %s", req_path, path)
  996. return False
  997. return True
  998. def vals_sorted_by_key(adict):
  999. keys = adict.keys()
  1000. keys.sort()
  1001. return map(adict.get, keys)
  1002. def deepvalues(mapping):
  1003. """Iterates over nested mapping, depth-first, in sorted order by key."""
  1004. values = vals_sorted_by_key(mapping)
  1005. for obj in values:
  1006. mapping = False
  1007. try:
  1008. obj.items
  1009. except AttributeError:
  1010. pass
  1011. else:
  1012. mapping = True
  1013. for subobj in deepvalues(obj):
  1014. yield subobj
  1015. if not mapping:
  1016. yield obj
  1017. # Used as second parameter to dict.get() method, to distinguish absent
  1018. # dict key from one with a None value.
  1019. class Absent: pass
  1020. class CookieJar:
  1021. """Collection of HTTP cookies.
  1022. You may not need to know about this class: try
  1023. urllib2.build_opener(HTTPCookieProcessor).open(url).
  1024. """
  1025. non_word_re = re.compile(r"\W")
  1026. quote_re = re.compile(r"([\"\\])")
  1027. strict_domain_re = re.compile(r"\.?[^.]*")
  1028. domain_re = re.compile(r"[^.]*")
  1029. dots_re = re.compile(r"^\.+")
  1030. magic_re = r"^\#LWP-Cookies-(\d+\.\d+)"
  1031. def __init__(self, policy=None):
  1032. if policy is None:
  1033. policy = DefaultCookiePolicy()
  1034. self._policy = policy
  1035. self._cookies_lock = _threading.RLock()
  1036. self._cookies = {}
  1037. def set_policy(self, policy):
  1038. self._policy = policy
  1039. def _cookies_for_domain(self, domain, request):
  1040. cookies = []
  1041. if not self._policy.domain_return_ok(domain, request):
  1042. return []
  1043. _debug("Checking %s for cookies to return", domain)
  1044. cookies_by_path = self._cookies[domain]
  1045. for path in cookies_by_path.keys():
  1046. if not self._policy.path_return_ok(path, request):
  1047. continue
  1048. cookies_by_name = cookies_by_path[path]
  1049. for cookie in cookies_by_name.values():
  1050. if not self._policy.return_ok(cookie, request):
  1051. _debug(" not returning cookie")
  1052. continue
  1053. _debug(" it's a match")
  1054. cookies.append(cookie)
  1055. return cookies
  1056. def _cookies_for_request(self, request):
  1057. """Return a list of cookies to be returned to server."""
  1058. cookies = []
  1059. for domain in self._cookies.keys():
  1060. cookies.extend(self._cookies_for_domain(domain, request))
  1061. return cookies
  1062. def _cookie_attrs(self, cookies):
  1063. """Return a list of cookie-attributes to be returned to server.
  1064. like ['foo="bar"; $Path="/"', ...]
  1065. The $Version attribute is also added when appropriate (currently only
  1066. once per request).
  1067. """
  1068. # add cookies in order of most specific (ie. longest) path first
  1069. cookies.sort(key=lambda arg: len(arg.path), reverse=True)
  1070. version_set = False
  1071. attrs = []
  1072. for cookie in cookies:
  1073. # set version of Cookie header
  1074. # XXX
  1075. # What should it be if multiple matching Set-Cookie headers have
  1076. # different versions themselves?
  1077. # Answer: there is no answer; was supposed to be settled by
  1078. # RFC 2965 errata, but that may never appear...
  1079. version = cookie.version
  1080. if not version_set:
  1081. version_set = True
  1082. if version > 0:
  1083. attrs.append("$Version=%s" % version)
  1084. # quote cookie value if necessary
  1085. # (not for Netscape protocol, which already has any quotes
  1086. # intact, due to the poorly-specified Netscape Cookie: syntax)
  1087. if ((cookie.value is not None) and
  1088. self.non_word_re.search(cookie.value) and version > 0):
  1089. value = self.quote_re.sub(r"\\\1", cookie.value)
  1090. else:
  1091. value = cookie.value
  1092. # add cookie-attributes to be returned in Cookie header
  1093. if cookie.value is None:
  1094. attrs.append(cookie.name)
  1095. else:
  1096. attrs.append("%s=%s" % (cookie.name, value))
  1097. if version > 0:
  1098. if cookie.path_specified:
  1099. attrs.append('$Path="%s"' % cookie.path)
  1100. if cookie.domain.startswith("."):
  1101. domain = cookie.domain
  1102. if (not cookie.domain_initial_dot and
  1103. domain.startswith(".")):
  1104. domain = domain[1:]
  1105. attrs.append('$Domain="%s"' % domain)
  1106. if cookie.port is not None:
  1107. p = "$Port"
  1108. if cookie.port_specified:
  1109. p = p + ('="%s"' % cookie.port)
  1110. attrs.append(p)
  1111. return attrs
  1112. def add_cookie_header(self, request):
  1113. """Add correct Cookie: header to request (urllib2.Request object).
  1114. The Cookie2 header is also added unless policy.hide_cookie2 is true.
  1115. """
  1116. _debug("add_cookie_header")
  1117. self._cookies_lock.acquire()
  1118. try:
  1119. self._policy._now = self._now = int(time.time())
  1120. cookies = self._cookies_for_request(request)
  1121. attrs = self._cookie_attrs(cookies)
  1122. if attrs:
  1123. if not request.has_header("Cookie"):
  1124. request.add_unredirected_header(
  1125. "Cookie", "; ".join(attrs))
  1126. # if necessary, advertise that we know RFC 2965
  1127. if (self._policy.rfc2965 and not self._policy.hide_cookie2 and
  1128. not request.has_header("Cookie2")):
  1129. for cookie in cookies:
  1130. if cookie.version != 1:
  1131. request.add_unredirected_header("Cookie2", '$Version="1"')
  1132. break
  1133. finally:
  1134. self._cookies_lock.release()
  1135. self.clear_expired_cookies()
  1136. def _normalized_cookie_tuples(self, attrs_set):
  1137. """Return list of tuples containing normalised cookie information.
  1138. attrs_set is the list of lists of key,value pairs extracted from
  1139. the Set-Cookie or Set-Cookie2 headers.
  1140. Tuples are name, value, standard, rest, where name and value are the
  1141. cookie name and value, standard is a dictionary containing the standard
  1142. cookie-attributes (discard, secure, version, expires or max-age,
  1143. domain, path and port) and rest is a dictionary containing the rest of
  1144. the cookie-attributes.
  1145. """
  1146. cookie_tuples = []
  1147. boolean_attrs = "discard", "secure"
  1148. value_attrs = ("version",
  1149. "expires", "max-age",
  1150. "domain", "path", "port",
  1151. "comment", "commenturl")
  1152. for cookie_attrs in attrs_set:
  1153. name, value = cookie_attrs[0]
  1154. # Build dictionary of standard cookie-attributes (standard) and
  1155. # dictionary of other cookie-attributes (rest).
  1156. # Note: expiry time is normalised to seconds since epoch. V0
  1157. # cookies should have the Expires cookie-attribute, and V1 cookies
  1158. # should have Max-Age, but since V1 includes RFC 2109 cookies (and
  1159. # since V0 cookies may be a mish-mash of Netscape and RFC 2109), we
  1160. # accept either (but prefer Max-Age).
  1161. max_age_set = False
  1162. bad_cookie = False
  1163. standard = {}
  1164. rest = {}
  1165. for k, v in cookie_attrs[1:]:
  1166. lc = k.lower()
  1167. # don't lose case distinction for unknown fields
  1168. if lc in value_attrs or lc in boolean_attrs:
  1169. k = lc
  1170. if k in boolean_attrs and v is None:
  1171. # boolean cookie-attribute is present, but has no value
  1172. # (like "discard", rather than "port=80")
  1173. v = True
  1174. if k in standard:
  1175. # only first value is significant
  1176. continue
  1177. if k == "domain":
  1178. if v is None:
  1179. _debug(" missing value for domain attribute")
  1180. bad_cookie = True
  1181. break
  1182. # RFC 2965 section 3.3.3
  1183. v = v.lower()
  1184. if k == "expires":
  1185. if max_age_set:
  1186. # Prefer max-age to expires (like Mozilla)
  1187. continue
  1188. if v is None:
  1189. _debug(" missing or invalid value for expires "
  1190. "attribute: treating as session cookie")
  1191. continue
  1192. if k == "max-age":
  1193. max_age_set = True
  1194. try:
  1195. v = int(v)
  1196. except ValueError:
  1197. _debug(" missing or invalid (non-numeric) value for "
  1198. "max-age attribute")
  1199. bad_cookie = True
  1200. break
  1201. # convert RFC 2965 Max-Age to seconds since epoch
  1202. # XXX Strictly you're supposed to follow RFC 2616
  1203. # age-calculation rules. Remember that zero Max-Age is a
  1204. # is a request to discard (old and new) cookie, though.
  1205. k = "expires"
  1206. v = self._now + v
  1207. if (k in value_attrs) or (k in boolean_attrs):
  1208. if (v is None and
  1209. k not in ("port", "comment", "commenturl")):
  1210. _debug(" missing value for %s attribute" % k)
  1211. bad_cookie = True
  1212. break
  1213. standard[k] = v
  1214. else:
  1215. rest[k] = v
  1216. if bad_cookie:
  1217. continue
  1218. cookie_tuples.append((name, value, standard, rest))
  1219. return cookie_tuples
  1220. def _cookie_from_cookie_tuple(self, tup, request):
  1221. # standard is dict of standard cookie-attributes, rest is dict of the
  1222. # rest of them
  1223. name, value, standard, rest = tup
  1224. domain = standard.get("domain", Absent)
  1225. path = standard.get("path", Absent)
  1226. port = standard.get("port", Absent)
  1227. expires = standard.get("expires", Absent)
  1228. # set the easy defaults
  1229. version = standard.get("version", None)
  1230. if version is not None:
  1231. try:
  1232. version = int(version)
  1233. except ValueError:
  1234. return None # invalid version, ignore cookie
  1235. secure = standard.get("secure", False)
  1236. # (discard is also set if expires is Absent)
  1237. discard = standard.get("discard", False)
  1238. comment = standard.get("comment", None)
  1239. comment_url = standard.get("commenturl", None)
  1240. # set default path
  1241. if path is not Absent and path != "":
  1242. path_specified = True
  1243. path = escape_path(path)
  1244. else:
  1245. path_specified = False
  1246. path = request_path(request)
  1247. i = path.rfind("/")
  1248. if i != -1:
  1249. if version == 0:
  1250. # Netscape spec parts company from reality here
  1251. path = path[:i]
  1252. else:
  1253. path = path[:i+1]
  1254. if len(path) == 0: path = "/"
  1255. # set default domain
  1256. domain_specified = domain is not Absent
  1257. # but first we have to remember whether it starts with a dot
  1258. domain_initial_dot = False
  1259. if domain_specified:
  1260. domain_initial_dot = bool(domain.startswith("."))
  1261. if domain is Absent:
  1262. req_host, erhn = eff_request_host(request)
  1263. domain = erhn
  1264. elif not domain.startswith("."):
  1265. domain = "."+domain
  1266. # set default port
  1267. port_specified = False
  1268. if port is not Absent:
  1269. if port is None:
  1270. # Port attr present, but has no value: default to request port.
  1271. # Cookie should then only be sent back on that port.
  1272. port = request_port(request)
  1273. else:
  1274. port_specified = True
  1275. port = re.sub(r"\s+", "", port)
  1276. else:
  1277. # No port attr present. Cookie can be sent back on any port.
  1278. port = None
  1279. # set default expires and discard
  1280. if expires is Absent:
  1281. expires = None
  1282. discard = True
  1283. elif expires <= self._now:
  1284. # Expiry date in past is request to delete cookie. This can't be
  1285. # in DefaultCookiePolicy, because can't delete cookies there.
  1286. try:
  1287. self.clear(domain, path, name)
  1288. except KeyError:
  1289. pass
  1290. _debug("Expiring cookie, domain='%s', path='%s', name='%s'",
  1291. domain, path, name)
  1292. return None
  1293. return Cookie(version,
  1294. name, value,
  1295. port, port_specified,
  1296. domain, domain_specified, domain_initial_dot,
  1297. path, path_specified,
  1298. secure,
  1299. expires,
  1300. discard,
  1301. comment,
  1302. comment_url,
  1303. rest)
  1304. def _cookies_from_attrs_set(self, attrs_set, request):
  1305. cookie_tuples = self._normalized_cookie_tuples(attrs_set)
  1306. cookies = []
  1307. for tup in cookie_tuples:
  1308. cookie = self._cookie_from_cookie_tuple(tup, request)
  1309. if cookie: cookies.append(cookie)
  1310. return cookies
  1311. def _process_rfc2109_cookies(self, cookies):
  1312. rfc2109_as_ns = getattr(self._policy, 'rfc2109_as_netscape', None)
  1313. if rfc2109_as_ns is None:
  1314. rfc2109_as_ns = not self._policy.rfc2965
  1315. for cookie in cookies:
  1316. if cookie.version == 1:
  1317. cookie.rfc2109 = True
  1318. if rfc2109_as_ns:
  1319. # treat 2109 cookies as Netscape cookies rather than
  1320. # as RFC2965 cookies
  1321. cookie.version = 0
  1322. def make_cookies(self, response, request):
  1323. """Return sequence of Cookie objects extracted from response object."""
  1324. # get cookie-attributes for RFC 2965 and Netscape protocols
  1325. headers = response.info()
  1326. rfc2965_hdrs = headers.getheaders("Set-Cookie2")
  1327. ns_hdrs = headers.getheaders("Set-Cookie")
  1328. rfc2965 = self._policy.rfc2965
  1329. netscape = self._policy.netscape
  1330. if ((not rfc2965_hdrs and not ns_hdrs) or
  1331. (not ns_hdrs and not rfc2965) or
  1332. (not rfc2965_hdrs and not netscape) or
  1333. (not netscape and not rfc2965)):
  1334. return [] # no relevant cookie headers: quick exit
  1335. try:
  1336. cookies = self._cookies_from_attrs_set(
  1337. split_header_words(rfc2965_hdrs), request)
  1338. except Exception:
  1339. _warn_unhandled_exception()
  1340. cookies = []
  1341. if ns_hdrs and netscape:
  1342. try:
  1343. # RFC 2109 and Netscape cookies
  1344. ns_cookies = self._cookies_from_attrs_set(
  1345. parse_ns_headers(ns_hdrs), request)
  1346. except Exception:
  1347. _warn_unhandled_exception()
  1348. ns_cookies = []
  1349. self._process_rfc2109_cookies(ns_cookies)
  1350. # Look for Netscape cookies (from Set-Cookie headers) that match
  1351. # corresponding RFC 2965 cookies (from Set-Cookie2 headers).
  1352. # For each match, keep the RFC 2965 cookie and ignore the Netscape
  1353. # cookie (RFC 2965 section 9.1). Actually, RFC 2109 cookies are
  1354. # bundled in with the Netscape cookies for this purpose, which is
  1355. # reasonable behaviour.
  1356. if rfc2965:
  1357. lookup = {}
  1358. for cookie in cookies:
  1359. lookup[(cookie.domain, cookie.path, cookie.name)] = None
  1360. def no_matching_rfc2965(ns_cookie, lookup=lookup):
  1361. key = ns_cookie.domain, ns_cookie.path, ns_cookie.name
  1362. return key not in lookup
  1363. ns_cookies = filter(no_matching_rfc2965, ns_cookies)
  1364. if ns_cookies:
  1365. cookies.extend(ns_cookies)
  1366. return cookies
  1367. def set_cookie_if_ok(self, cookie, request):
  1368. """Set a cookie if policy says it's OK to do so."""
  1369. self._cookies_lock.acquire()
  1370. try:
  1371. self._policy._now = self._now = int(time.time())
  1372. if self._policy.set_ok(cookie, request):
  1373. self.set_cookie(cookie)
  1374. finally:
  1375. self._cookies_lock.release()
  1376. def set_cookie(self, cookie):
  1377. """Set a cookie, without checking whether or not it should be set."""
  1378. c = self._cookies
  1379. self._cookies_lock.acquire()
  1380. try:
  1381. if cookie.domain not in c: c[cookie.domain] = {}
  1382. c2 = c[cookie.domain]
  1383. if cookie.path not in c2: c2[cookie.path] = {}
  1384. c3 = c2[cookie.path]
  1385. c3[cookie.name] = cookie
  1386. finally:
  1387. self._cookies_lock.release()
  1388. def extract_cookies(self, response, request):
  1389. """Extract cookies from response, where allowable given the request."""
  1390. _debug("extract_cookies: %s", response.info())
  1391. self._cookies_lock.acquire()
  1392. try:
  1393. self._policy._now = self._now = int(time.time())
  1394. for cookie in self.make_cookies(response, request):
  1395. if self._policy.set_ok(cookie, request):
  1396. _debug(" setting cookie: %s", cookie)
  1397. self.set_cookie(cookie)
  1398. finally:
  1399. self._cookies_lock.release()
  1400. def clear(self, domain=None, path=None, name=None):
  1401. """Clear some cookies.
  1402. Invoking this method without arguments will clear all cookies. If
  1403. given a single argument, only cookies belonging to that domain will be
  1404. removed. If given two arguments, cookies belonging to the specified
  1405. path within that domain are removed. If given three arguments, then
  1406. the cookie with the specified name, path and domain is removed.
  1407. Raises KeyError if no matching cookie exists.
  1408. """
  1409. if name is not None:
  1410. if (domain is None) or (path is None):
  1411. raise ValueError(
  1412. "domain and path must be given to remove a cookie by name")
  1413. del self._cookies[domain][path][name]
  1414. elif path is not None:
  1415. if domain is None:
  1416. raise ValueError(
  1417. "domain must be given to remove cookies by path")
  1418. del self._cookies[domain][path]
  1419. elif domain is not None:
  1420. del self._cookies[domain]
  1421. else:
  1422. self._cookies = {}
  1423. def clear_session_cookies(self):
  1424. """Discard all session cookies.
  1425. Note that the .save() method won't save session cookies anyway, unless
  1426. you ask otherwise by passing a true ignore_discard argument.
  1427. """
  1428. self._cookies_lock.acquire()
  1429. try:
  1430. for cookie in self:
  1431. if cookie.discard:
  1432. self.clear(cookie.domain, cookie.path, cookie.name)
  1433. finally:
  1434. self._cookies_lock.release()
  1435. def clear_expired_cookies(self):
  1436. """Discard all expired cookies.
  1437. You probably don't need to call this method: expired cookies are never
  1438. sent back to the server (provided you're using DefaultCookiePolicy),
  1439. this method is called by CookieJar itself every so often, and the
  1440. .save() method won't save expired cookies anyway (unless you ask
  1441. otherwise by passing a true ignore_expires argument).
  1442. """
  1443. self._cookies_lock.acquire()
  1444. try:
  1445. now = time.time()
  1446. for cookie in self:
  1447. if cookie.is_expired(now):
  1448. self.clear(cookie.domain, cookie.path, cookie.name)
  1449. finally:
  1450. self._cookies_lock.release()
  1451. def __iter__(self):
  1452. return deepvalues(self._cookies)
  1453. def __len__(self):
  1454. """Return number of contained cookies."""
  1455. i = 0
  1456. for cookie in self: i = i + 1
  1457. return i
  1458. def __repr__(self):
  1459. r = []
  1460. for cookie in self: r.append(repr(cookie))
  1461. return "<%s[%s]>" % (self.__class__.__name__, ", ".join(r))
  1462. def __str__(self):
  1463. r = []
  1464. for cookie in self: r.append(str(cookie))
  1465. return "<%s[%s]>" % (self.__class__.__name__, ", ".join(r))
  1466. # derives from IOError for backwards-compatibility with Python 2.4.0
  1467. class LoadError(IOError): pass
  1468. class FileCookieJar(CookieJar):
  1469. """CookieJar that can be loaded from and saved to a file."""
  1470. def __init__(self, filename=None, delayload=False, policy=None):
  1471. """
  1472. Cookies are NOT loaded from the named file until either the .load() or
  1473. .revert() method is called.
  1474. """
  1475. CookieJar.__init__(self, policy)
  1476. if filename is not None:
  1477. try:
  1478. filename+""
  1479. except:
  1480. raise ValueError("filename must be string-like")
  1481. self.filename = filename
  1482. self.delayload = bool(delayload)
  1483. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  1484. """Save cookies to a file."""
  1485. raise NotImplementedError()
  1486. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  1487. """Load cookies from a file."""
  1488. if filename is None:
  1489. if self.filename is not None: filename = self.filename
  1490. else: raise ValueError(MISSING_FILENAME_TEXT)
  1491. f = open(filename)
  1492. try:
  1493. self._really_load(f, filename, ignore_discard, ignore_expires)
  1494. finally:
  1495. f.close()
  1496. def revert(self, filename=None,
  1497. ignore_discard=False, ignore_expires=False):
  1498. """Clear all cookies and reload cookies from a saved file.
  1499. Raises LoadError (or IOError) if reversion is not successful; the
  1500. object's state will not be altered if this happens.
  1501. """
  1502. if filename is None:
  1503. if self.filename is not None: filename = self.filename
  1504. else: raise ValueError(MISSING_FILENAME_TEXT)
  1505. self._cookies_lock.acquire()
  1506. try:
  1507. old_state = copy.deepcopy(self._cookies)
  1508. self._cookies = {}
  1509. try:
  1510. self.load(filename, ignore_discard, ignore_expires)
  1511. except (LoadError, IOError):
  1512. self._cookies = old_state
  1513. raise
  1514. finally:
  1515. self._cookies_lock.release()
  1516. from _LWPCookieJar import LWPCookieJar, lwp_cookie_str
  1517. from _MozillaCookieJar import MozillaCookieJar