cookiejar.py 76 KB

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