home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / cookielib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-29  |  53.8 KB  |  1,826 lines

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