cookiejar.py 75 KB

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