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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import base64
  5. import copy
  6. import os
  7. import posixpath
  8. import random
  9. import re
  10. import time
  11. import urlparse
  12.  
  13. try:
  14.     import hashlib
  15. except ImportError:
  16.     import md5
  17.     import sha
  18.     
  19.     def sha1_digest(bytes):
  20.         return sha.new(bytes).hexdigest()
  21.  
  22.     
  23.     def md5_digest(bytes):
  24.         return md5.new(bytes).hexdigest()
  25.  
  26.  
  27.  
  28. def sha1_digest(bytes):
  29.     return hashlib.sha1(bytes).hexdigest()
  30.  
  31.  
  32. def md5_digest(bytes):
  33.     return hashlib.md5(bytes).hexdigest()
  34.  
  35. from urllib2 import BaseHandler, HTTPError, parse_keqv_list, parse_http_list
  36. from urllib import getproxies, unquote, splittype, splituser, splitpasswd, splitport
  37.  
  38. def _parse_proxy(proxy):
  39.     (scheme, r_scheme) = splittype(proxy)
  40.     if not r_scheme.startswith('/'):
  41.         scheme = None
  42.         authority = proxy
  43.     elif not r_scheme.startswith('//'):
  44.         raise ValueError('proxy URL with no authority: %r' % proxy)
  45.     
  46.     end = r_scheme.find('/', 2)
  47.     if end == -1:
  48.         end = None
  49.     
  50.     authority = r_scheme[2:end]
  51.     (userinfo, hostport) = splituser(authority)
  52.     if userinfo is not None:
  53.         (user, password) = splitpasswd(userinfo)
  54.     else:
  55.         user = None
  56.         password = None
  57.     return (scheme, user, password, hostport)
  58.  
  59.  
  60. class ProxyHandler(BaseHandler):
  61.     handler_order = 100
  62.     
  63.     def __init__(self, proxies = None):
  64.         if proxies is None:
  65.             proxies = getproxies()
  66.         
  67.         self.proxies = proxies
  68.         for type, url in proxies.items():
  69.             setattr(self, '%s_open' % type, (lambda r, proxy = url, type = type, meth = self.proxy_open: meth(r, proxy, type)))
  70.         
  71.  
  72.     
  73.     def proxy_open(self, req, proxy, type):
  74.         orig_type = req.get_type()
  75.         (proxy_type, user, password, hostport) = _parse_proxy(proxy)
  76.         if proxy_type is None:
  77.             proxy_type = orig_type
  78.         
  79.         if user and password:
  80.             user_pass = '%s:%s' % (unquote(user), unquote(password))
  81.             creds = base64.encodestring(user_pass).strip()
  82.             req.add_header('Proxy-authorization', 'Basic ' + creds)
  83.         
  84.         hostport = unquote(hostport)
  85.         req.set_proxy(hostport, proxy_type)
  86.         if orig_type == proxy_type:
  87.             return None
  88.         return self.parent.open(req)
  89.  
  90.  
  91.  
  92. class HTTPPasswordMgr:
  93.     
  94.     def __init__(self):
  95.         self.passwd = { }
  96.  
  97.     
  98.     def add_password(self, realm, uri, user, passwd):
  99.         if isinstance(uri, basestring):
  100.             uri = [
  101.                 uri]
  102.         
  103.         if realm not in self.passwd:
  104.             self.passwd[realm] = { }
  105.         
  106.         for default_port in (True, False):
  107.             reduced_uri = []([ self.reduce_uri(u, default_port) for u in uri ])
  108.             self.passwd[realm][reduced_uri] = (user, passwd)
  109.         
  110.  
  111.     
  112.     def find_user_password(self, realm, authuri):
  113.         domains = self.passwd.get(realm, { })
  114.         for default_port in (True, False):
  115.             reduced_authuri = self.reduce_uri(authuri, default_port)
  116.             for uris, authinfo in domains.iteritems():
  117.                 for uri in uris:
  118.                     if self.is_suburi(uri, reduced_authuri):
  119.                         return authinfo
  120.                 
  121.             
  122.         
  123.         return (None, None)
  124.  
  125.     
  126.     def reduce_uri(self, uri, default_port = True):
  127.         parts = urlparse.urlsplit(uri)
  128.         if parts[1]:
  129.             scheme = parts[0]
  130.             authority = parts[1]
  131.             if not parts[2]:
  132.                 pass
  133.             path = '/'
  134.         else:
  135.             scheme = None
  136.             authority = uri
  137.             path = '/'
  138.         (host, port) = splitport(authority)
  139.         if default_port and port is None and scheme is not None:
  140.             dport = {
  141.                 'http': 80,
  142.                 'https': 443 }.get(scheme)
  143.             if dport is not None:
  144.                 authority = '%s:%d' % (host, dport)
  145.             
  146.         
  147.         return (authority, path)
  148.  
  149.     
  150.     def is_suburi(self, base, test):
  151.         if base == test:
  152.             return True
  153.         if base[0] != test[0]:
  154.             return False
  155.         common = posixpath.commonprefix((base[1], test[1]))
  156.         if len(common) == len(base[1]):
  157.             return True
  158.         return False
  159.  
  160.  
  161.  
  162. class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
  163.     
  164.     def find_user_password(self, realm, authuri):
  165.         (user, password) = HTTPPasswordMgr.find_user_password(self, realm, authuri)
  166.         if user is not None:
  167.             return (user, password)
  168.         return HTTPPasswordMgr.find_user_password(self, None, authuri)
  169.  
  170.  
  171.  
  172. class AbstractBasicAuthHandler:
  173.     rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
  174.     
  175.     def __init__(self, password_mgr = None):
  176.         if password_mgr is None:
  177.             password_mgr = HTTPPasswordMgr()
  178.         
  179.         self.passwd = password_mgr
  180.         self.add_password = self.passwd.add_password
  181.  
  182.     
  183.     def http_error_auth_reqed(self, authreq, host, req, headers):
  184.         authreq = headers.get(authreq, None)
  185.         if authreq:
  186.             mo = AbstractBasicAuthHandler.rx.search(authreq)
  187.             if mo:
  188.                 (scheme, realm) = mo.groups()
  189.                 if scheme.lower() == 'basic':
  190.                     return self.retry_http_basic_auth(host, req, realm)
  191.             
  192.         
  193.  
  194.     
  195.     def retry_http_basic_auth(self, host, req, realm):
  196.         (user, pw) = self.passwd.find_user_password(realm, host)
  197.         if pw is not None:
  198.             raw = '%s:%s' % (user, pw)
  199.             auth = 'Basic %s' % base64.encodestring(raw).strip()
  200.             if req.headers.get(self.auth_header, None) == auth:
  201.                 return None
  202.             newreq = copy.copy(req)
  203.             newreq.add_header(self.auth_header, auth)
  204.             newreq.visit = False
  205.             return self.parent.open(newreq)
  206.         return None
  207.  
  208.  
  209.  
  210. class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  211.     auth_header = 'Authorization'
  212.     
  213.     def http_error_401(self, req, fp, code, msg, headers):
  214.         url = req.get_full_url()
  215.         return self.http_error_auth_reqed('www-authenticate', url, req, headers)
  216.  
  217.  
  218.  
  219. class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
  220.     auth_header = 'Proxy-authorization'
  221.     
  222.     def http_error_407(self, req, fp, code, msg, headers):
  223.         authority = req.get_host()
  224.         return self.http_error_auth_reqed('proxy-authenticate', authority, req, headers)
  225.  
  226.  
  227.  
  228. def randombytes(n):
  229.     if os.path.exists('/dev/urandom'):
  230.         f = open('/dev/urandom')
  231.         s = f.read(n)
  232.         f.close()
  233.         return s
  234.     L = [ chr(random.randrange(0, 256)) for i in range(n) ]
  235.     return ''.join(L)
  236.  
  237.  
  238. class AbstractDigestAuthHandler:
  239.     
  240.     def __init__(self, passwd = None):
  241.         if passwd is None:
  242.             passwd = HTTPPasswordMgr()
  243.         
  244.         self.passwd = passwd
  245.         self.add_password = self.passwd.add_password
  246.         self.retried = 0
  247.         self.nonce_count = 0
  248.  
  249.     
  250.     def reset_retry_count(self):
  251.         self.retried = 0
  252.  
  253.     
  254.     def http_error_auth_reqed(self, auth_header, host, req, headers):
  255.         authreq = headers.get(auth_header, None)
  256.         if self.retried > 5:
  257.             raise HTTPError(req.get_full_url(), 401, 'digest auth failed', headers, None)
  258.         self.retried > 5
  259.         self.retried += 1
  260.  
  261.     
  262.     def retry_http_digest_auth(self, req, auth):
  263.         (token, challenge) = auth.split(' ', 1)
  264.         chal = parse_keqv_list(parse_http_list(challenge))
  265.         auth = self.get_authorization(req, chal)
  266.         if auth:
  267.             auth_val = 'Digest %s' % auth
  268.             if req.headers.get(self.auth_header, None) == auth_val:
  269.                 return None
  270.             newreq = copy.copy(req)
  271.             newreq.add_unredirected_header(self.auth_header, auth_val)
  272.             newreq.visit = False
  273.             return self.parent.open(newreq)
  274.  
  275.     
  276.     def get_cnonce(self, nonce):
  277.         dig = sha1_digest('%s:%s:%s:%s' % (self.nonce_count, nonce, time.ctime(), randombytes(8)))
  278.         return dig[:16]
  279.  
  280.     
  281.     def get_authorization(self, req, chal):
  282.         
  283.         try:
  284.             realm = chal['realm']
  285.             nonce = chal['nonce']
  286.             qop = chal.get('qop')
  287.             algorithm = chal.get('algorithm', 'MD5')
  288.             opaque = chal.get('opaque', None)
  289.         except KeyError:
  290.             return None
  291.  
  292.         (H, KD) = self.get_algorithm_impls(algorithm)
  293.         if H is None:
  294.             return None
  295.         (user, pw) = self.passwd.find_user_password(realm, req.get_full_url())
  296.         if user is None:
  297.             return None
  298.         A1 = '%s:%s:%s' % (user, realm, pw)
  299.         A2 = '%s:%s' % (req.get_method(), req.get_selector())
  300.         if qop == 'auth':
  301.             self.nonce_count += 1
  302.             ncvalue = '%08x' % self.nonce_count
  303.             cnonce = self.get_cnonce(nonce)
  304.             noncebit = '%s:%s:%s:%s:%s' % (nonce, ncvalue, cnonce, qop, H(A2))
  305.             respdig = KD(H(A1), noncebit)
  306.         elif qop is None:
  307.             respdig = KD(H(A1), '%s:%s' % (nonce, H(A2)))
  308.         
  309.         base = 'username="%s", realm="%s", nonce="%s", uri="%s", response="%s"' % (user, realm, nonce, req.get_selector(), respdig)
  310.         if opaque:
  311.             base += ', opaque="%s"' % opaque
  312.         
  313.         if entdig:
  314.             base += ', digest="%s"' % entdig
  315.         
  316.         base += ', algorithm="%s"' % algorithm
  317.         if qop:
  318.             base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  319.         
  320.         return base
  321.  
  322.     
  323.     def get_algorithm_impls(self, algorithm):
  324.         if algorithm == 'MD5':
  325.             H = md5_digest
  326.         elif algorithm == 'SHA':
  327.             H = sha1_digest
  328.         
  329.         
  330.         KD = lambda s, d: H('%s:%s' % (s, d))
  331.         return (H, KD)
  332.  
  333.     
  334.     def get_entity_digest(self, data, chal):
  335.         pass
  336.  
  337.  
  338.  
  339. class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  340.     auth_header = 'Authorization'
  341.     handler_order = 490
  342.     
  343.     def http_error_401(self, req, fp, code, msg, headers):
  344.         host = urlparse.urlparse(req.get_full_url())[1]
  345.         retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  346.         self.reset_retry_count()
  347.         return retry
  348.  
  349.  
  350.  
  351. class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
  352.     auth_header = 'Proxy-Authorization'
  353.     handler_order = 490
  354.     
  355.     def http_error_407(self, req, fp, code, msg, headers):
  356.         host = req.get_host()
  357.         retry = self.http_error_auth_reqed('proxy-authenticate', host, req, headers)
  358.         self.reset_retry_count()
  359.         return retry
  360.  
  361.  
  362.  
  363. class HTTPProxyPasswordMgr(HTTPPasswordMgr):
  364.     
  365.     def add_password(self, realm, uri, user, passwd):
  366.         if uri is None or isinstance(uri, basestring):
  367.             uris = [
  368.                 uri]
  369.         else:
  370.             uris = uri
  371.         passwd_by_domain = self.passwd.setdefault(realm, { })
  372.         for uri in uris:
  373.             for default_port in (True, False):
  374.                 reduced_uri = self.reduce_uri(uri, default_port)
  375.                 passwd_by_domain[reduced_uri] = (user, passwd)
  376.             
  377.         
  378.  
  379.     
  380.     def find_user_password(self, realm, authuri):
  381.         attempts = [
  382.             (realm, authuri),
  383.             (None, authuri)]
  384.         for default_uri in (False, True):
  385.             for realm, authuri in attempts:
  386.                 authinfo_by_domain = self.passwd.get(realm, { })
  387.                 for default_port in (True, False):
  388.                     reduced_authuri = self.reduce_uri(authuri, default_port)
  389.                     for uri, authinfo in authinfo_by_domain.iteritems():
  390.                         if uri is None and not default_uri:
  391.                             continue
  392.                         
  393.                         if self.is_suburi(uri, reduced_authuri):
  394.                             return authinfo
  395.                     
  396.                     (user, password) = (None, None)
  397.                     if user is not None:
  398.                         break
  399.                         continue
  400.                     self.is_suburi(uri, reduced_authuri)
  401.                 
  402.             
  403.         
  404.         return (user, password)
  405.  
  406.     
  407.     def reduce_uri(self, uri, default_port = True):
  408.         if uri is None:
  409.             return None
  410.         return HTTPPasswordMgr.reduce_uri(self, uri, default_port)
  411.  
  412.     
  413.     def is_suburi(self, base, test):
  414.         if base is None:
  415.             (hostport, path) = test
  416.             base = (hostport, '/')
  417.         
  418.         return HTTPPasswordMgr.is_suburi(self, base, test)
  419.  
  420.  
  421.  
  422. class HTTPSClientCertMgr(HTTPPasswordMgr):
  423.     
  424.     def add_key_cert(self, uri, key_file, cert_file):
  425.         self.add_password(None, uri, key_file, cert_file)
  426.  
  427.     
  428.     def find_key_cert(self, authuri):
  429.         return HTTPPasswordMgr.find_user_password(self, None, authuri)
  430.  
  431.  
  432.