PageRenderTime 68ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/other/FetchData/mechanize/_clientcookie.py

http://github.com/jbeezley/wrf-fire
Python | 1707 lines | 1647 code | 15 blank | 45 comment | 42 complexity | 51c693d2189f75f85a006bf7468a6d9d MD5 | raw file
Possible License(s): AGPL-1.0
  1. """HTTP cookie handling for web clients.
  2. This module originally developed from my port of 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. CookieJar____
  8. / \ \
  9. FileCookieJar \ \
  10. / | \ \ \
  11. MozillaCookieJar | LWPCookieJar \ \
  12. | | \
  13. | ---MSIEBase | \
  14. | / | | \
  15. | / MSIEDBCookieJar BSDDBCookieJar
  16. |/
  17. MSIECookieJar
  18. Comments to John J Lee <jjl@pobox.com>.
  19. Copyright 2002-2006 John J Lee <jjl@pobox.com>
  20. Copyright 1997-1999 Gisle Aas (original libwww-perl code)
  21. Copyright 2002-2003 Johnny Lee (original MSIE Perl code)
  22. This code is free software; you can redistribute it and/or modify it
  23. under the terms of the BSD or ZPL 2.1 licenses (see the file
  24. COPYING.txt included with the distribution).
  25. """
  26. import sys, re, copy, time, urllib, types, logging
  27. try:
  28. import threading
  29. _threading = threading; del threading
  30. except ImportError:
  31. import dummy_threading
  32. _threading = dummy_threading; del dummy_threading
  33. MISSING_FILENAME_TEXT = ("a filename was not supplied (nor was the CookieJar "
  34. "instance initialised with one)")
  35. DEFAULT_HTTP_PORT = "80"
  36. from _headersutil import split_header_words, parse_ns_headers
  37. from _util import isstringlike
  38. import _rfc3986
  39. debug = logging.getLogger("mechanize.cookies").debug
  40. def reraise_unmasked_exceptions(unmasked=()):
  41. # There are a few catch-all except: statements in this module, for
  42. # catching input that's bad in unexpected ways.
  43. # This function re-raises some exceptions we don't want to trap.
  44. import mechanize, warnings
  45. if not mechanize.USE_BARE_EXCEPT:
  46. raise
  47. unmasked = unmasked + (KeyboardInterrupt, SystemExit, MemoryError)
  48. etype = sys.exc_info()[0]
  49. if issubclass(etype, unmasked):
  50. raise
  51. # swallowed an exception
  52. import traceback, StringIO
  53. f = StringIO.StringIO()
  54. traceback.print_exc(None, f)
  55. msg = f.getvalue()
  56. warnings.warn("mechanize bug!\n%s" % msg, stacklevel=2)
  57. IPV4_RE = re.compile(r"\.\d+$")
  58. def is_HDN(text):
  59. """Return True if text is a host domain name."""
  60. # XXX
  61. # This may well be wrong. Which RFC is HDN defined in, if any (for
  62. # the purposes of RFC 2965)?
  63. # For the current implementation, what about IPv6? Remember to look
  64. # at other uses of IPV4_RE also, if change this.
  65. return not (IPV4_RE.search(text) or
  66. text == "" or
  67. text[0] == "." or text[-1] == ".")
  68. def domain_match(A, B):
  69. """Return True if domain A domain-matches domain B, according to RFC 2965.
  70. A and B may be host domain names or IP addresses.
  71. RFC 2965, section 1:
  72. Host names can be specified either as an IP address or a HDN string.
  73. Sometimes we compare one host name with another. (Such comparisons SHALL
  74. be case-insensitive.) Host A's name domain-matches host B's if
  75. * their host name strings string-compare equal; or
  76. * A is a HDN string and has the form NB, where N is a non-empty
  77. name string, B has the form .B', and B' is a HDN string. (So,
  78. x.y.com domain-matches .Y.com but not Y.com.)
  79. Note that domain-match is not a commutative operation: a.b.c.com
  80. domain-matches .c.com, but not the reverse.
  81. """
  82. # Note that, if A or B are IP addresses, the only relevant part of the
  83. # definition of the domain-match algorithm is the direct string-compare.
  84. A = A.lower()
  85. B = B.lower()
  86. if A == B:
  87. return True
  88. if not is_HDN(A):
  89. return False
  90. i = A.rfind(B)
  91. has_form_nb = not (i == -1 or i == 0)
  92. return (
  93. has_form_nb and
  94. B.startswith(".") and
  95. is_HDN(B[1:])
  96. )
  97. def liberal_is_HDN(text):
  98. """Return True if text is a sort-of-like a host domain name.
  99. For accepting/blocking domains.
  100. """
  101. return not IPV4_RE.search(text)
  102. def user_domain_match(A, B):
  103. """For blocking/accepting domains.
  104. A and B may be host domain names or IP addresses.
  105. """
  106. A = A.lower()
  107. B = B.lower()
  108. if not (liberal_is_HDN(A) and liberal_is_HDN(B)):
  109. if A == B:
  110. # equal IP addresses
  111. return True
  112. return False
  113. initial_dot = B.startswith(".")
  114. if initial_dot and A.endswith(B):
  115. return True
  116. if not initial_dot and A == B:
  117. return True
  118. return False
  119. cut_port_re = re.compile(r":\d+$")
  120. def request_host(request):
  121. """Return request-host, as defined by RFC 2965.
  122. Variation from RFC: returned value is lowercased, for convenient
  123. comparison.
  124. """
  125. url = request.get_full_url()
  126. host = _rfc3986.urlsplit(url)[1]
  127. if host is None:
  128. host = request.get_header("Host", "")
  129. # remove port, if present
  130. return cut_port_re.sub("", host, 1)
  131. def request_host_lc(request):
  132. return request_host(request).lower()
  133. def eff_request_host(request):
  134. """Return a tuple (request-host, effective request-host name)."""
  135. erhn = req_host = request_host(request)
  136. if req_host.find(".") == -1 and not IPV4_RE.search(req_host):
  137. erhn = req_host + ".local"
  138. return req_host, erhn
  139. def eff_request_host_lc(request):
  140. req_host, erhn = eff_request_host(request)
  141. return req_host.lower(), erhn.lower()
  142. def effective_request_host(request):
  143. """Return the effective request-host, as defined by RFC 2965."""
  144. return eff_request_host(request)[1]
  145. def request_path(request):
  146. """request-URI, as defined by RFC 2965."""
  147. url = request.get_full_url()
  148. path, query, frag = _rfc3986.urlsplit(url)[2:]
  149. path = escape_path(path)
  150. req_path = _rfc3986.urlunsplit((None, None, path, query, frag))
  151. if not req_path.startswith("/"):
  152. req_path = "/"+req_path
  153. return req_path
  154. def request_port(request):
  155. host = request.get_host()
  156. i = host.find(':')
  157. if i >= 0:
  158. port = host[i+1:]
  159. try:
  160. int(port)
  161. except ValueError:
  162. debug("nonnumeric port: '%s'", port)
  163. return None
  164. else:
  165. port = DEFAULT_HTTP_PORT
  166. return port
  167. def request_is_unverifiable(request):
  168. try:
  169. return request.is_unverifiable()
  170. except AttributeError:
  171. if hasattr(request, "unverifiable"):
  172. return request.unverifiable
  173. else:
  174. raise
  175. # Characters in addition to A-Z, a-z, 0-9, '_', '.', and '-' that don't
  176. # need to be escaped to form a valid HTTP URL (RFCs 2396 and 1738).
  177. HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()"
  178. ESCAPED_CHAR_RE = re.compile(r"%([0-9a-fA-F][0-9a-fA-F])")
  179. def uppercase_escaped_char(match):
  180. return "%%%s" % match.group(1).upper()
  181. def escape_path(path):
  182. """Escape any invalid characters in HTTP URL, and uppercase all escapes."""
  183. # There's no knowing what character encoding was used to create URLs
  184. # containing %-escapes, but since we have to pick one to escape invalid
  185. # path characters, we pick UTF-8, as recommended in the HTML 4.0
  186. # specification:
  187. # http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.2.1
  188. # And here, kind of: draft-fielding-uri-rfc2396bis-03
  189. # (And in draft IRI specification: draft-duerst-iri-05)
  190. # (And here, for new URI schemes: RFC 2718)
  191. if isinstance(path, types.UnicodeType):
  192. path = path.encode("utf-8")
  193. path = urllib.quote(path, HTTP_PATH_SAFE)
  194. path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)
  195. return path
  196. def reach(h):
  197. """Return reach of host h, as defined by RFC 2965, section 1.
  198. The reach R of a host name H is defined as follows:
  199. * If
  200. - H is the host domain name of a host; and,
  201. - H has the form A.B; and
  202. - A has no embedded (that is, interior) dots; and
  203. - B has at least one embedded dot, or B is the string "local".
  204. then the reach of H is .B.
  205. * Otherwise, the reach of H is H.
  206. >>> reach("www.acme.com")
  207. '.acme.com'
  208. >>> reach("acme.com")
  209. 'acme.com'
  210. >>> reach("acme.local")
  211. '.local'
  212. """
  213. i = h.find(".")
  214. if i >= 0:
  215. #a = h[:i] # this line is only here to show what a is
  216. b = h[i+1:]
  217. i = b.find(".")
  218. if is_HDN(h) and (i >= 0 or b == "local"):
  219. return "."+b
  220. return h
  221. def is_third_party(request):
  222. """
  223. RFC 2965, section 3.3.6:
  224. An unverifiable transaction is to a third-party host if its request-
  225. host U does not domain-match the reach R of the request-host O in the
  226. origin transaction.
  227. """
  228. req_host = request_host_lc(request)
  229. # the origin request's request-host was stuffed into request by
  230. # _urllib2_support.AbstractHTTPHandler
  231. return not domain_match(req_host, reach(request.origin_req_host))
  232. class Cookie:
  233. """HTTP Cookie.
  234. This class represents both Netscape and RFC 2965 cookies.
  235. This is deliberately a very simple class. It just holds attributes. It's
  236. possible to construct Cookie instances that don't comply with the cookie
  237. standards. CookieJar.make_cookies is the factory function for Cookie
  238. objects -- it deals with cookie parsing, supplying defaults, and
  239. normalising to the representation used in this class. CookiePolicy is
  240. responsible for checking them to see whether they should be accepted from
  241. and returned to the server.
  242. version: integer;
  243. name: string;
  244. value: string (may be None);
  245. port: string; None indicates no attribute was supplied (eg. "Port", rather
  246. than eg. "Port=80"); otherwise, a port string (eg. "80") or a port list
  247. string (eg. "80,8080")
  248. port_specified: boolean; true if a value was supplied with the Port
  249. cookie-attribute
  250. domain: string;
  251. domain_specified: boolean; true if Domain was explicitly set
  252. domain_initial_dot: boolean; true if Domain as set in HTTP header by server
  253. started with a dot (yes, this really is necessary!)
  254. path: string;
  255. path_specified: boolean; true if Path was explicitly set
  256. secure: boolean; true if should only be returned over secure connection
  257. expires: integer; seconds since epoch (RFC 2965 cookies should calculate
  258. this value from the Max-Age attribute)
  259. discard: boolean, true if this is a session cookie; (if no expires value,
  260. this should be true)
  261. comment: string;
  262. comment_url: string;
  263. rfc2109: boolean; true if cookie arrived in a Set-Cookie: (not
  264. Set-Cookie2:) header, but had a version cookie-attribute of 1
  265. rest: mapping of other cookie-attributes
  266. Note that the port may be present in the headers, but unspecified ("Port"
  267. rather than"Port=80", for example); if this is the case, port is None.
  268. """
  269. def __init__(self, version, name, value,
  270. port, port_specified,
  271. domain, domain_specified, domain_initial_dot,
  272. path, path_specified,
  273. secure,
  274. expires,
  275. discard,
  276. comment,
  277. comment_url,
  278. rest,
  279. rfc2109=False,
  280. ):
  281. if version is not None: version = int(version)
  282. if expires is not None: expires = int(expires)
  283. if port is None and port_specified is True:
  284. raise ValueError("if port is None, port_specified must be false")
  285. self.version = version
  286. self.name = name
  287. self.value = value
  288. self.port = port
  289. self.port_specified = port_specified
  290. # normalise case, as per RFC 2965 section 3.3.3
  291. self.domain = domain.lower()
  292. self.domain_specified = domain_specified
  293. # Sigh. We need to know whether the domain given in the
  294. # cookie-attribute had an initial dot, in order to follow RFC 2965
  295. # (as clarified in draft errata). Needed for the returned $Domain
  296. # value.
  297. self.domain_initial_dot = domain_initial_dot
  298. self.path = path
  299. self.path_specified = path_specified
  300. self.secure = secure
  301. self.expires = expires
  302. self.discard = discard
  303. self.comment = comment
  304. self.comment_url = comment_url
  305. self.rfc2109 = rfc2109
  306. self._rest = copy.copy(rest)
  307. def has_nonstandard_attr(self, name):
  308. return self._rest.has_key(name)
  309. def get_nonstandard_attr(self, name, default=None):
  310. return self._rest.get(name, default)
  311. def set_nonstandard_attr(self, name, value):
  312. self._rest[name] = value
  313. def nonstandard_attr_keys(self):
  314. return self._rest.keys()
  315. def is_expired(self, now=None):
  316. if now is None: now = time.time()
  317. return (self.expires is not None) and (self.expires <= now)
  318. def __str__(self):
  319. if self.port is None: p = ""
  320. else: p = ":"+self.port
  321. limit = self.domain + p + self.path
  322. if self.value is not None:
  323. namevalue = "%s=%s" % (self.name, self.value)
  324. else:
  325. namevalue = self.name
  326. return "<Cookie %s for %s>" % (namevalue, limit)
  327. def __repr__(self):
  328. args = []
  329. for name in ["version", "name", "value",
  330. "port", "port_specified",
  331. "domain", "domain_specified", "domain_initial_dot",
  332. "path", "path_specified",
  333. "secure", "expires", "discard", "comment", "comment_url",
  334. ]:
  335. attr = getattr(self, name)
  336. args.append("%s=%s" % (name, repr(attr)))
  337. args.append("rest=%s" % repr(self._rest))
  338. args.append("rfc2109=%s" % repr(self.rfc2109))
  339. return "Cookie(%s)" % ", ".join(args)
  340. class CookiePolicy:
  341. """Defines which cookies get accepted from and returned to server.
  342. May also modify cookies.
  343. The subclass DefaultCookiePolicy defines the standard rules for Netscape
  344. and RFC 2965 cookies -- override that if you want a customised policy.
  345. As well as implementing set_ok and return_ok, implementations of this
  346. interface must also supply the following attributes, indicating which
  347. protocols should be used, and how. These can be read and set at any time,
  348. though whether that makes complete sense from the protocol point of view is
  349. doubtful.
  350. Public attributes:
  351. netscape: implement netscape protocol
  352. rfc2965: implement RFC 2965 protocol
  353. rfc2109_as_netscape:
  354. WARNING: This argument will change or go away if is not accepted into
  355. the Python standard library in this form!
  356. If true, treat RFC 2109 cookies as though they were Netscape cookies. The
  357. default is for this attribute to be None, which means treat 2109 cookies
  358. as RFC 2965 cookies unless RFC 2965 handling is switched off (which it is,
  359. by default), and as Netscape cookies otherwise.
  360. hide_cookie2: don't add Cookie2 header to requests (the presence of
  361. this header indicates to the server that we understand RFC 2965
  362. cookies)
  363. """
  364. def set_ok(self, cookie, request):
  365. """Return true if (and only if) cookie should be accepted from server.
  366. Currently, pre-expired cookies never get this far -- the CookieJar
  367. class deletes such cookies itself.
  368. cookie: mechanize.Cookie object
  369. request: object implementing the interface defined by
  370. CookieJar.extract_cookies.__doc__
  371. """
  372. raise NotImplementedError()
  373. def return_ok(self, cookie, request):
  374. """Return true if (and only if) cookie should be returned to server.
  375. cookie: mechanize.Cookie object
  376. request: object implementing the interface defined by
  377. CookieJar.add_cookie_header.__doc__
  378. """
  379. raise NotImplementedError()
  380. def domain_return_ok(self, domain, request):
  381. """Return false if cookies should not be returned, given cookie domain.
  382. This is here as an optimization, to remove the need for checking every
  383. cookie with a particular domain (which may involve reading many files).
  384. The default implementations of domain_return_ok and path_return_ok
  385. (return True) leave all the work to return_ok.
  386. If domain_return_ok returns true for the cookie domain, path_return_ok
  387. is called for the cookie path. Otherwise, path_return_ok and return_ok
  388. are never called for that cookie domain. If path_return_ok returns
  389. true, return_ok is called with the Cookie object itself for a full
  390. check. Otherwise, return_ok is never called for that cookie path.
  391. Note that domain_return_ok is called for every *cookie* domain, not
  392. just for the *request* domain. For example, the function might be
  393. called with both ".acme.com" and "www.acme.com" if the request domain
  394. is "www.acme.com". The same goes for path_return_ok.
  395. For argument documentation, see the docstring for return_ok.
  396. """
  397. return True
  398. def path_return_ok(self, path, request):
  399. """Return false if cookies should not be returned, given cookie path.
  400. See the docstring for domain_return_ok.
  401. """
  402. return True
  403. class DefaultCookiePolicy(CookiePolicy):
  404. """Implements the standard rules for accepting and returning cookies.
  405. Both RFC 2965 and Netscape cookies are covered. RFC 2965 handling is
  406. switched off by default.
  407. The easiest way to provide your own policy is to override this class and
  408. call its methods in your overriden implementations before adding your own
  409. additional checks.
  410. import mechanize
  411. class MyCookiePolicy(mechanize.DefaultCookiePolicy):
  412. def set_ok(self, cookie, request):
  413. if not mechanize.DefaultCookiePolicy.set_ok(
  414. self, cookie, request):
  415. return False
  416. if i_dont_want_to_store_this_cookie():
  417. return False
  418. return True
  419. In addition to the features required to implement the CookiePolicy
  420. interface, this class allows you to block and allow domains from setting
  421. and receiving cookies. There are also some strictness switches that allow
  422. you to tighten up the rather loose Netscape protocol rules a little bit (at
  423. the cost of blocking some benign cookies).
  424. A domain blacklist and whitelist is provided (both off by default). Only
  425. domains not in the blacklist and present in the whitelist (if the whitelist
  426. is active) participate in cookie setting and returning. Use the
  427. blocked_domains constructor argument, and blocked_domains and
  428. set_blocked_domains methods (and the corresponding argument and methods for
  429. allowed_domains). If you set a whitelist, you can turn it off again by
  430. setting it to None.
  431. Domains in block or allow lists that do not start with a dot must
  432. string-compare equal. For example, "acme.com" matches a blacklist entry of
  433. "acme.com", but "www.acme.com" does not. Domains that do start with a dot
  434. are matched by more specific domains too. For example, both "www.acme.com"
  435. and "www.munitions.acme.com" match ".acme.com" (but "acme.com" itself does
  436. not). IP addresses are an exception, and must match exactly. For example,
  437. if blocked_domains contains "192.168.1.2" and ".168.1.2" 192.168.1.2 is
  438. blocked, but 193.168.1.2 is not.
  439. Additional Public Attributes:
  440. General strictness switches
  441. strict_domain: don't allow sites to set two-component domains with
  442. country-code top-level domains like .co.uk, .gov.uk, .co.nz. etc.
  443. This is far from perfect and isn't guaranteed to work!
  444. RFC 2965 protocol strictness switches
  445. strict_rfc2965_unverifiable: follow RFC 2965 rules on unverifiable
  446. transactions (usually, an unverifiable transaction is one resulting from
  447. a redirect or an image hosted on another site); if this is false, cookies
  448. are NEVER blocked on the basis of verifiability
  449. Netscape protocol strictness switches
  450. strict_ns_unverifiable: apply RFC 2965 rules on unverifiable transactions
  451. even to Netscape cookies
  452. strict_ns_domain: flags indicating how strict to be with domain-matching
  453. rules for Netscape cookies:
  454. DomainStrictNoDots: when setting cookies, host prefix must not contain a
  455. dot (eg. www.foo.bar.com can't set a cookie for .bar.com, because
  456. www.foo contains a dot)
  457. DomainStrictNonDomain: cookies that did not explicitly specify a Domain
  458. cookie-attribute can only be returned to a domain that string-compares
  459. equal to the domain that set the cookie (eg. rockets.acme.com won't
  460. be returned cookies from acme.com that had no Domain cookie-attribute)
  461. DomainRFC2965Match: when setting cookies, require a full RFC 2965
  462. domain-match
  463. DomainLiberal and DomainStrict are the most useful combinations of the
  464. above flags, for convenience
  465. strict_ns_set_initial_dollar: ignore cookies in Set-Cookie: headers that
  466. have names starting with '$'
  467. strict_ns_set_path: don't allow setting cookies whose path doesn't
  468. path-match request URI
  469. """
  470. DomainStrictNoDots = 1
  471. DomainStrictNonDomain = 2
  472. DomainRFC2965Match = 4
  473. DomainLiberal = 0
  474. DomainStrict = DomainStrictNoDots|DomainStrictNonDomain
  475. def __init__(self,
  476. blocked_domains=None, allowed_domains=None,
  477. netscape=True, rfc2965=False,
  478. # WARNING: this argument will change or go away if is not
  479. # accepted into the Python standard library in this form!
  480. # default, ie. treat 2109 as netscape iff not rfc2965
  481. rfc2109_as_netscape=None,
  482. hide_cookie2=False,
  483. strict_domain=False,
  484. strict_rfc2965_unverifiable=True,
  485. strict_ns_unverifiable=False,
  486. strict_ns_domain=DomainLiberal,
  487. strict_ns_set_initial_dollar=False,
  488. strict_ns_set_path=False,
  489. ):
  490. """
  491. Constructor arguments should be used as keyword arguments only.
  492. blocked_domains: sequence of domain names that we never accept cookies
  493. from, nor return cookies to
  494. allowed_domains: if not None, this is a sequence of the only domains
  495. for which we accept and return cookies
  496. For other arguments, see CookiePolicy.__doc__ and
  497. DefaultCookiePolicy.__doc__..
  498. """
  499. self.netscape = netscape
  500. self.rfc2965 = rfc2965
  501. self.rfc2109_as_netscape = rfc2109_as_netscape
  502. self.hide_cookie2 = hide_cookie2
  503. self.strict_domain = strict_domain
  504. self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable
  505. self.strict_ns_unverifiable = strict_ns_unverifiable
  506. self.strict_ns_domain = strict_ns_domain
  507. self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar
  508. self.strict_ns_set_path = strict_ns_set_path
  509. if blocked_domains is not None:
  510. self._blocked_domains = tuple(blocked_domains)
  511. else:
  512. self._blocked_domains = ()
  513. if allowed_domains is not None:
  514. allowed_domains = tuple(allowed_domains)
  515. self._allowed_domains = allowed_domains
  516. def blocked_domains(self):
  517. """Return the sequence of blocked domains (as a tuple)."""
  518. return self._blocked_domains
  519. def set_blocked_domains(self, blocked_domains):
  520. """Set the sequence of blocked domains."""
  521. self._blocked_domains = tuple(blocked_domains)
  522. def is_blocked(self, domain):
  523. for blocked_domain in self._blocked_domains:
  524. if user_domain_match(domain, blocked_domain):
  525. return True
  526. return False
  527. def allowed_domains(self):
  528. """Return None, or the sequence of allowed domains (as a tuple)."""
  529. return self._allowed_domains
  530. def set_allowed_domains(self, allowed_domains):
  531. """Set the sequence of allowed domains, or None."""
  532. if allowed_domains is not None:
  533. allowed_domains = tuple(allowed_domains)
  534. self._allowed_domains = allowed_domains
  535. def is_not_allowed(self, domain):
  536. if self._allowed_domains is None:
  537. return False
  538. for allowed_domain in self._allowed_domains:
  539. if user_domain_match(domain, allowed_domain):
  540. return False
  541. return True
  542. def set_ok(self, cookie, request):
  543. """
  544. If you override set_ok, be sure to call this method. If it returns
  545. false, so should your subclass (assuming your subclass wants to be more
  546. strict about which cookies to accept).
  547. """
  548. debug(" - checking cookie %s", cookie)
  549. assert cookie.name is not None
  550. for n in "version", "verifiability", "name", "path", "domain", "port":
  551. fn_name = "set_ok_"+n
  552. fn = getattr(self, fn_name)
  553. if not fn(cookie, request):
  554. return False
  555. return True
  556. def set_ok_version(self, cookie, request):
  557. if cookie.version is None:
  558. # Version is always set to 0 by parse_ns_headers if it's a Netscape
  559. # cookie, so this must be an invalid RFC 2965 cookie.
  560. debug(" Set-Cookie2 without version attribute (%s)", cookie)
  561. return False
  562. if cookie.version > 0 and not self.rfc2965:
  563. debug(" RFC 2965 cookies are switched off")
  564. return False
  565. elif cookie.version == 0 and not self.netscape:
  566. debug(" Netscape cookies are switched off")
  567. return False
  568. return True
  569. def set_ok_verifiability(self, cookie, request):
  570. if request_is_unverifiable(request) and is_third_party(request):
  571. if cookie.version > 0 and self.strict_rfc2965_unverifiable:
  572. debug(" third-party RFC 2965 cookie during "
  573. "unverifiable transaction")
  574. return False
  575. elif cookie.version == 0 and self.strict_ns_unverifiable:
  576. debug(" third-party Netscape cookie during "
  577. "unverifiable transaction")
  578. return False
  579. return True
  580. def set_ok_name(self, cookie, request):
  581. # Try and stop servers setting V0 cookies designed to hack other
  582. # servers that know both V0 and V1 protocols.
  583. if (cookie.version == 0 and self.strict_ns_set_initial_dollar and
  584. cookie.name.startswith("$")):
  585. debug(" illegal name (starts with '$'): '%s'", cookie.name)
  586. return False
  587. return True
  588. def set_ok_path(self, cookie, request):
  589. if cookie.path_specified:
  590. req_path = request_path(request)
  591. if ((cookie.version > 0 or
  592. (cookie.version == 0 and self.strict_ns_set_path)) and
  593. not req_path.startswith(cookie.path)):
  594. debug(" path attribute %s is not a prefix of request "
  595. "path %s", cookie.path, req_path)
  596. return False
  597. return True
  598. def set_ok_countrycode_domain(self, cookie, request):
  599. """Return False if explicit cookie domain is not acceptable.
  600. Called by set_ok_domain, for convenience of overriding by
  601. subclasses.
  602. """
  603. if cookie.domain_specified and self.strict_domain:
  604. domain = cookie.domain
  605. # since domain was specified, we know that:
  606. assert domain.startswith(".")
  607. if domain.count(".") == 2:
  608. # domain like .foo.bar
  609. i = domain.rfind(".")
  610. tld = domain[i+1:]
  611. sld = domain[1:i]
  612. if (sld.lower() in [
  613. "co", "ac",
  614. "com", "edu", "org", "net", "gov", "mil", "int",
  615. "aero", "biz", "cat", "coop", "info", "jobs", "mobi",
  616. "museum", "name", "pro", "travel",
  617. ] and
  618. len(tld) == 2):
  619. # domain like .co.uk
  620. return False
  621. return True
  622. def set_ok_domain(self, cookie, request):
  623. if self.is_blocked(cookie.domain):
  624. debug(" domain %s is in user block-list", cookie.domain)
  625. return False
  626. if self.is_not_allowed(cookie.domain):
  627. debug(" domain %s is not in user allow-list", cookie.domain)
  628. return False
  629. if not self.set_ok_countrycode_domain(cookie, request):
  630. debug(" country-code second level domain %s", cookie.domain)
  631. return False
  632. if cookie.domain_specified:
  633. req_host, erhn = eff_request_host_lc(request)
  634. domain = cookie.domain
  635. if domain.startswith("."):
  636. undotted_domain = domain[1:]
  637. else:
  638. undotted_domain = domain
  639. embedded_dots = (undotted_domain.find(".") >= 0)
  640. if not embedded_dots and domain != ".local":
  641. debug(" non-local domain %s contains no embedded dot",
  642. domain)
  643. return False
  644. if cookie.version == 0:
  645. if (not erhn.endswith(domain) and
  646. (not erhn.startswith(".") and
  647. not ("."+erhn).endswith(domain))):
  648. debug(" effective request-host %s (even with added "
  649. "initial dot) does not end end with %s",
  650. erhn, domain)
  651. return False
  652. if (cookie.version > 0 or
  653. (self.strict_ns_domain & self.DomainRFC2965Match)):
  654. if not domain_match(erhn, domain):
  655. debug(" effective request-host %s does not domain-match "
  656. "%s", erhn, domain)
  657. return False
  658. if (cookie.version > 0 or
  659. (self.strict_ns_domain & self.DomainStrictNoDots)):
  660. host_prefix = req_host[:-len(domain)]
  661. if (host_prefix.find(".") >= 0 and
  662. not IPV4_RE.search(req_host)):
  663. debug(" host prefix %s for domain %s contains a dot",
  664. host_prefix, domain)
  665. return False
  666. return True
  667. def set_ok_port(self, cookie, request):
  668. if cookie.port_specified:
  669. req_port = request_port(request)
  670. if req_port is None:
  671. req_port = "80"
  672. else:
  673. req_port = str(req_port)
  674. for p in cookie.port.split(","):
  675. try:
  676. int(p)
  677. except ValueError:
  678. debug(" bad port %s (not numeric)", p)
  679. return False
  680. if p == req_port:
  681. break
  682. else:
  683. debug(" request port (%s) not found in %s",
  684. req_port, cookie.port)
  685. return False
  686. return True
  687. def return_ok(self, cookie, request):
  688. """
  689. If you override return_ok, be sure to call this method. If it returns
  690. false, so should your subclass (assuming your subclass wants to be more
  691. strict about which cookies to return).
  692. """
  693. # Path has already been checked by path_return_ok, and domain blocking
  694. # done by domain_return_ok.
  695. debug(" - checking cookie %s", cookie)
  696. for n in ("version", "verifiability", "secure", "expires", "port",
  697. "domain"):
  698. fn_name = "return_ok_"+n
  699. fn = getattr(self, fn_name)
  700. if not fn(cookie, request):
  701. return False
  702. return True
  703. def return_ok_version(self, cookie, request):
  704. if cookie.version > 0 and not self.rfc2965:
  705. debug(" RFC 2965 cookies are switched off")
  706. return False
  707. elif cookie.version == 0 and not self.netscape:
  708. debug(" Netscape cookies are switched off")
  709. return False
  710. return True
  711. def return_ok_verifiability(self, cookie, request):
  712. if request_is_unverifiable(request) and is_third_party(request):
  713. if cookie.version > 0 and self.strict_rfc2965_unverifiable:
  714. debug(" third-party RFC 2965 cookie during unverifiable "
  715. "transaction")
  716. return False
  717. elif cookie.version == 0 and self.strict_ns_unverifiable:
  718. debug(" third-party Netscape cookie during unverifiable "
  719. "transaction")
  720. return False
  721. return True
  722. def return_ok_secure(self, cookie, request):
  723. if cookie.secure and request.get_type() != "https":
  724. debug(" secure cookie with non-secure request")
  725. return False
  726. return True
  727. def return_ok_expires(self, cookie, request):
  728. if cookie.is_expired(self._now):
  729. debug(" cookie expired")
  730. return False
  731. return True
  732. def return_ok_port(self, cookie, request):
  733. if cookie.port:
  734. req_port = request_port(request)
  735. if req_port is None:
  736. req_port = "80"
  737. for p in cookie.port.split(","):
  738. if p == req_port:
  739. break
  740. else:
  741. debug(" request port %s does not match cookie port %s",
  742. req_port, cookie.port)
  743. return False
  744. return True
  745. def return_ok_domain(self, cookie, request):
  746. req_host, erhn = eff_request_host_lc(request)
  747. domain = cookie.domain
  748. # strict check of non-domain cookies: Mozilla does this, MSIE5 doesn't
  749. if (cookie.version == 0 and
  750. (self.strict_ns_domain & self.DomainStrictNonDomain) and
  751. not cookie.domain_specified and domain != erhn):
  752. debug(" cookie with unspecified domain does not string-compare "
  753. "equal to request domain")
  754. return False
  755. if cookie.version > 0 and not domain_match(erhn, domain):
  756. debug(" effective request-host name %s does not domain-match "
  757. "RFC 2965 cookie domain %s", erhn, domain)
  758. return False
  759. if cookie.version == 0 and not ("."+erhn).endswith(domain):
  760. debug(" request-host %s does not match Netscape cookie domain "
  761. "%s", req_host, domain)
  762. return False
  763. return True
  764. def domain_return_ok(self, domain, request):
  765. # Liberal check of domain. This is here as an optimization to avoid
  766. # having to load lots of MSIE cookie files unless necessary.
  767. # Munge req_host and erhn to always start with a dot, so as to err on
  768. # the side of letting cookies through.
  769. dotted_req_host, dotted_erhn = eff_request_host_lc(request)
  770. if not dotted_req_host.startswith("."):
  771. dotted_req_host = "."+dotted_req_host
  772. if not dotted_erhn.startswith("."):
  773. dotted_erhn = "."+dotted_erhn
  774. if not (dotted_req_host.endswith(domain) or
  775. dotted_erhn.endswith(domain)):
  776. #debug(" request domain %s does not match cookie domain %s",
  777. # req_host, domain)
  778. return False
  779. if self.is_blocked(domain):
  780. debug(" domain %s is in user block-list", domain)
  781. return False
  782. if self.is_not_allowed(domain):
  783. debug(" domain %s is not in user allow-list", domain)
  784. return False
  785. return True
  786. def path_return_ok(self, path, request):
  787. debug("- checking cookie path=%s", path)
  788. req_path = request_path(request)
  789. if not req_path.startswith(path):
  790. debug(" %s does not path-match %s", req_path, path)
  791. return False
  792. return True
  793. def vals_sorted_by_key(adict):
  794. keys = adict.keys()
  795. keys.sort()
  796. return map(adict.get, keys)
  797. class MappingIterator:
  798. """Iterates over nested mapping, depth-first, in sorted order by key."""
  799. def __init__(self, mapping):
  800. self._s = [(vals_sorted_by_key(mapping), 0, None)] # LIFO stack
  801. def __iter__(self): return self
  802. def next(self):
  803. # this is hairy because of lack of generators
  804. while 1:
  805. try:
  806. vals, i, prev_item = self._s.pop()
  807. except IndexError:
  808. raise StopIteration()
  809. if i < len(vals):
  810. item = vals[i]
  811. i = i + 1
  812. self._s.append((vals, i, prev_item))
  813. try:
  814. item.items
  815. except AttributeError:
  816. # non-mapping
  817. break
  818. else:
  819. # mapping
  820. self._s.append((vals_sorted_by_key(item), 0, item))
  821. continue
  822. return item
  823. # Used as second parameter to dict.get method, to distinguish absent
  824. # dict key from one with a None value.
  825. class Absent: pass
  826. class CookieJar:
  827. """Collection of HTTP cookies.
  828. You may not need to know about this class: try mechanize.urlopen().
  829. The major methods are extract_cookies and add_cookie_header; these are all
  830. you are likely to need.
  831. CookieJar supports the iterator protocol:
  832. for cookie in cookiejar:
  833. # do something with cookie
  834. Methods:
  835. add_cookie_header(request)
  836. extract_cookies(response, request)
  837. get_policy()
  838. set_policy(policy)
  839. cookies_for_request(request)
  840. make_cookies(response, request)
  841. set_cookie_if_ok(cookie, request)
  842. set_cookie(cookie)
  843. clear_session_cookies()
  844. clear_expired_cookies()
  845. clear(domain=None, path=None, name=None)
  846. Public attributes
  847. policy: CookiePolicy object
  848. """
  849. non_word_re = re.compile(r"\W")
  850. quote_re = re.compile(r"([\"\\])")
  851. strict_domain_re = re.compile(r"\.?[^.]*")
  852. domain_re = re.compile(r"[^.]*")
  853. dots_re = re.compile(r"^\.+")
  854. def __init__(self, policy=None):
  855. """
  856. See CookieJar.__doc__ for argument documentation.
  857. """
  858. if policy is None:
  859. policy = DefaultCookiePolicy()
  860. self._policy = policy
  861. self._cookies = {}
  862. # for __getitem__ iteration in pre-2.2 Pythons
  863. self._prev_getitem_index = 0
  864. def get_policy(self):
  865. return self._policy
  866. def set_policy(self, policy):
  867. self._policy = policy
  868. def _cookies_for_domain(self, domain, request):
  869. cookies = []
  870. if not self._policy.domain_return_ok(domain, request):
  871. return []
  872. debug("Checking %s for cookies to return", domain)
  873. cookies_by_path = self._cookies[domain]
  874. for path in cookies_by_path.keys():
  875. if not self._policy.path_return_ok(path, request):
  876. continue
  877. cookies_by_name = cookies_by_path[path]
  878. for cookie in cookies_by_name.values():
  879. if not self._policy.return_ok(cookie, request):
  880. debug(" not returning cookie")
  881. continue
  882. debug(" it's a match")
  883. cookies.append(cookie)
  884. return cookies
  885. def cookies_for_request(self, request):
  886. """Return a list of cookies to be returned to server.
  887. The returned list of cookie instances is sorted in the order they
  888. should appear in the Cookie: header for return to the server.
  889. See add_cookie_header.__doc__ for the interface required of the
  890. request argument.
  891. New in version 0.1.10
  892. """
  893. self._policy._now = self._now = int(time.time())
  894. cookies = self._cookies_for_request(request)
  895. # add cookies in order of most specific (i.e. longest) path first
  896. def decreasing_size(a, b): return cmp(len(b.path), len(a.path))
  897. cookies.sort(decreasing_size)
  898. return cookies
  899. def _cookies_for_request(self, request):
  900. """Return a list of cookies to be returned to server."""
  901. # this method still exists (alongside cookies_for_request) because it
  902. # is part of an implied protected interface for subclasses of cookiejar
  903. # XXX document that implied interface, or provide another way of
  904. # implementing cookiejars than subclassing
  905. cookies = []
  906. for domain in self._cookies.keys():
  907. cookies.extend(self._cookies_for_domain(domain, request))
  908. return cookies
  909. def _cookie_attrs(self, cookies):
  910. """Return a list of cookie-attributes to be returned to server.
  911. The $Version attribute is also added when appropriate (currently only
  912. once per request).
  913. >>> jar = CookieJar()
  914. >>> ns_cookie = Cookie(0, "foo", '"bar"', None, False,
  915. ... "example.com", False, False,
  916. ... "/", False, False, None, True,
  917. ... None, None, {})
  918. >>> jar._cookie_attrs([ns_cookie])
  919. ['foo="bar"']
  920. >>> rfc2965_cookie = Cookie(1, "foo", "bar", None, False,
  921. ... ".example.com", True, False,
  922. ... "/", False, False, None, True,
  923. ... None, None, {})
  924. >>> jar._cookie_attrs([rfc2965_cookie])
  925. ['$Version=1', 'foo=bar', '$Domain="example.com"']
  926. """
  927. version_set = False
  928. attrs = []
  929. for cookie in cookies:
  930. # set version of Cookie header
  931. # XXX
  932. # What should it be if multiple matching Set-Cookie headers have
  933. # different versions themselves?
  934. # Answer: there is no answer; was supposed to be settled by
  935. # RFC 2965 errata, but that may never appear...
  936. version = cookie.version
  937. if not version_set:
  938. version_set = True
  939. if version > 0:
  940. attrs.append("$Version=%s" % version)
  941. # quote cookie value if necessary
  942. # (not for Netscape protocol, which already has any quotes
  943. # intact, due to the poorly-specified Netscape Cookie: syntax)
  944. if ((cookie.value is not None) and
  945. self.non_word_re.search(cookie.value) and version > 0):
  946. value = self.quote_re.sub(r"\\\1", cookie.value)
  947. else:
  948. value = cookie.value
  949. # add cookie-attributes to be returned in Cookie header
  950. if cookie.value is None:
  951. attrs.append(cookie.name)
  952. else:
  953. attrs.append("%s=%s" % (cookie.name, value))
  954. if version > 0:
  955. if cookie.path_specified:
  956. attrs.append('$Path="%s"' % cookie.path)
  957. if cookie.domain.startswith("."):
  958. domain = cookie.domain
  959. if (not cookie.domain_initial_dot and
  960. domain.startswith(".")):
  961. domain = domain[1:]
  962. attrs.append('$Domain="%s"' % domain)
  963. if cookie.port is not None:
  964. p = "$Port"
  965. if cookie.port_specified:
  966. p = p + ('="%s"' % cookie.port)
  967. attrs.append(p)
  968. return attrs
  969. def add_cookie_header(self, request):
  970. """Add correct Cookie: header to request (urllib2.Request object).
  971. The Cookie2 header is also added unless policy.hide_cookie2 is true.
  972. The request object (usually a urllib2.Request instance) must support
  973. the methods get_full_url, get_host, is_unverifiable, get_type,
  974. has_header, get_header, header_items and add_unredirected_header, as
  975. documented by urllib2, and the port attribute (the port number).
  976. Actually, RequestUpgradeProcessor will automatically upgrade your
  977. Request object to one with has_header, get_header, header_items and
  978. add_unredirected_header, if it lacks those methods, for compatibility
  979. with pre-2.4 versions of urllib2.
  980. """
  981. debug("add_cookie_header")
  982. cookies = self.cookies_for_request(request)
  983. attrs = self._cookie_attrs(cookies)
  984. if attrs:
  985. if not request.has_header("Cookie"):
  986. request.add_unredirected_header("Cookie", "; ".join(attrs))
  987. # if necessary, advertise that we know RFC 2965
  988. if self._policy.rfc2965 and not self._policy.hide_cookie2:
  989. for cookie in cookies:
  990. if cookie.version != 1 and not request.has_header("Cookie2"):
  991. request.add_unredirected_header("Cookie2", '$Version="1"')
  992. break
  993. self.clear_expired_cookies()
  994. def _normalized_cookie_tuples(self, attrs_set):
  995. """Return list of tuples containing normalised cookie information.
  996. attrs_set is the list of lists of key,value pairs extracted from
  997. the Set-Cookie or Set-Cookie2 headers.
  998. Tuples are name, value, standard, rest, where name and value are the
  999. cookie name and value, standard is a dictionary containing the standard
  1000. cookie-attributes (discard, secure, version, expires or max-age,
  1001. domain, path and port) and rest is a dictionary containing the rest of
  1002. the cookie-attributes.
  1003. """
  1004. cookie_tuples = []
  1005. boolean_attrs = "discard", "secure"
  1006. value_attrs = ("version",
  1007. "expires", "max-age",
  1008. "domain", "path", "port",
  1009. "comment", "commenturl")
  1010. for cookie_attrs in attrs_set:
  1011. name, value = cookie_attrs[0]
  1012. # Build dictionary of standard cookie-attributes (standard) and
  1013. # dictionary of other cookie-attributes (rest).
  1014. # Note: expiry time is normalised to seconds since epoch. V0
  1015. # cookies should have the Expires cookie-attribute, and V1 cookies
  1016. # should have Max-Age, but since V1 includes RFC 2109 cookies (and
  1017. # since V0 cookies may be a mish-mash of Netscape and RFC 2109), we
  1018. # accept either (but prefer Max-Age).
  1019. max_age_set = False
  1020. bad_cookie = False
  1021. standard = {}
  1022. rest = {}
  1023. for k, v in cookie_attrs[1:]:
  1024. lc = k.lower()
  1025. # don't lose case distinction for unknown fields
  1026. if lc in value_attrs or lc in boolean_attrs:
  1027. k = lc
  1028. if k in boolean_attrs and v is None:
  1029. # boolean cookie-attribute is present, but has no value
  1030. # (like "discard", rather than "port=80")
  1031. v = True
  1032. if standard.has_key(k):
  1033. # only first value is significant
  1034. continue
  1035. if k == "domain":
  1036. if v is None:
  1037. debug(" missing value for domain attribute")
  1038. bad_cookie = True
  1039. break
  1040. # RFC 2965 section 3.3.3
  1041. v = v.lower()
  1042. if k == "expires":
  1043. if max_age_set:
  1044. # Prefer max-age to expires (like Mozilla)
  1045. continue
  1046. if v is None:
  1047. debug(" missing or invalid value for expires "
  1048. "attribute: treating as session cookie")
  1049. continue
  1050. if k == "max-age":
  1051. max_age_set = True
  1052. if v is None:
  1053. debug(" missing value for max-age attribute")
  1054. bad_cookie = True
  1055. break
  1056. try:
  1057. v = int(v)
  1058. except ValueError:
  1059. debug(" missing or invalid (non-numeric) value for "
  1060. "max-age attribute")
  1061. bad_cookie = True
  1062. break
  1063. # convert RFC 2965 Max-Age to seconds since epoch
  1064. # XXX Strictly you're supposed to follow RFC 2616
  1065. # age-calculation rules. Remember that zero Max-Age is a
  1066. # is a request to discard (old and new) cookie, though.
  1067. k = "expires"
  1068. v = self._now + v
  1069. if (k in value_attrs) or (k in boolean_attrs):
  1070. if (v is None and
  1071. k not in ["port", "comment", "commenturl"]):
  1072. debug(" missing value for %s attribute" % k)
  1073. bad_cookie = True
  1074. break
  1075. standard[k] = v
  1076. else:
  1077. rest[k] = v
  1078. if bad_cookie:
  1079. continue
  1080. cookie_tuples.append((name, value, standard, rest))
  1081. return cookie_tuples
  1082. def _cookie_from_cookie_tuple(self, tup, request):
  1083. # standard is dict of standard cookie-attributes, rest is dict of the
  1084. # rest of them
  1085. name, value, standard, rest = tup
  1086. domain = standard.get("domain", Absent)
  1087. path = standard.get("path", Absent)
  1088. port = standard.get("port", Absent)
  1089. expires = standard.get("expires", Absent)
  1090. # set the easy defaults
  1091. version = standard.get("version", None)
  1092. if version is not None:
  1093. try:
  1094. version = int(version)
  1095. except ValueError:
  1096. return None # invalid version, ignore cookie
  1097. secure = standard.get("secure", False)
  1098. # (discard is also set if expires is Absent)
  1099. discard = standard.get("discard", False)
  1100. comment = standard.get("comment", None)
  1101. comment_url = standard.get("commenturl", None)
  1102. # set default path
  1103. if path is not Absent and path != "":
  1104. path_specified = True
  1105. path = escape_path(path)
  1106. else:
  1107. path_specified = False
  1108. path = request_path(request)
  1109. i = path.rfind("/")
  1110. if i != -1:
  1111. if version == 0:
  1112. # Netscape spec parts company from reality here
  1113. path = path[:i]
  1114. else:
  1115. path = path[:i+1]
  1116. if len(path) == 0: path = "/"
  1117. # set default domain
  1118. domain_specified = domain is not Absent
  1119. # but first we have to remember whether it starts with a dot
  1120. domain_initial_dot = False
  1121. if domain_specified:
  1122. domain_initial_dot = bool(domain.startswith("."))
  1123. if domain is Absent:
  1124. req_host, erhn = eff_request_host_lc(request)
  1125. domain = erhn
  1126. elif not domain.startswith("."):
  1127. domain = "."+domain
  1128. # set default port
  1129. port_specified = False
  1130. if port is not Absent:
  1131. if port is None:
  1132. # Port attr present, but has no value: default to request port.
  1133. # Cookie should then only be sent back on that port.
  1134. port = request_port(request)
  1135. else:
  1136. port_specified = True
  1137. port = re.sub(r"\s+", "", port)
  1138. else:
  1139. # No port attr present. Cookie can be sent back on any port.
  1140. port = None
  1141. # set default expires and discard
  1142. if expires is Absent:
  1143. expires = None
  1144. discard = True
  1145. return Cookie(version,
  1146. name, value,
  1147. port, port_specified,
  1148. domain, domain_specified, domain_initial_dot,
  1149. path, path_specified,
  1150. secure,
  1151. expires,
  1152. discard,
  1153. comment,
  1154. comment_url,
  1155. rest)
  1156. def _cookies_from_attrs_set(self, attrs_set, request):
  1157. cookie_tuples = self._normalized_cookie_tuples(attrs_set)
  1158. cookies = []
  1159. for tup in cookie_tuples:
  1160. cookie = self._cookie_from_cookie_tuple(tup, request)
  1161. if cookie: cookies.append(cookie)
  1162. return cookies
  1163. def _process_rfc2109_cookies(self, cookies):
  1164. if self._policy.rfc2109_as_netscape is None:
  1165. rfc2109_as_netscape = not self._policy.rfc2965
  1166. else:
  1167. rfc2109_as_netscape = self._policy.rfc2109_as_netscape
  1168. for cookie in cookies:
  1169. if cookie.version == 1:
  1170. cookie.rfc2109 = True
  1171. if rfc2109_as_netscape:
  1172. # treat 2109 cookies as Netscape cookies rather than
  1173. # as RFC2965 cookies
  1174. cookie.version = 0
  1175. def _make_cookies(self, response, request):
  1176. # get cookie-attributes for RFC 2965 and Netscape protocols
  1177. headers = response.info()
  1178. rfc2965_hdrs = headers.getheaders("Set-Cookie2")
  1179. ns_hdrs = headers.getheaders("Set-Cookie")
  1180. rfc2965 = self._policy.rfc2965
  1181. netscape = self._policy.netscape
  1182. if ((not rfc2965_hdrs and not ns_hdrs) or
  1183. (not ns_hdrs and not rfc2965) or
  1184. (not rfc2965_hdrs and not netscape) or
  1185. (not netscape and not rfc2965)):
  1186. return [] # no relevant cookie headers: quick exit
  1187. try:
  1188. cookies = self._cookies_from_attrs_set(
  1189. split_header_words(rfc2965_hdrs), request)
  1190. except:
  1191. reraise_unmasked_exceptions()
  1192. cookies = []
  1193. if ns_hdrs and netscape:
  1194. try:
  1195. # RFC 2109 and Netscape cookies
  1196. ns_cookies = self._cookies_from_attrs_set(
  1197. parse_ns_headers(ns_hdrs), request)
  1198. except:
  1199. reraise_unmasked_exceptions()
  1200. ns_cookies = []
  1201. self._process_rfc2109_cookies(ns_cookies)
  1202. # Look for Netscape cookies (from Set-Cookie headers) that match
  1203. # corresponding RFC 2965 cookies (from Set-Cookie2 headers).
  1204. # For each match, keep the RFC 2965 cookie and ignore the Netscape
  1205. # cookie (RFC 2965 section 9.1). Actually, RFC 2109 cookies are
  1206. # bundled in with the Netscape cookies for this purpose, which is
  1207. # reasonable behaviour.
  1208. if rfc2965:
  1209. lookup = {}
  1210. for cookie in cookies:
  1211. lookup[(cookie.domain, cookie.path, cookie.name)] = None
  1212. def no_matching_rfc2965(ns_cookie, lookup=lookup):
  1213. key = ns_cookie.domain, ns_cookie.path, ns_cookie.name
  1214. return not lookup.has_key(key)
  1215. ns_cookies = filter(no_matching_rfc2965, ns_cookies)
  1216. if ns_cookies:
  1217. cookies.extend(ns_cookies)
  1218. return cookies
  1219. def make_cookies(self, response, request):
  1220. """Return sequence of Cookie objects extracted from response object.
  1221. See extract_cookies.__doc__ for the interface required of the
  1222. response and request arguments.
  1223. """
  1224. self._policy._now = self._now = int(time.time())
  1225. return [cookie for cookie in self._make_cookies(response, request)
  1226. if cookie.expires is None or not cookie.expires <= self._now]
  1227. def set_cookie_if_ok(self, cookie, request):
  1228. """Set a cookie if policy says it's OK to do so.
  1229. cookie: mechanize.Cookie instance
  1230. request: see extract_cookies.__doc__ for the required interface
  1231. """
  1232. self._policy._now = self._now = int(time.time())
  1233. if self._policy.set_ok(cookie, request):
  1234. self.set_cookie(cookie)
  1235. def set_cookie(self, cookie):
  1236. """Set a cookie, without checking whether or not it should be set.
  1237. cookie: mechanize.Cookie instance
  1238. """
  1239. c = self._cookies
  1240. if not c.has_key(cookie.domain): c[cookie.domain] = {}
  1241. c2 = c[cookie.domain]
  1242. if not c2.has_key(cookie.path): c2[cookie.path] = {}
  1243. c3 = c2[cookie.path]
  1244. c3[cookie.name] = cookie
  1245. def extract_cookies(self, response, request):
  1246. """Extract cookies from response, where allowable given the request.
  1247. Look for allowable Set-Cookie: and Set-Cookie2: headers in the response
  1248. object passed as argument. Any of these headers that are found are
  1249. used to update the state of the object (subject to the policy.set_ok
  1250. method's approval).
  1251. The response object (usually be the result of a call to
  1252. mechanize.urlopen, or similar) should support an info method, which
  1253. returns a mimetools.Message object (in fact, the 'mimetools.Message
  1254. object' may be any object that provides a getheaders method).
  1255. The request object (usually a urllib2.Request instance) must support
  1256. the methods get_full_url, get_type, get_host, and is_unverifiable, as
  1257. documented by urllib2, and the port attribute (the port number). The
  1258. request is used to set default values for cookie-attributes as well as
  1259. for checking that the cookie is OK to be set.
  1260. """
  1261. debug("extract_cookies: %s", response.info())
  1262. self._policy._now = self._now = int(time.time())
  1263. for cookie in self._make_cookies(response, request):
  1264. if cookie.expires is not None and cookie.expires <= self._now:
  1265. # Expiry date in past is request to delete cookie. This can't be
  1266. # in DefaultCookiePolicy, because can't delete cookies there.
  1267. try:
  1268. self.clear(cookie.domain, cookie.path, cookie.name)
  1269. except KeyError:
  1270. pass
  1271. debug("Expiring cookie, domain='%s', path='%s', name='%s'",
  1272. cookie.domain, cookie.path, cookie.name)
  1273. elif self._policy.set_ok(cookie, request):
  1274. debug(" setting cookie: %s", cookie)
  1275. self.set_cookie(cookie)
  1276. def clear(self, domain=None, path=None, name=None):
  1277. """Clear some cookies.
  1278. Invoking this method without arguments will clear all cookies. If
  1279. given a single argument, only cookies belonging to that domain will be
  1280. removed. If given two arguments, cookies belonging to the specified
  1281. path within that domain are removed. If given three arguments, then
  1282. the cookie with the specified name, path and domain is removed.
  1283. Raises KeyError if no matching cookie exists.
  1284. """
  1285. if name is not None:
  1286. if (domain is None) or (path is None):
  1287. raise ValueError(
  1288. "domain and path must be given to remove a cookie by name")
  1289. del self._cookies[domain][path][name]
  1290. elif path is not None:
  1291. if domain is None:
  1292. raise ValueError(
  1293. "domain must be given to remove cookies by path")
  1294. del self._cookies[domain][path]
  1295. elif domain is not None:
  1296. del self._cookies[domain]
  1297. else:
  1298. self._cookies = {}
  1299. def clear_session_cookies(self):
  1300. """Discard all session cookies.
  1301. Discards all cookies held by object which had either no Max-Age or
  1302. Expires cookie-attribute or an explicit Discard cookie-attribute, or
  1303. which otherwise have ended up with a true discard attribute. For
  1304. interactive browsers, the end of a session usually corresponds to
  1305. closing the browser window.
  1306. Note that the save method won't save session cookies anyway, unless you
  1307. ask otherwise by passing a true ignore_discard argument.
  1308. """
  1309. for cookie in self:
  1310. if cookie.discard:
  1311. self.clear(cookie.domain, cookie.path, cookie.name)
  1312. def clear_expired_cookies(self):
  1313. """Discard all expired cookies.
  1314. You probably don't need to call this method: expired cookies are never
  1315. sent back to the server (provided you're using DefaultCookiePolicy),
  1316. this method is called by CookieJar itself every so often, and the save
  1317. method won't save expired cookies anyway (unless you ask otherwise by
  1318. passing a true ignore_expires argument).
  1319. """
  1320. now = time.time()
  1321. for cookie in self:
  1322. if cookie.is_expired(now):
  1323. self.clear(cookie.domain, cookie.path, cookie.name)
  1324. def __getitem__(self, i):
  1325. if i == 0:
  1326. self._getitem_iterator = self.__iter__()
  1327. elif self._prev_getitem_index != i-1: raise IndexError(
  1328. "CookieJar.__getitem__ only supports sequential iteration")
  1329. self._prev_getitem_index = i
  1330. try:
  1331. return self._getitem_iterator.next()
  1332. except StopIteration:
  1333. raise IndexError()
  1334. def __iter__(self):
  1335. return MappingIterator(self._cookies)
  1336. def __len__(self):
  1337. """Return number of contained cookies."""
  1338. i = 0
  1339. for cookie in self: i = i + 1
  1340. return i
  1341. def __repr__(self):
  1342. r = []
  1343. for cookie in self: r.append(repr(cookie))
  1344. return "<%s[%s]>" % (self.__class__, ", ".join(r))
  1345. def __str__(self):
  1346. r = []
  1347. for cookie in self: r.append(str(cookie))
  1348. return "<%s[%s]>" % (self.__class__, ", ".join(r))
  1349. class LoadError(Exception): pass
  1350. class FileCookieJar(CookieJar):
  1351. """CookieJar that can be loaded from and saved to a file.
  1352. Additional methods
  1353. save(filename=None, ignore_discard=False, ignore_expires=False)
  1354. load(filename=None, ignore_discard=False, ignore_expires=False)
  1355. revert(filename=None, ignore_discard=False, ignore_expires=False)
  1356. Additional public attributes
  1357. filename: filename for loading and saving cookies
  1358. Additional public readable attributes
  1359. delayload: request that cookies are lazily loaded from disk; this is only
  1360. a hint since this only affects performance, not behaviour (unless the
  1361. cookies on disk are changing); a CookieJar object may ignore it (in fact,
  1362. only MSIECookieJar lazily loads cookies at the moment)
  1363. """
  1364. def __init__(self, filename=None, delayload=False, policy=None):
  1365. """
  1366. See FileCookieJar.__doc__ for argument documentation.
  1367. Cookies are NOT loaded from the named file until either the load or
  1368. revert method is called.
  1369. """
  1370. CookieJar.__init__(self, policy)
  1371. if filename is not None and not isstringlike(filename):
  1372. raise ValueError("filename must be string-like")
  1373. self.filename = filename
  1374. self.delayload = bool(delayload)
  1375. def save(self, filename=None, ignore_discard=False, ignore_expires=False):
  1376. """Save cookies to a file.
  1377. filename: name of file in which to save cookies
  1378. ignore_discard: save even cookies set to be discarded
  1379. ignore_expires: save even cookies that have expired
  1380. The file is overwritten if it already exists, thus wiping all its
  1381. cookies. Saved cookies can be restored later using the load or revert
  1382. methods. If filename is not specified, self.filename is used; if
  1383. self.filename is None, ValueError is raised.
  1384. """
  1385. raise NotImplementedError()
  1386. def load(self, filename=None, ignore_discard=False, ignore_expires=False):
  1387. """Load cookies from a file.
  1388. Old cookies are kept unless overwritten by newly loaded ones.
  1389. Arguments are as for .save().
  1390. If filename is not specified, self.filename is used; if self.filename
  1391. is None, ValueError is raised. The named file must be in the format
  1392. understood by the class, or LoadError will be raised. This format will
  1393. be identical to that written by the save method, unless the load format
  1394. is not sufficiently well understood (as is the case for MSIECookieJar).
  1395. """
  1396. if filename is None:
  1397. if self.filename is not None: filename = self.filename
  1398. else: raise ValueError(MISSING_FILENAME_TEXT)
  1399. f = open(filename)
  1400. try:
  1401. self._really_load(f, filename, ignore_discard, ignore_expires)
  1402. finally:
  1403. f.close()
  1404. def revert(self, filename=None,
  1405. ignore_discard=False, ignore_expires=False):
  1406. """Clear all cookies and reload cookies from a saved file.
  1407. Raises LoadError (or IOError) if reversion is not successful; the
  1408. object's state will not be altered if this happens.
  1409. """
  1410. if filename is None:
  1411. if self.filename is not None: filename = self.filename
  1412. else: raise ValueError(MISSING_FILENAME_TEXT)
  1413. old_state = copy.deepcopy(self._cookies)
  1414. self._cookies = {}
  1415. try:
  1416. self.load(filename, ignore_discard, ignore_expires)
  1417. except (LoadError, IOError):
  1418. self._cookies = old_state
  1419. raise