import urllib3
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 784b671 · Browse files · 5 files·+727 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+727 added−0 removed
- other:+727 added−0 removed
Provenance
- Commit
84434fd- Tree
3c806f5- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
784b671
5 files changed+727 added−0 removed
added:requests/packages/urllib3/contrib/__init__.py
added:requests/packages/urllib3/contrib/ntlmpool.py+111 added
1+"""2+NTLM authenticating pool, contributed by erikcederstran3+4+Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=105+"""6+7+import httplib8+from logging import getLogger9+from ntlm import ntlm10+11+from urllib3 import HTTPSConnectionPool12+13+14+log = getLogger(__name__)15+16+17+class NTLMConnectionPool(HTTPSConnectionPool):18+ """19+ Implements an NTLM authentication version of an urllib3 connection pool20+ """21+22+ scheme = 'https'23+24+ def __init__(self, user, pw, authurl, *args, **kwargs):25+ """26+ authurl is a random URL on the server that is protected by NTLM.27+ user is the Windows user, probably in the DOMAIN\username format.28+ pw is the password for the user.29+ """30+ super(NTLMConnectionPool, self).__init__(*args, **kwargs)31+ self.authurl = authurl32+ self.rawuser = user33+ user_parts = user.split('\\', 1)34+ self.domain = user_parts[0].upper()35+ self.user = user_parts[1]36+ self.pw = pw37+38+ def _new_conn(self):39+ # Performs the NTLM handshake that secures the connection. The socket40+ # must be kept open while requests are performed.41+ self.num_connections += 142+ log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' %43+ (self.num_connections, self.host, self.authurl))44+45+ headers = {}46+ headers['Connection'] = 'Keep-Alive'47+ req_header = 'Authorization'48+ resp_header = 'www-authenticate'49+50+ conn = httplib.HTTPSConnection(host=self.host, port=self.port)51+52+ # Send negotiation message53+ headers[req_header] = (54+ 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))55+ log.debug('Request headers: %s' % headers)56+ conn.request('GET', self.authurl, None, headers)57+ res = conn.getresponse()58+ reshdr = dict(res.getheaders())59+ log.debug('Response status: %s %s' % (res.status, res.reason))60+ log.debug('Response headers: %s' % reshdr)61+ log.debug('Response data: %s [...]' % res.read(100))62+63+ # Remove the reference to the socket, so that it can not be closed by64+ # the response object (we want to keep the socket open)65+ res.fp = None66+67+ # Server should respond with a challenge message68+ auth_header_values = reshdr[resp_header].split(', ')69+ auth_header_value = None70+ for s in auth_header_values:71+ if s[:5] == 'NTLM ':72+ auth_header_value = s[5:]73+ if auth_header_value is None:74+ raise Exception('Unexpected %s response header: %s' %75+ (resp_header, reshdr[resp_header]))76+77+ # Send authentication message78+ ServerChallenge, NegotiateFlags = \79+ ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)80+ auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,81+ self.user,82+ self.domain,83+ self.pw,84+ NegotiateFlags)85+ headers[req_header] = 'NTLM %s' % auth_msg86+ log.debug('Request headers: %s' % headers)87+ conn.request('GET', self.authurl, None, headers)88+ res = conn.getresponse()89+ log.debug('Response status: %s %s' % (res.status, res.reason))90+ log.debug('Response headers: %s' % dict(res.getheaders()))91+ log.debug('Response data: %s [...]' % res.read()[:100])92+ if res.status != 200:93+ if res.status == 401:94+ raise Exception('Server rejected request: wrong '95+ 'username or password')96+ raise Exception('Wrong server response: %s %s' %97+ (res.status, res.reason))98+99+ res.fp = None100+ log.debug('Connection established')101+ return conn102+103+ def urlopen(self, method, url, body=None, headers=None, retries=3,104+ redirect=True, assert_same_host=True):105+ if headers is None:106+ headers = {}107+ headers['Connection'] = 'Keep-Alive'108+ return super(NTLMConnectionPool, self).urlopen(method, url, body,109+ headers, retries,110+ redirect,111+ assert_same_host)added:requests/packages/urllib3/__init__.py+22 added
1+"""2+urllib3 - Thread-safe connection pooling and re-using.3+"""4+5+from connectionpool import (6+ connection_from_url,7+ get_host,8+ HTTPConnectionPool,9+ HTTPSConnectionPool,10+ make_headers)11+# Possible exceptions12+from connectionpool import (13+ HTTPError,14+ MaxRetryError,15+ SSLError,16+ TimeoutError)17+from filepost import encode_multipart_formdata18+19+20+__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"21+__license__ = "MIT"22+__version__ = "$Rev$"added:requests/packages/urllib3/connectionpool.py+544 added
1+import gzip2+import zlib3+import logging4+import socket5+6+7+from urllib import urlencode8+from httplib import HTTPConnection, HTTPSConnection, HTTPException9+from Queue import Queue, Empty, Full10+from select import select11+from socket import error as SocketError, timeout as SocketTimeout12+13+14+try:15+ import ssl16+ BaseSSLError = ssl.SSLError17+except ImportError, e:18+ ssl = None19+ BaseSSLError = None20+21+try:22+ from cStringIO import StringIO23+except ImportError, e:24+ from StringIO import StringIO25+26+27+from filepost import encode_multipart_formdata28+29+30+log = logging.getLogger(__name__)31+32+33+## Exceptions34+35+class HTTPError(Exception):36+ "Base exception used by this module."37+ pass38+39+40+class SSLError(Exception):41+ "Raised when SSL certificate fails in an HTTPS connection."42+ pass43+44+45+class MaxRetryError(HTTPError):46+ "Raised when the maximum number of retries is exceeded."47+ pass48+49+50+class TimeoutError(HTTPError):51+ "Raised when a socket timeout occurs."52+ pass53+54+55+class HostChangedError(HTTPError):56+ "Raised when an existing pool gets a request for a foreign host."57+ pass58+59+60+## Response objects61+62+class HTTPResponse(object):63+ """64+ HTTP Response container.65+66+ Similar to httplib's HTTPResponse but the data is pre-loaded.67+ """68+69+ def __init__(self, data='', headers=None, status=0, version=0, reason=None,70+ strict=0):71+ self.data = data72+ self.headers = headers or {}73+ self.status = status74+ self.version = version75+ self.reason = reason76+ self.strict = strict77+78+ @staticmethod79+ def from_httplib(r):80+ """81+ Given an httplib.HTTPResponse instance, return a corresponding82+ urllib3.HTTPResponse object.83+84+ NOTE: This method will perform r.read() which will have side effects85+ on the original http.HTTPResponse object.86+ """87+ tmp_data = r.read()88+ try:89+ if r.getheader('content-encoding') == 'gzip':90+ log.debug("Received response with content-encoding: gzip, "91+ "decompressing with gzip.")92+93+ gzipper = gzip.GzipFile(fileobj=StringIO(tmp_data))94+ data = gzipper.read()95+ elif r.getheader('content-encoding') == 'deflate':96+ log.debug("Received response with content-encoding: deflate, "97+ "decompressing with zlib.")98+ try:99+ data = zlib.decompress(tmp_data)100+ except zlib.error, e:101+ data = zlib.decompress(tmp_data, -zlib.MAX_WBITS)102+ else:103+ data = tmp_data104+105+ except IOError:106+ raise HTTPError("Received response with content-encoding: %s, "107+ "but failed to decompress it." %108+ (r.getheader('content-encoding')))109+110+ return HTTPResponse(data=data,111+ headers=dict(r.getheaders()),112+ status=r.status,113+ version=r.version,114+ reason=r.reason,115+ strict=r.strict)116+117+ # Backwards-compatibility methods for httplib.HTTPResponse118+ def getheaders(self):119+ return self.headers120+121+ def getheader(self, name, default=None):122+ return self.headers.get(name, default)123+124+125+## Connection objects126+127+class VerifiedHTTPSConnection(HTTPSConnection):128+ """129+ Based on httplib.HTTPSConnection but wraps the socket with130+ SSL certification.131+ """132+133+ def set_cert(self, key_file=None, cert_file=None, cert_reqs='CERT_NONE',134+ ca_certs=None):135+ ssl_req_scheme = {136+ 'CERT_NONE': ssl.CERT_NONE,137+ 'CERT_OPTIONAL': ssl.CERT_OPTIONAL,138+ 'CERT_REQUIRED': ssl.CERT_REQUIRED139+ }140+141+ self.key_file = key_file142+ self.cert_file = cert_file143+ self.cert_reqs = ssl_req_scheme.get(cert_reqs) or ssl.CERT_NONE144+ self.ca_certs = ca_certs145+146+ def connect(self):147+ # Add certificate verification148+ sock = socket.create_connection((self.host, self.port), self.timeout)149+150+ # Wrap socket using verification with the root certs in151+ # trusted_root_certs152+ self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,153+ cert_reqs=self.cert_reqs,154+ ca_certs=self.ca_certs)155+156+157+## Pool objects158+159+class HTTPConnectionPool(object):160+ """161+ Thread-safe connection pool for one host.162+163+ host164+ Host used for this HTTP Connection (e.g. "localhost"), passed into165+ httplib.HTTPConnection()166+167+ port168+ Port used for this HTTP Connection (None is equivalent to 80), passed169+ into httplib.HTTPConnection()170+171+ strict172+ Causes BadStatusLine to be raised if the status line can't be parsed173+ as a valid HTTP/1.0 or 1.1 status line, passed into174+ httplib.HTTPConnection()175+176+ timeout177+ Socket timeout for each individual connection, can be a float. None178+ disables timeout.179+180+ maxsize181+ Number of connections to save that can be reused. More than 1 is useful182+ in multithreaded situations. If ``block`` is set to false, more183+ connections will be created but they will not be saved once they've184+ been used.185+186+ block187+ If set to True, no more than ``maxsize`` connections will be used at188+ a time. When no free connections are available, the call will block189+ until a connection has been released. This is a useful side effect for190+ particular multithreaded situations where one does not want to use more191+ than maxsize connections per host to prevent flooding.192+193+ headers194+ Headers to include with all requests, unless other headers are given195+ explicitly.196+ """197+198+ scheme = 'http'199+200+ def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,201+ block=False, headers=None):202+ self.host = host203+ self.port = port204+ self.strict = strict205+ self.timeout = timeout206+ self.pool = Queue(maxsize)207+ self.block = block208+ self.headers = headers or {}209+210+ # Fill the queue up so that doing get() on it will block properly211+ [self.pool.put(None) for i in xrange(maxsize)]212+213+ self.num_connections = 0214+ self.num_requests = 0215+216+ def _new_conn(self):217+ """218+ Return a fresh HTTPConnection.219+ """220+ self.num_connections += 1221+ log.info("Starting new HTTP connection (%d): %s" %222+ (self.num_connections, self.host))223+ return HTTPConnection(host=self.host, port=self.port)224+225+ def _get_conn(self, timeout=None):226+ """227+ Get a connection. Will return a pooled connection if one is available.228+ Otherwise, a fresh connection is returned.229+ """230+ conn = None231+ try:232+ conn = self.pool.get(block=self.block, timeout=timeout)233+234+ # If this is a persistent connection, check if it got disconnected235+ if conn and conn.sock and select([conn.sock], [], [], 0.0)[0]:236+ # Either data is buffered (bad), or the connection is dropped.237+ log.warning("Connection pool detected dropped "238+ "connection, resetting: %s" % self.host)239+ conn.close()240+241+ except Empty, e:242+ pass # Oh well, we'll create a new connection then243+244+ return conn or self._new_conn()245+246+ def _put_conn(self, conn):247+ """248+ Put a connection back into the pool.249+ If the pool is already full, the connection is discarded because we250+ exceeded maxsize. If connections are discarded frequently, then maxsize251+ should be increased.252+ """253+ try:254+ self.pool.put(conn, block=False)255+ except Full, e:256+ # This should never happen if self.block == True257+ log.warning("HttpConnectionPool is full, discarding connection: %s"258+ % self.host)259+260+ def is_same_host(self, url):261+ return (url.startswith('/') or262+ get_host(url) == (self.scheme, self.host, self.port))263+264+ def urlopen(self, method, url, body=None, headers=None, retries=3,265+ redirect=True, assert_same_host=True):266+ """267+ Get a connection from the pool and perform an HTTP request.268+269+ method270+ HTTP request method (such as GET, POST, PUT, etc.)271+272+ body273+ Data to send in the request body (useful for creating274+ POST requests, see HTTPConnectionPool.post_url for275+ more convenience).276+277+ headers278+ Dictionary of custom headers to send, such as User-Agent,279+ If-None-Match, etc. If None, pool headers are used. If provided,280+ these headers completely replace any pool-specific headers.281+282+ retries283+ Number of retries to allow before raising284+ a MaxRetryError exception.285+286+ redirect287+ Automatically handle redirects (status codes 301, 302, 303, 307),288+ each redirect counts as a retry.289+290+ assert_same_host291+ If True, will make sure that the host of the pool requests is292+ consistent else will raise HostChangedError. When False, you can293+ use the pool on an HTTP proxy and request foreign hosts.294+ """295+ if headers == None:296+ headers = self.headers297+298+ if retries < 0:299+ raise MaxRetryError("Max retries exceeded for url: %s" % url)300+301+ # Check host302+ if assert_same_host and not self.is_same_host(url):303+ host = "%s://%s" % (self.scheme, self.host)304+ if self.port:305+ host = "%s:%d" % (host, self.port)306+307+ raise HostChangedError("Connection pool with host '%s' tried to "308+ "open a foreign host: %s" % (host, url))309+310+ try:311+ # Request a connection from the queue312+ conn = self._get_conn()313+314+ # Make the request315+ self.num_requests += 1316+ conn.request(method, url, body=body, headers=headers)317+ conn.sock.settimeout(self.timeout)318+ httplib_response = conn.getresponse()319+ log.debug("\"%s %s %s\" %s %s" %320+ (method, url, conn._http_vsn_str,321+ httplib_response.status, httplib_response.length))322+323+ # from_httplib will perform httplib_response.read() which will have324+ # the side effect of letting us use this connection for another325+ # request.326+ response = HTTPResponse.from_httplib(httplib_response)327+328+ # Put the connection back to be reused329+ self._put_conn(conn)330+331+ except (SocketTimeout, Empty), e:332+ # Timed out either by socket or queue333+ raise TimeoutError("Request timed out after %f seconds" %334+ self.timeout)335+336+ except (BaseSSLError), e:337+ # SSL certificate error338+ raise SSLError(e)339+340+ except (HTTPException, SocketError), e:341+ log.warn("Retrying (%d attempts remain) after connection "342+ "broken by '%r': %s" % (retries, e, url))343+ return self.urlopen(method, url, body, headers, retries - 1,344+ redirect, assert_same_host) # Try again345+346+ # Handle redirection347+ if (redirect and348+ response.status in [301, 302, 303, 307] and349+ 'location' in response.headers): # Redirect, retry350+ log.info("Redirecting %s -> %s" %351+ (url, response.headers.get('location')))352+ return self.urlopen(method, response.headers.get('location'), body,353+ headers, retries - 1, redirect,354+ assert_same_host)355+356+ return response357+358+ def get_url(self, url, fields=None, headers=None, retries=3,359+ redirect=True):360+ """361+ Wrapper for performing GET with urlopen (see urlopen for more details).362+363+ Supports an optional ``fields`` dictionary parameter key/value strings.364+ If provided, they will be added to the url.365+ """366+ if fields:367+ url += '?' + urlencode(fields)368+ return self.urlopen('GET', url, headers=headers, retries=retries,369+ redirect=redirect)370+371+ def post_url(self, url, fields=None, headers=None, retries=3,372+ redirect=True, encode_multipart=True):373+ """374+ Wrapper for performing POST with urlopen (see urlopen375+ for more details).376+377+ Supports an optional ``fields`` parameter of key/value strings AND378+ key/filetuple. A filetuple is a (filename, data) tuple. For example:379+380+ fields = {381+ 'foo': 'bar',382+ 'foofile': ('foofile.txt', 'contents of foofile'),383+ }384+385+ If encode_multipart=True (default), then386+ ``urllib3.filepost.encode_multipart_formdata`` is used to encode the387+ payload with the appropriate content type. Otherwise388+ ``urllib.urlencode`` is used with 'application/x-www-form-urlencoded'389+ content type.390+391+ Multipart encoding must be used when posting files, and it's reasonably392+ safe to use it other times too. It may break request signing, such as393+ OAuth.394+395+ NOTE: If ``headers`` are supplied, the 'Content-Type' value will be396+ overwritten because it depends on the dynamic random boundary string397+ which is used to compose the body of the request.398+ """399+ if encode_multipart:400+ body, content_type = encode_multipart_formdata(fields or {})401+ else:402+ body, content_type = (403+ urlencode(fields or {}),404+ 'application/x-www-form-urlencoded')405+406+ headers = headers or {}407+ headers.update({'Content-Type': content_type})408+409+ return self.urlopen('POST', url, body, headers=headers,410+ retries=retries, redirect=redirect)411+412+413+class HTTPSConnectionPool(HTTPConnectionPool):414+ """415+ Same as HTTPConnectionPool, but HTTPS.416+ """417+418+ scheme = 'https'419+420+ def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,421+ block=False, headers=None, key_file=None,422+ cert_file=None, cert_reqs='CERT_NONE', ca_certs=None):423+ self.host = host424+ self.port = port425+ self.strict = strict426+ self.timeout = timeout427+ self.pool = Queue(maxsize)428+ self.block = block429+ self.headers = headers or {}430+431+ self.key_file = key_file432+ self.cert_file = cert_file433+ self.cert_reqs = cert_reqs434+ self.ca_certs = ca_certs435+436+ # Fill the queue up so that doing get() on it will block properly437+ [self.pool.put(None) for i in xrange(maxsize)]438+439+ self.num_connections = 0440+ self.num_requests = 0441+442+ def _new_conn(self):443+ """444+ Return a fresh HTTPSConnection.445+ """446+ self.num_connections += 1447+ log.info("Starting new HTTPS connection (%d): %s"448+ % (self.num_connections, self.host))449+450+ if not ssl:451+ return HTTPSConnection(host=self.host, port=self.port)452+453+ connection = VerifiedHTTPSConnection(host=self.host, port=self.port)454+ connection.set_cert(key_file=self.key_file, cert_file=self.cert_file,455+ cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)456+ return connection457+458+459+## Helpers460+461+def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,462+ basic_auth=None):463+ """464+ Shortcuts for generating request headers.465+466+ keep_alive467+ If true, adds 'connection: keep-alive' header.468+469+ accept_encoding470+ Can be a boolean, list, or string.471+ True translates to 'gzip,deflate'.472+ List will get joined by comma.473+ String will be used as provided.474+475+ user_agent476+ String representing the user-agent you want, such as477+ "python-urllib3/0.6"478+479+ basic_auth480+ Colon-separated username:password string for 'authorization: basic ...'481+ auth header.482+ """483+ headers = {}484+ if accept_encoding:485+ if isinstance(accept_encoding, str):486+ pass487+ elif isinstance(accept_encoding, list):488+ accept_encoding = ','.join(accept_encoding)489+ else:490+ accept_encoding = 'gzip,deflate'491+ headers['accept-encoding'] = accept_encoding492+493+ if user_agent:494+ headers['user-agent'] = user_agent495+496+ if keep_alive:497+ headers['connection'] = 'keep-alive'498+499+ if basic_auth:500+ headers['authorization'] = 'Basic ' + \501+ basic_auth.encode('base64').strip()502+503+ return headers504+505+506+def get_host(url):507+ """508+ Given a url, return its scheme, host and port (None if it's not there).509+510+ For example:511+ >>> get_host('http://google.com/mail/')512+ http, google.com, None513+ >>> get_host('google.com:80')514+ http, google.com, 80515+ """516+ # This code is actually similar to urlparse.urlsplit, but much517+ # simplified for our needs.518+ port = None519+ scheme = 'http'520+ if '//' in url:521+ scheme, url = url.split('://', 1)522+ if '/' in url:523+ url, path = url.split('/', 1)524+ if ':' in url:525+ url, port = url.split(':', 1)526+ port = int(port)527+ return scheme, url, port528+529+530+def connection_from_url(url, **kw):531+ """532+ Given a url, return an HTTP(S)ConnectionPool instance of its host.533+534+ This is a shortcut for not having to determine the host of the url535+ before creating an HTTP(S)ConnectionPool instance.536+537+ Passes on whatever kw arguments to the constructor of538+ HTTP(S)ConnectionPool. (e.g. timeout, maxsize, block)539+ """540+ scheme, host, port = get_host(url)541+ if scheme == 'https':542+ return HTTPSConnectionPool(host, port=port, **kw)543+ else:544+ return HTTPConnectionPool(host, port=port, **kw)added:requests/packages/urllib3/filepost.py+50 added
1+import codecs2+import mimetools3+import mimetypes4+try:5+ from cStringIO import StringIO6+except:7+ from StringIO import StringIO8+9+10+writer = codecs.lookup('utf-8')[3]11+12+13+def get_content_type(filename):14+ return mimetypes.guess_type(filename)[0] or 'application/octet-stream'15+16+17+def encode_multipart_formdata(fields):18+ body = StringIO()19+ BOUNDARY = mimetools.choose_boundary()20+21+ for fieldname, value in fields.iteritems():22+ body.write('--%s\r\n' % (BOUNDARY))23+24+ if isinstance(value, tuple):25+ filename, data = value26+ writer(body).write('Content-Disposition: form-data; name="%s"; '27+ 'filename="%s"\r\n' % (fieldname, filename))28+ body.write('Content-Type: %s\r\n\r\n' %29+ (get_content_type(filename)))30+ else:31+ data = value32+ writer(body).write('Content-Disposition: form-data; name="%s"\r\n'33+ % (fieldname))34+ body.write('Content-Type: text/plain\r\n\r\n')35+36+ if isinstance(data, int):37+ data = str(data) # Backwards compatibility38+39+ if isinstance(data, unicode):40+ writer(body).write(data)41+ else:42+ body.write(data)43+44+ body.write('\r\n')45+46+ body.write('--%s--\r\n' % (BOUNDARY))47+48+ content_type = 'multipart/form-data; boundary=%s' % BOUNDARY49+50+ return body.getvalue(), content_type