Debian Codegraph @

cpython27/Lib/cookielib.py

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