home *** CD-ROM | disk | FTP | other *** search
- # Source Generated with Decompyle++
- # File: in.pyc (Python 2.6)
-
- import base64
- import copy
- import os
- import posixpath
- import random
- import re
- import time
- import urlparse
-
- try:
- import hashlib
- except ImportError:
- import md5
- import sha
-
- def sha1_digest(bytes):
- return sha.new(bytes).hexdigest()
-
-
- def md5_digest(bytes):
- return md5.new(bytes).hexdigest()
-
-
-
- def sha1_digest(bytes):
- return hashlib.sha1(bytes).hexdigest()
-
-
- def md5_digest(bytes):
- return hashlib.md5(bytes).hexdigest()
-
- from urllib2 import BaseHandler, HTTPError, parse_keqv_list, parse_http_list
- from urllib import getproxies, unquote, splittype, splituser, splitpasswd, splitport
-
- def _parse_proxy(proxy):
- (scheme, r_scheme) = splittype(proxy)
- if not r_scheme.startswith('/'):
- scheme = None
- authority = proxy
- elif not r_scheme.startswith('//'):
- raise ValueError('proxy URL with no authority: %r' % proxy)
-
- end = r_scheme.find('/', 2)
- if end == -1:
- end = None
-
- authority = r_scheme[2:end]
- (userinfo, hostport) = splituser(authority)
- if userinfo is not None:
- (user, password) = splitpasswd(userinfo)
- else:
- user = None
- password = None
- return (scheme, user, password, hostport)
-
-
- class ProxyHandler(BaseHandler):
- handler_order = 100
-
- def __init__(self, proxies = None):
- if proxies is None:
- proxies = getproxies()
-
- self.proxies = proxies
- for type, url in proxies.items():
- setattr(self, '%s_open' % type, (lambda r, proxy = url, type = type, meth = self.proxy_open: meth(r, proxy, type)))
-
-
-
- def proxy_open(self, req, proxy, type):
- orig_type = req.get_type()
- (proxy_type, user, password, hostport) = _parse_proxy(proxy)
- if proxy_type is None:
- proxy_type = orig_type
-
- if user and password:
- user_pass = '%s:%s' % (unquote(user), unquote(password))
- creds = base64.encodestring(user_pass).strip()
- req.add_header('Proxy-authorization', 'Basic ' + creds)
-
- hostport = unquote(hostport)
- req.set_proxy(hostport, proxy_type)
- if orig_type == proxy_type:
- return None
- return self.parent.open(req)
-
-
-
- class HTTPPasswordMgr:
-
- def __init__(self):
- self.passwd = { }
-
-
- def add_password(self, realm, uri, user, passwd):
- if isinstance(uri, basestring):
- uri = [
- uri]
-
- if realm not in self.passwd:
- self.passwd[realm] = { }
-
- for default_port in (True, False):
- reduced_uri = []([ self.reduce_uri(u, default_port) for u in uri ])
- self.passwd[realm][reduced_uri] = (user, passwd)
-
-
-
- def find_user_password(self, realm, authuri):
- domains = self.passwd.get(realm, { })
- for default_port in (True, False):
- reduced_authuri = self.reduce_uri(authuri, default_port)
- for uris, authinfo in domains.iteritems():
- for uri in uris:
- if self.is_suburi(uri, reduced_authuri):
- return authinfo
-
-
-
- return (None, None)
-
-
- def reduce_uri(self, uri, default_port = True):
- parts = urlparse.urlsplit(uri)
- if parts[1]:
- scheme = parts[0]
- authority = parts[1]
- if not parts[2]:
- pass
- path = '/'
- else:
- scheme = None
- authority = uri
- path = '/'
- (host, port) = splitport(authority)
- if default_port and port is None and scheme is not None:
- dport = {
- 'http': 80,
- 'https': 443 }.get(scheme)
- if dport is not None:
- authority = '%s:%d' % (host, dport)
-
-
- return (authority, path)
-
-
- def is_suburi(self, base, test):
- if base == test:
- return True
- if base[0] != test[0]:
- return False
- common = posixpath.commonprefix((base[1], test[1]))
- if len(common) == len(base[1]):
- return True
- return False
-
-
-
- class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):
-
- def find_user_password(self, realm, authuri):
- (user, password) = HTTPPasswordMgr.find_user_password(self, realm, authuri)
- if user is not None:
- return (user, password)
- return HTTPPasswordMgr.find_user_password(self, None, authuri)
-
-
-
- class AbstractBasicAuthHandler:
- rx = re.compile('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', re.I)
-
- def __init__(self, password_mgr = None):
- if password_mgr is None:
- password_mgr = HTTPPasswordMgr()
-
- self.passwd = password_mgr
- self.add_password = self.passwd.add_password
-
-
- def http_error_auth_reqed(self, authreq, host, req, headers):
- authreq = headers.get(authreq, None)
- if authreq:
- mo = AbstractBasicAuthHandler.rx.search(authreq)
- if mo:
- (scheme, realm) = mo.groups()
- if scheme.lower() == 'basic':
- return self.retry_http_basic_auth(host, req, realm)
-
-
-
-
- def retry_http_basic_auth(self, host, req, realm):
- (user, pw) = self.passwd.find_user_password(realm, host)
- if pw is not None:
- raw = '%s:%s' % (user, pw)
- auth = 'Basic %s' % base64.encodestring(raw).strip()
- if req.headers.get(self.auth_header, None) == auth:
- return None
- newreq = copy.copy(req)
- newreq.add_header(self.auth_header, auth)
- newreq.visit = False
- return self.parent.open(newreq)
- return None
-
-
-
- class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
- auth_header = 'Authorization'
-
- def http_error_401(self, req, fp, code, msg, headers):
- url = req.get_full_url()
- return self.http_error_auth_reqed('www-authenticate', url, req, headers)
-
-
-
- class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):
- auth_header = 'Proxy-authorization'
-
- def http_error_407(self, req, fp, code, msg, headers):
- authority = req.get_host()
- return self.http_error_auth_reqed('proxy-authenticate', authority, req, headers)
-
-
-
- def randombytes(n):
- if os.path.exists('/dev/urandom'):
- f = open('/dev/urandom')
- s = f.read(n)
- f.close()
- return s
- L = [ chr(random.randrange(0, 256)) for i in range(n) ]
- return ''.join(L)
-
-
- class AbstractDigestAuthHandler:
-
- def __init__(self, passwd = None):
- if passwd is None:
- passwd = HTTPPasswordMgr()
-
- self.passwd = passwd
- self.add_password = self.passwd.add_password
- self.retried = 0
- self.nonce_count = 0
-
-
- def reset_retry_count(self):
- self.retried = 0
-
-
- def http_error_auth_reqed(self, auth_header, host, req, headers):
- authreq = headers.get(auth_header, None)
- if self.retried > 5:
- raise HTTPError(req.get_full_url(), 401, 'digest auth failed', headers, None)
- self.retried > 5
- self.retried += 1
-
-
- def retry_http_digest_auth(self, req, auth):
- (token, challenge) = auth.split(' ', 1)
- chal = parse_keqv_list(parse_http_list(challenge))
- auth = self.get_authorization(req, chal)
- if auth:
- auth_val = 'Digest %s' % auth
- if req.headers.get(self.auth_header, None) == auth_val:
- return None
- newreq = copy.copy(req)
- newreq.add_unredirected_header(self.auth_header, auth_val)
- newreq.visit = False
- return self.parent.open(newreq)
-
-
- def get_cnonce(self, nonce):
- dig = sha1_digest('%s:%s:%s:%s' % (self.nonce_count, nonce, time.ctime(), randombytes(8)))
- return dig[:16]
-
-
- def get_authorization(self, req, chal):
-
- try:
- realm = chal['realm']
- nonce = chal['nonce']
- qop = chal.get('qop')
- algorithm = chal.get('algorithm', 'MD5')
- opaque = chal.get('opaque', None)
- except KeyError:
- return None
-
- (H, KD) = self.get_algorithm_impls(algorithm)
- if H is None:
- return None
- (user, pw) = self.passwd.find_user_password(realm, req.get_full_url())
- if user is None:
- return None
- A1 = '%s:%s:%s' % (user, realm, pw)
- A2 = '%s:%s' % (req.get_method(), req.get_selector())
- if qop == 'auth':
- self.nonce_count += 1
- ncvalue = '%08x' % self.nonce_count
- cnonce = self.get_cnonce(nonce)
- noncebit = '%s:%s:%s:%s:%s' % (nonce, ncvalue, cnonce, qop, H(A2))
- respdig = KD(H(A1), noncebit)
- elif qop is None:
- respdig = KD(H(A1), '%s:%s' % (nonce, H(A2)))
-
- base = 'username="%s", realm="%s", nonce="%s", uri="%s", response="%s"' % (user, realm, nonce, req.get_selector(), respdig)
- if opaque:
- base += ', opaque="%s"' % opaque
-
- if entdig:
- base += ', digest="%s"' % entdig
-
- base += ', algorithm="%s"' % algorithm
- if qop:
- base += ', qop=auth, nc=%s, cnonce="%s"' % (ncvalue, cnonce)
-
- return base
-
-
- def get_algorithm_impls(self, algorithm):
- if algorithm == 'MD5':
- H = md5_digest
- elif algorithm == 'SHA':
- H = sha1_digest
-
-
- KD = lambda s, d: H('%s:%s' % (s, d))
- return (H, KD)
-
-
- def get_entity_digest(self, data, chal):
- pass
-
-
-
- class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
- auth_header = 'Authorization'
- handler_order = 490
-
- def http_error_401(self, req, fp, code, msg, headers):
- host = urlparse.urlparse(req.get_full_url())[1]
- retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
- self.reset_retry_count()
- return retry
-
-
-
- class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):
- auth_header = 'Proxy-Authorization'
- handler_order = 490
-
- def http_error_407(self, req, fp, code, msg, headers):
- host = req.get_host()
- retry = self.http_error_auth_reqed('proxy-authenticate', host, req, headers)
- self.reset_retry_count()
- return retry
-
-
-
- class HTTPProxyPasswordMgr(HTTPPasswordMgr):
-
- def add_password(self, realm, uri, user, passwd):
- if uri is None or isinstance(uri, basestring):
- uris = [
- uri]
- else:
- uris = uri
- passwd_by_domain = self.passwd.setdefault(realm, { })
- for uri in uris:
- for default_port in (True, False):
- reduced_uri = self.reduce_uri(uri, default_port)
- passwd_by_domain[reduced_uri] = (user, passwd)
-
-
-
-
- def find_user_password(self, realm, authuri):
- attempts = [
- (realm, authuri),
- (None, authuri)]
- for default_uri in (False, True):
- for realm, authuri in attempts:
- authinfo_by_domain = self.passwd.get(realm, { })
- for default_port in (True, False):
- reduced_authuri = self.reduce_uri(authuri, default_port)
- for uri, authinfo in authinfo_by_domain.iteritems():
- if uri is None and not default_uri:
- continue
-
- if self.is_suburi(uri, reduced_authuri):
- return authinfo
-
- (user, password) = (None, None)
- if user is not None:
- break
- continue
- self.is_suburi(uri, reduced_authuri)
-
-
-
- return (user, password)
-
-
- def reduce_uri(self, uri, default_port = True):
- if uri is None:
- return None
- return HTTPPasswordMgr.reduce_uri(self, uri, default_port)
-
-
- def is_suburi(self, base, test):
- if base is None:
- (hostport, path) = test
- base = (hostport, '/')
-
- return HTTPPasswordMgr.is_suburi(self, base, test)
-
-
-
- class HTTPSClientCertMgr(HTTPPasswordMgr):
-
- def add_key_cert(self, uri, key_file, cert_file):
- self.add_password(None, uri, key_file, cert_file)
-
-
- def find_key_cert(self, authuri):
- return HTTPPasswordMgr.find_user_password(self, None, authuri)
-
-
-