cookiejar.py 75 KB

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