logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

cookiejar.py (77407B)


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