Skip to content
Myr

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

5 files+727 added−0 removed

added:requests/packages/urllib3/contrib/__init__.py
added:requests/packages/urllib3/contrib/ntlmpool.py+111 added
1"""2NTLM authenticating pool, contributed by erikcederstran34Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=105"""67import httplib8from logging import getLogger9from ntlm import ntlm1011from urllib3 import HTTPSConnectionPool121314log = getLogger(__name__)151617class NTLMConnectionPool(HTTPSConnectionPool):18 """19 Implements an NTLM authentication version of an urllib3 connection pool20 """2122 scheme = 'https'2324 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 = pw3738 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))4445 headers = {}46 headers['Connection'] = 'Keep-Alive'47 req_header = 'Authorization'48 resp_header = 'www-authenticate'4950 conn = httplib.HTTPSConnection(host=self.host, port=self.port)5152 # 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))6263 # 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 = None6667 # 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]))7677 # 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))9899 res.fp = None100 log.debug('Connection established')101 return conn102103 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"""2urllib3 - Thread-safe connection pooling and re-using.3"""45from connectionpool import (6 connection_from_url,7 get_host,8 HTTPConnectionPool,9 HTTPSConnectionPool,10 make_headers)11# Possible exceptions12from connectionpool import (13 HTTPError,14 MaxRetryError,15 SSLError,16 TimeoutError)17from filepost import encode_multipart_formdata181920__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"21__license__ = "MIT"22__version__ = "$Rev$"
added:requests/packages/urllib3/connectionpool.py+544 added
1import gzip2import zlib3import logging4import socket567from urllib import urlencode8from httplib import HTTPConnection, HTTPSConnection, HTTPException9from Queue import Queue, Empty, Full10from select import select11from socket import error as SocketError, timeout as SocketTimeout121314try:15 import ssl16 BaseSSLError = ssl.SSLError17except ImportError, e:18 ssl = None19 BaseSSLError = None2021try:22 from cStringIO import StringIO23except ImportError, e:24 from StringIO import StringIO252627from filepost import encode_multipart_formdata282930log = logging.getLogger(__name__)313233## Exceptions3435class HTTPError(Exception):36 "Base exception used by this module."37 pass383940class SSLError(Exception):41 "Raised when SSL certificate fails in an HTTPS connection."42 pass434445class MaxRetryError(HTTPError):46 "Raised when the maximum number of retries is exceeded."47 pass484950class TimeoutError(HTTPError):51 "Raised when a socket timeout occurs."52 pass535455class HostChangedError(HTTPError):56 "Raised when an existing pool gets a request for a foreign host."57 pass585960## Response objects6162class HTTPResponse(object):63 """64 HTTP Response container.6566 Similar to httplib's HTTPResponse but the data is pre-loaded.67 """6869 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 = strict7778 @staticmethod79 def from_httplib(r):80 """81 Given an httplib.HTTPResponse instance, return a corresponding82 urllib3.HTTPResponse object.8384 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.")9293 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_data104105 except IOError:106 raise HTTPError("Received response with content-encoding: %s, "107 "but failed to decompress it." %108 (r.getheader('content-encoding')))109110 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)116117 # Backwards-compatibility methods for httplib.HTTPResponse118 def getheaders(self):119 return self.headers120121 def getheader(self, name, default=None):122 return self.headers.get(name, default)123124125## Connection objects126127class VerifiedHTTPSConnection(HTTPSConnection):128 """129 Based on httplib.HTTPSConnection but wraps the socket with130 SSL certification.131 """132133 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 }140141 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_certs145146 def connect(self):147 # Add certificate verification148 sock = socket.create_connection((self.host, self.port), self.timeout)149150 # 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)155156157## Pool objects158159class HTTPConnectionPool(object):160 """161 Thread-safe connection pool for one host.162163 host164 Host used for this HTTP Connection (e.g. "localhost"), passed into165 httplib.HTTPConnection()166167 port168 Port used for this HTTP Connection (None is equivalent to 80), passed169 into httplib.HTTPConnection()170171 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()175176 timeout177 Socket timeout for each individual connection, can be a float. None178 disables timeout.179180 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.185186 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.192193 headers194 Headers to include with all requests, unless other headers are given195 explicitly.196 """197198 scheme = 'http'199200 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 {}209210 # Fill the queue up so that doing get() on it will block properly211 [self.pool.put(None) for i in xrange(maxsize)]212213 self.num_connections = 0214 self.num_requests = 0215216 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)224225 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)233234 # 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()240241 except Empty, e:242 pass # Oh well, we'll create a new connection then243244 return conn or self._new_conn()245246 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)259260 def is_same_host(self, url):261 return (url.startswith('/') or262 get_host(url) == (self.scheme, self.host, self.port))263264 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.268269 method270 HTTP request method (such as GET, POST, PUT, etc.)271272 body273 Data to send in the request body (useful for creating274 POST requests, see HTTPConnectionPool.post_url for275 more convenience).276277 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.281282 retries283 Number of retries to allow before raising284 a MaxRetryError exception.285286 redirect287 Automatically handle redirects (status codes 301, 302, 303, 307),288 each redirect counts as a retry.289290 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.headers297298 if retries < 0:299 raise MaxRetryError("Max retries exceeded for url: %s" % url)300301 # 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)306307 raise HostChangedError("Connection pool with host '%s' tried to "308 "open a foreign host: %s" % (host, url))309310 try:311 # Request a connection from the queue312 conn = self._get_conn()313314 # 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))322323 # 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)327328 # Put the connection back to be reused329 self._put_conn(conn)330331 except (SocketTimeout, Empty), e:332 # Timed out either by socket or queue333 raise TimeoutError("Request timed out after %f seconds" %334 self.timeout)335336 except (BaseSSLError), e:337 # SSL certificate error338 raise SSLError(e)339340 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 again345346 # 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)355356 return response357358 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).362363 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)370371 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).376377 Supports an optional ``fields`` parameter of key/value strings AND378 key/filetuple. A filetuple is a (filename, data) tuple. For example:379380 fields = {381 'foo': 'bar',382 'foofile': ('foofile.txt', 'contents of foofile'),383 }384385 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.390391 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.394395 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')405406 headers = headers or {}407 headers.update({'Content-Type': content_type})408409 return self.urlopen('POST', url, body, headers=headers,410 retries=retries, redirect=redirect)411412413class HTTPSConnectionPool(HTTPConnectionPool):414 """415 Same as HTTPConnectionPool, but HTTPS.416 """417418 scheme = 'https'419420 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 {}430431 self.key_file = key_file432 self.cert_file = cert_file433 self.cert_reqs = cert_reqs434 self.ca_certs = ca_certs435436 # Fill the queue up so that doing get() on it will block properly437 [self.pool.put(None) for i in xrange(maxsize)]438439 self.num_connections = 0440 self.num_requests = 0441442 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))449450 if not ssl:451 return HTTPSConnection(host=self.host, port=self.port)452453 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 connection457458459## Helpers460461def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,462 basic_auth=None):463 """464 Shortcuts for generating request headers.465466 keep_alive467 If true, adds 'connection: keep-alive' header.468469 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.474475 user_agent476 String representing the user-agent you want, such as477 "python-urllib3/0.6"478479 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_encoding492493 if user_agent:494 headers['user-agent'] = user_agent495496 if keep_alive:497 headers['connection'] = 'keep-alive'498499 if basic_auth:500 headers['authorization'] = 'Basic ' + \501 basic_auth.encode('base64').strip()502503 return headers504505506def get_host(url):507 """508 Given a url, return its scheme, host and port (None if it's not there).509510 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, port528529530def connection_from_url(url, **kw):531 """532 Given a url, return an HTTP(S)ConnectionPool instance of its host.533534 This is a shortcut for not having to determine the host of the url535 before creating an HTTP(S)ConnectionPool instance.536537 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
1import codecs2import mimetools3import mimetypes4try:5 from cStringIO import StringIO6except:7 from StringIO import StringIO8910writer = codecs.lookup('utf-8')[3]111213def get_content_type(filename):14 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'151617def encode_multipart_formdata(fields):18 body = StringIO()19 BOUNDARY = mimetools.choose_boundary()2021 for fieldname, value in fields.iteritems():22 body.write('--%s\r\n' % (BOUNDARY))2324 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')3536 if isinstance(data, int):37 data = str(data) # Backwards compatibility3839 if isinstance(data, unicode):40 writer(body).write(data)41 else:42 body.write(data)4344 body.write('\r\n')4546 body.write('--%s--\r\n' % (BOUNDARY))4748 content_type = 'multipart/form-data; boundary=%s' % BOUNDARY4950 return body.getvalue(), content_type