cookiejar.py 75 KB

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