cookiejar.py 75 KB

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