Debian Codegraph @

Lib/http/cookies.py

raw
1 ####
2 # Copyright 2000 by Timothy O'Malley <[email protected]>
3 #
4 # All Rights Reserved
5 #
6 # Permission to use, copy, modify, and distribute this software
7 # and its documentation for any purpose and without fee is hereby
8 # granted, provided that the above copyright notice appear in all
9 # copies and that both that copyright notice and this permission
10 # notice appear in supporting documentation, and that the name of
11 # Timothy O'Malley not be used in advertising or publicity
12 # pertaining to distribution of the software without specific, written
13 # prior permission.
14 #
15 # Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
16 # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17 # AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
18 # ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20 # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
21 # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22 # PERFORMANCE OF THIS SOFTWARE.
23 #
24 ####
25 #
26 # Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp
27 # by Timothy O'Malley <[email protected]>
28 #
29 # Cookie.py is a Python module for the handling of HTTP
30 # cookies as a Python dictionary. See RFC 2109 for more
31 # information on cookies.
32 #
33 # The original idea to treat Cookies as a dictionary came from
34 # Dave Mitchell ([email protected]) in 1995, when he released the
35 # first version of nscookie.py.
36 #
37 ####
38
39 r"""
40 Here's a sample session to show how to use this module.
41 At the moment, this is the only documentation.
42
43 The Basics
44 ----------
45
46 Importing is easy...
47
48 >>> from http import cookies
49
50 Most of the time you start by creating a cookie.
51
52 >>> C = cookies.SimpleCookie()
53
54 Once you've created your Cookie, you can add values just as if it were
55 a dictionary.
56
57 >>> C = cookies.SimpleCookie()
58 >>> C["fig"] = "newton"
59 >>> C["sugar"] = "wafer"
60 >>> C.output()
61 'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer'
62
63 Notice that the printable representation of a Cookie is the
64 appropriate format for a Set-Cookie: header. This is the
65 default behavior. You can change the header and printed
66 attributes by using the .output() function
67
68 >>> C = cookies.SimpleCookie()
69 >>> C["rocky"] = "road"
70 >>> C["rocky"]["path"] = "/cookie"
71 >>> print(C.output(header="Cookie:"))
72 Cookie: rocky=road; Path=/cookie
73 >>> print(C.output(attrs=[], header="Cookie:"))
74 Cookie: rocky=road
75
76 The load() method of a Cookie extracts cookies from a string. In a
77 CGI script, you would use this method to extract the cookies from the
78 HTTP_COOKIE environment variable.
79
80 >>> C = cookies.SimpleCookie()
81 >>> C.load("chips=ahoy; vienna=finger")
82 >>> C.output()
83 'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger'
84
85 The load() method is darn-tootin smart about identifying cookies
86 within a string. Escaped quotation marks, nested semicolons, and other
87 such trickeries do not confuse it.
88
89 >>> C = cookies.SimpleCookie()
90 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=;";')
91 >>> print(C)
92 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=;"
93
94 Each element of the Cookie also supports all of the RFC 2109
95 Cookie attributes. Here's an example which sets the Path
96 attribute.
97
98 >>> C = cookies.SimpleCookie()
99 >>> C["oreo"] = "doublestuff"
100 >>> C["oreo"]["path"] = "/"
101 >>> print(C)
102 Set-Cookie: oreo=doublestuff; Path=/
103
104 Each dictionary element has a 'value' attribute, which gives you
105 back the value associated with the key.
106
107 >>> C = cookies.SimpleCookie()
108 >>> C["twix"] = "none for you"
109 >>> C["twix"].value
110 'none for you'
111
112 The SimpleCookie expects that all values should be standard strings.
113 Just to be sure, SimpleCookie invokes the str() builtin to convert
114 the value to a string, when the values are set dictionary-style.
115
116 >>> C = cookies.SimpleCookie()
117 >>> C["number"] = 7
118 >>> C["string"] = "seven"
119 >>> C["number"].value
120 '7'
121 >>> C["string"].value
122 'seven'
123 >>> C.output()
124 'Set-Cookie: number=7\r\nSet-Cookie: string=seven'
125
126 Finis.
127 """
128
129 #
130 # Import our required modules
131 #
132 import re
133 import string
134 import types
135
136 __all__ = ["CookieError", "BaseCookie", "SimpleCookie"]
137
138 _nulljoin = ''.join
139 _semispacejoin = '; '.join
140 _spacejoin = ' '.join
141
142 #
143 # Define an exception visible to External modules
144 #
145 class CookieError(Exception):
146 pass
147
148
149 # These quoting routines conform to the RFC2109 specification, which in
150 # turn references the character definitions from RFC2068. They provide
151 # a two-way quoting algorithm. Any non-text character is translated
152 # into a 4 character sequence: a forward-slash followed by the
153 # three-digit octal equivalent of the character. Any '\' or '"' is
154 # quoted with a preceding '\' slash.
155 # Because of the way browsers really handle cookies (as opposed to what
156 # the RFC says) we also encode "," and ";".
157 #
158 # These are taken from RFC2068 and RFC2109.
159 # _LegalChars is the list of chars which don't require "'s
160 # _Translator hash-table for fast quoting
161 #
162 _LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:"
163 _UnescapedChars = _LegalChars + ' ()/<=>?@[]{}'
164
165 _Translator = {n: '\\%03o' % n
166 for n in set(range(256)) - set(map(ord, _UnescapedChars))}
167 _Translator.update({
168 ord('"'): '\\"',
169 ord('\\'): '\\\\',
170 })
171
172 _is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch
173 _control_character_re = re.compile(r'[\x00-\x1F\x7F]')
174
175
176 def _has_control_character(*val):
177 """Detects control characters within a value.
178 Supports any type, as header values can be any type.
179 """
180 return any(_control_character_re.search(str(v)) for v in val)
181
182
183 def _quote(str):
184 r"""Quote a string for use in a cookie header.
185
186 If the string does not need to be double-quoted, then just return the
187 string. Otherwise, surround the string in doublequotes and quote
188 (with a \) special characters.
189 """
190 if str is None or _is_legal_key(str):
191 return str
192 else:
193 return '"' + str.translate(_Translator) + '"'
194
195
196 _unquote_sub = re.compile(r'\\(?:([0-3][0-7][0-7])|(.))').sub
197
198 def _unquote_replace(m):
199 if m[1]:
200 return chr(int(m[1], 8))
201 else:
202 return m[2]
203
204 def _unquote(str):
205 # If there aren't any doublequotes,
206 # then there can't be any special characters. See RFC 2109.
207 if str is None or len(str) < 2:
208 return str
209 if str[0] != '"' or str[-1] != '"':
210 return str
211
212 # We have to assume that we must decode this string.
213 # Down to work.
214
215 # Remove the "s
216 str = str[1:-1]
217
218 # Check for special sequences. Examples:
219 # \012 --> \n
220 # \" --> "
221 #
222 return _unquote_sub(_unquote_replace, str)
223
224 # The _getdate() routine is used to set the expiration time in the cookie's HTTP
225 # header. By default, _getdate() returns the current time in the appropriate
226 # "expires" format for a Set-Cookie header. The one optional argument is an
227 # offset from now, in seconds. For example, an offset of -3600 means "one hour
228 # ago". The offset may be a floating-point number.
229 #
230
231 _weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
232
233 _monthname = [None,
234 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
235 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
236
237 def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):
238 from time import gmtime, time
239 now = time()
240 year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)
241 return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \
242 (weekdayname[wd], day, monthname[month], year, hh, mm, ss)
243
244
245 class Morsel(dict):
246 """A class to hold ONE (key, value) pair.
247
248 In a cookie, each such pair may have several attributes, so this class is
249 used to keep the attributes associated with the appropriate key,value pair.
250 This class also includes a coded_value attribute, which is used to hold
251 the network representation of the value.
252 """
253 # RFC 2109 lists these attributes as reserved:
254 # path comment domain
255 # max-age secure version
256 #
257 # For historical reasons, these attributes are also reserved:
258 # expires
259 #
260 # This is an extension from Microsoft:
261 # httponly
262 #
263 # This dictionary provides a mapping from the lowercase
264 # variant on the left to the appropriate traditional
265 # formatting on the right.
266 _reserved = {
267 "expires" : "expires",
268 "path" : "Path",
269 "comment" : "Comment",
270 "domain" : "Domain",
271 "max-age" : "Max-Age",
272 "secure" : "Secure",
273 "httponly" : "HttpOnly",
274 "version" : "Version",
275 "samesite" : "SameSite",
276 }
277
278 _flags = {'secure', 'httponly'}
279
280 def __init__(self):
281 # Set defaults
282 self._key = self._value = self._coded_value = None
283
284 # Set default attributes
285 for key in self._reserved:
286 dict.__setitem__(self, key, "")
287
288 @property
289 def key(self):
290 return self._key
291
292 @property
293 def value(self):
294 return self._value
295
296 @property
297 def coded_value(self):
298 return self._coded_value
299
300 def __setitem__(self, K, V):
301 K = K.lower()
302 if not K in self._reserved:
303 raise CookieError("Invalid attribute %r" % (K,))
304 if _has_control_character(K, V):
305 raise CookieError(f"Control characters are not allowed in cookies {K!r} {V!r}")
306 dict.__setitem__(self, K, V)
307
308 def setdefault(self, key, val=None):
309 key = key.lower()
310 if key not in self._reserved:
311 raise CookieError("Invalid attribute %r" % (key,))
312 if _has_control_character(key, val):
313 raise CookieError("Control characters are not allowed in cookies %r %r" % (key, val,))
314 return dict.setdefault(self, key, val)
315
316 def __eq__(self, morsel):
317 if not isinstance(morsel, Morsel):
318 return NotImplemented
319 return (dict.__eq__(self, morsel) and
320 self._value == morsel._value and
321 self._key == morsel._key and
322 self._coded_value == morsel._coded_value)
323
324 __ne__ = object.__ne__
325
326 def copy(self):
327 morsel = Morsel()
328 dict.update(morsel, self)
329 morsel.__dict__.update(self.__dict__)
330 return morsel
331
332 def update(self, values):
333 data = {}
334 for key, val in dict(values).items():
335 key = key.lower()
336 if key not in self._reserved:
337 raise CookieError("Invalid attribute %r" % (key,))
338 data[key] = val
339 dict.update(self, data)
340
341 def isReservedKey(self, K):
342 return K.lower() in self._reserved
343
344 def set(self, key, val, coded_val):
345 if key.lower() in self._reserved:
346 raise CookieError('Attempt to set a reserved key %r' % (key,))
347 if not _is_legal_key(key):
348 raise CookieError('Illegal key %r' % (key,))
349 if _has_control_character(key, val, coded_val):
350 raise CookieError(
351 "Control characters are not allowed in cookies %r %r %r" % (key, val, coded_val,))
352
353 # It's a good key, so save it.
354 self._key = key
355 self._value = val
356 self._coded_value = coded_val
357
358 def __getstate__(self):
359 return {
360 'key': self._key,
361 'value': self._value,
362 'coded_value': self._coded_value,
363 }
364
365 def __setstate__(self, state):
366 self._key = state['key']
367 self._value = state['value']
368 self._coded_value = state['coded_value']
369
370 def output(self, attrs=None, header="Set-Cookie:"):
371 return "%s %s" % (header, self.OutputString(attrs))
372
373 __str__ = output
374
375 def __repr__(self):
376 return '<%s: %s>' % (self.__class__.__name__, self.OutputString())
377
378 def js_output(self, attrs=None):
379 # Print javascript
380 return """
381 <script type="text/javascript">
382 <!-- begin hiding
383 document.cookie = \"%s\";
384 // end hiding -->
385 </script>
386 """ % (self.OutputString(attrs).replace('"', r'\"'))
387
388 def OutputString(self, attrs=None):
389 # Build up our result
390 #
391 result = []
392 append = result.append
393
394 # First, the key=value pair
395 append("%s=%s" % (self.key, self.coded_value))
396
397 # Now add any defined attributes
398 if attrs is None:
399 attrs = self._reserved
400 items = sorted(self.items())
401 for key, value in items:
402 if value == "":
403 continue
404 if key not in attrs:
405 continue
406 if key == "expires" and isinstance(value, int):
407 append("%s=%s" % (self._reserved[key], _getdate(value)))
408 elif key == "max-age" and isinstance(value, int):
409 append("%s=%d" % (self._reserved[key], value))
410 elif key == "comment" and isinstance(value, str):
411 append("%s=%s" % (self._reserved[key], _quote(value)))
412 elif key in self._flags:
413 if value:
414 append(str(self._reserved[key]))
415 else:
416 append("%s=%s" % (self._reserved[key], value))
417
418 # Return the result
419 return _semispacejoin(result)
420
421 __class_getitem__ = classmethod(types.GenericAlias)
422
423
424 #
425 # Pattern for finding cookie
426 #
427 # This used to be strict parsing based on the RFC2109 and RFC2068
428 # specifications. I have since discovered that MSIE 3.0x doesn't
429 # follow the character rules outlined in those specs. As a
430 # result, the parsing rules here are less strict.
431 #
432
433 _LegalKeyChars = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\="
434 _LegalValueChars = _LegalKeyChars + r'\[\]'
435 _CookiePattern = re.compile(r"""
436 \s* # Optional whitespace at start of cookie
437 (?P<key> # Start of group 'key'
438 [""" + _LegalKeyChars + r"""]+? # Any word of at least one letter
439 ) # End of group 'key'
440 ( # Optional group: there may not be a value.
441 \s*=\s* # Equal Sign
442 (?P<val> # Start of group 'val'
443 "(?:[^\\"]|\\.)*" # Any double-quoted string
444 | # or
445 # Special case for "expires" attr
446 (\w{3,6}day|\w{3}),\s # Day of the week or abbreviated day
447 [\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Date and time in specific format
448 | # or
449 [""" + _LegalValueChars + r"""]* # Any word or empty string
450 ) # End of group 'val'
451 )? # End of optional value group
452 \s* # Any number of spaces.
453 (\s+|;|$) # Ending either at space, semicolon, or EOS.
454 """, re.ASCII | re.VERBOSE) # re.ASCII may be removed if safe.
455
456
457 # At long last, here is the cookie class. Using this class is almost just like
458 # using a dictionary. See this module's docstring for example usage.
459 #
460 class BaseCookie(dict):
461 """A container class for a set of Morsels."""
462
463 def value_decode(self, val):
464 """real_value, coded_value = value_decode(STRING)
465 Called prior to setting a cookie's value from the network
466 representation. The VALUE is the value read from HTTP
467 header.
468 Override this function to modify the behavior of cookies.
469 """
470 return val, val
471
472 def value_encode(self, val):
473 """real_value, coded_value = value_encode(VALUE)
474 Called prior to setting a cookie's value from the dictionary
475 representation. The VALUE is the value being assigned.
476 Override this function to modify the behavior of cookies.
477 """
478 strval = str(val)
479 return strval, strval
480
481 def __init__(self, input=None):
482 if input:
483 self.load(input)
484
485 def __set(self, key, real_value, coded_value):
486 """Private method for setting a cookie's value"""
487 M = self.get(key, Morsel())
488 M.set(key, real_value, coded_value)
489 dict.__setitem__(self, key, M)
490
491 def __setitem__(self, key, value):
492 """Dictionary style assignment."""
493 if isinstance(value, Morsel):
494 # allow assignment of constructed Morsels (e.g. for pickling)
495 dict.__setitem__(self, key, value)
496 else:
497 rval, cval = self.value_encode(value)
498 self.__set(key, rval, cval)
499
500 def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
501 """Return a string suitable for HTTP."""
502 result = []
503 items = sorted(self.items())
504 for key, value in items:
505 value_output = value.output(attrs, header)
506 if _has_control_character(value_output):
507 raise CookieError("Control characters are not allowed in cookies")
508 result.append(value_output)
509 return sep.join(result)
510
511 __str__ = output
512
513 def __repr__(self):
514 l = []
515 items = sorted(self.items())
516 for key, value in items:
517 l.append('%s=%s' % (key, repr(value.value)))
518 return '<%s: %s>' % (self.__class__.__name__, _spacejoin(l))
519
520 def js_output(self, attrs=None):
521 """Return a string suitable for JavaScript."""
522 result = []
523 items = sorted(self.items())
524 for key, value in items:
525 result.append(value.js_output(attrs))
526 return _nulljoin(result)
527
528 def load(self, rawdata):
529 """Load cookies from a string (presumably HTTP_COOKIE) or
530 from a dictionary. Loading cookies from a dictionary 'd'
531 is equivalent to calling:
532 map(Cookie.__setitem__, d.keys(), d.values())
533 """
534 if isinstance(rawdata, str):
535 self.__parse_string(rawdata)
536 else:
537 # self.update() wouldn't call our custom __setitem__
538 for key, value in rawdata.items():
539 self[key] = value
540 return
541
542 def __parse_string(self, str, patt=_CookiePattern):
543 i = 0 # Our starting point
544 n = len(str) # Length of string
545 parsed_items = [] # Parsed (type, key, value) triples
546 morsel_seen = False # A key=value pair was previously encountered
547
548 TYPE_ATTRIBUTE = 1
549 TYPE_KEYVALUE = 2
550
551 # We first parse the whole cookie string and reject it if it's
552 # syntactically invalid (this helps avoid some classes of injection
553 # attacks).
554 while 0 <= i < n:
555 # Start looking for a cookie
556 match = patt.match(str, i)
557 if not match:
558 # No more cookies
559 break
560
561 key, value = match.group("key"), match.group("val")
562 i = match.end(0)
563
564 if key[0] == "$":
565 if not morsel_seen:
566 # We ignore attributes which pertain to the cookie
567 # mechanism as a whole, such as "$Version".
568 # See RFC 2965. (Does anyone care?)
569 continue
570 parsed_items.append((TYPE_ATTRIBUTE, key[1:], value))
571 elif key.lower() in Morsel._reserved:
572 if not morsel_seen:
573 # Invalid cookie string
574 return
575 if value is None:
576 if key.lower() in Morsel._flags:
577 parsed_items.append((TYPE_ATTRIBUTE, key, True))
578 else:
579 # Invalid cookie string
580 return
581 else:
582 parsed_items.append((TYPE_ATTRIBUTE, key, _unquote(value)))
583 elif value is not None:
584 parsed_items.append((TYPE_KEYVALUE, key, self.value_decode(value)))
585 morsel_seen = True
586 else:
587 # Invalid cookie string
588 return
589
590 # The cookie string is valid, apply it.
591 M = None # current morsel
592 for tp, key, value in parsed_items:
593 if tp == TYPE_ATTRIBUTE:
594 assert M is not None
595 M[key] = value
596 else:
597 assert tp == TYPE_KEYVALUE
598 rval, cval = value
599 self.__set(key, rval, cval)
600 M = self[key]
601
602
603 class SimpleCookie(BaseCookie):
604 """
605 SimpleCookie supports strings as cookie values. When setting
606 the value using the dictionary assignment notation, SimpleCookie
607 calls the builtin str() to convert the value to a string. Values
608 received from HTTP are kept as strings.
609 """
610 def value_decode(self, val):
611 return _unquote(val), val
612
613 def value_encode(self, val):
614 strval = str(val)
615 return strval, _quote(strval)