Update urllib3 to v1.21.1
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Cory Benfield · committed by Cory Benfield · parent 823519d · Browse files · 18 files·+2035 added−137 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+2035 added−137 removed
- other:+2035 added−137 removed
Provenance
- Commit
d49f3e2- Tree
26bb1d2- Author
Cory Benfield <lukasaoz@gmail.com>- Committer
Cory Benfield <lukasaoz@gmail.com>- Parent
823519d
18 files changed+2035 added−137 removed
added:requests/packages/urllib3/contrib/_securetransport/__init__.py
added:requests/packages/urllib3/contrib/_securetransport/bindings.py+590 added
1+"""2+This module uses ctypes to bind a whole bunch of functions and constants from3+SecureTransport. The goal here is to provide the low-level API to4+SecureTransport. These are essentially the C-level functions and constants, and5+they're pretty gross to work with.6+7+This code is a bastardised version of the code found in Will Bond's oscrypto8+library. An enormous debt is owed to him for blazing this trail for us. For9+that reason, this code should be considered to be covered both by urllib3's10+license and by oscrypto's:11+12+ Copyright (c) 2015-2016 Will Bond <will@wbond.net>13+14+ Permission is hereby granted, free of charge, to any person obtaining a15+ copy of this software and associated documentation files (the "Software"),16+ to deal in the Software without restriction, including without limitation17+ the rights to use, copy, modify, merge, publish, distribute, sublicense,18+ and/or sell copies of the Software, and to permit persons to whom the19+ Software is furnished to do so, subject to the following conditions:20+21+ The above copyright notice and this permission notice shall be included in22+ all copies or substantial portions of the Software.23+24+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR25+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,26+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE27+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER28+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING29+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER30+ DEALINGS IN THE SOFTWARE.31+"""32+from __future__ import absolute_import33+34+import platform35+from ctypes.util import find_library36+from ctypes import (37+ c_void_p, c_int32, c_char_p, c_size_t, c_byte, c_uint32, c_ulong, c_long,38+ c_bool39+)40+from ctypes import CDLL, POINTER, CFUNCTYPE41+42+43+security_path = find_library('Security')44+if not security_path:45+ raise ImportError('The library Security could not be found')46+47+48+core_foundation_path = find_library('CoreFoundation')49+if not core_foundation_path:50+ raise ImportError('The library CoreFoundation could not be found')51+52+53+version = platform.mac_ver()[0]54+version_info = tuple(map(int, version.split('.')))55+if version_info < (10, 8):56+ raise OSError(57+ 'Only OS X 10.8 and newer are supported, not %s.%s' % (58+ version_info[0], version_info[1]59+ )60+ )61+62+Security = CDLL(security_path, use_errno=True)63+CoreFoundation = CDLL(core_foundation_path, use_errno=True)64+65+Boolean = c_bool66+CFIndex = c_long67+CFStringEncoding = c_uint3268+CFData = c_void_p69+CFString = c_void_p70+CFArray = c_void_p71+CFMutableArray = c_void_p72+CFDictionary = c_void_p73+CFError = c_void_p74+CFType = c_void_p75+CFTypeID = c_ulong76+77+CFTypeRef = POINTER(CFType)78+CFAllocatorRef = c_void_p79+80+OSStatus = c_int3281+82+CFDataRef = POINTER(CFData)83+CFStringRef = POINTER(CFString)84+CFArrayRef = POINTER(CFArray)85+CFMutableArrayRef = POINTER(CFMutableArray)86+CFDictionaryRef = POINTER(CFDictionary)87+CFArrayCallBacks = c_void_p88+CFDictionaryKeyCallBacks = c_void_p89+CFDictionaryValueCallBacks = c_void_p90+91+SecCertificateRef = POINTER(c_void_p)92+SecExternalFormat = c_uint3293+SecExternalItemType = c_uint3294+SecIdentityRef = POINTER(c_void_p)95+SecItemImportExportFlags = c_uint3296+SecItemImportExportKeyParameters = c_void_p97+SecKeychainRef = POINTER(c_void_p)98+SSLProtocol = c_uint3299+SSLCipherSuite = c_uint32100+SSLContextRef = POINTER(c_void_p)101+SecTrustRef = POINTER(c_void_p)102+SSLConnectionRef = c_uint32103+SecTrustResultType = c_uint32104+SecTrustOptionFlags = c_uint32105+SSLProtocolSide = c_uint32106+SSLConnectionType = c_uint32107+SSLSessionOption = c_uint32108+109+110+try:111+ Security.SecItemImport.argtypes = [112+ CFDataRef,113+ CFStringRef,114+ POINTER(SecExternalFormat),115+ POINTER(SecExternalItemType),116+ SecItemImportExportFlags,117+ POINTER(SecItemImportExportKeyParameters),118+ SecKeychainRef,119+ POINTER(CFArrayRef),120+ ]121+ Security.SecItemImport.restype = OSStatus122+123+ Security.SecCertificateGetTypeID.argtypes = []124+ Security.SecCertificateGetTypeID.restype = CFTypeID125+126+ Security.SecIdentityGetTypeID.argtypes = []127+ Security.SecIdentityGetTypeID.restype = CFTypeID128+129+ Security.SecKeyGetTypeID.argtypes = []130+ Security.SecKeyGetTypeID.restype = CFTypeID131+132+ Security.SecCertificateCreateWithData.argtypes = [133+ CFAllocatorRef,134+ CFDataRef135+ ]136+ Security.SecCertificateCreateWithData.restype = SecCertificateRef137+138+ Security.SecCertificateCopyData.argtypes = [139+ SecCertificateRef140+ ]141+ Security.SecCertificateCopyData.restype = CFDataRef142+143+ Security.SecCopyErrorMessageString.argtypes = [144+ OSStatus,145+ c_void_p146+ ]147+ Security.SecCopyErrorMessageString.restype = CFStringRef148+149+ Security.SecIdentityCreateWithCertificate.argtypes = [150+ CFTypeRef,151+ SecCertificateRef,152+ POINTER(SecIdentityRef)153+ ]154+ Security.SecIdentityCreateWithCertificate.restype = OSStatus155+156+ Security.SecKeychainCreate.argtypes = [157+ c_char_p,158+ c_uint32,159+ c_void_p,160+ Boolean,161+ c_void_p,162+ POINTER(SecKeychainRef)163+ ]164+ Security.SecKeychainCreate.restype = OSStatus165+166+ Security.SecKeychainDelete.argtypes = [167+ SecKeychainRef168+ ]169+ Security.SecKeychainDelete.restype = OSStatus170+171+ Security.SecPKCS12Import.argtypes = [172+ CFDataRef,173+ CFDictionaryRef,174+ POINTER(CFArrayRef)175+ ]176+ Security.SecPKCS12Import.restype = OSStatus177+178+ SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t))179+ SSLWriteFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t))180+181+ Security.SSLSetIOFuncs.argtypes = [182+ SSLContextRef,183+ SSLReadFunc,184+ SSLWriteFunc185+ ]186+ Security.SSLSetIOFuncs.restype = OSStatus187+188+ Security.SSLSetPeerID.argtypes = [189+ SSLContextRef,190+ c_char_p,191+ c_size_t192+ ]193+ Security.SSLSetPeerID.restype = OSStatus194+195+ Security.SSLSetCertificate.argtypes = [196+ SSLContextRef,197+ CFArrayRef198+ ]199+ Security.SSLSetCertificate.restype = OSStatus200+201+ Security.SSLSetCertificateAuthorities.argtypes = [202+ SSLContextRef,203+ CFTypeRef,204+ Boolean205+ ]206+ Security.SSLSetCertificateAuthorities.restype = OSStatus207+208+ Security.SSLSetConnection.argtypes = [209+ SSLContextRef,210+ SSLConnectionRef211+ ]212+ Security.SSLSetConnection.restype = OSStatus213+214+ Security.SSLSetPeerDomainName.argtypes = [215+ SSLContextRef,216+ c_char_p,217+ c_size_t218+ ]219+ Security.SSLSetPeerDomainName.restype = OSStatus220+221+ Security.SSLHandshake.argtypes = [222+ SSLContextRef223+ ]224+ Security.SSLHandshake.restype = OSStatus225+226+ Security.SSLRead.argtypes = [227+ SSLContextRef,228+ c_char_p,229+ c_size_t,230+ POINTER(c_size_t)231+ ]232+ Security.SSLRead.restype = OSStatus233+234+ Security.SSLWrite.argtypes = [235+ SSLContextRef,236+ c_char_p,237+ c_size_t,238+ POINTER(c_size_t)239+ ]240+ Security.SSLWrite.restype = OSStatus241+242+ Security.SSLClose.argtypes = [243+ SSLContextRef244+ ]245+ Security.SSLClose.restype = OSStatus246+247+ Security.SSLGetNumberSupportedCiphers.argtypes = [248+ SSLContextRef,249+ POINTER(c_size_t)250+ ]251+ Security.SSLGetNumberSupportedCiphers.restype = OSStatus252+253+ Security.SSLGetSupportedCiphers.argtypes = [254+ SSLContextRef,255+ POINTER(SSLCipherSuite),256+ POINTER(c_size_t)257+ ]258+ Security.SSLGetSupportedCiphers.restype = OSStatus259+260+ Security.SSLSetEnabledCiphers.argtypes = [261+ SSLContextRef,262+ POINTER(SSLCipherSuite),263+ c_size_t264+ ]265+ Security.SSLSetEnabledCiphers.restype = OSStatus266+267+ Security.SSLGetNumberEnabledCiphers.argtype = [268+ SSLContextRef,269+ POINTER(c_size_t)270+ ]271+ Security.SSLGetNumberEnabledCiphers.restype = OSStatus272+273+ Security.SSLGetEnabledCiphers.argtypes = [274+ SSLContextRef,275+ POINTER(SSLCipherSuite),276+ POINTER(c_size_t)277+ ]278+ Security.SSLGetEnabledCiphers.restype = OSStatus279+280+ Security.SSLGetNegotiatedCipher.argtypes = [281+ SSLContextRef,282+ POINTER(SSLCipherSuite)283+ ]284+ Security.SSLGetNegotiatedCipher.restype = OSStatus285+286+ Security.SSLGetNegotiatedProtocolVersion.argtypes = [287+ SSLContextRef,288+ POINTER(SSLProtocol)289+ ]290+ Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus291+292+ Security.SSLCopyPeerTrust.argtypes = [293+ SSLContextRef,294+ POINTER(SecTrustRef)295+ ]296+ Security.SSLCopyPeerTrust.restype = OSStatus297+298+ Security.SecTrustSetAnchorCertificates.argtypes = [299+ SecTrustRef,300+ CFArrayRef301+ ]302+ Security.SecTrustSetAnchorCertificates.restype = OSStatus303+304+ Security.SecTrustSetAnchorCertificatesOnly.argstypes = [305+ SecTrustRef,306+ Boolean307+ ]308+ Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus309+310+ Security.SecTrustEvaluate.argtypes = [311+ SecTrustRef,312+ POINTER(SecTrustResultType)313+ ]314+ Security.SecTrustEvaluate.restype = OSStatus315+316+ Security.SecTrustGetCertificateCount.argtypes = [317+ SecTrustRef318+ ]319+ Security.SecTrustGetCertificateCount.restype = CFIndex320+321+ Security.SecTrustGetCertificateAtIndex.argtypes = [322+ SecTrustRef,323+ CFIndex324+ ]325+ Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef326+327+ Security.SSLCreateContext.argtypes = [328+ CFAllocatorRef,329+ SSLProtocolSide,330+ SSLConnectionType331+ ]332+ Security.SSLCreateContext.restype = SSLContextRef333+334+ Security.SSLSetSessionOption.argtypes = [335+ SSLContextRef,336+ SSLSessionOption,337+ Boolean338+ ]339+ Security.SSLSetSessionOption.restype = OSStatus340+341+ Security.SSLSetProtocolVersionMin.argtypes = [342+ SSLContextRef,343+ SSLProtocol344+ ]345+ Security.SSLSetProtocolVersionMin.restype = OSStatus346+347+ Security.SSLSetProtocolVersionMax.argtypes = [348+ SSLContextRef,349+ SSLProtocol350+ ]351+ Security.SSLSetProtocolVersionMax.restype = OSStatus352+353+ Security.SecCopyErrorMessageString.argtypes = [354+ OSStatus,355+ c_void_p356+ ]357+ Security.SecCopyErrorMessageString.restype = CFStringRef358+359+ Security.SSLReadFunc = SSLReadFunc360+ Security.SSLWriteFunc = SSLWriteFunc361+ Security.SSLContextRef = SSLContextRef362+ Security.SSLProtocol = SSLProtocol363+ Security.SSLCipherSuite = SSLCipherSuite364+ Security.SecIdentityRef = SecIdentityRef365+ Security.SecKeychainRef = SecKeychainRef366+ Security.SecTrustRef = SecTrustRef367+ Security.SecTrustResultType = SecTrustResultType368+ Security.SecExternalFormat = SecExternalFormat369+ Security.OSStatus = OSStatus370+371+ Security.kSecImportExportPassphrase = CFStringRef.in_dll(372+ Security, 'kSecImportExportPassphrase'373+ )374+ Security.kSecImportItemIdentity = CFStringRef.in_dll(375+ Security, 'kSecImportItemIdentity'376+ )377+378+ # CoreFoundation time!379+ CoreFoundation.CFRetain.argtypes = [380+ CFTypeRef381+ ]382+ CoreFoundation.CFRetain.restype = CFTypeRef383+384+ CoreFoundation.CFRelease.argtypes = [385+ CFTypeRef386+ ]387+ CoreFoundation.CFRelease.restype = None388+389+ CoreFoundation.CFGetTypeID.argtypes = [390+ CFTypeRef391+ ]392+ CoreFoundation.CFGetTypeID.restype = CFTypeID393+394+ CoreFoundation.CFStringCreateWithCString.argtypes = [395+ CFAllocatorRef,396+ c_char_p,397+ CFStringEncoding398+ ]399+ CoreFoundation.CFStringCreateWithCString.restype = CFStringRef400+401+ CoreFoundation.CFStringGetCStringPtr.argtypes = [402+ CFStringRef,403+ CFStringEncoding404+ ]405+ CoreFoundation.CFStringGetCStringPtr.restype = c_char_p406+407+ CoreFoundation.CFStringGetCString.argtypes = [408+ CFStringRef,409+ c_char_p,410+ CFIndex,411+ CFStringEncoding412+ ]413+ CoreFoundation.CFStringGetCString.restype = c_bool414+415+ CoreFoundation.CFDataCreate.argtypes = [416+ CFAllocatorRef,417+ c_char_p,418+ CFIndex419+ ]420+ CoreFoundation.CFDataCreate.restype = CFDataRef421+422+ CoreFoundation.CFDataGetLength.argtypes = [423+ CFDataRef424+ ]425+ CoreFoundation.CFDataGetLength.restype = CFIndex426+427+ CoreFoundation.CFDataGetBytePtr.argtypes = [428+ CFDataRef429+ ]430+ CoreFoundation.CFDataGetBytePtr.restype = c_void_p431+432+ CoreFoundation.CFDictionaryCreate.argtypes = [433+ CFAllocatorRef,434+ POINTER(CFTypeRef),435+ POINTER(CFTypeRef),436+ CFIndex,437+ CFDictionaryKeyCallBacks,438+ CFDictionaryValueCallBacks439+ ]440+ CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef441+442+ CoreFoundation.CFDictionaryGetValue.argtypes = [443+ CFDictionaryRef,444+ CFTypeRef445+ ]446+ CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef447+448+ CoreFoundation.CFArrayCreate.argtypes = [449+ CFAllocatorRef,450+ POINTER(CFTypeRef),451+ CFIndex,452+ CFArrayCallBacks,453+ ]454+ CoreFoundation.CFArrayCreate.restype = CFArrayRef455+456+ CoreFoundation.CFArrayCreateMutable.argtypes = [457+ CFAllocatorRef,458+ CFIndex,459+ CFArrayCallBacks460+ ]461+ CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef462+463+ CoreFoundation.CFArrayAppendValue.argtypes = [464+ CFMutableArrayRef,465+ c_void_p466+ ]467+ CoreFoundation.CFArrayAppendValue.restype = None468+469+ CoreFoundation.CFArrayGetCount.argtypes = [470+ CFArrayRef471+ ]472+ CoreFoundation.CFArrayGetCount.restype = CFIndex473+474+ CoreFoundation.CFArrayGetValueAtIndex.argtypes = [475+ CFArrayRef,476+ CFIndex477+ ]478+ CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p479+480+ CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll(481+ CoreFoundation, 'kCFAllocatorDefault'482+ )483+ CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll(CoreFoundation, 'kCFTypeArrayCallBacks')484+ CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll(485+ CoreFoundation, 'kCFTypeDictionaryKeyCallBacks'486+ )487+ CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll(488+ CoreFoundation, 'kCFTypeDictionaryValueCallBacks'489+ )490+491+ CoreFoundation.CFTypeRef = CFTypeRef492+ CoreFoundation.CFArrayRef = CFArrayRef493+ CoreFoundation.CFStringRef = CFStringRef494+ CoreFoundation.CFDictionaryRef = CFDictionaryRef495+496+except (AttributeError):497+ raise ImportError('Error initializing ctypes')498+499+500+class CFConst(object):501+ """502+ A class object that acts as essentially a namespace for CoreFoundation503+ constants.504+ """505+ kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)506+507+508+class SecurityConst(object):509+ """510+ A class object that acts as essentially a namespace for Security constants.511+ """512+ kSSLSessionOptionBreakOnServerAuth = 0513+514+ kSSLProtocol2 = 1515+ kSSLProtocol3 = 2516+ kTLSProtocol1 = 4517+ kTLSProtocol11 = 7518+ kTLSProtocol12 = 8519+520+ kSSLClientSide = 1521+ kSSLStreamType = 0522+523+ kSecFormatPEMSequence = 10524+525+ kSecTrustResultInvalid = 0526+ kSecTrustResultProceed = 1527+ # This gap is present on purpose: this was kSecTrustResultConfirm, which528+ # is deprecated.529+ kSecTrustResultDeny = 3530+ kSecTrustResultUnspecified = 4531+ kSecTrustResultRecoverableTrustFailure = 5532+ kSecTrustResultFatalTrustFailure = 6533+ kSecTrustResultOtherError = 7534+535+ errSSLProtocol = -9800536+ errSSLWouldBlock = -9803537+ errSSLClosedGraceful = -9805538+ errSSLClosedNoNotify = -9816539+ errSSLClosedAbort = -9806540+541+ errSSLXCertChainInvalid = -9807542+ errSSLCrypto = -9809543+ errSSLInternal = -9810544+ errSSLCertExpired = -9814545+ errSSLCertNotYetValid = -9815546+ errSSLUnknownRootCert = -9812547+ errSSLNoRootCert = -9813548+ errSSLHostNameMismatch = -9843549+ errSSLPeerHandshakeFail = -9824550+ errSSLPeerUserCancelled = -9839551+ errSSLWeakPeerEphemeralDHKey = -9850552+ errSSLServerAuthCompleted = -9841553+ errSSLRecordOverflow = -9847554+555+ errSecVerifyFailed = -67808556+ errSecNoTrustSettings = -25263557+ errSecItemNotFound = -25300558+ errSecInvalidTrustSettings = -25262559+560+ # Cipher suites. We only pick the ones our default cipher string allows.561+ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C562+ TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030563+ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B564+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F565+ TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = 0x00A3566+ TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F567+ TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = 0x00A2568+ TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E569+ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024570+ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028571+ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A572+ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014573+ TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B574+ TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x006A575+ TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039576+ TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038577+ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023578+ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027579+ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009580+ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013581+ TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067582+ TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x0040583+ TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033584+ TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032585+ TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D586+ TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C587+ TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D588+ TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C589+ TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035590+ TLS_RSA_WITH_AES_128_CBC_SHA = 0x002Fadded:requests/packages/urllib3/contrib/_securetransport/low_level.py+343 added
1+"""2+Low-level helpers for the SecureTransport bindings.3+4+These are Python functions that are not directly related to the high-level APIs5+but are necessary to get them to work. They include a whole bunch of low-level6+CoreFoundation messing about and memory management. The concerns in this module7+are almost entirely about trying to avoid memory leaks and providing8+appropriate and useful assistance to the higher-level code.9+"""10+import base6411+import ctypes12+import itertools13+import re14+import os15+import ssl16+import tempfile17+18+from .bindings import Security, CoreFoundation, CFConst19+20+21+# This regular expression is used to grab PEM data out of a PEM bundle.22+_PEM_CERTS_RE = re.compile(23+ b"-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----", re.DOTALL24+)25+26+27+def _cf_data_from_bytes(bytestring):28+ """29+ Given a bytestring, create a CFData object from it. This CFData object must30+ be CFReleased by the caller.31+ """32+ return CoreFoundation.CFDataCreate(33+ CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring)34+ )35+36+37+def _cf_dictionary_from_tuples(tuples):38+ """39+ Given a list of Python tuples, create an associated CFDictionary.40+ """41+ dictionary_size = len(tuples)42+43+ # We need to get the dictionary keys and values out in the same order.44+ keys = (t[0] for t in tuples)45+ values = (t[1] for t in tuples)46+ cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys)47+ cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values)48+49+ return CoreFoundation.CFDictionaryCreate(50+ CoreFoundation.kCFAllocatorDefault,51+ cf_keys,52+ cf_values,53+ dictionary_size,54+ CoreFoundation.kCFTypeDictionaryKeyCallBacks,55+ CoreFoundation.kCFTypeDictionaryValueCallBacks,56+ )57+58+59+def _cf_string_to_unicode(value):60+ """61+ Creates a Unicode string from a CFString object. Used entirely for error62+ reporting.63+64+ Yes, it annoys me quite a lot that this function is this complex.65+ """66+ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))67+68+ string = CoreFoundation.CFStringGetCStringPtr(69+ value_as_void_p,70+ CFConst.kCFStringEncodingUTF871+ )72+ if string is None:73+ buffer = ctypes.create_string_buffer(1024)74+ result = CoreFoundation.CFStringGetCString(75+ value_as_void_p,76+ buffer,77+ 1024,78+ CFConst.kCFStringEncodingUTF879+ )80+ if not result:81+ raise OSError('Error copying C string from CFStringRef')82+ string = buffer.value83+ if string is not None:84+ string = string.decode('utf-8')85+ return string86+87+88+def _assert_no_error(error, exception_class=None):89+ """90+ Checks the return code and throws an exception if there is an error to91+ report92+ """93+ if error == 0:94+ return95+96+ cf_error_string = Security.SecCopyErrorMessageString(error, None)97+ output = _cf_string_to_unicode(cf_error_string)98+ CoreFoundation.CFRelease(cf_error_string)99+100+ if output is None or output == u'':101+ output = u'OSStatus %s' % error102+103+ if exception_class is None:104+ exception_class = ssl.SSLError105+106+ raise exception_class(output)107+108+109+def _cert_array_from_pem(pem_bundle):110+ """111+ Given a bundle of certs in PEM format, turns them into a CFArray of certs112+ that can be used to validate a cert chain.113+ """114+ der_certs = [115+ base64.b64decode(match.group(1))116+ for match in _PEM_CERTS_RE.finditer(pem_bundle)117+ ]118+ if not der_certs:119+ raise ssl.SSLError("No root certificates specified")120+121+ cert_array = CoreFoundation.CFArrayCreateMutable(122+ CoreFoundation.kCFAllocatorDefault,123+ 0,124+ ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks)125+ )126+ if not cert_array:127+ raise ssl.SSLError("Unable to allocate memory!")128+129+ try:130+ for der_bytes in der_certs:131+ certdata = _cf_data_from_bytes(der_bytes)132+ if not certdata:133+ raise ssl.SSLError("Unable to allocate memory!")134+ cert = Security.SecCertificateCreateWithData(135+ CoreFoundation.kCFAllocatorDefault, certdata136+ )137+ CoreFoundation.CFRelease(certdata)138+ if not cert:139+ raise ssl.SSLError("Unable to build cert object!")140+141+ CoreFoundation.CFArrayAppendValue(cert_array, cert)142+ CoreFoundation.CFRelease(cert)143+ except Exception:144+ # We need to free the array before the exception bubbles further.145+ # We only want to do that if an error occurs: otherwise, the caller146+ # should free.147+ CoreFoundation.CFRelease(cert_array)148+149+ return cert_array150+151+152+def _is_cert(item):153+ """154+ Returns True if a given CFTypeRef is a certificate.155+ """156+ expected = Security.SecCertificateGetTypeID()157+ return CoreFoundation.CFGetTypeID(item) == expected158+159+160+def _is_identity(item):161+ """162+ Returns True if a given CFTypeRef is an identity.163+ """164+ expected = Security.SecIdentityGetTypeID()165+ return CoreFoundation.CFGetTypeID(item) == expected166+167+168+def _temporary_keychain():169+ """170+ This function creates a temporary Mac keychain that we can use to work with171+ credentials. This keychain uses a one-time password and a temporary file to172+ store the data. We expect to have one keychain per socket. The returned173+ SecKeychainRef must be freed by the caller, including calling174+ SecKeychainDelete.175+176+ Returns a tuple of the SecKeychainRef and the path to the temporary177+ directory that contains it.178+ """179+ # Unfortunately, SecKeychainCreate requires a path to a keychain. This180+ # means we cannot use mkstemp to use a generic temporary file. Instead,181+ # we're going to create a temporary directory and a filename to use there.182+ # This filename will be 8 random bytes expanded into base64. We also need183+ # some random bytes to password-protect the keychain we're creating, so we184+ # ask for 40 random bytes.185+ random_bytes = os.urandom(40)186+ filename = base64.b64encode(random_bytes[:8]).decode('utf-8')187+ password = base64.b64encode(random_bytes[8:]) # Must be valid UTF-8188+ tempdirectory = tempfile.mkdtemp()189+190+ keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')191+192+ # We now want to create the keychain itself.193+ keychain = Security.SecKeychainRef()194+ status = Security.SecKeychainCreate(195+ keychain_path,196+ len(password),197+ password,198+ False,199+ None,200+ ctypes.byref(keychain)201+ )202+ _assert_no_error(status)203+204+ # Having created the keychain, we want to pass it off to the caller.205+ return keychain, tempdirectory206+207+208+def _load_items_from_file(keychain, path):209+ """210+ Given a single file, loads all the trust objects from it into arrays and211+ the keychain.212+ Returns a tuple of lists: the first list is a list of identities, the213+ second a list of certs.214+ """215+ certificates = []216+ identities = []217+ result_array = None218+219+ with open(path, 'rb') as f:220+ raw_filedata = f.read()221+222+ try:223+ filedata = CoreFoundation.CFDataCreate(224+ CoreFoundation.kCFAllocatorDefault,225+ raw_filedata,226+ len(raw_filedata)227+ )228+ result_array = CoreFoundation.CFArrayRef()229+ result = Security.SecItemImport(230+ filedata, # cert data231+ None, # Filename, leaving it out for now232+ None, # What the type of the file is, we don't care233+ None, # what's in the file, we don't care234+ 0, # import flags235+ None, # key params, can include passphrase in the future236+ keychain, # The keychain to insert into237+ ctypes.byref(result_array) # Results238+ )239+ _assert_no_error(result)240+241+ # A CFArray is not very useful to us as an intermediary242+ # representation, so we are going to extract the objects we want243+ # and then free the array. We don't need to keep hold of keys: the244+ # keychain already has them!245+ result_count = CoreFoundation.CFArrayGetCount(result_array)246+ for index in range(result_count):247+ item = CoreFoundation.CFArrayGetValueAtIndex(248+ result_array, index249+ )250+ item = ctypes.cast(item, CoreFoundation.CFTypeRef)251+252+ if _is_cert(item):253+ CoreFoundation.CFRetain(item)254+ certificates.append(item)255+ elif _is_identity(item):256+ CoreFoundation.CFRetain(item)257+ identities.append(item)258+ finally:259+ if result_array:260+ CoreFoundation.CFRelease(result_array)261+262+ CoreFoundation.CFRelease(filedata)263+264+ return (identities, certificates)265+266+267+def _load_client_cert_chain(keychain, *paths):268+ """269+ Load certificates and maybe keys from a number of files. Has the end goal270+ of returning a CFArray containing one SecIdentityRef, and then zero or more271+ SecCertificateRef objects, suitable for use as a client certificate trust272+ chain.273+ """274+ # Ok, the strategy.275+ #276+ # This relies on knowing that macOS will not give you a SecIdentityRef277+ # unless you have imported a key into a keychain. This is a somewhat278+ # artificial limitation of macOS (for example, it doesn't necessarily279+ # affect iOS), but there is nothing inside Security.framework that lets you280+ # get a SecIdentityRef without having a key in a keychain.281+ #282+ # So the policy here is we take all the files and iterate them in order.283+ # Each one will use SecItemImport to have one or more objects loaded from284+ # it. We will also point at a keychain that macOS can use to work with the285+ # private key.286+ #287+ # Once we have all the objects, we'll check what we actually have. If we288+ # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,289+ # we'll take the first certificate (which we assume to be our leaf) and290+ # ask the keychain to give us a SecIdentityRef with that cert's associated291+ # key.292+ #293+ # We'll then return a CFArray containing the trust chain: one294+ # SecIdentityRef and then zero-or-more SecCertificateRef objects. The295+ # responsibility for freeing this CFArray will be with the caller. This296+ # CFArray must remain alive for the entire connection, so in practice it297+ # will be stored with a single SSLSocket, along with the reference to the298+ # keychain.299+ certificates = []300+ identities = []301+302+ # Filter out bad paths.303+ paths = (path for path in paths if path)304+305+ try:306+ for file_path in paths:307+ new_identities, new_certs = _load_items_from_file(308+ keychain, file_path309+ )310+ identities.extend(new_identities)311+ certificates.extend(new_certs)312+313+ # Ok, we have everything. The question is: do we have an identity? If314+ # not, we want to grab one from the first cert we have.315+ if not identities:316+ new_identity = Security.SecIdentityRef()317+ status = Security.SecIdentityCreateWithCertificate(318+ keychain,319+ certificates[0],320+ ctypes.byref(new_identity)321+ )322+ _assert_no_error(status)323+ identities.append(new_identity)324+325+ # We now want to release the original certificate, as we no longer326+ # need it.327+ CoreFoundation.CFRelease(certificates.pop(0))328+329+ # We now need to build a new CFArray that holds the trust chain.330+ trust_chain = CoreFoundation.CFArrayCreateMutable(331+ CoreFoundation.kCFAllocatorDefault,332+ 0,333+ ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),334+ )335+ for item in itertools.chain(identities, certificates):336+ # ArrayAppendValue does a CFRetain on the item. That's fine,337+ # because the finally block will release our other refs to them.338+ CoreFoundation.CFArrayAppendValue(trust_chain, item)339+340+ return trust_chain341+ finally:342+ for obj in itertools.chain(identities, certificates):343+ CoreFoundation.CFRelease(obj)modified:requests/packages/urllib3/contrib/pyopenssl.py+2 added
302 unmodified lines303 wr = util.wait_for_write(self.socket, self.socket.gettimeout())304 if not wr:305 raise timeout()306 continue307+ except OpenSSL.SSL.SysCallError as e:308+ raise SocketError(str(e))309 310 def sendall(self, data):311 total_sent = 0312 while total_sent < len(data):140 unmodified linesadded:requests/packages/urllib3/contrib/securetransport.py+807 added
1+"""2+SecureTranport support for urllib3 via ctypes.3+4+This makes platform-native TLS available to urllib3 users on macOS without the5+use of a compiler. This is an important feature because the Python Package6+Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL7+that ships with macOS is not capable of doing TLSv1.2. The only way to resolve8+this is to give macOS users an alternative solution to the problem, and that9+solution is to use SecureTransport.10+11+We use ctypes here because this solution must not require a compiler. That's12+because pip is not allowed to require a compiler either.13+14+This is not intended to be a seriously long-term solution to this problem.15+The hope is that PEP 543 will eventually solve this issue for us, at which16+point we can retire this contrib module. But in the short term, we need to17+solve the impending tire fire that is Python on Mac without this kind of18+contrib module. So...here we are.19+20+To use this module, simply import and inject it::21+22+ import urllib3.contrib.securetransport23+ urllib3.contrib.securetransport.inject_into_urllib3()24+25+Happy TLSing!26+"""27+from __future__ import absolute_import28+29+import contextlib30+import ctypes31+import errno32+import os.path33+import shutil34+import socket35+import ssl36+import threading37+import weakref38+39+from .. import util40+from ._securetransport.bindings import (41+ Security, SecurityConst, CoreFoundation42+)43+from ._securetransport.low_level import (44+ _assert_no_error, _cert_array_from_pem, _temporary_keychain,45+ _load_client_cert_chain46+)47+48+try: # Platform-specific: Python 249+ from socket import _fileobject50+except ImportError: # Platform-specific: Python 351+ _fileobject = None52+ from ..packages.backports.makefile import backport_makefile53+54+try:55+ memoryview(b'')56+except NameError:57+ raise ImportError("SecureTransport only works on Pythons with memoryview")58+59+__all__ = ['inject_into_urllib3', 'extract_from_urllib3']60+61+# SNI always works62+HAS_SNI = True63+64+orig_util_HAS_SNI = util.HAS_SNI65+orig_util_SSLContext = util.ssl_.SSLContext66+67+# This dictionary is used by the read callback to obtain a handle to the68+# calling wrapped socket. This is a pretty silly approach, but for now it'll69+# do. I feel like I should be able to smuggle a handle to the wrapped socket70+# directly in the SSLConnectionRef, but for now this approach will work I71+# guess.72+#73+# We need to lock around this structure for inserts, but we don't do it for74+# reads/writes in the callbacks. The reasoning here goes as follows:75+#76+# 1. It is not possible to call into the callbacks before the dictionary is77+# populated, so once in the callback the id must be in the dictionary.78+# 2. The callbacks don't mutate the dictionary, they only read from it, and79+# so cannot conflict with any of the insertions.80+#81+# This is good: if we had to lock in the callbacks we'd drastically slow down82+# the performance of this code.83+_connection_refs = weakref.WeakValueDictionary()84+_connection_ref_lock = threading.Lock()85+86+# Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over87+# for no better reason than we need *a* limit, and this one is right there.88+SSL_WRITE_BLOCKSIZE = 1638489+90+# This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to91+# individual cipher suites. We need to do this becuase this is how92+# SecureTransport wants them.93+CIPHER_SUITES = [94+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,95+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,96+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,97+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,98+ SecurityConst.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384,99+ SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,100+ SecurityConst.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,101+ SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,102+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,103+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,104+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,105+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,106+ SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,107+ SecurityConst.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,108+ SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,109+ SecurityConst.TLS_DHE_DSS_WITH_AES_256_CBC_SHA,110+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,111+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,112+ SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,113+ SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,114+ SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,115+ SecurityConst.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,116+ SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,117+ SecurityConst.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,118+ SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384,119+ SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256,120+ SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256,121+ SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256,122+ SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA,123+ SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA,124+]125+126+# Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of127+# TLSv1 and a high of TLSv1.2. For everything else, we pin to that version.128+_protocol_to_min_max = {129+ ssl.PROTOCOL_SSLv23: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),130+}131+132+if hasattr(ssl, "PROTOCOL_SSLv2"):133+ _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = (134+ SecurityConst.kSSLProtocol2, SecurityConst.kSSLProtocol2135+ )136+if hasattr(ssl, "PROTOCOL_SSLv3"):137+ _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = (138+ SecurityConst.kSSLProtocol3, SecurityConst.kSSLProtocol3139+ )140+if hasattr(ssl, "PROTOCOL_TLSv1"):141+ _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = (142+ SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol1143+ )144+if hasattr(ssl, "PROTOCOL_TLSv1_1"):145+ _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = (146+ SecurityConst.kTLSProtocol11, SecurityConst.kTLSProtocol11147+ )148+if hasattr(ssl, "PROTOCOL_TLSv1_2"):149+ _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = (150+ SecurityConst.kTLSProtocol12, SecurityConst.kTLSProtocol12151+ )152+if hasattr(ssl, "PROTOCOL_TLS"):153+ _protocol_to_min_max[ssl.PROTOCOL_TLS] = _protocol_to_min_max[ssl.PROTOCOL_SSLv23]154+155+156+def inject_into_urllib3():157+ """158+ Monkey-patch urllib3 with SecureTransport-backed SSL-support.159+ """160+ util.ssl_.SSLContext = SecureTransportContext161+ util.HAS_SNI = HAS_SNI162+ util.ssl_.HAS_SNI = HAS_SNI163+ util.IS_SECURETRANSPORT = True164+ util.ssl_.IS_SECURETRANSPORT = True165+166+167+def extract_from_urllib3():168+ """169+ Undo monkey-patching by :func:`inject_into_urllib3`.170+ """171+ util.ssl_.SSLContext = orig_util_SSLContext172+ util.HAS_SNI = orig_util_HAS_SNI173+ util.ssl_.HAS_SNI = orig_util_HAS_SNI174+ util.IS_SECURETRANSPORT = False175+ util.ssl_.IS_SECURETRANSPORT = False176+177+178+def _read_callback(connection_id, data_buffer, data_length_pointer):179+ """180+ SecureTransport read callback. This is called by ST to request that data181+ be returned from the socket.182+ """183+ wrapped_socket = None184+ try:185+ wrapped_socket = _connection_refs.get(connection_id)186+ if wrapped_socket is None:187+ return SecurityConst.errSSLInternal188+ base_socket = wrapped_socket.socket189+190+ requested_length = data_length_pointer[0]191+192+ timeout = wrapped_socket.gettimeout()193+ error = None194+ read_count = 0195+ buffer = (ctypes.c_char * requested_length).from_address(data_buffer)196+ buffer_view = memoryview(buffer)197+198+ try:199+ while read_count < requested_length:200+ if timeout is None or timeout >= 0:201+ readables = util.wait_for_read([base_socket], timeout)202+ if not readables:203+ raise socket.error(errno.EAGAIN, 'timed out')204+205+ # We need to tell ctypes that we have a buffer that can be206+ # written to. Upsettingly, we do that like this:207+ chunk_size = base_socket.recv_into(208+ buffer_view[read_count:requested_length]209+ )210+ read_count += chunk_size211+ if not chunk_size:212+ if not read_count:213+ return SecurityConst.errSSLClosedGraceful214+ break215+ except (socket.error) as e:216+ error = e.errno217+218+ if error is not None and error != errno.EAGAIN:219+ if error == errno.ECONNRESET:220+ return SecurityConst.errSSLClosedAbort221+ raise222+223+ data_length_pointer[0] = read_count224+225+ if read_count != requested_length:226+ return SecurityConst.errSSLWouldBlock227+228+ return 0229+ except Exception as e:230+ if wrapped_socket is not None:231+ wrapped_socket._exception = e232+ return SecurityConst.errSSLInternal233+234+235+def _write_callback(connection_id, data_buffer, data_length_pointer):236+ """237+ SecureTransport write callback. This is called by ST to request that data238+ actually be sent on the network.239+ """240+ wrapped_socket = None241+ try:242+ wrapped_socket = _connection_refs.get(connection_id)243+ if wrapped_socket is None:244+ return SecurityConst.errSSLInternal245+ base_socket = wrapped_socket.socket246+247+ bytes_to_write = data_length_pointer[0]248+ data = ctypes.string_at(data_buffer, bytes_to_write)249+250+ timeout = wrapped_socket.gettimeout()251+ error = None252+ sent = 0253+254+ try:255+ while sent < bytes_to_write:256+ if timeout is None or timeout >= 0:257+ writables = util.wait_for_write([base_socket], timeout)258+ if not writables:259+ raise socket.error(errno.EAGAIN, 'timed out')260+ chunk_sent = base_socket.send(data)261+ sent += chunk_sent262+263+ # This has some needless copying here, but I'm not sure there's264+ # much value in optimising this data path.265+ data = data[chunk_sent:]266+ except (socket.error) as e:267+ error = e.errno268+269+ if error is not None and error != errno.EAGAIN:270+ if error == errno.ECONNRESET:271+ return SecurityConst.errSSLClosedAbort272+ raise273+274+ data_length_pointer[0] = sent275+ if sent != bytes_to_write:276+ return SecurityConst.errSSLWouldBlock277+278+ return 0279+ except Exception as e:280+ if wrapped_socket is not None:281+ wrapped_socket._exception = e282+ return SecurityConst.errSSLInternal283+284+285+# We need to keep these two objects references alive: if they get GC'd while286+# in use then SecureTransport could attempt to call a function that is in freed287+# memory. That would be...uh...bad. Yeah, that's the word. Bad.288+_read_callback_pointer = Security.SSLReadFunc(_read_callback)289+_write_callback_pointer = Security.SSLWriteFunc(_write_callback)290+291+292+class WrappedSocket(object):293+ """294+ API-compatibility wrapper for Python's OpenSSL wrapped socket object.295+296+ Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage297+ collector of PyPy.298+ """299+ def __init__(self, socket):300+ self.socket = socket301+ self.context = None302+ self._makefile_refs = 0303+ self._closed = False304+ self._exception = None305+ self._keychain = None306+ self._keychain_dir = None307+ self._client_cert_chain = None308+309+ # We save off the previously-configured timeout and then set it to310+ # zero. This is done because we use select and friends to handle the311+ # timeouts, but if we leave the timeout set on the lower socket then312+ # Python will "kindly" call select on that socket again for us. Avoid313+ # that by forcing the timeout to zero.314+ self._timeout = self.socket.gettimeout()315+ self.socket.settimeout(0)316+317+ @contextlib.contextmanager318+ def _raise_on_error(self):319+ """320+ A context manager that can be used to wrap calls that do I/O from321+ SecureTransport. If any of the I/O callbacks hit an exception, this322+ context manager will correctly propagate the exception after the fact.323+ This avoids silently swallowing those exceptions.324+325+ It also correctly forces the socket closed.326+ """327+ self._exception = None328+329+ # We explicitly don't catch around this yield because in the unlikely330+ # event that an exception was hit in the block we don't want to swallow331+ # it.332+ yield333+ if self._exception is not None:334+ exception, self._exception = self._exception, None335+ self.close()336+ raise exception337+338+ def _set_ciphers(self):339+ """340+ Sets up the allowed ciphers. By default this matches the set in341+ util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done342+ custom and doesn't allow changing at this time, mostly because parsing343+ OpenSSL cipher strings is going to be a freaking nightmare.344+ """345+ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES)346+ result = Security.SSLSetEnabledCiphers(347+ self.context, ciphers, len(CIPHER_SUITES)348+ )349+ _assert_no_error(result)350+351+ def _custom_validate(self, verify, trust_bundle):352+ """353+ Called when we have set custom validation. We do this in two cases:354+ first, when cert validation is entirely disabled; and second, when355+ using a custom trust DB.356+ """357+ # If we disabled cert validation, just say: cool.358+ if not verify:359+ return360+361+ # We want data in memory, so load it up.362+ if os.path.isfile(trust_bundle):363+ with open(trust_bundle, 'rb') as f:364+ trust_bundle = f.read()365+366+ cert_array = None367+ trust = Security.SecTrustRef()368+369+ try:370+ # Get a CFArray that contains the certs we want.371+ cert_array = _cert_array_from_pem(trust_bundle)372+373+ # Ok, now the hard part. We want to get the SecTrustRef that ST has374+ # created for this connection, shove our CAs into it, tell ST to375+ # ignore everything else it knows, and then ask if it can build a376+ # chain. This is a buuuunch of code.377+ result = Security.SSLCopyPeerTrust(378+ self.context, ctypes.byref(trust)379+ )380+ _assert_no_error(result)381+ if not trust:382+ raise ssl.SSLError("Failed to copy trust reference")383+384+ result = Security.SecTrustSetAnchorCertificates(trust, cert_array)385+ _assert_no_error(result)386+387+ result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)388+ _assert_no_error(result)389+390+ trust_result = Security.SecTrustResultType()391+ result = Security.SecTrustEvaluate(392+ trust, ctypes.byref(trust_result)393+ )394+ _assert_no_error(result)395+ finally:396+ if trust:397+ CoreFoundation.CFRelease(trust)398+399+ if cert_array is None:400+ CoreFoundation.CFRelease(cert_array)401+402+ # Ok, now we can look at what the result was.403+ successes = (404+ SecurityConst.kSecTrustResultUnspecified,405+ SecurityConst.kSecTrustResultProceed406+ )407+ if trust_result.value not in successes:408+ raise ssl.SSLError(409+ "certificate verify failed, error code: %d" %410+ trust_result.value411+ )412+413+ def handshake(self,414+ server_hostname,415+ verify,416+ trust_bundle,417+ min_version,418+ max_version,419+ client_cert,420+ client_key,421+ client_key_passphrase):422+ """423+ Actually performs the TLS handshake. This is run automatically by424+ wrapped socket, and shouldn't be needed in user code.425+ """426+ # First, we do the initial bits of connection setup. We need to create427+ # a context, set its I/O funcs, and set the connection reference.428+ self.context = Security.SSLCreateContext(429+ None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType430+ )431+ result = Security.SSLSetIOFuncs(432+ self.context, _read_callback_pointer, _write_callback_pointer433+ )434+ _assert_no_error(result)435+436+ # Here we need to compute the handle to use. We do this by taking the437+ # id of self modulo 2**31 - 1. If this is already in the dictionary, we438+ # just keep incrementing by one until we find a free space.439+ with _connection_ref_lock:440+ handle = id(self) % 2147483647441+ while handle in _connection_refs:442+ handle = (handle + 1) % 2147483647443+ _connection_refs[handle] = self444+445+ result = Security.SSLSetConnection(self.context, handle)446+ _assert_no_error(result)447+448+ # If we have a server hostname, we should set that too.449+ if server_hostname:450+ if not isinstance(server_hostname, bytes):451+ server_hostname = server_hostname.encode('utf-8')452+453+ result = Security.SSLSetPeerDomainName(454+ self.context, server_hostname, len(server_hostname)455+ )456+ _assert_no_error(result)457+458+ # Setup the ciphers.459+ self._set_ciphers()460+461+ # Set the minimum and maximum TLS versions.462+ result = Security.SSLSetProtocolVersionMin(self.context, min_version)463+ _assert_no_error(result)464+ result = Security.SSLSetProtocolVersionMax(self.context, max_version)465+ _assert_no_error(result)466+467+ # If there's a trust DB, we need to use it. We do that by telling468+ # SecureTransport to break on server auth. We also do that if we don't469+ # want to validate the certs at all: we just won't actually do any470+ # authing in that case.471+ if not verify or trust_bundle is not None:472+ result = Security.SSLSetSessionOption(473+ self.context,474+ SecurityConst.kSSLSessionOptionBreakOnServerAuth,475+ True476+ )477+ _assert_no_error(result)478+479+ # If there's a client cert, we need to use it.480+ if client_cert:481+ self._keychain, self._keychain_dir = _temporary_keychain()482+ self._client_cert_chain = _load_client_cert_chain(483+ self._keychain, client_cert, client_key484+ )485+ result = Security.SSLSetCertificate(486+ self.context, self._client_cert_chain487+ )488+ _assert_no_error(result)489+490+ while True:491+ with self._raise_on_error():492+ result = Security.SSLHandshake(self.context)493+494+ if result == SecurityConst.errSSLWouldBlock:495+ raise socket.timeout("handshake timed out")496+ elif result == SecurityConst.errSSLServerAuthCompleted:497+ self._custom_validate(verify, trust_bundle)498+ continue499+ else:500+ _assert_no_error(result)501+ break502+503+ def fileno(self):504+ return self.socket.fileno()505+506+ # Copy-pasted from Python 3.5 source code507+ def _decref_socketios(self):508+ if self._makefile_refs > 0:509+ self._makefile_refs -= 1510+ if self._closed:511+ self.close()512+513+ def recv(self, bufsiz):514+ buffer = ctypes.create_string_buffer(bufsiz)515+ bytes_read = self.recv_into(buffer, bufsiz)516+ data = buffer[:bytes_read]517+ return data518+519+ def recv_into(self, buffer, nbytes=None):520+ # Read short on EOF.521+ if self._closed:522+ return 0523+524+ if nbytes is None:525+ nbytes = len(buffer)526+527+ buffer = (ctypes.c_char * nbytes).from_buffer(buffer)528+ processed_bytes = ctypes.c_size_t(0)529+530+ with self._raise_on_error():531+ result = Security.SSLRead(532+ self.context, buffer, nbytes, ctypes.byref(processed_bytes)533+ )534+535+ # There are some result codes that we want to treat as "not always536+ # errors". Specifically, those are errSSLWouldBlock,537+ # errSSLClosedGraceful, and errSSLClosedNoNotify.538+ if (result == SecurityConst.errSSLWouldBlock):539+ # If we didn't process any bytes, then this was just a time out.540+ # However, we can get errSSLWouldBlock in situations when we *did*541+ # read some data, and in those cases we should just read "short"542+ # and return.543+ if processed_bytes.value == 0:544+ # Timed out, no data read.545+ raise socket.timeout("recv timed out")546+ elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):547+ # The remote peer has closed this connection. We should do so as548+ # well. Note that we don't actually return here because in549+ # principle this could actually be fired along with return data.550+ # It's unlikely though.551+ self.close()552+ else:553+ _assert_no_error(result)554+555+ # Ok, we read and probably succeeded. We should return whatever data556+ # was actually read.557+ return processed_bytes.value558+559+ def settimeout(self, timeout):560+ self._timeout = timeout561+562+ def gettimeout(self):563+ return self._timeout564+565+ def send(self, data):566+ processed_bytes = ctypes.c_size_t(0)567+568+ with self._raise_on_error():569+ result = Security.SSLWrite(570+ self.context, data, len(data), ctypes.byref(processed_bytes)571+ )572+573+ if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0:574+ # Timed out575+ raise socket.timeout("send timed out")576+ else:577+ _assert_no_error(result)578+579+ # We sent, and probably succeeded. Tell them how much we sent.580+ return processed_bytes.value581+582+ def sendall(self, data):583+ total_sent = 0584+ while total_sent < len(data):585+ sent = self.send(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])586+ total_sent += sent587+588+ def shutdown(self):589+ with self._raise_on_error():590+ Security.SSLClose(self.context)591+592+ def close(self):593+ # TODO: should I do clean shutdown here? Do I have to?594+ if self._makefile_refs < 1:595+ self._closed = True596+ if self.context:597+ CoreFoundation.CFRelease(self.context)598+ self.context = None599+ if self._client_cert_chain:600+ CoreFoundation.CFRelease(self._client_cert_chain)601+ self._client_cert_chain = None602+ if self._keychain:603+ Security.SecKeychainDelete(self._keychain)604+ CoreFoundation.CFRelease(self._keychain)605+ shutil.rmtree(self._keychain_dir)606+ self._keychain = self._keychain_dir = None607+ return self.socket.close()608+ else:609+ self._makefile_refs -= 1610+611+ def getpeercert(self, binary_form=False):612+ # Urgh, annoying.613+ #614+ # Here's how we do this:615+ #616+ # 1. Call SSLCopyPeerTrust to get hold of the trust object for this617+ # connection.618+ # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf.619+ # 3. To get the CN, call SecCertificateCopyCommonName and process that620+ # string so that it's of the appropriate type.621+ # 4. To get the SAN, we need to do something a bit more complex:622+ # a. Call SecCertificateCopyValues to get the data, requesting623+ # kSecOIDSubjectAltName.624+ # b. Mess about with this dictionary to try to get the SANs out.625+ #626+ # This is gross. Really gross. It's going to be a few hundred LoC extra627+ # just to repeat something that SecureTransport can *already do*. So my628+ # operating assumption at this time is that what we want to do is629+ # instead to just flag to urllib3 that it shouldn't do its own hostname630+ # validation when using SecureTransport.631+ if not binary_form:632+ raise ValueError(633+ "SecureTransport only supports dumping binary certs"634+ )635+ trust = Security.SecTrustRef()636+ certdata = None637+ der_bytes = None638+639+ try:640+ # Grab the trust store.641+ result = Security.SSLCopyPeerTrust(642+ self.context, ctypes.byref(trust)643+ )644+ _assert_no_error(result)645+ if not trust:646+ # Probably we haven't done the handshake yet. No biggie.647+ return None648+649+ cert_count = Security.SecTrustGetCertificateCount(trust)650+ if not cert_count:651+ # Also a case that might happen if we haven't handshaked.652+ # Handshook? Handshaken?653+ return None654+655+ leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)656+ assert leaf657+658+ # Ok, now we want the DER bytes.659+ certdata = Security.SecCertificateCopyData(leaf)660+ assert certdata661+662+ data_length = CoreFoundation.CFDataGetLength(certdata)663+ data_buffer = CoreFoundation.CFDataGetBytePtr(certdata)664+ der_bytes = ctypes.string_at(data_buffer, data_length)665+ finally:666+ if certdata:667+ CoreFoundation.CFRelease(certdata)668+ if trust:669+ CoreFoundation.CFRelease(trust)670+671+ return der_bytes672+673+ def _reuse(self):674+ self._makefile_refs += 1675+676+ def _drop(self):677+ if self._makefile_refs < 1:678+ self.close()679+ else:680+ self._makefile_refs -= 1681+682+683+if _fileobject: # Platform-specific: Python 2684+ def makefile(self, mode, bufsize=-1):685+ self._makefile_refs += 1686+ return _fileobject(self, mode, bufsize, close=True)687+else: # Platform-specific: Python 3688+ def makefile(self, mode="r", buffering=None, *args, **kwargs):689+ # We disable buffering with SecureTransport because it conflicts with690+ # the buffering that ST does internally (see issue #1153 for more).691+ buffering = 0692+ return backport_makefile(self, mode, buffering, *args, **kwargs)693+694+WrappedSocket.makefile = makefile695+696+697+class SecureTransportContext(object):698+ """699+ I am a wrapper class for the SecureTransport library, to translate the700+ interface of the standard library ``SSLContext`` object to calls into701+ SecureTransport.702+ """703+ def __init__(self, protocol):704+ self._min_version, self._max_version = _protocol_to_min_max[protocol]705+ self._options = 0706+ self._verify = False707+ self._trust_bundle = None708+ self._client_cert = None709+ self._client_key = None710+ self._client_key_passphrase = None711+712+ @property713+ def check_hostname(self):714+ """715+ SecureTransport cannot have its hostname checking disabled. For more,716+ see the comment on getpeercert() in this file.717+ """718+ return True719+720+ @check_hostname.setter721+ def check_hostname(self, value):722+ """723+ SecureTransport cannot have its hostname checking disabled. For more,724+ see the comment on getpeercert() in this file.725+ """726+ pass727+728+ @property729+ def options(self):730+ # TODO: Well, crap.731+ #732+ # So this is the bit of the code that is the most likely to cause us733+ # trouble. Essentially we need to enumerate all of the SSL options that734+ # users might want to use and try to see if we can sensibly translate735+ # them, or whether we should just ignore them.736+ return self._options737+738+ @options.setter739+ def options(self, value):740+ # TODO: Update in line with above.741+ self._options = value742+743+ @property744+ def verify_mode(self):745+ return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE746+747+ @verify_mode.setter748+ def verify_mode(self, value):749+ self._verify = True if value == ssl.CERT_REQUIRED else False750+751+ def set_default_verify_paths(self):752+ # So, this has to do something a bit weird. Specifically, what it does753+ # is nothing.754+ #755+ # This means that, if we had previously had load_verify_locations756+ # called, this does not undo that. We need to do that because it turns757+ # out that the rest of the urllib3 code will attempt to load the758+ # default verify paths if it hasn't been told about any paths, even if759+ # the context itself was sometime earlier. We resolve that by just760+ # ignoring it.761+ pass762+763+ def load_default_certs(self):764+ return self.set_default_verify_paths()765+766+ def set_ciphers(self, ciphers):767+ # For now, we just require the default cipher string.768+ if ciphers != util.ssl_.DEFAULT_CIPHERS:769+ raise ValueError(770+ "SecureTransport doesn't support custom cipher strings"771+ )772+773+ def load_verify_locations(self, cafile=None, capath=None, cadata=None):774+ # OK, we only really support cadata and cafile.775+ if capath is not None:776+ raise ValueError(777+ "SecureTransport does not support cert directories"778+ )779+780+ self._trust_bundle = cafile or cadata781+782+ def load_cert_chain(self, certfile, keyfile=None, password=None):783+ self._client_cert = certfile784+ self._client_key = keyfile785+ self._client_cert_passphrase = password786+787+ def wrap_socket(self, sock, server_side=False,788+ do_handshake_on_connect=True, suppress_ragged_eofs=True,789+ server_hostname=None):790+ # So, what do we do here? Firstly, we assert some properties. This is a791+ # stripped down shim, so there is some functionality we don't support.792+ # See PEP 543 for the real deal.793+ assert not server_side794+ assert do_handshake_on_connect795+ assert suppress_ragged_eofs796+797+ # Ok, we're good to go. Now we want to create the wrapped socket object798+ # and store it in the appropriate place.799+ wrapped_socket = WrappedSocket(sock)800+801+ # Now we can handshake802+ wrapped_socket.handshake(803+ server_hostname, self._verify, self._trust_bundle,804+ self._min_version, self._max_version, self._client_cert,805+ self._client_key, self._client_key_passphrase806+ )807+ return wrapped_socketmodified:requests/packages/urllib3/util/__init__.py+2 added
5 unmodified lines6 from .ssl_ import (7 SSLContext,8 HAS_SNI,9 IS_PYOPENSSL,10+ IS_SECURETRANSPORT,11 assert_fingerprint,12 resolve_cert_reqs,13 resolve_ssl_version,14 ssl_wrap_socket,17 unmodified lines32 33 __all__ = (34 'HAS_SNI',35 'IS_PYOPENSSL',36+ 'IS_SECURETRANSPORT',37 'SSLContext',38 'Retry',39 'Timeout',40 'Url',14 unmodified linesmodified:requests/packages/urllib3/util/request.py+1 added-1 removed
106 unmodified lines107 if body_seek is not None and isinstance(body_pos, integer_types):108 try:109 body_seek(body_pos)110 except (IOError, OSError):111- raise UnrewindableBodyError("An error occured when rewinding request "111+ raise UnrewindableBodyError("An error occurred when rewinding request "112 "body for redirect/retry.")113 elif body_pos is _FAILEDTELL:114 raise UnrewindableBodyError("Unable to record file position for rewinding "115 "request body during a redirect/retry.")3 unmodified linesmodified:requests/packages/urllib3/util/retry.py+17 added-5 removed
83 unmodified lines84 Set to ``0`` to fail on the first retry of this type.85 86 Set to ``False`` to disable and imply ``raise_on_redirect=False``.87 88+ :param int status:89+ How many times to retry on bad status codes.90+91+ These are retries made on responses, where status code matches92+ ``status_forcelist``.93+94+ Set to ``0`` to fail on the first retry of this type.95+96 :param iterable method_whitelist:97 Set of uppercased HTTP method verbs that we should retry on.98 99 By default, we only retry on methods which are considered to be48 unmodified lines148 149 #: Maximum backoff time.150 BACKOFF_MAX = 120151 144- def __init__(self, total=10, connect=None, read=None, redirect=None,152+ def __init__(self, total=10, connect=None, read=None, redirect=None, status=None,153 method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None,154 backoff_factor=0, raise_on_redirect=True, raise_on_status=True,155 history=None, respect_retry_after_header=True):156 157 self.total = total158 self.connect = connect159 self.read = read160+ self.status = status161 162 if redirect is False or total is False:163 redirect = 0164 raise_on_redirect = False9 unmodified lines174 175 def new(self, **kw):176 params = dict(177 total=self.total,169- connect=self.connect, read=self.read, redirect=self.redirect,178+ connect=self.connect, read=self.read, redirect=self.redirect, status=self.status,179 method_whitelist=self.method_whitelist,180 status_forcelist=self.status_forcelist,181 backoff_factor=self.backoff_factor,182 raise_on_redirect=self.raise_on_redirect,125 unmodified lines308 has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES))309 310 def is_exhausted(self):311 """ Are we out of retries? """303- retry_counts = (self.total, self.connect, self.read, self.redirect)312+ retry_counts = (self.total, self.connect, self.read, self.redirect, self.status)313 retry_counts = list(filter(None, retry_counts))314 if not retry_counts:315 return False316 21 unmodified lines338 339 connect = self.connect340 read = self.read341 redirect = self.redirect342+ status_count = self.status343 cause = 'unknown'344 status = None345 redirect_location = None346 23 unmodified lines370 # Incrementing because of a server error like a 500 in371 # status_forcelist and a the given method is in the whitelist372 cause = ResponseError.GENERIC_ERROR373 if response and response.status:374+ if status_count is not None:375+ status_count -= 1376 cause = ResponseError.SPECIFIC_ERROR.format(377 status_code=response.status)378 status = response.status379 380 history = self.history + (RequestHistory(method, url, error, status, redirect_location),)381 382 new_retry = self.new(383 total=total,372- connect=connect, read=read, redirect=redirect,384+ connect=connect, read=read, redirect=redirect, status=status_count,385 history=history)386 387 if new_retry.is_exhausted():388 raise MaxRetryError(_pool, url, error or ResponseError(cause))3 unmodified lines392 return new_retry393 394 def __repr__(self):395 return ('{cls.__name__}(total={self.total}, connect={self.connect}, '384- 'read={self.read}, redirect={self.redirect})').format(396+ 'read={self.read}, redirect={self.redirect}, status={self.status})').format(397 cls=type(self), self=self)398 399 400 # For backwards compatibility (equivalent to pre-v1.9):1 unmodified linemodified:requests/packages/urllib3/util/selectors.py+118 added-61 removed
6 unmodified lines7 8 import errno9 import math10 import select11+import socket12+import sys13+import time14 from collections import namedtuple, Mapping15 13-import time16 try:17 monotonic = time.monotonic18 except (AttributeError, ImportError): # Python 3.3<19 monotonic = time.time2 unmodified lines22 EVENT_WRITE = (1 << 1)23 24 HAS_SELECT = True # Variable that shows whether the platform has a selector.25 _SYSCALL_SENTINEL = object() # Sentinel in case a system call returns None.26+_DEFAULT_SELECTOR = None27 28 29 class SelectorError(Exception):30 def __init__(self, errcode):21 unmodified lines52 raise ValueError("Invalid file descriptor: {0}".format(fd))53 return fd54 55 53-def _syscall_wrapper(func, recalc_timeout, *args, **kwargs):54- """ Wrapper function for syscalls that could fail due to EINTR.55- All functions should be retried if there is time left in the timeout56- in accordance with PEP 475. """57- timeout = kwargs.get("timeout", None)58- if timeout is None:59- expires = None60- recalc_timeout = False61- else:62- timeout = float(timeout)63- if timeout < 0.0: # Timeout less than 0 treated as no timeout.64- expires = None65- else:66- expires = monotonic() + timeout67-68- args = list(args)69- if recalc_timeout and "timeout" not in kwargs:70- raise ValueError(71- "Timeout must be in args or kwargs to be recalculated")72-73- result = _SYSCALL_SENTINEL74- while result is _SYSCALL_SENTINEL:56+# Determine which function to use to wrap system calls because Python 3.5+57+# already handles the case when system calls are interrupted.58+if sys.version_info >= (3, 5):59+ def _syscall_wrapper(func, _, *args, **kwargs):60+ """ This is the short-circuit version of the below logic61+ because in Python 3.5+ all system calls automatically restart62+ and recalculate their timeouts. """63 try:76- result = func(*args, **kwargs)77- # OSError is thrown by select.select78- # IOError is thrown by select.epoll.poll79- # select.error is thrown by select.poll.poll80- # Aren't we thankful for Python 3.x rework for exceptions?64+ return func(*args, **kwargs)65 except (OSError, IOError, select.error) as e:82- # select.error wasn't a subclass of OSError in the past.66 errcode = None67 if hasattr(e, "errno"):68 errcode = e.errno86- elif hasattr(e, "args"):87- errcode = e.args[0]69+ raise SelectorError(errcode)70+else:71+ def _syscall_wrapper(func, recalc_timeout, *args, **kwargs):72+ """ Wrapper function for syscalls that could fail due to EINTR.73+ All functions should be retried if there is time left in the timeout74+ in accordance with PEP 475. """75+ timeout = kwargs.get("timeout", None)76+ if timeout is None:77+ expires = None78+ recalc_timeout = False79+ else:80+ timeout = float(timeout)81+ if timeout < 0.0: # Timeout less than 0 treated as no timeout.82+ expires = None83+ else:84+ expires = monotonic() + timeout85 89- # Also test for the Windows equivalent of EINTR.90- is_interrupt = (errcode == errno.EINTR or (hasattr(errno, "WSAEINTR") and91- errcode == errno.WSAEINTR))86+ args = list(args)87+ if recalc_timeout and "timeout" not in kwargs:88+ raise ValueError(89+ "Timeout must be in args or kwargs to be recalculated")90 93- if is_interrupt:94- if expires is not None:95- current_time = monotonic()96- if current_time > expires:97- raise OSError(errno=errno.ETIMEDOUT)98- if recalc_timeout:99- if "timeout" in kwargs:100- kwargs["timeout"] = expires - current_time101- continue102- if errcode:103- raise SelectorError(errcode)104- else:105- raise106- return result91+ result = _SYSCALL_SENTINEL92+ while result is _SYSCALL_SENTINEL:93+ try:94+ result = func(*args, **kwargs)95+ # OSError is thrown by select.select96+ # IOError is thrown by select.epoll.poll97+ # select.error is thrown by select.poll.poll98+ # Aren't we thankful for Python 3.x rework for exceptions?99+ except (OSError, IOError, select.error) as e:100+ # select.error wasn't a subclass of OSError in the past.101+ errcode = None102+ if hasattr(e, "errno"):103+ errcode = e.errno104+ elif hasattr(e, "args"):105+ errcode = e.args[0]106 107+ # Also test for the Windows equivalent of EINTR.108+ is_interrupt = (errcode == errno.EINTR or (hasattr(errno, "WSAEINTR") and109+ errcode == errno.WSAEINTR))110 111+ if is_interrupt:112+ if expires is not None:113+ current_time = monotonic()114+ if current_time > expires:115+ raise OSError(errno=errno.ETIMEDOUT)116+ if recalc_timeout:117+ if "timeout" in kwargs:118+ kwargs["timeout"] = expires - current_time119+ continue120+ if errcode:121+ raise SelectorError(errcode)122+ else:123+ raise124+ return result125+126+127 SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data'])128 129 130 class _SelectorMapping(Mapping):77 unmodified lines208 try:209 key = self._fd_to_key.pop(self._fileobj_lookup(fileobj))210 except KeyError:211 raise KeyError("{0!r} is not registered".format(fileobj))212+213+ # Getting the fileno of a closed socket on Windows errors with EBADF.214+ except socket.error as e: # Platform-specific: Windows.215+ if e.errno != errno.EBADF:216+ raise217+ else:218+ for key in self._fd_to_key.values():219+ if key.fileobj is fileobj:220+ self._fd_to_key.pop(key.fd)221+ break222+ else:223+ raise KeyError("{0!r} is not registered".format(fileobj))224 return key225 226 def modify(self, fileobj, events, data=None):227 """ Change a registered file object monitored events and data. """307 unmodified lines535 self._kqueue.close()536 super(KqueueSelector, self).close()537 538 539+if not hasattr(select, 'select'): # Platform-specific: AppEngine540+ HAS_SELECT = False541+542+543+def _can_allocate(struct):544+ """ Checks that select structs can be allocated by the underlying545+ operating system, not just advertised by the select module. We don't546+ check select() because we'll be hopeful that most platforms that547+ don't have it available will not advertise it. (ie: GAE) """548+ try:549+ # select.poll() objects won't fail until used.550+ if struct == 'poll':551+ p = select.poll()552+ p.poll(0)553+554+ # All others will fail on allocation.555+ else:556+ getattr(select, struct)().close()557+ return True558+ except (OSError, AttributeError) as e:559+ return False560+561+562 # Choose the best implementation, roughly:563 # kqueue == epoll > poll > select. Devpoll not supported. (See above)564 # select() also can't accept a FD > FD_SETSIZE (usually around 1024)512-if 'KqueueSelector' in globals(): # Platform-specific: Mac OS and BSD513- DefaultSelector = KqueueSelector514-elif 'EpollSelector' in globals(): # Platform-specific: Linux515- DefaultSelector = EpollSelector516-elif 'PollSelector' in globals(): # Platform-specific: Linux517- DefaultSelector = PollSelector518-elif 'SelectSelector' in globals(): # Platform-specific: Windows519- DefaultSelector = SelectSelector520-else: # Platform-specific: AppEngine521- def no_selector(_):522- raise ValueError("Platform does not have a selector")523- DefaultSelector = no_selector524- HAS_SELECT = False565+def DefaultSelector():566+ """ This function serves as a first call for DefaultSelector to567+ detect if the select module is being monkey-patched incorrectly568+ by eventlet, greenlet, and preserve proper behavior. """569+ global _DEFAULT_SELECTOR570+ if _DEFAULT_SELECTOR is None:571+ if _can_allocate('kqueue'):572+ _DEFAULT_SELECTOR = KqueueSelector573+ elif _can_allocate('epoll'):574+ _DEFAULT_SELECTOR = EpollSelector575+ elif _can_allocate('poll'):576+ _DEFAULT_SELECTOR = PollSelector577+ elif hasattr(select, 'select'):578+ _DEFAULT_SELECTOR = SelectSelector579+ else: # Platform-specific: AppEngine580+ raise ValueError('Platform does not have a selector')581+ return _DEFAULT_SELECTOR()modified:requests/packages/urllib3/util/ssl_.py+1 added
10 unmodified lines11 12 SSLContext = None13 HAS_SNI = False14 IS_PYOPENSSL = False15+IS_SECURETRANSPORT = False16 17 # Maps the length of a digest to a possible hash function producing this digest18 HASHFUNC_MAP = {19 32: md5,318 unmodified linesmodified:requests/packages/urllib3/util/url.py+5 added-1 removed
4 unmodified lines5 6 7 url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment']8 9+# We only want to normalize urls with an HTTP(S) scheme.10+# urllib3 infers URLs without a scheme (None) to be http.11+NORMALIZABLE_SCHEMES = ('http', 'https', None)12 13+14 class Url(namedtuple('Url', url_attrs)):15 """16 Datastructure for representing an HTTP URL. Used as a return value for17 :func:`parse_url`. Both the scheme and host are normalized as they are6 unmodified lines24 if path and not path.startswith('/'):25 path = '/' + path26 if scheme:27 scheme = scheme.lower()24- if host:28+ if host and scheme in NORMALIZABLE_SCHEMES:29 host = host.lower()30 return super(Url, cls).__new__(cls, scheme, auth, host, port, path,31 query, fragment)32 198 unmodified linesmodified:requests/packages/urllib3/__init__.py+1 added-1 removed
30 unmodified lines31 pass32 33 __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'34 __license__ = 'MIT'35-__version__ = '1.20'35+__version__ = '1.21.1'36 37 __all__ = (38 'HTTPConnectionPool',39 'HTTPSConnectionPool',58 unmodified linesmodified:requests/packages/urllib3/_collections.py+4 added-14 removed
142 unmodified lines143 if kwargs:144 self.extend(kwargs)145 146 def __setitem__(self, key, val):147- self._container[key.lower()] = (key, val)147+ self._container[key.lower()] = [key, val]148 return self._container[key.lower()]149 150 def __getitem__(self, key):151 val = self._container[key.lower()]62 unmodified lines214 >>> headers['foo']215 'bar, baz'216 """217 key_lower = key.lower()218- new_vals = key, val218+ new_vals = [key, val]219 # Keep the common case aka no item present as fast as possible220 vals = self._container.setdefault(key_lower, new_vals)221 if new_vals is not vals:222- # new_vals was not inserted, as there was a previous one223- if isinstance(vals, list):224- # If already several items got inserted, we have a list225- vals.append(val)222+ vals.append(val)226- else:227- # vals should be a tuple then, i.e. only one item so far228- # Need to convert the tuple to list for further extension229- self._container[key_lower] = [vals[0], vals[1], val]223 224 def extend(self, *args, **kwargs):225 """Generic import function for any type of header-like object.226 Adapted version of MutableMapping.update in order to insert items27 unmodified lines254 vals = self._container[key.lower()]255 except KeyError:256 return []257 else:265- if isinstance(vals, tuple):266- return [vals[1]]267- else:268- return vals[1:]258+ return vals[1:]259 260 # Backwards compatibility for httplib261 getheaders = getlist262 getallmatchingheaders = getlist52 unmodified linesmodified:requests/packages/urllib3/connection.py+4 added
327 unmodified lines328 if self.assert_fingerprint:329 assert_fingerprint(self.sock.getpeercert(binary_form=True),330 self.assert_fingerprint)331 elif context.verify_mode != ssl.CERT_NONE \332+ and not getattr(context, 'check_hostname', False) \333 and self.assert_hostname is not False:334+ # While urllib3 attempts to always turn off hostname matching from335+ # the TLS library, this cannot always be done. So we check whether336+ # the TLS Library still thinks it's matching hostnames.337 cert = self.sock.getpeercert()338 if not cert.get('subjectAltName', ()):339 warnings.warn((340 'Certificate for {0} has no `subjectAltName`, falling back to check for a '33 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+130 added-53 removed
19 unmodified lines20 21 SSL_KEYWORDS = ('key_file', 'cert_file', 'cert_reqs', 'ca_certs',22 'ssl_version', 'ca_cert_dir', 'ssl_context')23 24-# The base fields to use when determining what pool to get a connection from;25-# these do not rely on the ``connection_pool_kw`` and can be determined by the26-# URL and potentially the ``urllib3.connection.port_by_scheme`` dictionary.27-#28-# All custom key schemes should include the fields in this key at a minimum.29-BasePoolKey = collections.namedtuple('BasePoolKey', ('scheme', 'host', 'port'))30-31-# The fields to use when determining what pool to get a HTTP and HTTPS32-# connection from. All additional fields must be present in the PoolManager's33-# ``connection_pool_kw`` instance variable.34-HTTPPoolKey = collections.namedtuple(35- 'HTTPPoolKey', BasePoolKey._fields + ('timeout', 'retries', 'strict',36- 'block', 'source_address')24+# All known keyword arguments that could be provided to the pool manager, its25+# pools, or the underlying connections. This is used to construct a pool key.26+_key_fields = (27+ 'key_scheme', # str28+ 'key_host', # str29+ 'key_port', # int30+ 'key_timeout', # int or float or Timeout31+ 'key_retries', # int or Retry32+ 'key_strict', # bool33+ 'key_block', # bool34+ 'key_source_address', # str35+ 'key_key_file', # str36+ 'key_cert_file', # str37+ 'key_cert_reqs', # str38+ 'key_ca_certs', # str39+ 'key_ssl_version', # str40+ 'key_ca_cert_dir', # str41+ 'key_ssl_context', # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext42+ 'key_maxsize', # int43+ 'key_headers', # dict44+ 'key__proxy', # parsed proxy url45+ 'key__proxy_headers', # dict46+ 'key_socket_options', # list of (level (int), optname (int), value (int or str)) tuples47+ 'key__socks_options', # dict48+ 'key_assert_hostname', # bool or string49+ 'key_assert_fingerprint', # str50 )38-HTTPSPoolKey = collections.namedtuple(39- 'HTTPSPoolKey', HTTPPoolKey._fields + SSL_KEYWORDS40-)51 52+#: The namedtuple class used to construct keys for the connection pool.53+#: All custom key schemes should include the fields in this key at a minimum.54+PoolKey = collections.namedtuple('PoolKey', _key_fields)55 56+57 def _default_key_normalizer(key_class, request_context):58 """45- Create a pool key of type ``key_class`` for a request.59+ Create a pool key out of a request context dictionary.60 61 According to RFC 3986, both the scheme and host are case-insensitive.62 Therefore, this function normalizes both before constructing the pool63 key for an HTTPS request. If you wish to change this behaviour, provide1 unmodified line65 66 :param key_class:67 The class to use when constructing the key. This should be a namedtuple68 with the ``scheme`` and ``host`` keys at a minimum.55-69+ :type key_class: namedtuple70 :param request_context:71 A dictionary-like object that contain the context for a request.58- It should contain a key for each field in the :class:`HTTPPoolKey`72+ :type request_context: dict73+74+ :return: A namedtuple that can be used as a connection pool key.75+ :rtype: PoolKey76 """60- context = {}61- for key in key_class._fields:62- context[key] = request_context.get(key)77+ # Since we mutate the dictionary, make a copy first78+ context = request_context.copy()79 context['scheme'] = context['scheme'].lower()80 context['host'] = context['host'].lower()81+82+ # These are both dictionaries and need to be transformed into frozensets83+ for key in ('headers', '_proxy_headers', '_socks_options'):84+ if key in context and context[key] is not None:85+ context[key] = frozenset(context[key].items())86+87+ # The socket_options key may be a list and needs to be transformed into a88+ # tuple.89+ socket_opts = context.get('socket_options')90+ if socket_opts is not None:91+ context['socket_options'] = tuple(socket_opts)92+93+ # Map the kwargs to the names in the namedtuple - this is necessary since94+ # namedtuples can't have fields starting with '_'.95+ for key in list(context.keys()):96+ context['key_' + key] = context.pop(key)97+98+ # Default to ``None`` for keys missing from the context99+ for field in key_class._fields:100+ if field not in context:101+ context[field] = None102+103 return key_class(**context)104 105 68-# A dictionary that maps a scheme to a callable that creates a pool key.69-# This can be used to alter the way pool keys are constructed, if desired.70-# Each PoolManager makes a copy of this dictionary so they can be configured71-# globally here, or individually on the instance.106+#: A dictionary that maps a scheme to a callable that creates a pool key.107+#: This can be used to alter the way pool keys are constructed, if desired.108+#: Each PoolManager makes a copy of this dictionary so they can be configured109+#: globally here, or individually on the instance.110 key_fn_by_scheme = {73- 'http': functools.partial(_default_key_normalizer, HTTPPoolKey),74- 'https': functools.partial(_default_key_normalizer, HTTPSPoolKey),111+ 'http': functools.partial(_default_key_normalizer, PoolKey),112+ 'https': functools.partial(_default_key_normalizer, PoolKey),113 }114 115 pool_classes_by_scheme = {116 'http': HTTPConnectionPool,49 unmodified lines166 self.clear()167 # Return False to re-raise any potential exceptions168 return False169 132- def _new_pool(self, scheme, host, port):170+ def _new_pool(self, scheme, host, port, request_context=None):171 """134- Create a new :class:`ConnectionPool` based on host, port and scheme.172+ Create a new :class:`ConnectionPool` based on host, port, scheme, and173+ any additional pool keyword arguments.174 136- This method is used to actually create the connection pools handed out137- by :meth:`connection_from_url` and companion methods. It is intended138- to be overridden for customization.175+ If ``request_context`` is provided, it is provided as keyword arguments176+ to the pool class used. This method is used to actually create the177+ connection pools handed out by :meth:`connection_from_url` and178+ companion methods. It is intended to be overridden for customization.179 """180 pool_cls = self.pool_classes_by_scheme[scheme]141- kwargs = self.connection_pool_kw181+ if request_context is None:182+ request_context = self.connection_pool_kw.copy()183+184+ # Although the context has everything necessary to create the pool,185+ # this function has historically only used the scheme, host, and port186+ # in the positional args. When an API change is acceptable these can187+ # be removed.188+ for key in ('scheme', 'host', 'port'):189+ request_context.pop(key, None)190+191 if scheme == 'http':143- kwargs = self.connection_pool_kw.copy()192 for kw in SSL_KEYWORDS:145- kwargs.pop(kw, None)193+ request_context.pop(kw, None)194 147- return pool_cls(host, port, **kwargs)195+ return pool_cls(host, port, **request_context)196 197 def clear(self):198 """199 Empty our store of pools and direct them all to close.2 unmodified lines202 re-used after completion.203 """204 self.pools.clear()205 158- def connection_from_host(self, host, port=None, scheme='http'):206+ def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):207 """208 Get a :class:`ConnectionPool` based on the host, port, and scheme.209 210 If ``port`` isn't given, it will be derived from the ``scheme`` using163- ``urllib3.connectionpool.port_by_scheme``.211+ ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is212+ provided, it is merged with the instance's ``connection_pool_kw``213+ variable and used to create the new connection pool, if one is214+ needed.215 """216 217 if not host:218 raise LocationValueError("No host specified.")219 169- request_context = self.connection_pool_kw.copy()220+ request_context = self._merge_pool_kwargs(pool_kwargs)221 request_context['scheme'] = scheme or 'http'222 if not port:223 port = port_by_scheme.get(request_context['scheme'].lower(), 80)224 request_context['port'] = port11 unmodified lines236 scheme = request_context['scheme'].lower()237 pool_key_constructor = self.key_fn_by_scheme[scheme]238 pool_key = pool_key_constructor(request_context)239 189- return self.connection_from_pool_key(pool_key)240+ return self.connection_from_pool_key(pool_key, request_context=request_context)241 191- def connection_from_pool_key(self, pool_key):242+ def connection_from_pool_key(self, pool_key, request_context=None):243 """244 Get a :class:`ConnectionPool` based on the provided pool key.245 246 ``pool_key`` should be a namedtuple that only contains immutable7 unmodified lines254 if pool:255 return pool256 257 # Make a fresh ConnectionPool of the desired type207- pool = self._new_pool(pool_key.scheme, pool_key.host, pool_key.port)258+ scheme = request_context['scheme']259+ host = request_context['host']260+ port = request_context['port']261+ pool = self._new_pool(scheme, host, port, request_context=request_context)262 self.pools[pool_key] = pool263 264 return pool265 212- def connection_from_url(self, url):266+ def connection_from_url(self, url, pool_kwargs=None):267 """214- Similar to :func:`urllib3.connectionpool.connection_from_url` but215- doesn't pass any additional parameters to the216- :class:`urllib3.connectionpool.ConnectionPool` constructor.268+ Similar to :func:`urllib3.connectionpool.connection_from_url`.269 218- Additional parameters are taken from the :class:`.PoolManager`219- constructor.270+ If ``pool_kwargs`` is not provided and a new pool needs to be271+ constructed, ``self.connection_pool_kw`` is used to initialize272+ the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``273+ is provided, it is used instead. Note that if a new pool does not274+ need to be created for the request, the provided ``pool_kwargs`` are275+ not used.276 """277 u = parse_url(url)222- return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)278+ return self.connection_from_host(u.host, port=u.port, scheme=u.scheme,279+ pool_kwargs=pool_kwargs)280 281+ def _merge_pool_kwargs(self, override):282+ """283+ Merge a dictionary of override values for self.connection_pool_kw.284+285+ This does not modify self.connection_pool_kw and returns a new dict.286+ Any keys in the override dictionary with a value of ``None`` are287+ removed from the merged dictionary.288+ """289+ base_pool_kwargs = self.connection_pool_kw.copy()290+ if override:291+ for key, value in override.items():292+ if value is None:293+ try:294+ del base_pool_kwargs[key]295+ except KeyError:296+ pass297+ else:298+ base_pool_kwargs[key] = value299+ return base_pool_kwargs300+301 def urlopen(self, method, url, redirect=True, **kw):302 """303 Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`304 with custom cross-host redirect logic and only sends the request-uri93 unmodified lines398 399 super(ProxyManager, self).__init__(400 num_pools, headers, **connection_pool_kw)401 325- def connection_from_host(self, host, port=None, scheme='http'):402+ def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):403 if scheme == "https":404 return super(ProxyManager, self).connection_from_host(328- host, port, scheme)405+ host, port, scheme, pool_kwargs=pool_kwargs)406 407 return super(ProxyManager, self).connection_from_host(331- self.proxy.host, self.proxy.port, self.proxy.scheme)408+ self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs)409 410 def _set_proxy_headers(self, url, headers=None):411 """412 Sets headers needed by proxies: specifically, the Accept and Host28 unmodified linesmodified:requests/packages/urllib3/response.py+5 added-1 removed
36 unmodified lines37 return self._obj.decompress(data)38 39 self._data += data40 try:41- return self._obj.decompress(data)41+ decompressed = self._obj.decompress(data)42+ if decompressed:43+ self._first_try = False44+ self._data = None45+ return decompressed46 except zlib.error:47 self._first_try = False48 self._obj = zlib.decompressobj(-zlib.MAX_WBITS)49 try:573 unmodified linesmodified:HISTORY.rst+4 added
37 unmodified lines38 - Fixed some code that was firing ``DeprecationWarning``s on Python 3.6.39 - The dismayed person emoticon (``/o\\``) no longer has a big head. I'm sure40 this is what you were all worrying about most.41 42+**Miscellaneous**43+44+- Updated bundled urllib3 to v1.21.1.45+46 2.13.0 (2017-01-24)47 +++++++++++++++++++48 49 **Features**1299 unmodified linesmodified:setup.py+1 added
42 unmodified lines43 'requests.packages.urllib3.contrib',44 'requests.packages.urllib3.util',45 'requests.packages.urllib3.packages.ssl_match_hostname',46 'requests.packages.urllib3.packages.backports',47+ 'requests.packages.urllib3.contrib._securetransport',48 ]49 50 requires = []51 test_requirements = ['pytest>=2.8.0', 'pytest-httpbin==0.0.7', 'pytest-cov', 'pytest-mock']53 unmodified lines