You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2153 lines
77KB

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