cookielib.py 63 KB

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