home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2025 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  37.7 KB  |  1,143 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import sys
  5. import re
  6. import copy
  7. import time
  8. import urllib
  9. import types
  10. import logging
  11.  
  12. try:
  13.     import threading
  14.     _threading = threading
  15.     del threading
  16. except ImportError:
  17.     import dummy_threading
  18.     _threading = dummy_threading
  19.     del dummy_threading
  20.  
  21. MISSING_FILENAME_TEXT = 'a filename was not supplied (nor was the CookieJar instance initialised with one)'
  22. DEFAULT_HTTP_PORT = '80'
  23. from _headersutil import split_header_words, parse_ns_headers
  24. from _util import isstringlike
  25. import _rfc3986
  26. debug = logging.getLogger('mechanize.cookies').debug
  27.  
  28. def reraise_unmasked_exceptions(unmasked = ()):
  29.     import mechanize
  30.     import warnings
  31.     if not mechanize.USE_BARE_EXCEPT:
  32.         raise 
  33.     mechanize.USE_BARE_EXCEPT
  34.     unmasked = unmasked + (KeyboardInterrupt, SystemExit, MemoryError)
  35.     etype = sys.exc_info()[0]
  36.     if issubclass(etype, unmasked):
  37.         raise 
  38.     issubclass(etype, unmasked)
  39.     import traceback
  40.     import StringIO
  41.     f = StringIO.StringIO()
  42.     traceback.print_exc(None, f)
  43.     msg = f.getvalue()
  44.     warnings.warn('mechanize bug!\n%s' % msg, stacklevel = 2)
  45.  
  46. IPV4_RE = re.compile('\\.\\d+$')
  47.  
  48. def is_HDN(text):
  49.     if not IPV4_RE.search(text) and text == '' and text[0] == '.':
  50.         pass
  51.     return not (text[-1] == '.')
  52.  
  53.  
  54. def domain_match(A, B):
  55.     A = A.lower()
  56.     B = B.lower()
  57.     if A == B:
  58.         return True
  59.     if not is_HDN(A):
  60.         return False
  61.     i = A.rfind(B)
  62.     if not i == -1:
  63.         pass
  64.     has_form_nb = not (i == 0)
  65.     if has_form_nb and B.startswith('.'):
  66.         pass
  67.     return is_HDN(B[1:])
  68.  
  69.  
  70. def liberal_is_HDN(text):
  71.     return not IPV4_RE.search(text)
  72.  
  73.  
  74. def user_domain_match(A, B):
  75.     A = A.lower()
  76.     B = B.lower()
  77.     if not liberal_is_HDN(A) and liberal_is_HDN(B):
  78.         if A == B:
  79.             return True
  80.         return False
  81.     initial_dot = B.startswith('.')
  82.     if initial_dot and A.endswith(B):
  83.         return True
  84.     if not initial_dot and A == B:
  85.         return True
  86.     return False
  87.  
  88. cut_port_re = re.compile(':\\d+$')
  89.  
  90. def request_host(request):
  91.     url = request.get_full_url()
  92.     host = _rfc3986.urlsplit(url)[1]
  93.     if host is None:
  94.         host = request.get_header('Host', '')
  95.     
  96.     return cut_port_re.sub('', host, 1)
  97.  
  98.  
  99. def request_host_lc(request):
  100.     return request_host(request).lower()
  101.  
  102.  
  103. def eff_request_host(request):
  104.     erhn = req_host = request_host(request)
  105.     if req_host.find('.') == -1 and not IPV4_RE.search(req_host):
  106.         erhn = req_host + '.local'
  107.     
  108.     return (req_host, erhn)
  109.  
  110.  
  111. def eff_request_host_lc(request):
  112.     (req_host, erhn) = eff_request_host(request)
  113.     return (req_host.lower(), erhn.lower())
  114.  
  115.  
  116. def effective_request_host(request):
  117.     return eff_request_host(request)[1]
  118.  
  119.  
  120. def request_path(request):
  121.     url = request.get_full_url()
  122.     (path, query, frag) = _rfc3986.urlsplit(url)[2:]
  123.     path = escape_path(path)
  124.     req_path = _rfc3986.urlunsplit((None, None, path, query, frag))
  125.     if not req_path.startswith('/'):
  126.         req_path = '/' + req_path
  127.     
  128.     return req_path
  129.  
  130.  
  131. def request_port(request):
  132.     host = request.get_host()
  133.     i = host.find(':')
  134.     if i >= 0:
  135.         port = host[i + 1:]
  136.         
  137.         try:
  138.             int(port)
  139.         except ValueError:
  140.             debug("nonnumeric port: '%s'", port)
  141.             return None
  142.         
  143.  
  144.     None<EXCEPTION MATCH>ValueError
  145.     port = DEFAULT_HTTP_PORT
  146.     return port
  147.  
  148.  
  149. def request_is_unverifiable(request):
  150.     
  151.     try:
  152.         return request.is_unverifiable()
  153.     except AttributeError:
  154.         if hasattr(request, 'unverifiable'):
  155.             return request.unverifiable
  156.         raise 
  157.     except:
  158.         hasattr(request, 'unverifiable')
  159.  
  160.  
  161. HTTP_PATH_SAFE = "%/;:@&=+$,!~*'()"
  162. ESCAPED_CHAR_RE = re.compile('%([0-9a-fA-F][0-9a-fA-F])')
  163.  
  164. def uppercase_escaped_char(match):
  165.     return '%%%s' % match.group(1).upper()
  166.  
  167.  
  168. def escape_path(path):
  169.     if isinstance(path, types.UnicodeType):
  170.         path = path.encode('utf-8')
  171.     
  172.     path = urllib.quote(path, HTTP_PATH_SAFE)
  173.     path = ESCAPED_CHAR_RE.sub(uppercase_escaped_char, path)
  174.     return path
  175.  
  176.  
  177. def reach(h):
  178.     i = h.find('.')
  179.     if i >= 0:
  180.         b = h[i + 1:]
  181.         i = b.find('.')
  182.         if is_HDN(h):
  183.             if i >= 0 or b == 'local':
  184.                 return '.' + b
  185.         
  186.     return h
  187.  
  188.  
  189. def is_third_party(request):
  190.     req_host = request_host_lc(request)
  191.     return not domain_match(req_host, reach(request.origin_req_host))
  192.  
  193.  
  194. class Cookie:
  195.     
  196.     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):
  197.         if version is not None:
  198.             version = int(version)
  199.         
  200.         if expires is not None:
  201.             expires = int(expires)
  202.         
  203.         if port is None and port_specified is True:
  204.             raise ValueError('if port is None, port_specified must be false')
  205.         port_specified is True
  206.         self.version = version
  207.         self.name = name
  208.         self.value = value
  209.         self.port = port
  210.         self.port_specified = port_specified
  211.         self.domain = domain.lower()
  212.         self.domain_specified = domain_specified
  213.         self.domain_initial_dot = domain_initial_dot
  214.         self.path = path
  215.         self.path_specified = path_specified
  216.         self.secure = secure
  217.         self.expires = expires
  218.         self.discard = discard
  219.         self.comment = comment
  220.         self.comment_url = comment_url
  221.         self.rfc2109 = rfc2109
  222.         self._rest = copy.copy(rest)
  223.  
  224.     
  225.     def has_nonstandard_attr(self, name):
  226.         return self._rest.has_key(name)
  227.  
  228.     
  229.     def get_nonstandard_attr(self, name, default = None):
  230.         return self._rest.get(name, default)
  231.  
  232.     
  233.     def set_nonstandard_attr(self, name, value):
  234.         self._rest[name] = value
  235.  
  236.     
  237.     def nonstandard_attr_keys(self):
  238.         return self._rest.keys()
  239.  
  240.     
  241.     def is_expired(self, now = None):
  242.         if now is None:
  243.             now = time.time()
  244.         
  245.         if self.expires is not None:
  246.             pass
  247.         return self.expires <= now
  248.  
  249.     
  250.     def __str__(self):
  251.         if self.port is None:
  252.             p = ''
  253.         else:
  254.             p = ':' + self.port
  255.         limit = self.domain + p + self.path
  256.         if self.value is not None:
  257.             namevalue = '%s=%s' % (self.name, self.value)
  258.         else:
  259.             namevalue = self.name
  260.         return '<Cookie %s for %s>' % (namevalue, limit)
  261.  
  262.     
  263.     def __repr__(self):
  264.         args = []
  265.         for name in [
  266.             'version',
  267.             'name',
  268.             'value',
  269.             'port',
  270.             'port_specified',
  271.             'domain',
  272.             'domain_specified',
  273.             'domain_initial_dot',
  274.             'path',
  275.             'path_specified',
  276.             'secure',
  277.             'expires',
  278.             'discard',
  279.             'comment',
  280.             'comment_url']:
  281.             attr = getattr(self, name)
  282.             args.append('%s=%s' % (name, repr(attr)))
  283.         
  284.         args.append('rest=%s' % repr(self._rest))
  285.         args.append('rfc2109=%s' % repr(self.rfc2109))
  286.         return 'Cookie(%s)' % ', '.join(args)
  287.  
  288.  
  289.  
  290. class CookiePolicy:
  291.     
  292.     def set_ok(self, cookie, request):
  293.         raise NotImplementedError()
  294.  
  295.     
  296.     def return_ok(self, cookie, request):
  297.         raise NotImplementedError()
  298.  
  299.     
  300.     def domain_return_ok(self, domain, request):
  301.         return True
  302.  
  303.     
  304.     def path_return_ok(self, path, request):
  305.         return True
  306.  
  307.  
  308.  
  309. class DefaultCookiePolicy(CookiePolicy):
  310.     DomainStrictNoDots = 1
  311.     DomainStrictNonDomain = 2
  312.     DomainRFC2965Match = 4
  313.     DomainLiberal = 0
  314.     DomainStrict = DomainStrictNoDots | DomainStrictNonDomain
  315.     
  316.     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):
  317.         self.netscape = netscape
  318.         self.rfc2965 = rfc2965
  319.         self.rfc2109_as_netscape = rfc2109_as_netscape
  320.         self.hide_cookie2 = hide_cookie2
  321.         self.strict_domain = strict_domain
  322.         self.strict_rfc2965_unverifiable = strict_rfc2965_unverifiable
  323.         self.strict_ns_unverifiable = strict_ns_unverifiable
  324.         self.strict_ns_domain = strict_ns_domain
  325.         self.strict_ns_set_initial_dollar = strict_ns_set_initial_dollar
  326.         self.strict_ns_set_path = strict_ns_set_path
  327.         if blocked_domains is not None:
  328.             self._blocked_domains = tuple(blocked_domains)
  329.         else:
  330.             self._blocked_domains = ()
  331.         if allowed_domains is not None:
  332.             allowed_domains = tuple(allowed_domains)
  333.         
  334.         self._allowed_domains = allowed_domains
  335.  
  336.     
  337.     def blocked_domains(self):
  338.         return self._blocked_domains
  339.  
  340.     
  341.     def set_blocked_domains(self, blocked_domains):
  342.         self._blocked_domains = tuple(blocked_domains)
  343.  
  344.     
  345.     def is_blocked(self, domain):
  346.         for blocked_domain in self._blocked_domains:
  347.             if user_domain_match(domain, blocked_domain):
  348.                 return True
  349.         
  350.         return False
  351.  
  352.     
  353.     def allowed_domains(self):
  354.         return self._allowed_domains
  355.  
  356.     
  357.     def set_allowed_domains(self, allowed_domains):
  358.         if allowed_domains is not None:
  359.             allowed_domains = tuple(allowed_domains)
  360.         
  361.         self._allowed_domains = allowed_domains
  362.  
  363.     
  364.     def is_not_allowed(self, domain):
  365.         if self._allowed_domains is None:
  366.             return False
  367.         for allowed_domain in self._allowed_domains:
  368.             if user_domain_match(domain, allowed_domain):
  369.                 return False
  370.         
  371.         return True
  372.  
  373.     
  374.     def set_ok(self, cookie, request):
  375.         debug(' - checking cookie %s', cookie)
  376.         for n in ('version', 'verifiability', 'name', 'path', 'domain', 'port'):
  377.             fn_name = 'set_ok_' + n
  378.             fn = getattr(self, fn_name)
  379.             if not fn(cookie, request):
  380.                 return False
  381.         
  382.         return True
  383.  
  384.     
  385.     def set_ok_version(self, cookie, request):
  386.         if cookie.version is None:
  387.             debug('   Set-Cookie2 without version attribute (%s)', cookie)
  388.             return False
  389.         if cookie.version > 0 and not (self.rfc2965):
  390.             debug('   RFC 2965 cookies are switched off')
  391.             return False
  392.         if cookie.version == 0 and not (self.netscape):
  393.             debug('   Netscape cookies are switched off')
  394.             return False
  395.         return True
  396.  
  397.     
  398.     def set_ok_verifiability(self, cookie, request):
  399.         return True
  400.  
  401.     
  402.     def set_ok_name(self, cookie, request):
  403.         if cookie.version == 0 and self.strict_ns_set_initial_dollar and cookie.name.startswith('$'):
  404.             debug("   illegal name (starts with '$'): '%s'", cookie.name)
  405.             return False
  406.         return True
  407.  
  408.     
  409.     def set_ok_path(self, cookie, request):
  410.         if cookie.path_specified:
  411.             req_path = request_path(request)
  412.             if (cookie.version > 0 or cookie.version == 0 or self.strict_ns_set_path) and not req_path.startswith(cookie.path):
  413.                 debug('   path attribute %s is not a prefix of request path %s', cookie.path, req_path)
  414.                 return False
  415.         
  416.         return True
  417.  
  418.     
  419.     def set_ok_countrycode_domain(self, cookie, request):
  420.         if cookie.domain_specified and self.strict_domain:
  421.             domain = cookie.domain
  422.             if domain.count('.') == 2:
  423.                 i = domain.rfind('.')
  424.                 tld = domain[i + 1:]
  425.                 sld = domain[1:i]
  426.                 if sld.lower() in ('co', 'ac', 'com', 'edu', 'org', 'net', 'gov', 'mil', 'int', 'aero', 'biz', 'cat', 'coop', 'info', 'jobs', 'mobi', 'museum', 'name', 'pro', 'travel') and len(tld) == 2:
  427.                     return False
  428.             
  429.         
  430.         return True
  431.  
  432.     
  433.     def set_ok_domain(self, cookie, request):
  434.         if self.is_blocked(cookie.domain):
  435.             debug('   domain %s is in user block-list', cookie.domain)
  436.             return False
  437.         if self.is_not_allowed(cookie.domain):
  438.             debug('   domain %s is not in user allow-list', cookie.domain)
  439.             return False
  440.         if not self.set_ok_countrycode_domain(cookie, request):
  441.             debug('   country-code second level domain %s', cookie.domain)
  442.             return False
  443.         if cookie.domain_specified:
  444.             (req_host, erhn) = eff_request_host_lc(request)
  445.             domain = cookie.domain
  446.             embedded_dots = undotted_domain.find('.') >= 0
  447.             if not embedded_dots and domain != '.local':
  448.                 debug('   non-local domain %s contains no embedded dot', domain)
  449.                 return False
  450.             if cookie.version > 0 or self.strict_ns_domain & self.DomainStrictNoDots:
  451.                 host_prefix = req_host[:-len(domain)]
  452.                 if host_prefix.find('.') >= 0 and not IPV4_RE.search(req_host):
  453.                     debug('   host prefix %s for domain %s contains a dot', host_prefix, domain)
  454.                     return False
  455.             
  456.         
  457.         return True
  458.  
  459.     
  460.     def set_ok_port(self, cookie, request):
  461.         if cookie.port_specified:
  462.             req_port = request_port(request)
  463.             if req_port is None:
  464.                 req_port = '80'
  465.             else:
  466.                 req_port = str(req_port)
  467.             for p in cookie.port.split(','):
  468.                 
  469.                 try:
  470.                     int(p)
  471.                 except ValueError:
  472.                     debug('   bad port %s (not numeric)', p)
  473.                     return False
  474.  
  475.                 if p == req_port:
  476.                     break
  477.                     continue
  478.             else:
  479.                 return False
  480.         return True
  481.  
  482.     
  483.     def return_ok(self, cookie, request):
  484.         debug(' - checking cookie %s', cookie)
  485.         for n in ('version', 'verifiability', 'secure', 'expires', 'port', 'domain'):
  486.             fn_name = 'return_ok_' + n
  487.             fn = getattr(self, fn_name)
  488.             if not fn(cookie, request):
  489.                 return False
  490.         
  491.         return True
  492.  
  493.     
  494.     def return_ok_version(self, cookie, request):
  495.         if cookie.version > 0 and not (self.rfc2965):
  496.             debug('   RFC 2965 cookies are switched off')
  497.             return False
  498.         if cookie.version == 0 and not (self.netscape):
  499.             debug('   Netscape cookies are switched off')
  500.             return False
  501.         return True
  502.  
  503.     
  504.     def return_ok_verifiability(self, cookie, request):
  505.         return True
  506.  
  507.     
  508.     def return_ok_secure(self, cookie, request):
  509.         if cookie.secure and request.get_type() != 'https':
  510.             debug('   secure cookie with non-secure request')
  511.             return False
  512.         return True
  513.  
  514.     
  515.     def return_ok_expires(self, cookie, request):
  516.         if cookie.is_expired(self._now):
  517.             debug('   cookie expired')
  518.             return False
  519.         return True
  520.  
  521.     
  522.     def return_ok_port(self, cookie, request):
  523.         if cookie.port:
  524.             req_port = request_port(request)
  525.             if req_port is None:
  526.                 req_port = '80'
  527.             
  528.             for p in cookie.port.split(','):
  529.                 if p == req_port:
  530.                     break
  531.                     continue
  532.             else:
  533.                 return False
  534.         return True
  535.  
  536.     
  537.     def return_ok_domain(self, cookie, request):
  538.         (req_host, erhn) = eff_request_host_lc(request)
  539.         domain = cookie.domain
  540.         if cookie.version == 0 and self.strict_ns_domain & self.DomainStrictNonDomain and not (cookie.domain_specified) and domain != erhn:
  541.             debug('   cookie with unspecified domain does not string-compare equal to request domain')
  542.             return False
  543.         if cookie.version > 0 and not domain_match(erhn, domain):
  544.             debug('   effective request-host name %s does not domain-match RFC 2965 cookie domain %s', erhn, domain)
  545.             return False
  546.         if cookie.version == 0 and not ('.' + erhn).endswith(domain):
  547.             debug('   request-host %s does not match Netscape cookie domain %s', req_host, domain)
  548.             return False
  549.         return True
  550.  
  551.     
  552.     def domain_return_ok(self, domain, request):
  553.         (dotted_req_host, dotted_erhn) = eff_request_host_lc(request)
  554.         if not dotted_req_host.startswith('.'):
  555.             dotted_req_host = '.' + dotted_req_host
  556.         
  557.         if not dotted_erhn.startswith('.'):
  558.             dotted_erhn = '.' + dotted_erhn
  559.         
  560.         if not dotted_req_host.endswith(domain) or dotted_erhn.endswith(domain):
  561.             return False
  562.         if self.is_blocked(domain):
  563.             debug('   domain %s is in user block-list', domain)
  564.             return False
  565.         if self.is_not_allowed(domain):
  566.             debug('   domain %s is not in user allow-list', domain)
  567.             return False
  568.         return True
  569.  
  570.     
  571.     def path_return_ok(self, path, request):
  572.         debug('- checking cookie path=%s', path)
  573.         req_path = request_path(request)
  574.         if not req_path.startswith(path):
  575.             debug('  %s does not path-match %s', req_path, path)
  576.             return False
  577.         return True
  578.  
  579.  
  580.  
  581. def vals_sorted_by_key(adict):
  582.     keys = adict.keys()
  583.     keys.sort()
  584.     return map(adict.get, keys)
  585.  
  586.  
  587. class MappingIterator:
  588.     
  589.     def __init__(self, mapping):
  590.         self._s = [
  591.             (vals_sorted_by_key(mapping), 0, None)]
  592.  
  593.     
  594.     def __iter__(self):
  595.         return self
  596.  
  597.     
  598.     def next(self):
  599.         while None:
  600.             
  601.             try:
  602.                 (vals, i, prev_item) = self._s.pop()
  603.             except IndexError:
  604.                 raise StopIteration()
  605.  
  606.             if i < len(vals):
  607.                 item = vals[i]
  608.                 i = i + 1
  609.                 self._s.append((vals, i, prev_item))
  610.                 
  611.                 try:
  612.                     item.items
  613.                 except AttributeError:
  614.                     break
  615.  
  616.                 self._s.append((vals_sorted_by_key(item), 0, item))
  617.                 continue
  618.                 continue
  619.             continue
  620.             return item
  621.  
  622.  
  623.  
  624. class Absent:
  625.     pass
  626.  
  627.  
  628. class CookieJar:
  629.     non_word_re = re.compile('\\W')
  630.     quote_re = re.compile('([\\"\\\\])')
  631.     strict_domain_re = re.compile('\\.?[^.]*')
  632.     domain_re = re.compile('[^.]*')
  633.     dots_re = re.compile('^\\.+')
  634.     
  635.     def __init__(self, policy = None):
  636.         if policy is None:
  637.             policy = DefaultCookiePolicy()
  638.         
  639.         self._policy = policy
  640.         self._cookies = { }
  641.         self._prev_getitem_index = 0
  642.  
  643.     
  644.     def get_policy(self):
  645.         return self._policy
  646.  
  647.     
  648.     def set_policy(self, policy):
  649.         self._policy = policy
  650.  
  651.     
  652.     def _cookies_for_domain(self, domain, request):
  653.         cookies = []
  654.         if not self._policy.domain_return_ok(domain, request):
  655.             return []
  656.         debug('Checking %s for cookies to return', domain)
  657.         cookies_by_path = self._cookies[domain]
  658.         for path in cookies_by_path.keys():
  659.             if not self._policy.path_return_ok(path, request):
  660.                 continue
  661.             
  662.             cookies_by_name = cookies_by_path[path]
  663.             for cookie in cookies_by_name.values():
  664.                 if not self._policy.return_ok(cookie, request):
  665.                     debug('   not returning cookie')
  666.                     continue
  667.                 
  668.                 debug("   it's a match")
  669.                 cookies.append(cookie)
  670.             
  671.         
  672.         return cookies
  673.  
  674.     
  675.     def cookies_for_request(self, request):
  676.         self._policy._now = self._now = int(time.time())
  677.         cookies = self._cookies_for_request(request)
  678.         
  679.         def decreasing_size(a, b):
  680.             return cmp(len(b.path), len(a.path))
  681.  
  682.         cookies.sort(decreasing_size)
  683.         return cookies
  684.  
  685.     
  686.     def _cookies_for_request(self, request):
  687.         cookies = []
  688.         for domain in self._cookies.keys():
  689.             cookies.extend(self._cookies_for_domain(domain, request))
  690.         
  691.         return cookies
  692.  
  693.     
  694.     def _cookie_attrs(self, cookies):
  695.         version_set = False
  696.         attrs = []
  697.         for cookie in cookies:
  698.             version = cookie.version
  699.             if not version_set:
  700.                 version_set = True
  701.                 if version > 0:
  702.                     attrs.append('$Version=%s' % version)
  703.                 
  704.             
  705.             if cookie.value is not None and self.non_word_re.search(cookie.value) and version > 0:
  706.                 value = self.quote_re.sub('\\\\\\1', cookie.value)
  707.             else:
  708.                 value = cookie.value
  709.             if cookie.value is None:
  710.                 attrs.append(cookie.name)
  711.             else:
  712.                 attrs.append('%s=%s' % (cookie.name, value))
  713.             if version > 0:
  714.                 if cookie.path_specified:
  715.                     attrs.append('$Path="%s"' % cookie.path)
  716.                 
  717.                 if cookie.domain.startswith('.'):
  718.                     domain = cookie.domain
  719.                     if not (cookie.domain_initial_dot) and domain.startswith('.'):
  720.                         domain = domain[1:]
  721.                     
  722.                     attrs.append('$Domain="%s"' % domain)
  723.                 
  724.                 if cookie.port is not None:
  725.                     p = '$Port'
  726.                     if cookie.port_specified:
  727.                         p = p + '="%s"' % cookie.port
  728.                     
  729.                     attrs.append(p)
  730.                 
  731.             cookie.port is not None
  732.         
  733.         return attrs
  734.  
  735.     
  736.     def add_cookie_header(self, request):
  737.         debug('add_cookie_header')
  738.         cookies = self.cookies_for_request(request)
  739.         attrs = self._cookie_attrs(cookies)
  740.         if attrs:
  741.             if not request.has_header('Cookie'):
  742.                 request.add_unredirected_header('Cookie', '; '.join(attrs))
  743.             
  744.         
  745.         if self._policy.rfc2965 and not (self._policy.hide_cookie2):
  746.             for cookie in cookies:
  747.                 if cookie.version != 1 and not request.has_header('Cookie2'):
  748.                     request.add_unredirected_header('Cookie2', '$Version="1"')
  749.                     break
  750.                     continue
  751.             
  752.         
  753.         self.clear_expired_cookies()
  754.  
  755.     
  756.     def _normalized_cookie_tuples(self, attrs_set):
  757.         cookie_tuples = []
  758.         boolean_attrs = ('discard', 'secure')
  759.         value_attrs = ('version', 'expires', 'max-age', 'domain', 'path', 'port', 'comment', 'commenturl')
  760.         for cookie_attrs in attrs_set:
  761.             (name, value) = cookie_attrs[0]
  762.             max_age_set = False
  763.             bad_cookie = False
  764.             standard = { }
  765.             rest = { }
  766.             for k, v in cookie_attrs[1:]:
  767.                 lc = k.lower()
  768.                 if lc in value_attrs or lc in boolean_attrs:
  769.                     k = lc
  770.                 
  771.                 if k in boolean_attrs and v is None:
  772.                     v = True
  773.                 
  774.                 if standard.has_key(k):
  775.                     continue
  776.                 
  777.                 if k == 'domain':
  778.                     if v is None:
  779.                         debug('   missing value for domain attribute')
  780.                         bad_cookie = True
  781.                         break
  782.                     
  783.                     v = v.lower()
  784.                 
  785.                 if k == 'expires':
  786.                     if max_age_set:
  787.                         continue
  788.                     
  789.                     if v is None:
  790.                         debug('   missing or invalid value for expires attribute: treating as session cookie')
  791.                         continue
  792.                     
  793.                 
  794.                 if k == 'max-age':
  795.                     max_age_set = True
  796.                     if v is None:
  797.                         debug('   missing value for max-age attribute')
  798.                         bad_cookie = True
  799.                         break
  800.                     
  801.                     
  802.                     try:
  803.                         v = int(v)
  804.                     except ValueError:
  805.                         debug('   missing or invalid (non-numeric) value for max-age attribute')
  806.                         bad_cookie = True
  807.                         break
  808.  
  809.                     k = 'expires'
  810.                     v = self._now + v
  811.                 
  812.                 if k in value_attrs or k in boolean_attrs:
  813.                     if v is None and k not in ('port', 'comment', 'commenturl'):
  814.                         debug('   missing value for %s attribute' % k)
  815.                         bad_cookie = True
  816.                         break
  817.                     
  818.                     standard[k] = v
  819.                     continue
  820.                 rest[k] = v
  821.             
  822.             if bad_cookie:
  823.                 continue
  824.             
  825.             cookie_tuples.append((name, value, standard, rest))
  826.         
  827.         return cookie_tuples
  828.  
  829.     
  830.     def _cookie_from_cookie_tuple(self, tup, request):
  831.         (name, value, standard, rest) = tup
  832.         domain = standard.get('domain', Absent)
  833.         path = standard.get('path', Absent)
  834.         port = standard.get('port', Absent)
  835.         expires = standard.get('expires', Absent)
  836.         version = standard.get('version', None)
  837.         if version is not None:
  838.             
  839.             try:
  840.                 version = int(version)
  841.             except ValueError:
  842.                 return None
  843.             
  844.  
  845.         None<EXCEPTION MATCH>ValueError
  846.         secure = standard.get('secure', False)
  847.         discard = standard.get('discard', False)
  848.         comment = standard.get('comment', None)
  849.         comment_url = standard.get('commenturl', None)
  850.         if path is not Absent and path != '':
  851.             path_specified = True
  852.             path = escape_path(path)
  853.         else:
  854.             path_specified = False
  855.             path = request_path(request)
  856.             i = path.rfind('/')
  857.             if i != -1:
  858.                 if version == 0:
  859.                     path = path[:i]
  860.                 else:
  861.                     path = path[:i + 1]
  862.             
  863.             if len(path) == 0:
  864.                 path = '/'
  865.             
  866.         domain_specified = domain is not Absent
  867.         domain_initial_dot = False
  868.         if domain_specified:
  869.             domain_initial_dot = bool(domain.startswith('.'))
  870.         
  871.         if domain is Absent:
  872.             (req_host, erhn) = eff_request_host_lc(request)
  873.             domain = erhn
  874.         elif not domain.startswith('.'):
  875.             domain = '.' + domain
  876.         
  877.         port_specified = False
  878.         if port is not Absent:
  879.             if port is None:
  880.                 port = request_port(request)
  881.             else:
  882.                 port_specified = True
  883.                 port = re.sub('\\s+', '', port)
  884.         else:
  885.             port = None
  886.         if expires is Absent:
  887.             expires = None
  888.             discard = True
  889.         
  890.         return Cookie(version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest)
  891.  
  892.     
  893.     def _cookies_from_attrs_set(self, attrs_set, request):
  894.         cookie_tuples = self._normalized_cookie_tuples(attrs_set)
  895.         cookies = []
  896.         for tup in cookie_tuples:
  897.             cookie = self._cookie_from_cookie_tuple(tup, request)
  898.             if cookie:
  899.                 cookies.append(cookie)
  900.                 continue
  901.         
  902.         return cookies
  903.  
  904.     
  905.     def _process_rfc2109_cookies(self, cookies):
  906.         if self._policy.rfc2109_as_netscape is None:
  907.             rfc2109_as_netscape = not (self._policy.rfc2965)
  908.         else:
  909.             rfc2109_as_netscape = self._policy.rfc2109_as_netscape
  910.         for cookie in cookies:
  911.             if cookie.version == 1:
  912.                 cookie.rfc2109 = True
  913.                 if rfc2109_as_netscape:
  914.                     cookie.version = 0
  915.                 
  916.             rfc2109_as_netscape
  917.         
  918.  
  919.     
  920.     def _make_cookies(self, response, request):
  921.         headers = response.info()
  922.         rfc2965_hdrs = headers.getheaders('Set-Cookie2')
  923.         ns_hdrs = headers.getheaders('Set-Cookie')
  924.         rfc2965 = self._policy.rfc2965
  925.         netscape = self._policy.netscape
  926.         if not not rfc2965_hdrs or not ns_hdrs:
  927.             if not not ns_hdrs or not rfc2965:
  928.                 if (not rfc2965_hdrs or not netscape or not netscape) and not rfc2965:
  929.                     return []
  930.                 
  931.                 try:
  932.                     cookies = self._cookies_from_attrs_set(split_header_words(rfc2965_hdrs), request)
  933.                 except:
  934.                     not rfc2965
  935.                     reraise_unmasked_exceptions()
  936.                     cookies = []
  937.  
  938.                 if ns_hdrs and netscape:
  939.                     
  940.                     try:
  941.                         ns_cookies = self._cookies_from_attrs_set(parse_ns_headers(ns_hdrs), request)
  942.                     except:
  943.                         not rfc2965
  944.                         reraise_unmasked_exceptions()
  945.                         ns_cookies = []
  946.  
  947.                     self._process_rfc2109_cookies(ns_cookies)
  948.                     if rfc2965:
  949.                         lookup = { }
  950.                         for cookie in cookies:
  951.                             lookup[(cookie.domain, cookie.path, cookie.name)] = None
  952.                         
  953.                         
  954.                         def no_matching_rfc2965(ns_cookie, lookup = lookup):
  955.                             key = (ns_cookie.domain, ns_cookie.path, ns_cookie.name)
  956.                             return not lookup.has_key(key)
  957.  
  958.                         ns_cookies = filter(no_matching_rfc2965, ns_cookies)
  959.                     
  960.                     if ns_cookies:
  961.                         cookies.extend(ns_cookies)
  962.                     
  963.                 
  964.         return cookies
  965.  
  966.     
  967.     def make_cookies(self, response, request):
  968.         self._policy._now = self._now = int(time.time())
  969.         return _[1]
  970.  
  971.     
  972.     def set_cookie_if_ok(self, cookie, request):
  973.         self._policy._now = self._now = int(time.time())
  974.         if self._policy.set_ok(cookie, request):
  975.             self.set_cookie(cookie)
  976.         
  977.  
  978.     
  979.     def set_cookie(self, cookie):
  980.         c = self._cookies
  981.         if not c.has_key(cookie.domain):
  982.             c[cookie.domain] = { }
  983.         
  984.         c2 = c[cookie.domain]
  985.         if not c2.has_key(cookie.path):
  986.             c2[cookie.path] = { }
  987.         
  988.         c3 = c2[cookie.path]
  989.         c3[cookie.name] = cookie
  990.  
  991.     
  992.     def extract_cookies(self, response, request):
  993.         debug('extract_cookies: %s', response.info())
  994.         self._policy._now = self._now = int(time.time())
  995.         for cookie in self._make_cookies(response, request):
  996.             if cookie.expires is not None and cookie.expires <= self._now:
  997.                 
  998.                 try:
  999.                     self.clear(cookie.domain, cookie.path, cookie.name)
  1000.                 except KeyError:
  1001.                     pass
  1002.  
  1003.                 debug("Expiring cookie, domain='%s', path='%s', name='%s'", cookie.domain, cookie.path, cookie.name)
  1004.                 continue
  1005.             if self._policy.set_ok(cookie, request):
  1006.                 debug(' setting cookie: %s', cookie)
  1007.                 self.set_cookie(cookie)
  1008.                 continue
  1009.         
  1010.  
  1011.     
  1012.     def clear(self, domain = None, path = None, name = None):
  1013.         if name is not None:
  1014.             if domain is None or path is None:
  1015.                 raise ValueError('domain and path must be given to remove a cookie by name')
  1016.             path is None
  1017.             del self._cookies[domain][path][name]
  1018.         elif path is not None:
  1019.             if domain is None:
  1020.                 raise ValueError('domain must be given to remove cookies by path')
  1021.             domain is None
  1022.             del self._cookies[domain][path]
  1023.         elif domain is not None:
  1024.             del self._cookies[domain]
  1025.         else:
  1026.             self._cookies = { }
  1027.  
  1028.     
  1029.     def clear_session_cookies(self):
  1030.         for cookie in self:
  1031.             if cookie.discard:
  1032.                 self.clear(cookie.domain, cookie.path, cookie.name)
  1033.                 continue
  1034.         
  1035.  
  1036.     
  1037.     def clear_expired_cookies(self):
  1038.         now = time.time()
  1039.         for cookie in self:
  1040.             if cookie.is_expired(now):
  1041.                 self.clear(cookie.domain, cookie.path, cookie.name)
  1042.                 continue
  1043.         
  1044.  
  1045.     
  1046.     def __getitem__(self, i):
  1047.         if i == 0:
  1048.             self._getitem_iterator = self.__iter__()
  1049.         elif self._prev_getitem_index != i - 1:
  1050.             raise IndexError('CookieJar.__getitem__ only supports sequential iteration')
  1051.         
  1052.         self._prev_getitem_index = i
  1053.         
  1054.         try:
  1055.             return self._getitem_iterator.next()
  1056.         except StopIteration:
  1057.             raise IndexError()
  1058.  
  1059.  
  1060.     
  1061.     def __iter__(self):
  1062.         return MappingIterator(self._cookies)
  1063.  
  1064.     
  1065.     def __len__(self):
  1066.         i = 0
  1067.         for cookie in self:
  1068.             i = i + 1
  1069.         
  1070.         return i
  1071.  
  1072.     
  1073.     def __repr__(self):
  1074.         r = []
  1075.         for cookie in self:
  1076.             r.append(repr(cookie))
  1077.         
  1078.         return '<%s[%s]>' % (self.__class__, ', '.join(r))
  1079.  
  1080.     
  1081.     def __str__(self):
  1082.         r = []
  1083.         for cookie in self:
  1084.             r.append(str(cookie))
  1085.         
  1086.         return '<%s[%s]>' % (self.__class__, ', '.join(r))
  1087.  
  1088.  
  1089.  
  1090. class LoadError(Exception):
  1091.     pass
  1092.  
  1093.  
  1094. class FileCookieJar(CookieJar):
  1095.     
  1096.     def __init__(self, filename = None, delayload = False, policy = None):
  1097.         CookieJar.__init__(self, policy)
  1098.         if filename is not None and not isstringlike(filename):
  1099.             raise ValueError('filename must be string-like')
  1100.         not isstringlike(filename)
  1101.         self.filename = filename
  1102.         self.delayload = bool(delayload)
  1103.  
  1104.     
  1105.     def save(self, filename = None, ignore_discard = False, ignore_expires = False):
  1106.         raise NotImplementedError()
  1107.  
  1108.     
  1109.     def load(self, filename = None, ignore_discard = False, ignore_expires = False):
  1110.         if filename is None:
  1111.             if self.filename is not None:
  1112.                 filename = self.filename
  1113.             else:
  1114.                 raise ValueError(MISSING_FILENAME_TEXT)
  1115.         self.filename is not None
  1116.         f = open(filename)
  1117.         
  1118.         try:
  1119.             self._really_load(f, filename, ignore_discard, ignore_expires)
  1120.         finally:
  1121.             f.close()
  1122.  
  1123.  
  1124.     
  1125.     def revert(self, filename = None, ignore_discard = False, ignore_expires = False):
  1126.         if filename is None:
  1127.             if self.filename is not None:
  1128.                 filename = self.filename
  1129.             else:
  1130.                 raise ValueError(MISSING_FILENAME_TEXT)
  1131.         self.filename is not None
  1132.         old_state = copy.deepcopy(self._cookies)
  1133.         self._cookies = { }
  1134.         
  1135.         try:
  1136.             self.load(filename, ignore_discard, ignore_expires)
  1137.         except (LoadError, IOError):
  1138.             self._cookies = old_state
  1139.             raise 
  1140.  
  1141.  
  1142.  
  1143.