PageRenderTime 57ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/python/lib/Lib/cookielib.py

http://github.com/JetBrains/intellij-community
Python | 1776 lines | 1701 code | 24 blank | 51 comment | 54 complexity | 76d1b4ae6b32644aad8712cd751322be MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0

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

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