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

/lib-python/2.7/cookielib.py

https://bitbucket.org/evelyn559/pypy
Python | 1794 lines | 1718 code | 25 blank | 51 comment | 58 complexity | e44e95a69089ddc4d506f329f6e663c8 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file