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