summaryrefslogtreecommitdiff
path: root/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib
diff options
context:
space:
mode:
authorShubham Saini <shubham6405@gmail.com>2019-08-05 08:32:33 +0000
committerShubham Saini <shubham6405@gmail.com>2019-08-05 08:32:33 +0000
commit227b2d30a8675b44918f9d9ca89b24144a938215 (patch)
tree9f8e6a28724514b6fdf463a9ab2067a7ef309b72 /venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib
parent842a8cfbbbdb1f92889d892e4859dbd5d40c5be8 (diff)
removing venv files
Diffstat (limited to 'venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib')
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/__init__.py0
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/__init__.py0
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/bindings.py593
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/low_level.py343
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/appengine.py296
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/ntlmpool.py112
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/pyopenssl.py455
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/securetransport.py810
-rw-r--r--venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/socks.py188
9 files changed, 0 insertions, 2797 deletions
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/__init__.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/__init__.py
+++ /dev/null
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/__init__.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/__init__.py
+++ /dev/null
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/bindings.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/bindings.py
deleted file mode 100644
index 9787b02..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/bindings.py
+++ /dev/null
@@ -1,593 +0,0 @@
1"""
2This module uses ctypes to bind a whole bunch of functions and constants from
3SecureTransport. The goal here is to provide the low-level API to
4SecureTransport. These are essentially the C-level functions and constants, and
5they're pretty gross to work with.
6
7This code is a bastardised version of the code found in Will Bond's oscrypto
8library. An enormous debt is owed to him for blazing this trail for us. For
9that reason, this code should be considered to be covered both by urllib3's
10license 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 a
15 copy of this software and associated documentation files (the "Software"),
16 to deal in the Software without restriction, including without limitation
17 the rights to use, copy, modify, merge, publish, distribute, sublicense,
18 and/or sell copies of the Software, and to permit persons to whom the
19 Software is furnished to do so, subject to the following conditions:
20
21 The above copyright notice and this permission notice shall be included in
22 all copies or substantial portions of the Software.
23
24 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
30 DEALINGS IN THE SOFTWARE.
31"""
32from __future__ import absolute_import
33
34import platform
35from ctypes.util import find_library
36from ctypes import (
37 c_void_p, c_int32, c_char_p, c_size_t, c_byte, c_uint32, c_ulong, c_long,
38 c_bool
39)
40from ctypes import CDLL, POINTER, CFUNCTYPE
41
42
43security_path = find_library('Security')
44if not security_path:
45 raise ImportError('The library Security could not be found')
46
47
48core_foundation_path = find_library('CoreFoundation')
49if not core_foundation_path:
50 raise ImportError('The library CoreFoundation could not be found')
51
52
53version = platform.mac_ver()[0]
54version_info = tuple(map(int, version.split('.')))
55if 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
62Security = CDLL(security_path, use_errno=True)
63CoreFoundation = CDLL(core_foundation_path, use_errno=True)
64
65Boolean = c_bool
66CFIndex = c_long
67CFStringEncoding = c_uint32
68CFData = c_void_p
69CFString = c_void_p
70CFArray = c_void_p
71CFMutableArray = c_void_p
72CFDictionary = c_void_p
73CFError = c_void_p
74CFType = c_void_p
75CFTypeID = c_ulong
76
77CFTypeRef = POINTER(CFType)
78CFAllocatorRef = c_void_p
79
80OSStatus = c_int32
81
82CFDataRef = POINTER(CFData)
83CFStringRef = POINTER(CFString)
84CFArrayRef = POINTER(CFArray)
85CFMutableArrayRef = POINTER(CFMutableArray)
86CFDictionaryRef = POINTER(CFDictionary)
87CFArrayCallBacks = c_void_p
88CFDictionaryKeyCallBacks = c_void_p
89CFDictionaryValueCallBacks = c_void_p
90
91SecCertificateRef = POINTER(c_void_p)
92SecExternalFormat = c_uint32
93SecExternalItemType = c_uint32
94SecIdentityRef = POINTER(c_void_p)
95SecItemImportExportFlags = c_uint32
96SecItemImportExportKeyParameters = c_void_p
97SecKeychainRef = POINTER(c_void_p)
98SSLProtocol = c_uint32
99SSLCipherSuite = c_uint32
100SSLContextRef = POINTER(c_void_p)
101SecTrustRef = POINTER(c_void_p)
102SSLConnectionRef = c_uint32
103SecTrustResultType = c_uint32
104SecTrustOptionFlags = c_uint32
105SSLProtocolSide = c_uint32
106SSLConnectionType = c_uint32
107SSLSessionOption = c_uint32
108
109
110try:
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 = OSStatus
122
123 Security.SecCertificateGetTypeID.argtypes = []
124 Security.SecCertificateGetTypeID.restype = CFTypeID
125
126 Security.SecIdentityGetTypeID.argtypes = []
127 Security.SecIdentityGetTypeID.restype = CFTypeID
128
129 Security.SecKeyGetTypeID.argtypes = []
130 Security.SecKeyGetTypeID.restype = CFTypeID
131
132 Security.SecCertificateCreateWithData.argtypes = [
133 CFAllocatorRef,
134 CFDataRef
135 ]
136 Security.SecCertificateCreateWithData.restype = SecCertificateRef
137
138 Security.SecCertificateCopyData.argtypes = [
139 SecCertificateRef
140 ]
141 Security.SecCertificateCopyData.restype = CFDataRef
142
143 Security.SecCopyErrorMessageString.argtypes = [
144 OSStatus,
145 c_void_p
146 ]
147 Security.SecCopyErrorMessageString.restype = CFStringRef
148
149 Security.SecIdentityCreateWithCertificate.argtypes = [
150 CFTypeRef,
151 SecCertificateRef,
152 POINTER(SecIdentityRef)
153 ]
154 Security.SecIdentityCreateWithCertificate.restype = OSStatus
155
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 = OSStatus
165
166 Security.SecKeychainDelete.argtypes = [
167 SecKeychainRef
168 ]
169 Security.SecKeychainDelete.restype = OSStatus
170
171 Security.SecPKCS12Import.argtypes = [
172 CFDataRef,
173 CFDictionaryRef,
174 POINTER(CFArrayRef)
175 ]
176 Security.SecPKCS12Import.restype = OSStatus
177
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 SSLWriteFunc
185 ]
186 Security.SSLSetIOFuncs.restype = OSStatus
187
188 Security.SSLSetPeerID.argtypes = [
189 SSLContextRef,
190 c_char_p,
191 c_size_t
192 ]
193 Security.SSLSetPeerID.restype = OSStatus
194
195 Security.SSLSetCertificate.argtypes = [
196 SSLContextRef,
197 CFArrayRef
198 ]
199 Security.SSLSetCertificate.restype = OSStatus
200
201 Security.SSLSetCertificateAuthorities.argtypes = [
202 SSLContextRef,
203 CFTypeRef,
204 Boolean
205 ]
206 Security.SSLSetCertificateAuthorities.restype = OSStatus
207
208 Security.SSLSetConnection.argtypes = [
209 SSLContextRef,
210 SSLConnectionRef
211 ]
212 Security.SSLSetConnection.restype = OSStatus
213
214 Security.SSLSetPeerDomainName.argtypes = [
215 SSLContextRef,
216 c_char_p,
217 c_size_t
218 ]
219 Security.SSLSetPeerDomainName.restype = OSStatus
220
221 Security.SSLHandshake.argtypes = [
222 SSLContextRef
223 ]
224 Security.SSLHandshake.restype = OSStatus
225
226 Security.SSLRead.argtypes = [
227 SSLContextRef,
228 c_char_p,
229 c_size_t,
230 POINTER(c_size_t)
231 ]
232 Security.SSLRead.restype = OSStatus
233
234 Security.SSLWrite.argtypes = [
235 SSLContextRef,
236 c_char_p,
237 c_size_t,
238 POINTER(c_size_t)
239 ]
240 Security.SSLWrite.restype = OSStatus
241
242 Security.SSLClose.argtypes = [
243 SSLContextRef
244 ]
245 Security.SSLClose.restype = OSStatus
246
247 Security.SSLGetNumberSupportedCiphers.argtypes = [
248 SSLContextRef,
249 POINTER(c_size_t)
250 ]
251 Security.SSLGetNumberSupportedCiphers.restype = OSStatus
252
253 Security.SSLGetSupportedCiphers.argtypes = [
254 SSLContextRef,
255 POINTER(SSLCipherSuite),
256 POINTER(c_size_t)
257 ]
258 Security.SSLGetSupportedCiphers.restype = OSStatus
259
260 Security.SSLSetEnabledCiphers.argtypes = [
261 SSLContextRef,
262 POINTER(SSLCipherSuite),
263 c_size_t
264 ]
265 Security.SSLSetEnabledCiphers.restype = OSStatus
266
267 Security.SSLGetNumberEnabledCiphers.argtype = [
268 SSLContextRef,
269 POINTER(c_size_t)
270 ]
271 Security.SSLGetNumberEnabledCiphers.restype = OSStatus
272
273 Security.SSLGetEnabledCiphers.argtypes = [
274 SSLContextRef,
275 POINTER(SSLCipherSuite),
276 POINTER(c_size_t)
277 ]
278 Security.SSLGetEnabledCiphers.restype = OSStatus
279
280 Security.SSLGetNegotiatedCipher.argtypes = [
281 SSLContextRef,
282 POINTER(SSLCipherSuite)
283 ]
284 Security.SSLGetNegotiatedCipher.restype = OSStatus
285
286 Security.SSLGetNegotiatedProtocolVersion.argtypes = [
287 SSLContextRef,
288 POINTER(SSLProtocol)
289 ]
290 Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus
291
292 Security.SSLCopyPeerTrust.argtypes = [
293 SSLContextRef,
294 POINTER(SecTrustRef)
295 ]
296 Security.SSLCopyPeerTrust.restype = OSStatus
297
298 Security.SecTrustSetAnchorCertificates.argtypes = [
299 SecTrustRef,
300 CFArrayRef
301 ]
302 Security.SecTrustSetAnchorCertificates.restype = OSStatus
303
304 Security.SecTrustSetAnchorCertificatesOnly.argstypes = [
305 SecTrustRef,
306 Boolean
307 ]
308 Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus
309
310 Security.SecTrustEvaluate.argtypes = [
311 SecTrustRef,
312 POINTER(SecTrustResultType)
313 ]
314 Security.SecTrustEvaluate.restype = OSStatus
315
316 Security.SecTrustGetCertificateCount.argtypes = [
317 SecTrustRef
318 ]
319 Security.SecTrustGetCertificateCount.restype = CFIndex
320
321 Security.SecTrustGetCertificateAtIndex.argtypes = [
322 SecTrustRef,
323 CFIndex
324 ]
325 Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef
326
327 Security.SSLCreateContext.argtypes = [
328 CFAllocatorRef,
329 SSLProtocolSide,
330 SSLConnectionType
331 ]
332 Security.SSLCreateContext.restype = SSLContextRef
333
334 Security.SSLSetSessionOption.argtypes = [
335 SSLContextRef,
336 SSLSessionOption,
337 Boolean
338 ]
339 Security.SSLSetSessionOption.restype = OSStatus
340
341 Security.SSLSetProtocolVersionMin.argtypes = [
342 SSLContextRef,
343 SSLProtocol
344 ]
345 Security.SSLSetProtocolVersionMin.restype = OSStatus
346
347 Security.SSLSetProtocolVersionMax.argtypes = [
348 SSLContextRef,
349 SSLProtocol
350 ]
351 Security.SSLSetProtocolVersionMax.restype = OSStatus
352
353 Security.SecCopyErrorMessageString.argtypes = [
354 OSStatus,
355 c_void_p
356 ]
357 Security.SecCopyErrorMessageString.restype = CFStringRef
358
359 Security.SSLReadFunc = SSLReadFunc
360 Security.SSLWriteFunc = SSLWriteFunc
361 Security.SSLContextRef = SSLContextRef
362 Security.SSLProtocol = SSLProtocol
363 Security.SSLCipherSuite = SSLCipherSuite
364 Security.SecIdentityRef = SecIdentityRef
365 Security.SecKeychainRef = SecKeychainRef
366 Security.SecTrustRef = SecTrustRef
367 Security.SecTrustResultType = SecTrustResultType
368 Security.SecExternalFormat = SecExternalFormat
369 Security.OSStatus = OSStatus
370
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 CFTypeRef
381 ]
382 CoreFoundation.CFRetain.restype = CFTypeRef
383
384 CoreFoundation.CFRelease.argtypes = [
385 CFTypeRef
386 ]
387 CoreFoundation.CFRelease.restype = None
388
389 CoreFoundation.CFGetTypeID.argtypes = [
390 CFTypeRef
391 ]
392 CoreFoundation.CFGetTypeID.restype = CFTypeID
393
394 CoreFoundation.CFStringCreateWithCString.argtypes = [
395 CFAllocatorRef,
396 c_char_p,
397 CFStringEncoding
398 ]
399 CoreFoundation.CFStringCreateWithCString.restype = CFStringRef
400
401 CoreFoundation.CFStringGetCStringPtr.argtypes = [
402 CFStringRef,
403 CFStringEncoding
404 ]
405 CoreFoundation.CFStringGetCStringPtr.restype = c_char_p
406
407 CoreFoundation.CFStringGetCString.argtypes = [
408 CFStringRef,
409 c_char_p,
410 CFIndex,
411 CFStringEncoding
412 ]
413 CoreFoundation.CFStringGetCString.restype = c_bool
414
415 CoreFoundation.CFDataCreate.argtypes = [
416 CFAllocatorRef,
417 c_char_p,
418 CFIndex
419 ]
420 CoreFoundation.CFDataCreate.restype = CFDataRef
421
422 CoreFoundation.CFDataGetLength.argtypes = [
423 CFDataRef
424 ]
425 CoreFoundation.CFDataGetLength.restype = CFIndex
426
427 CoreFoundation.CFDataGetBytePtr.argtypes = [
428 CFDataRef
429 ]
430 CoreFoundation.CFDataGetBytePtr.restype = c_void_p
431
432 CoreFoundation.CFDictionaryCreate.argtypes = [
433 CFAllocatorRef,
434 POINTER(CFTypeRef),
435 POINTER(CFTypeRef),
436 CFIndex,
437 CFDictionaryKeyCallBacks,
438 CFDictionaryValueCallBacks
439 ]
440 CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef
441
442 CoreFoundation.CFDictionaryGetValue.argtypes = [
443 CFDictionaryRef,
444 CFTypeRef
445 ]
446 CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef
447
448 CoreFoundation.CFArrayCreate.argtypes = [
449 CFAllocatorRef,
450 POINTER(CFTypeRef),
451 CFIndex,
452 CFArrayCallBacks,
453 ]
454 CoreFoundation.CFArrayCreate.restype = CFArrayRef
455
456 CoreFoundation.CFArrayCreateMutable.argtypes = [
457 CFAllocatorRef,
458 CFIndex,
459 CFArrayCallBacks
460 ]
461 CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef
462
463 CoreFoundation.CFArrayAppendValue.argtypes = [
464 CFMutableArrayRef,
465 c_void_p
466 ]
467 CoreFoundation.CFArrayAppendValue.restype = None
468
469 CoreFoundation.CFArrayGetCount.argtypes = [
470 CFArrayRef
471 ]
472 CoreFoundation.CFArrayGetCount.restype = CFIndex
473
474 CoreFoundation.CFArrayGetValueAtIndex.argtypes = [
475 CFArrayRef,
476 CFIndex
477 ]
478 CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p
479
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 = CFTypeRef
492 CoreFoundation.CFArrayRef = CFArrayRef
493 CoreFoundation.CFStringRef = CFStringRef
494 CoreFoundation.CFDictionaryRef = CFDictionaryRef
495
496except (AttributeError):
497 raise ImportError('Error initializing ctypes')
498
499
500class CFConst(object):
501 """
502 A class object that acts as essentially a namespace for CoreFoundation
503 constants.
504 """
505 kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)
506
507
508class SecurityConst(object):
509 """
510 A class object that acts as essentially a namespace for Security constants.
511 """
512 kSSLSessionOptionBreakOnServerAuth = 0
513
514 kSSLProtocol2 = 1
515 kSSLProtocol3 = 2
516 kTLSProtocol1 = 4
517 kTLSProtocol11 = 7
518 kTLSProtocol12 = 8
519
520 kSSLClientSide = 1
521 kSSLStreamType = 0
522
523 kSecFormatPEMSequence = 10
524
525 kSecTrustResultInvalid = 0
526 kSecTrustResultProceed = 1
527 # This gap is present on purpose: this was kSecTrustResultConfirm, which
528 # is deprecated.
529 kSecTrustResultDeny = 3
530 kSecTrustResultUnspecified = 4
531 kSecTrustResultRecoverableTrustFailure = 5
532 kSecTrustResultFatalTrustFailure = 6
533 kSecTrustResultOtherError = 7
534
535 errSSLProtocol = -9800
536 errSSLWouldBlock = -9803
537 errSSLClosedGraceful = -9805
538 errSSLClosedNoNotify = -9816
539 errSSLClosedAbort = -9806
540
541 errSSLXCertChainInvalid = -9807
542 errSSLCrypto = -9809
543 errSSLInternal = -9810
544 errSSLCertExpired = -9814
545 errSSLCertNotYetValid = -9815
546 errSSLUnknownRootCert = -9812
547 errSSLNoRootCert = -9813
548 errSSLHostNameMismatch = -9843
549 errSSLPeerHandshakeFail = -9824
550 errSSLPeerUserCancelled = -9839
551 errSSLWeakPeerEphemeralDHKey = -9850
552 errSSLServerAuthCompleted = -9841
553 errSSLRecordOverflow = -9847
554
555 errSecVerifyFailed = -67808
556 errSecNoTrustSettings = -25263
557 errSecItemNotFound = -25300
558 errSecInvalidTrustSettings = -25262
559
560 # Cipher suites. We only pick the ones our default cipher string allows.
561 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C
562 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030
563 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B
564 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F
565 TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = 0x00A3
566 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F
567 TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = 0x00A2
568 TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E
569 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024
570 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028
571 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A
572 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014
573 TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B
574 TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x006A
575 TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039
576 TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038
577 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023
578 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027
579 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009
580 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013
581 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067
582 TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x0040
583 TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033
584 TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032
585 TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D
586 TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C
587 TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D
588 TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C
589 TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035
590 TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F
591 TLS_AES_128_GCM_SHA256 = 0x1301
592 TLS_AES_256_GCM_SHA384 = 0x1302
593 TLS_CHACHA20_POLY1305_SHA256 = 0x1303
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/low_level.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/low_level.py
deleted file mode 100644
index 4e5c0db..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/_securetransport/low_level.py
+++ /dev/null
@@ -1,343 +0,0 @@
1"""
2Low-level helpers for the SecureTransport bindings.
3
4These are Python functions that are not directly related to the high-level APIs
5but are necessary to get them to work. They include a whole bunch of low-level
6CoreFoundation messing about and memory management. The concerns in this module
7are almost entirely about trying to avoid memory leaks and providing
8appropriate and useful assistance to the higher-level code.
9"""
10import base64
11import ctypes
12import itertools
13import re
14import os
15import ssl
16import tempfile
17
18from .bindings import Security, CoreFoundation, CFConst
19
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.DOTALL
24)
25
26
27def _cf_data_from_bytes(bytestring):
28 """
29 Given a bytestring, create a CFData object from it. This CFData object must
30 be CFReleased by the caller.
31 """
32 return CoreFoundation.CFDataCreate(
33 CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring)
34 )
35
36
37def _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
59def _cf_string_to_unicode(value):
60 """
61 Creates a Unicode string from a CFString object. Used entirely for error
62 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.kCFStringEncodingUTF8
71 )
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.kCFStringEncodingUTF8
79 )
80 if not result:
81 raise OSError('Error copying C string from CFStringRef')
82 string = buffer.value
83 if string is not None:
84 string = string.decode('utf-8')
85 return string
86
87
88def _assert_no_error(error, exception_class=None):
89 """
90 Checks the return code and throws an exception if there is an error to
91 report
92 """
93 if error == 0:
94 return
95
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' % error
102
103 if exception_class is None:
104 exception_class = ssl.SSLError
105
106 raise exception_class(output)
107
108
109def _cert_array_from_pem(pem_bundle):
110 """
111 Given a bundle of certs in PEM format, turns them into a CFArray of certs
112 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, certdata
136 )
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 caller
146 # should free.
147 CoreFoundation.CFRelease(cert_array)
148
149 return cert_array
150
151
152def _is_cert(item):
153 """
154 Returns True if a given CFTypeRef is a certificate.
155 """
156 expected = Security.SecCertificateGetTypeID()
157 return CoreFoundation.CFGetTypeID(item) == expected
158
159
160def _is_identity(item):
161 """
162 Returns True if a given CFTypeRef is an identity.
163 """
164 expected = Security.SecIdentityGetTypeID()
165 return CoreFoundation.CFGetTypeID(item) == expected
166
167
168def _temporary_keychain():
169 """
170 This function creates a temporary Mac keychain that we can use to work with
171 credentials. This keychain uses a one-time password and a temporary file to
172 store the data. We expect to have one keychain per socket. The returned
173 SecKeychainRef must be freed by the caller, including calling
174 SecKeychainDelete.
175
176 Returns a tuple of the SecKeychainRef and the path to the temporary
177 directory that contains it.
178 """
179 # Unfortunately, SecKeychainCreate requires a path to a keychain. This
180 # 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 need
183 # some random bytes to password-protect the keychain we're creating, so we
184 # 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-8
188 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, tempdirectory
206
207
208def _load_items_from_file(keychain, path):
209 """
210 Given a single file, loads all the trust objects from it into arrays and
211 the keychain.
212 Returns a tuple of lists: the first list is a list of identities, the
213 second a list of certs.
214 """
215 certificates = []
216 identities = []
217 result_array = None
218
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 data
231 None, # Filename, leaving it out for now
232 None, # What the type of the file is, we don't care
233 None, # what's in the file, we don't care
234 0, # import flags
235 None, # key params, can include passphrase in the future
236 keychain, # The keychain to insert into
237 ctypes.byref(result_array) # Results
238 )
239 _assert_no_error(result)
240
241 # A CFArray is not very useful to us as an intermediary
242 # representation, so we are going to extract the objects we want
243 # and then free the array. We don't need to keep hold of keys: the
244 # 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, index
249 )
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
267def _load_client_cert_chain(keychain, *paths):
268 """
269 Load certificates and maybe keys from a number of files. Has the end goal
270 of returning a CFArray containing one SecIdentityRef, and then zero or more
271 SecCertificateRef objects, suitable for use as a client certificate trust
272 chain.
273 """
274 # Ok, the strategy.
275 #
276 # This relies on knowing that macOS will not give you a SecIdentityRef
277 # unless you have imported a key into a keychain. This is a somewhat
278 # artificial limitation of macOS (for example, it doesn't necessarily
279 # affect iOS), but there is nothing inside Security.framework that lets you
280 # 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 from
284 # it. We will also point at a keychain that macOS can use to work with the
285 # private key.
286 #
287 # Once we have all the objects, we'll check what we actually have. If we
288 # 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) and
290 # ask the keychain to give us a SecIdentityRef with that cert's associated
291 # key.
292 #
293 # We'll then return a CFArray containing the trust chain: one
294 # SecIdentityRef and then zero-or-more SecCertificateRef objects. The
295 # responsibility for freeing this CFArray will be with the caller. This
296 # CFArray must remain alive for the entire connection, so in practice it
297 # will be stored with a single SSLSocket, along with the reference to the
298 # 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_path
309 )
310 identities.extend(new_identities)
311 certificates.extend(new_certs)
312
313 # Ok, we have everything. The question is: do we have an identity? If
314 # 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 longer
326 # 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_chain
341 finally:
342 for obj in itertools.chain(identities, certificates):
343 CoreFoundation.CFRelease(obj)
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/appengine.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/appengine.py
deleted file mode 100644
index fc00d17..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/appengine.py
+++ /dev/null
@@ -1,296 +0,0 @@
1"""
2This module provides a pool manager that uses Google App Engine's
3`URLFetch Service <https://cloud.google.com/appengine/docs/python/urlfetch>`_.
4
5Example usage::
6
7 from pip._vendor.urllib3 import PoolManager
8 from pip._vendor.urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox
9
10 if is_appengine_sandbox():
11 # AppEngineManager uses AppEngine's URLFetch API behind the scenes
12 http = AppEngineManager()
13 else:
14 # PoolManager uses a socket-level API behind the scenes
15 http = PoolManager()
16
17 r = http.request('GET', 'https://google.com/')
18
19There are `limitations <https://cloud.google.com/appengine/docs/python/\
20urlfetch/#Python_Quotas_and_limits>`_ to the URLFetch service and it may not be
21the best choice for your application. There are three options for using
22urllib3 on Google App Engine:
23
241. You can use :class:`AppEngineManager` with URLFetch. URLFetch is
25 cost-effective in many circumstances as long as your usage is within the
26 limitations.
272. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets.
28 Sockets also have `limitations and restrictions
29 <https://cloud.google.com/appengine/docs/python/sockets/\
30 #limitations-and-restrictions>`_ and have a lower free quota than URLFetch.
31 To use sockets, be sure to specify the following in your ``app.yaml``::
32
33 env_variables:
34 GAE_USE_SOCKETS_HTTPLIB : 'true'
35
363. If you are using `App Engine Flexible
37<https://cloud.google.com/appengine/docs/flexible/>`_, you can use the standard
38:class:`PoolManager` without any configuration or special environment variables.
39"""
40
41from __future__ import absolute_import
42import logging
43import os
44import warnings
45from ..packages.six.moves.urllib.parse import urljoin
46
47from ..exceptions import (
48 HTTPError,
49 HTTPWarning,
50 MaxRetryError,
51 ProtocolError,
52 TimeoutError,
53 SSLError
54)
55
56from ..packages.six import BytesIO
57from ..request import RequestMethods
58from ..response import HTTPResponse
59from ..util.timeout import Timeout
60from ..util.retry import Retry
61
62try:
63 from google.appengine.api import urlfetch
64except ImportError:
65 urlfetch = None
66
67
68log = logging.getLogger(__name__)
69
70
71class AppEnginePlatformWarning(HTTPWarning):
72 pass
73
74
75class AppEnginePlatformError(HTTPError):
76 pass
77
78
79class AppEngineManager(RequestMethods):
80 """
81 Connection manager for Google App Engine sandbox applications.
82
83 This manager uses the URLFetch service directly instead of using the
84 emulated httplib, and is subject to URLFetch limitations as described in
85 the App Engine documentation `here
86 <https://cloud.google.com/appengine/docs/python/urlfetch>`_.
87
88 Notably it will raise an :class:`AppEnginePlatformError` if:
89 * URLFetch is not available.
90 * If you attempt to use this on App Engine Flexible, as full socket
91 support is available.
92 * If a request size is more than 10 megabytes.
93 * If a response size is more than 32 megabtyes.
94 * If you use an unsupported request method such as OPTIONS.
95
96 Beyond those cases, it will raise normal urllib3 errors.
97 """
98
99 def __init__(self, headers=None, retries=None, validate_certificate=True,
100 urlfetch_retries=True):
101 if not urlfetch:
102 raise AppEnginePlatformError(
103 "URLFetch is not available in this environment.")
104
105 if is_prod_appengine_mvms():
106 raise AppEnginePlatformError(
107 "Use normal urllib3.PoolManager instead of AppEngineManager"
108 "on Managed VMs, as using URLFetch is not necessary in "
109 "this environment.")
110
111 warnings.warn(
112 "urllib3 is using URLFetch on Google App Engine sandbox instead "
113 "of sockets. To use sockets directly instead of URLFetch see "
114 "https://urllib3.readthedocs.io/en/latest/reference/urllib3.contrib.html.",
115 AppEnginePlatformWarning)
116
117 RequestMethods.__init__(self, headers)
118 self.validate_certificate = validate_certificate
119 self.urlfetch_retries = urlfetch_retries
120
121 self.retries = retries or Retry.DEFAULT
122
123 def __enter__(self):
124 return self
125
126 def __exit__(self, exc_type, exc_val, exc_tb):
127 # Return False to re-raise any potential exceptions
128 return False
129
130 def urlopen(self, method, url, body=None, headers=None,
131 retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT,
132 **response_kw):
133
134 retries = self._get_retries(retries, redirect)
135
136 try:
137 follow_redirects = (
138 redirect and
139 retries.redirect != 0 and
140 retries.total)
141 response = urlfetch.fetch(
142 url,
143 payload=body,
144 method=method,
145 headers=headers or {},
146 allow_truncated=False,
147 follow_redirects=self.urlfetch_retries and follow_redirects,
148 deadline=self._get_absolute_timeout(timeout),
149 validate_certificate=self.validate_certificate,
150 )
151 except urlfetch.DeadlineExceededError as e:
152 raise TimeoutError(self, e)
153
154 except urlfetch.InvalidURLError as e:
155 if 'too large' in str(e):
156 raise AppEnginePlatformError(
157 "URLFetch request too large, URLFetch only "
158 "supports requests up to 10mb in size.", e)
159 raise ProtocolError(e)
160
161 except urlfetch.DownloadError as e:
162 if 'Too many redirects' in str(e):
163 raise MaxRetryError(self, url, reason=e)
164 raise ProtocolError(e)
165
166 except urlfetch.ResponseTooLargeError as e:
167 raise AppEnginePlatformError(
168 "URLFetch response too large, URLFetch only supports"
169 "responses up to 32mb in size.", e)
170
171 except urlfetch.SSLCertificateError as e:
172 raise SSLError(e)
173
174 except urlfetch.InvalidMethodError as e:
175 raise AppEnginePlatformError(
176 "URLFetch does not support method: %s" % method, e)
177
178 http_response = self._urlfetch_response_to_http_response(
179 response, retries=retries, **response_kw)
180
181 # Handle redirect?
182 redirect_location = redirect and http_response.get_redirect_location()
183 if redirect_location:
184 # Check for redirect response
185 if (self.urlfetch_retries and retries.raise_on_redirect):
186 raise MaxRetryError(self, url, "too many redirects")
187 else:
188 if http_response.status == 303:
189 method = 'GET'
190
191 try:
192 retries = retries.increment(method, url, response=http_response, _pool=self)
193 except MaxRetryError:
194 if retries.raise_on_redirect:
195 raise MaxRetryError(self, url, "too many redirects")
196 return http_response
197
198 retries.sleep_for_retry(http_response)
199 log.debug("Redirecting %s -> %s", url, redirect_location)
200 redirect_url = urljoin(url, redirect_location)
201 return self.urlopen(
202 method, redirect_url, body, headers,
203 retries=retries, redirect=redirect,
204 timeout=timeout, **response_kw)
205
206 # Check if we should retry the HTTP response.
207 has_retry_after = bool(http_response.getheader('Retry-After'))
208 if retries.is_retry(method, http_response.status, has_retry_after):
209 retries = retries.increment(
210 method, url, response=http_response, _pool=self)
211 log.debug("Retry: %s", url)
212 retries.sleep(http_response)
213 return self.urlopen(
214 method, url,
215 body=body, headers=headers,
216 retries=retries, redirect=redirect,
217 timeout=timeout, **response_kw)
218
219 return http_response
220
221 def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):
222
223 if is_prod_appengine():
224 # Production GAE handles deflate encoding automatically, but does
225 # not remove the encoding header.
226 content_encoding = urlfetch_resp.headers.get('content-encoding')
227
228 if content_encoding == 'deflate':
229 del urlfetch_resp.headers['content-encoding']
230
231 transfer_encoding = urlfetch_resp.headers.get('transfer-encoding')
232 # We have a full response's content,
233 # so let's make sure we don't report ourselves as chunked data.
234 if transfer_encoding == 'chunked':
235 encodings = transfer_encoding.split(",")
236 encodings.remove('chunked')
237 urlfetch_resp.headers['transfer-encoding'] = ','.join(encodings)
238
239 return HTTPResponse(
240 # In order for decoding to work, we must present the content as
241 # a file-like object.
242 body=BytesIO(urlfetch_resp.content),
243 headers=urlfetch_resp.headers,
244 status=urlfetch_resp.status_code,
245 **response_kw
246 )
247
248 def _get_absolute_timeout(self, timeout):
249 if timeout is Timeout.DEFAULT_TIMEOUT:
250 return None # Defer to URLFetch's default.
251 if isinstance(timeout, Timeout):
252 if timeout._read is not None or timeout._connect is not None:
253 warnings.warn(
254 "URLFetch does not support granular timeout settings, "
255 "reverting to total or default URLFetch timeout.",
256 AppEnginePlatformWarning)
257 return timeout.total
258 return timeout
259
260 def _get_retries(self, retries, redirect):
261 if not isinstance(retries, Retry):
262 retries = Retry.from_int(
263 retries, redirect=redirect, default=self.retries)
264
265 if retries.connect or retries.read or retries.redirect:
266 warnings.warn(
267 "URLFetch only supports total retries and does not "
268 "recognize connect, read, or redirect retry parameters.",
269 AppEnginePlatformWarning)
270
271 return retries
272
273
274def is_appengine():
275 return (is_local_appengine() or
276 is_prod_appengine() or
277 is_prod_appengine_mvms())
278
279
280def is_appengine_sandbox():
281 return is_appengine() and not is_prod_appengine_mvms()
282
283
284def is_local_appengine():
285 return ('APPENGINE_RUNTIME' in os.environ and
286 'Development/' in os.environ['SERVER_SOFTWARE'])
287
288
289def is_prod_appengine():
290 return ('APPENGINE_RUNTIME' in os.environ and
291 'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and
292 not is_prod_appengine_mvms())
293
294
295def is_prod_appengine_mvms():
296 return os.environ.get('GAE_VM', False) == 'true'
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/ntlmpool.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/ntlmpool.py
deleted file mode 100644
index 888e0ad..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/ntlmpool.py
+++ /dev/null
@@ -1,112 +0,0 @@
1"""
2NTLM authenticating pool, contributed by erikcederstran
3
4Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
5"""
6from __future__ import absolute_import
7
8from logging import getLogger
9from ntlm import ntlm
10
11from .. import HTTPSConnectionPool
12from ..packages.six.moves.http_client import HTTPSConnection
13
14
15log = getLogger(__name__)
16
17
18class NTLMConnectionPool(HTTPSConnectionPool):
19 """
20 Implements an NTLM authentication version of an urllib3 connection pool
21 """
22
23 scheme = 'https'
24
25 def __init__(self, user, pw, authurl, *args, **kwargs):
26 """
27 authurl is a random URL on the server that is protected by NTLM.
28 user is the Windows user, probably in the DOMAIN\\username format.
29 pw is the password for the user.
30 """
31 super(NTLMConnectionPool, self).__init__(*args, **kwargs)
32 self.authurl = authurl
33 self.rawuser = user
34 user_parts = user.split('\\', 1)
35 self.domain = user_parts[0].upper()
36 self.user = user_parts[1]
37 self.pw = pw
38
39 def _new_conn(self):
40 # Performs the NTLM handshake that secures the connection. The socket
41 # must be kept open while requests are performed.
42 self.num_connections += 1
43 log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s',
44 self.num_connections, self.host, self.authurl)
45
46 headers = {}
47 headers['Connection'] = 'Keep-Alive'
48 req_header = 'Authorization'
49 resp_header = 'www-authenticate'
50
51 conn = HTTPSConnection(host=self.host, port=self.port)
52
53 # Send negotiation message
54 headers[req_header] = (
55 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))
56 log.debug('Request headers: %s', headers)
57 conn.request('GET', self.authurl, None, headers)
58 res = conn.getresponse()
59 reshdr = dict(res.getheaders())
60 log.debug('Response status: %s %s', res.status, res.reason)
61 log.debug('Response headers: %s', reshdr)
62 log.debug('Response data: %s [...]', res.read(100))
63
64 # Remove the reference to the socket, so that it can not be closed by
65 # the response object (we want to keep the socket open)
66 res.fp = None
67
68 # Server should respond with a challenge message
69 auth_header_values = reshdr[resp_header].split(', ')
70 auth_header_value = None
71 for s in auth_header_values:
72 if s[:5] == 'NTLM ':
73 auth_header_value = s[5:]
74 if auth_header_value is None:
75 raise Exception('Unexpected %s response header: %s' %
76 (resp_header, reshdr[resp_header]))
77
78 # Send authentication message
79 ServerChallenge, NegotiateFlags = \
80 ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)
81 auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,
82 self.user,
83 self.domain,
84 self.pw,
85 NegotiateFlags)
86 headers[req_header] = 'NTLM %s' % auth_msg
87 log.debug('Request headers: %s', headers)
88 conn.request('GET', self.authurl, None, headers)
89 res = conn.getresponse()
90 log.debug('Response status: %s %s', res.status, res.reason)
91 log.debug('Response headers: %s', dict(res.getheaders()))
92 log.debug('Response data: %s [...]', res.read()[:100])
93 if res.status != 200:
94 if res.status == 401:
95 raise Exception('Server rejected request: wrong '
96 'username or password')
97 raise Exception('Wrong server response: %s %s' %
98 (res.status, res.reason))
99
100 res.fp = None
101 log.debug('Connection established')
102 return conn
103
104 def urlopen(self, method, url, body=None, headers=None, retries=3,
105 redirect=True, assert_same_host=True):
106 if headers is None:
107 headers = {}
108 headers['Connection'] = 'Keep-Alive'
109 return super(NTLMConnectionPool, self).urlopen(method, url, body,
110 headers, retries,
111 redirect,
112 assert_same_host)
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/pyopenssl.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/pyopenssl.py
deleted file mode 100644
index f13e2bc..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/pyopenssl.py
+++ /dev/null
@@ -1,455 +0,0 @@
1"""
2SSL with SNI_-support for Python 2. Follow these instructions if you would
3like to verify SSL certificates in Python 2. Note, the default libraries do
4*not* do certificate checking; you need to do additional work to validate
5certificates yourself.
6
7This needs the following packages installed:
8
9* pyOpenSSL (tested with 16.0.0)
10* cryptography (minimum 1.3.4, from pyopenssl)
11* idna (minimum 2.0, from cryptography)
12
13However, pyopenssl depends on cryptography, which depends on idna, so while we
14use all three directly here we end up having relatively few packages required.
15
16You can install them with the following command:
17
18 pip install pyopenssl cryptography idna
19
20To activate certificate checking, call
21:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code
22before you begin making HTTP requests. This can be done in a ``sitecustomize``
23module, or at any other time before your application begins using ``urllib3``,
24like this::
25
26 try:
27 import urllib3.contrib.pyopenssl
28 urllib3.contrib.pyopenssl.inject_into_urllib3()
29 except ImportError:
30 pass
31
32Now you can use :mod:`urllib3` as you normally would, and it will support SNI
33when the required modules are installed.
34
35Activating this module also has the positive side effect of disabling SSL/TLS
36compression in Python 2 (see `CRIME attack`_).
37
38If you want to configure the default list of supported cipher suites, you can
39set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable.
40
41.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication
42.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)
43"""
44from __future__ import absolute_import
45
46import OpenSSL.SSL
47from cryptography import x509
48from cryptography.hazmat.backends.openssl import backend as openssl_backend
49from cryptography.hazmat.backends.openssl.x509 import _Certificate
50
51from socket import timeout, error as SocketError
52from io import BytesIO
53
54try: # Platform-specific: Python 2
55 from socket import _fileobject
56except ImportError: # Platform-specific: Python 3
57 _fileobject = None
58 from ..packages.backports.makefile import backport_makefile
59
60import logging
61import ssl
62from ..packages import six
63import sys
64
65from .. import util
66
67__all__ = ['inject_into_urllib3', 'extract_from_urllib3']
68
69# SNI always works.
70HAS_SNI = True
71
72# Map from urllib3 to PyOpenSSL compatible parameter-values.
73_openssl_versions = {
74 ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD,
75 ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,
76}
77
78if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'):
79 _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD
80
81if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'):
82 _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD
83
84try:
85 _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD})
86except AttributeError:
87 pass
88
89_stdlib_to_openssl_verify = {
90 ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,
91 ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,
92 ssl.CERT_REQUIRED:
93 OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
94}
95_openssl_to_stdlib_verify = dict(
96 (v, k) for k, v in _stdlib_to_openssl_verify.items()
97)
98
99# OpenSSL will only write 16K at a time
100SSL_WRITE_BLOCKSIZE = 16384
101
102orig_util_HAS_SNI = util.HAS_SNI
103orig_util_SSLContext = util.ssl_.SSLContext
104
105
106log = logging.getLogger(__name__)
107
108
109def inject_into_urllib3():
110 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'
111
112 _validate_dependencies_met()
113
114 util.ssl_.SSLContext = PyOpenSSLContext
115 util.HAS_SNI = HAS_SNI
116 util.ssl_.HAS_SNI = HAS_SNI
117 util.IS_PYOPENSSL = True
118 util.ssl_.IS_PYOPENSSL = True
119
120
121def extract_from_urllib3():
122 'Undo monkey-patching by :func:`inject_into_urllib3`.'
123
124 util.ssl_.SSLContext = orig_util_SSLContext
125 util.HAS_SNI = orig_util_HAS_SNI
126 util.ssl_.HAS_SNI = orig_util_HAS_SNI
127 util.IS_PYOPENSSL = False
128 util.ssl_.IS_PYOPENSSL = False
129
130
131def _validate_dependencies_met():
132 """
133 Verifies that PyOpenSSL's package-level dependencies have been met.
134 Throws `ImportError` if they are not met.
135 """
136 # Method added in `cryptography==1.1`; not available in older versions
137 from cryptography.x509.extensions import Extensions
138 if getattr(Extensions, "get_extension_for_class", None) is None:
139 raise ImportError("'cryptography' module missing required functionality. "
140 "Try upgrading to v1.3.4 or newer.")
141
142 # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509
143 # attribute is only present on those versions.
144 from OpenSSL.crypto import X509
145 x509 = X509()
146 if getattr(x509, "_x509", None) is None:
147 raise ImportError("'pyOpenSSL' module missing required functionality. "
148 "Try upgrading to v0.14 or newer.")
149
150
151def _dnsname_to_stdlib(name):
152 """
153 Converts a dNSName SubjectAlternativeName field to the form used by the
154 standard library on the given Python version.
155
156 Cryptography produces a dNSName as a unicode string that was idna-decoded
157 from ASCII bytes. We need to idna-encode that string to get it back, and
158 then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib
159 uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).
160 """
161 def idna_encode(name):
162 """
163 Borrowed wholesale from the Python Cryptography Project. It turns out
164 that we can't just safely call `idna.encode`: it can explode for
165 wildcard names. This avoids that problem.
166 """
167 from pip._vendor import idna
168
169 for prefix in [u'*.', u'.']:
170 if name.startswith(prefix):
171 name = name[len(prefix):]
172 return prefix.encode('ascii') + idna.encode(name)
173 return idna.encode(name)
174
175 name = idna_encode(name)
176 if sys.version_info >= (3, 0):
177 name = name.decode('utf-8')
178 return name
179
180
181def get_subj_alt_name(peer_cert):
182 """
183 Given an PyOpenSSL certificate, provides all the subject alternative names.
184 """
185 # Pass the cert to cryptography, which has much better APIs for this.
186 if hasattr(peer_cert, "to_cryptography"):
187 cert = peer_cert.to_cryptography()
188 else:
189 # This is technically using private APIs, but should work across all
190 # relevant versions before PyOpenSSL got a proper API for this.
191 cert = _Certificate(openssl_backend, peer_cert._x509)
192
193 # We want to find the SAN extension. Ask Cryptography to locate it (it's
194 # faster than looping in Python)
195 try:
196 ext = cert.extensions.get_extension_for_class(
197 x509.SubjectAlternativeName
198 ).value
199 except x509.ExtensionNotFound:
200 # No such extension, return the empty list.
201 return []
202 except (x509.DuplicateExtension, x509.UnsupportedExtension,
203 x509.UnsupportedGeneralNameType, UnicodeError) as e:
204 # A problem has been found with the quality of the certificate. Assume
205 # no SAN field is present.
206 log.warning(
207 "A problem was encountered with the certificate that prevented "
208 "urllib3 from finding the SubjectAlternativeName field. This can "
209 "affect certificate validation. The error was %s",
210 e,
211 )
212 return []
213
214 # We want to return dNSName and iPAddress fields. We need to cast the IPs
215 # back to strings because the match_hostname function wants them as
216 # strings.
217 # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
218 # decoded. This is pretty frustrating, but that's what the standard library
219 # does with certificates, and so we need to attempt to do the same.
220 names = [
221 ('DNS', _dnsname_to_stdlib(name))
222 for name in ext.get_values_for_type(x509.DNSName)
223 ]
224 names.extend(
225 ('IP Address', str(name))
226 for name in ext.get_values_for_type(x509.IPAddress)
227 )
228
229 return names
230
231
232class WrappedSocket(object):
233 '''API-compatibility wrapper for Python OpenSSL's Connection-class.
234
235 Note: _makefile_refs, _drop() and _reuse() are needed for the garbage
236 collector of pypy.
237 '''
238
239 def __init__(self, connection, socket, suppress_ragged_eofs=True):
240 self.connection = connection
241 self.socket = socket
242 self.suppress_ragged_eofs = suppress_ragged_eofs
243 self._makefile_refs = 0
244 self._closed = False
245
246 def fileno(self):
247 return self.socket.fileno()
248
249 # Copy-pasted from Python 3.5 source code
250 def _decref_socketios(self):
251 if self._makefile_refs > 0:
252 self._makefile_refs -= 1
253 if self._closed:
254 self.close()
255
256 def recv(self, *args, **kwargs):
257 try:
258 data = self.connection.recv(*args, **kwargs)
259 except OpenSSL.SSL.SysCallError as e:
260 if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
261 return b''
262 else:
263 raise SocketError(str(e))
264 except OpenSSL.SSL.ZeroReturnError as e:
265 if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
266 return b''
267 else:
268 raise
269 except OpenSSL.SSL.WantReadError:
270 rd = util.wait_for_read(self.socket, self.socket.gettimeout())
271 if not rd:
272 raise timeout('The read operation timed out')
273 else:
274 return self.recv(*args, **kwargs)
275 else:
276 return data
277
278 def recv_into(self, *args, **kwargs):
279 try:
280 return self.connection.recv_into(*args, **kwargs)
281 except OpenSSL.SSL.SysCallError as e:
282 if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'):
283 return 0
284 else:
285 raise SocketError(str(e))
286 except OpenSSL.SSL.ZeroReturnError as e:
287 if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:
288 return 0
289 else:
290 raise
291 except OpenSSL.SSL.WantReadError:
292 rd = util.wait_for_read(self.socket, self.socket.gettimeout())
293 if not rd:
294 raise timeout('The read operation timed out')
295 else:
296 return self.recv_into(*args, **kwargs)
297
298 def settimeout(self, timeout):
299 return self.socket.settimeout(timeout)
300
301 def _send_until_done(self, data):
302 while True:
303 try:
304 return self.connection.send(data)
305 except OpenSSL.SSL.WantWriteError:
306 wr = util.wait_for_write(self.socket, self.socket.gettimeout())
307 if not wr:
308 raise timeout()
309 continue
310 except OpenSSL.SSL.SysCallError as e:
311 raise SocketError(str(e))
312
313 def sendall(self, data):
314 total_sent = 0
315 while total_sent < len(data):
316 sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
317 total_sent += sent
318
319 def shutdown(self):
320 # FIXME rethrow compatible exceptions should we ever use this
321 self.connection.shutdown()
322
323 def close(self):
324 if self._makefile_refs < 1:
325 try:
326 self._closed = True
327 return self.connection.close()
328 except OpenSSL.SSL.Error:
329 return
330 else:
331 self._makefile_refs -= 1
332
333 def getpeercert(self, binary_form=False):
334 x509 = self.connection.get_peer_certificate()
335
336 if not x509:
337 return x509
338
339 if binary_form:
340 return OpenSSL.crypto.dump_certificate(
341 OpenSSL.crypto.FILETYPE_ASN1,
342 x509)
343
344 return {
345 'subject': (
346 (('commonName', x509.get_subject().CN),),
347 ),
348 'subjectAltName': get_subj_alt_name(x509)
349 }
350
351 def _reuse(self):
352 self._makefile_refs += 1
353
354 def _drop(self):
355 if self._makefile_refs < 1:
356 self.close()
357 else:
358 self._makefile_refs -= 1
359
360
361if _fileobject: # Platform-specific: Python 2
362 def makefile(self, mode, bufsize=-1):
363 self._makefile_refs += 1
364 return _fileobject(self, mode, bufsize, close=True)
365else: # Platform-specific: Python 3
366 makefile = backport_makefile
367
368WrappedSocket.makefile = makefile
369
370
371class PyOpenSSLContext(object):
372 """
373 I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible
374 for translating the interface of the standard library ``SSLContext`` object
375 to calls into PyOpenSSL.
376 """
377 def __init__(self, protocol):
378 self.protocol = _openssl_versions[protocol]
379 self._ctx = OpenSSL.SSL.Context(self.protocol)
380 self._options = 0
381 self.check_hostname = False
382
383 @property
384 def options(self):
385 return self._options
386
387 @options.setter
388 def options(self, value):
389 self._options = value
390 self._ctx.set_options(value)
391
392 @property
393 def verify_mode(self):
394 return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]
395
396 @verify_mode.setter
397 def verify_mode(self, value):
398 self._ctx.set_verify(
399 _stdlib_to_openssl_verify[value],
400 _verify_callback
401 )
402
403 def set_default_verify_paths(self):
404 self._ctx.set_default_verify_paths()
405
406 def set_ciphers(self, ciphers):
407 if isinstance(ciphers, six.text_type):
408 ciphers = ciphers.encode('utf-8')
409 self._ctx.set_cipher_list(ciphers)
410
411 def load_verify_locations(self, cafile=None, capath=None, cadata=None):
412 if cafile is not None:
413 cafile = cafile.encode('utf-8')
414 if capath is not None:
415 capath = capath.encode('utf-8')
416 self._ctx.load_verify_locations(cafile, capath)
417 if cadata is not None:
418 self._ctx.load_verify_locations(BytesIO(cadata))
419
420 def load_cert_chain(self, certfile, keyfile=None, password=None):
421 self._ctx.use_certificate_file(certfile)
422 if password is not None:
423 self._ctx.set_passwd_cb(lambda max_length, prompt_twice, userdata: password)
424 self._ctx.use_privatekey_file(keyfile or certfile)
425
426 def wrap_socket(self, sock, server_side=False,
427 do_handshake_on_connect=True, suppress_ragged_eofs=True,
428 server_hostname=None):
429 cnx = OpenSSL.SSL.Connection(self._ctx, sock)
430
431 if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3
432 server_hostname = server_hostname.encode('utf-8')
433
434 if server_hostname is not None:
435 cnx.set_tlsext_host_name(server_hostname)
436
437 cnx.set_connect_state()
438
439 while True:
440 try:
441 cnx.do_handshake()
442 except OpenSSL.SSL.WantReadError:
443 rd = util.wait_for_read(sock, sock.gettimeout())
444 if not rd:
445 raise timeout('select timed out')
446 continue
447 except OpenSSL.SSL.Error as e:
448 raise ssl.SSLError('bad handshake: %r' % e)
449 break
450
451 return WrappedSocket(cnx, sock)
452
453
454def _verify_callback(cnx, x509, err_no, err_depth, return_code):
455 return err_no == 0
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/securetransport.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/securetransport.py
deleted file mode 100644
index 77cf861..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/securetransport.py
+++ /dev/null
@@ -1,810 +0,0 @@
1"""
2SecureTranport support for urllib3 via ctypes.
3
4This makes platform-native TLS available to urllib3 users on macOS without the
5use of a compiler. This is an important feature because the Python Package
6Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL
7that ships with macOS is not capable of doing TLSv1.2. The only way to resolve
8this is to give macOS users an alternative solution to the problem, and that
9solution is to use SecureTransport.
10
11We use ctypes here because this solution must not require a compiler. That's
12because pip is not allowed to require a compiler either.
13
14This is not intended to be a seriously long-term solution to this problem.
15The hope is that PEP 543 will eventually solve this issue for us, at which
16point we can retire this contrib module. But in the short term, we need to
17solve the impending tire fire that is Python on Mac without this kind of
18contrib module. So...here we are.
19
20To use this module, simply import and inject it::
21
22 import urllib3.contrib.securetransport
23 urllib3.contrib.securetransport.inject_into_urllib3()
24
25Happy TLSing!
26"""
27from __future__ import absolute_import
28
29import contextlib
30import ctypes
31import errno
32import os.path
33import shutil
34import socket
35import ssl
36import threading
37import weakref
38
39from .. import util
40from ._securetransport.bindings import (
41 Security, SecurityConst, CoreFoundation
42)
43from ._securetransport.low_level import (
44 _assert_no_error, _cert_array_from_pem, _temporary_keychain,
45 _load_client_cert_chain
46)
47
48try: # Platform-specific: Python 2
49 from socket import _fileobject
50except ImportError: # Platform-specific: Python 3
51 _fileobject = None
52 from ..packages.backports.makefile import backport_makefile
53
54try:
55 memoryview(b'')
56except NameError:
57 raise ImportError("SecureTransport only works on Pythons with memoryview")
58
59__all__ = ['inject_into_urllib3', 'extract_from_urllib3']
60
61# SNI always works
62HAS_SNI = True
63
64orig_util_HAS_SNI = util.HAS_SNI
65orig_util_SSLContext = util.ssl_.SSLContext
66
67# This dictionary is used by the read callback to obtain a handle to the
68# calling wrapped socket. This is a pretty silly approach, but for now it'll
69# do. I feel like I should be able to smuggle a handle to the wrapped socket
70# directly in the SSLConnectionRef, but for now this approach will work I
71# guess.
72#
73# We need to lock around this structure for inserts, but we don't do it for
74# 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 is
77# 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, and
79# 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 down
82# 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 over
87# for no better reason than we need *a* limit, and this one is right there.
88SSL_WRITE_BLOCKSIZE = 16384
89
90# This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to
91# individual cipher suites. We need to do this becuase this is how
92# SecureTransport wants them.
93CIPHER_SUITES = [
94 SecurityConst.TLS_AES_256_GCM_SHA384,
95 SecurityConst.TLS_CHACHA20_POLY1305_SHA256,
96 SecurityConst.TLS_AES_128_GCM_SHA256,
97 SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
98 SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
99 SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
100 SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
101 SecurityConst.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384,
102 SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
103 SecurityConst.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,
104 SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
105 SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
106 SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
107 SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
108 SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
109 SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
110 SecurityConst.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,
111 SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
112 SecurityConst.TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
113 SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
114 SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
115 SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
116 SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
117 SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
118 SecurityConst.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
119 SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
120 SecurityConst.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
121 SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384,
122 SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256,
123 SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256,
124 SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256,
125 SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA,
126 SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA,
127]
128
129# Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of
130# TLSv1 and a high of TLSv1.2. For everything else, we pin to that version.
131_protocol_to_min_max = {
132 ssl.PROTOCOL_SSLv23: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),
133}
134
135if hasattr(ssl, "PROTOCOL_SSLv2"):
136 _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = (
137 SecurityConst.kSSLProtocol2, SecurityConst.kSSLProtocol2
138 )
139if hasattr(ssl, "PROTOCOL_SSLv3"):
140 _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = (
141 SecurityConst.kSSLProtocol3, SecurityConst.kSSLProtocol3
142 )
143if hasattr(ssl, "PROTOCOL_TLSv1"):
144 _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = (
145 SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol1
146 )
147if hasattr(ssl, "PROTOCOL_TLSv1_1"):
148 _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = (
149 SecurityConst.kTLSProtocol11, SecurityConst.kTLSProtocol11
150 )
151if hasattr(ssl, "PROTOCOL_TLSv1_2"):
152 _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = (
153 SecurityConst.kTLSProtocol12, SecurityConst.kTLSProtocol12
154 )
155if hasattr(ssl, "PROTOCOL_TLS"):
156 _protocol_to_min_max[ssl.PROTOCOL_TLS] = _protocol_to_min_max[ssl.PROTOCOL_SSLv23]
157
158
159def inject_into_urllib3():
160 """
161 Monkey-patch urllib3 with SecureTransport-backed SSL-support.
162 """
163 util.ssl_.SSLContext = SecureTransportContext
164 util.HAS_SNI = HAS_SNI
165 util.ssl_.HAS_SNI = HAS_SNI
166 util.IS_SECURETRANSPORT = True
167 util.ssl_.IS_SECURETRANSPORT = True
168
169
170def extract_from_urllib3():
171 """
172 Undo monkey-patching by :func:`inject_into_urllib3`.
173 """
174 util.ssl_.SSLContext = orig_util_SSLContext
175 util.HAS_SNI = orig_util_HAS_SNI
176 util.ssl_.HAS_SNI = orig_util_HAS_SNI
177 util.IS_SECURETRANSPORT = False
178 util.ssl_.IS_SECURETRANSPORT = False
179
180
181def _read_callback(connection_id, data_buffer, data_length_pointer):
182 """
183 SecureTransport read callback. This is called by ST to request that data
184 be returned from the socket.
185 """
186 wrapped_socket = None
187 try:
188 wrapped_socket = _connection_refs.get(connection_id)
189 if wrapped_socket is None:
190 return SecurityConst.errSSLInternal
191 base_socket = wrapped_socket.socket
192
193 requested_length = data_length_pointer[0]
194
195 timeout = wrapped_socket.gettimeout()
196 error = None
197 read_count = 0
198 buffer = (ctypes.c_char * requested_length).from_address(data_buffer)
199 buffer_view = memoryview(buffer)
200
201 try:
202 while read_count < requested_length:
203 if timeout is None or timeout >= 0:
204 readables = util.wait_for_read([base_socket], timeout)
205 if not readables:
206 raise socket.error(errno.EAGAIN, 'timed out')
207
208 # We need to tell ctypes that we have a buffer that can be
209 # written to. Upsettingly, we do that like this:
210 chunk_size = base_socket.recv_into(
211 buffer_view[read_count:requested_length]
212 )
213 read_count += chunk_size
214 if not chunk_size:
215 if not read_count:
216 return SecurityConst.errSSLClosedGraceful
217 break
218 except (socket.error) as e:
219 error = e.errno
220
221 if error is not None and error != errno.EAGAIN:
222 if error == errno.ECONNRESET:
223 return SecurityConst.errSSLClosedAbort
224 raise
225
226 data_length_pointer[0] = read_count
227
228 if read_count != requested_length:
229 return SecurityConst.errSSLWouldBlock
230
231 return 0
232 except Exception as e:
233 if wrapped_socket is not None:
234 wrapped_socket._exception = e
235 return SecurityConst.errSSLInternal
236
237
238def _write_callback(connection_id, data_buffer, data_length_pointer):
239 """
240 SecureTransport write callback. This is called by ST to request that data
241 actually be sent on the network.
242 """
243 wrapped_socket = None
244 try:
245 wrapped_socket = _connection_refs.get(connection_id)
246 if wrapped_socket is None:
247 return SecurityConst.errSSLInternal
248 base_socket = wrapped_socket.socket
249
250 bytes_to_write = data_length_pointer[0]
251 data = ctypes.string_at(data_buffer, bytes_to_write)
252
253 timeout = wrapped_socket.gettimeout()
254 error = None
255 sent = 0
256
257 try:
258 while sent < bytes_to_write:
259 if timeout is None or timeout >= 0:
260 writables = util.wait_for_write([base_socket], timeout)
261 if not writables:
262 raise socket.error(errno.EAGAIN, 'timed out')
263 chunk_sent = base_socket.send(data)
264 sent += chunk_sent
265
266 # This has some needless copying here, but I'm not sure there's
267 # much value in optimising this data path.
268 data = data[chunk_sent:]
269 except (socket.error) as e:
270 error = e.errno
271
272 if error is not None and error != errno.EAGAIN:
273 if error == errno.ECONNRESET:
274 return SecurityConst.errSSLClosedAbort
275 raise
276
277 data_length_pointer[0] = sent
278 if sent != bytes_to_write:
279 return SecurityConst.errSSLWouldBlock
280
281 return 0
282 except Exception as e:
283 if wrapped_socket is not None:
284 wrapped_socket._exception = e
285 return SecurityConst.errSSLInternal
286
287
288# We need to keep these two objects references alive: if they get GC'd while
289# in use then SecureTransport could attempt to call a function that is in freed
290# memory. That would be...uh...bad. Yeah, that's the word. Bad.
291_read_callback_pointer = Security.SSLReadFunc(_read_callback)
292_write_callback_pointer = Security.SSLWriteFunc(_write_callback)
293
294
295class WrappedSocket(object):
296 """
297 API-compatibility wrapper for Python's OpenSSL wrapped socket object.
298
299 Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage
300 collector of PyPy.
301 """
302 def __init__(self, socket):
303 self.socket = socket
304 self.context = None
305 self._makefile_refs = 0
306 self._closed = False
307 self._exception = None
308 self._keychain = None
309 self._keychain_dir = None
310 self._client_cert_chain = None
311
312 # We save off the previously-configured timeout and then set it to
313 # zero. This is done because we use select and friends to handle the
314 # timeouts, but if we leave the timeout set on the lower socket then
315 # Python will "kindly" call select on that socket again for us. Avoid
316 # that by forcing the timeout to zero.
317 self._timeout = self.socket.gettimeout()
318 self.socket.settimeout(0)
319
320 @contextlib.contextmanager
321 def _raise_on_error(self):
322 """
323 A context manager that can be used to wrap calls that do I/O from
324 SecureTransport. If any of the I/O callbacks hit an exception, this
325 context manager will correctly propagate the exception after the fact.
326 This avoids silently swallowing those exceptions.
327
328 It also correctly forces the socket closed.
329 """
330 self._exception = None
331
332 # We explicitly don't catch around this yield because in the unlikely
333 # event that an exception was hit in the block we don't want to swallow
334 # it.
335 yield
336 if self._exception is not None:
337 exception, self._exception = self._exception, None
338 self.close()
339 raise exception
340
341 def _set_ciphers(self):
342 """
343 Sets up the allowed ciphers. By default this matches the set in
344 util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done
345 custom and doesn't allow changing at this time, mostly because parsing
346 OpenSSL cipher strings is going to be a freaking nightmare.
347 """
348 ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES)
349 result = Security.SSLSetEnabledCiphers(
350 self.context, ciphers, len(CIPHER_SUITES)
351 )
352 _assert_no_error(result)
353
354 def _custom_validate(self, verify, trust_bundle):
355 """
356 Called when we have set custom validation. We do this in two cases:
357 first, when cert validation is entirely disabled; and second, when
358 using a custom trust DB.
359 """
360 # If we disabled cert validation, just say: cool.
361 if not verify:
362 return
363
364 # We want data in memory, so load it up.
365 if os.path.isfile(trust_bundle):
366 with open(trust_bundle, 'rb') as f:
367 trust_bundle = f.read()
368
369 cert_array = None
370 trust = Security.SecTrustRef()
371
372 try:
373 # Get a CFArray that contains the certs we want.
374 cert_array = _cert_array_from_pem(trust_bundle)
375
376 # Ok, now the hard part. We want to get the SecTrustRef that ST has
377 # created for this connection, shove our CAs into it, tell ST to
378 # ignore everything else it knows, and then ask if it can build a
379 # chain. This is a buuuunch of code.
380 result = Security.SSLCopyPeerTrust(
381 self.context, ctypes.byref(trust)
382 )
383 _assert_no_error(result)
384 if not trust:
385 raise ssl.SSLError("Failed to copy trust reference")
386
387 result = Security.SecTrustSetAnchorCertificates(trust, cert_array)
388 _assert_no_error(result)
389
390 result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)
391 _assert_no_error(result)
392
393 trust_result = Security.SecTrustResultType()
394 result = Security.SecTrustEvaluate(
395 trust, ctypes.byref(trust_result)
396 )
397 _assert_no_error(result)
398 finally:
399 if trust:
400 CoreFoundation.CFRelease(trust)
401
402 if cert_array is None:
403 CoreFoundation.CFRelease(cert_array)
404
405 # Ok, now we can look at what the result was.
406 successes = (
407 SecurityConst.kSecTrustResultUnspecified,
408 SecurityConst.kSecTrustResultProceed
409 )
410 if trust_result.value not in successes:
411 raise ssl.SSLError(
412 "certificate verify failed, error code: %d" %
413 trust_result.value
414 )
415
416 def handshake(self,
417 server_hostname,
418 verify,
419 trust_bundle,
420 min_version,
421 max_version,
422 client_cert,
423 client_key,
424 client_key_passphrase):
425 """
426 Actually performs the TLS handshake. This is run automatically by
427 wrapped socket, and shouldn't be needed in user code.
428 """
429 # First, we do the initial bits of connection setup. We need to create
430 # a context, set its I/O funcs, and set the connection reference.
431 self.context = Security.SSLCreateContext(
432 None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType
433 )
434 result = Security.SSLSetIOFuncs(
435 self.context, _read_callback_pointer, _write_callback_pointer
436 )
437 _assert_no_error(result)
438
439 # Here we need to compute the handle to use. We do this by taking the
440 # id of self modulo 2**31 - 1. If this is already in the dictionary, we
441 # just keep incrementing by one until we find a free space.
442 with _connection_ref_lock:
443 handle = id(self) % 2147483647
444 while handle in _connection_refs:
445 handle = (handle + 1) % 2147483647
446 _connection_refs[handle] = self
447
448 result = Security.SSLSetConnection(self.context, handle)
449 _assert_no_error(result)
450
451 # If we have a server hostname, we should set that too.
452 if server_hostname:
453 if not isinstance(server_hostname, bytes):
454 server_hostname = server_hostname.encode('utf-8')
455
456 result = Security.SSLSetPeerDomainName(
457 self.context, server_hostname, len(server_hostname)
458 )
459 _assert_no_error(result)
460
461 # Setup the ciphers.
462 self._set_ciphers()
463
464 # Set the minimum and maximum TLS versions.
465 result = Security.SSLSetProtocolVersionMin(self.context, min_version)
466 _assert_no_error(result)
467 result = Security.SSLSetProtocolVersionMax(self.context, max_version)
468 _assert_no_error(result)
469
470 # If there's a trust DB, we need to use it. We do that by telling
471 # SecureTransport to break on server auth. We also do that if we don't
472 # want to validate the certs at all: we just won't actually do any
473 # authing in that case.
474 if not verify or trust_bundle is not None:
475 result = Security.SSLSetSessionOption(
476 self.context,
477 SecurityConst.kSSLSessionOptionBreakOnServerAuth,
478 True
479 )
480 _assert_no_error(result)
481
482 # If there's a client cert, we need to use it.
483 if client_cert:
484 self._keychain, self._keychain_dir = _temporary_keychain()
485 self._client_cert_chain = _load_client_cert_chain(
486 self._keychain, client_cert, client_key
487 )
488 result = Security.SSLSetCertificate(
489 self.context, self._client_cert_chain
490 )
491 _assert_no_error(result)
492
493 while True:
494 with self._raise_on_error():
495 result = Security.SSLHandshake(self.context)
496
497 if result == SecurityConst.errSSLWouldBlock:
498 raise socket.timeout("handshake timed out")
499 elif result == SecurityConst.errSSLServerAuthCompleted:
500 self._custom_validate(verify, trust_bundle)
501 continue
502 else:
503 _assert_no_error(result)
504 break
505
506 def fileno(self):
507 return self.socket.fileno()
508
509 # Copy-pasted from Python 3.5 source code
510 def _decref_socketios(self):
511 if self._makefile_refs > 0:
512 self._makefile_refs -= 1
513 if self._closed:
514 self.close()
515
516 def recv(self, bufsiz):
517 buffer = ctypes.create_string_buffer(bufsiz)
518 bytes_read = self.recv_into(buffer, bufsiz)
519 data = buffer[:bytes_read]
520 return data
521
522 def recv_into(self, buffer, nbytes=None):
523 # Read short on EOF.
524 if self._closed:
525 return 0
526
527 if nbytes is None:
528 nbytes = len(buffer)
529
530 buffer = (ctypes.c_char * nbytes).from_buffer(buffer)
531 processed_bytes = ctypes.c_size_t(0)
532
533 with self._raise_on_error():
534 result = Security.SSLRead(
535 self.context, buffer, nbytes, ctypes.byref(processed_bytes)
536 )
537
538 # There are some result codes that we want to treat as "not always
539 # errors". Specifically, those are errSSLWouldBlock,
540 # errSSLClosedGraceful, and errSSLClosedNoNotify.
541 if (result == SecurityConst.errSSLWouldBlock):
542 # If we didn't process any bytes, then this was just a time out.
543 # However, we can get errSSLWouldBlock in situations when we *did*
544 # read some data, and in those cases we should just read "short"
545 # and return.
546 if processed_bytes.value == 0:
547 # Timed out, no data read.
548 raise socket.timeout("recv timed out")
549 elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify):
550 # The remote peer has closed this connection. We should do so as
551 # well. Note that we don't actually return here because in
552 # principle this could actually be fired along with return data.
553 # It's unlikely though.
554 self.close()
555 else:
556 _assert_no_error(result)
557
558 # Ok, we read and probably succeeded. We should return whatever data
559 # was actually read.
560 return processed_bytes.value
561
562 def settimeout(self, timeout):
563 self._timeout = timeout
564
565 def gettimeout(self):
566 return self._timeout
567
568 def send(self, data):
569 processed_bytes = ctypes.c_size_t(0)
570
571 with self._raise_on_error():
572 result = Security.SSLWrite(
573 self.context, data, len(data), ctypes.byref(processed_bytes)
574 )
575
576 if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0:
577 # Timed out
578 raise socket.timeout("send timed out")
579 else:
580 _assert_no_error(result)
581
582 # We sent, and probably succeeded. Tell them how much we sent.
583 return processed_bytes.value
584
585 def sendall(self, data):
586 total_sent = 0
587 while total_sent < len(data):
588 sent = self.send(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE])
589 total_sent += sent
590
591 def shutdown(self):
592 with self._raise_on_error():
593 Security.SSLClose(self.context)
594
595 def close(self):
596 # TODO: should I do clean shutdown here? Do I have to?
597 if self._makefile_refs < 1:
598 self._closed = True
599 if self.context:
600 CoreFoundation.CFRelease(self.context)
601 self.context = None
602 if self._client_cert_chain:
603 CoreFoundation.CFRelease(self._client_cert_chain)
604 self._client_cert_chain = None
605 if self._keychain:
606 Security.SecKeychainDelete(self._keychain)
607 CoreFoundation.CFRelease(self._keychain)
608 shutil.rmtree(self._keychain_dir)
609 self._keychain = self._keychain_dir = None
610 return self.socket.close()
611 else:
612 self._makefile_refs -= 1
613
614 def getpeercert(self, binary_form=False):
615 # Urgh, annoying.
616 #
617 # Here's how we do this:
618 #
619 # 1. Call SSLCopyPeerTrust to get hold of the trust object for this
620 # connection.
621 # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf.
622 # 3. To get the CN, call SecCertificateCopyCommonName and process that
623 # string so that it's of the appropriate type.
624 # 4. To get the SAN, we need to do something a bit more complex:
625 # a. Call SecCertificateCopyValues to get the data, requesting
626 # kSecOIDSubjectAltName.
627 # b. Mess about with this dictionary to try to get the SANs out.
628 #
629 # This is gross. Really gross. It's going to be a few hundred LoC extra
630 # just to repeat something that SecureTransport can *already do*. So my
631 # operating assumption at this time is that what we want to do is
632 # instead to just flag to urllib3 that it shouldn't do its own hostname
633 # validation when using SecureTransport.
634 if not binary_form:
635 raise ValueError(
636 "SecureTransport only supports dumping binary certs"
637 )
638 trust = Security.SecTrustRef()
639 certdata = None
640 der_bytes = None
641
642 try:
643 # Grab the trust store.
644 result = Security.SSLCopyPeerTrust(
645 self.context, ctypes.byref(trust)
646 )
647 _assert_no_error(result)
648 if not trust:
649 # Probably we haven't done the handshake yet. No biggie.
650 return None
651
652 cert_count = Security.SecTrustGetCertificateCount(trust)
653 if not cert_count:
654 # Also a case that might happen if we haven't handshaked.
655 # Handshook? Handshaken?
656 return None
657
658 leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)
659 assert leaf
660
661 # Ok, now we want the DER bytes.
662 certdata = Security.SecCertificateCopyData(leaf)
663 assert certdata
664
665 data_length = CoreFoundation.CFDataGetLength(certdata)
666 data_buffer = CoreFoundation.CFDataGetBytePtr(certdata)
667 der_bytes = ctypes.string_at(data_buffer, data_length)
668 finally:
669 if certdata:
670 CoreFoundation.CFRelease(certdata)
671 if trust:
672 CoreFoundation.CFRelease(trust)
673
674 return der_bytes
675
676 def _reuse(self):
677 self._makefile_refs += 1
678
679 def _drop(self):
680 if self._makefile_refs < 1:
681 self.close()
682 else:
683 self._makefile_refs -= 1
684
685
686if _fileobject: # Platform-specific: Python 2
687 def makefile(self, mode, bufsize=-1):
688 self._makefile_refs += 1
689 return _fileobject(self, mode, bufsize, close=True)
690else: # Platform-specific: Python 3
691 def makefile(self, mode="r", buffering=None, *args, **kwargs):
692 # We disable buffering with SecureTransport because it conflicts with
693 # the buffering that ST does internally (see issue #1153 for more).
694 buffering = 0
695 return backport_makefile(self, mode, buffering, *args, **kwargs)
696
697WrappedSocket.makefile = makefile
698
699
700class SecureTransportContext(object):
701 """
702 I am a wrapper class for the SecureTransport library, to translate the
703 interface of the standard library ``SSLContext`` object to calls into
704 SecureTransport.
705 """
706 def __init__(self, protocol):
707 self._min_version, self._max_version = _protocol_to_min_max[protocol]
708 self._options = 0
709 self._verify = False
710 self._trust_bundle = None
711 self._client_cert = None
712 self._client_key = None
713 self._client_key_passphrase = None
714
715 @property
716 def check_hostname(self):
717 """
718 SecureTransport cannot have its hostname checking disabled. For more,
719 see the comment on getpeercert() in this file.
720 """
721 return True
722
723 @check_hostname.setter
724 def check_hostname(self, value):
725 """
726 SecureTransport cannot have its hostname checking disabled. For more,
727 see the comment on getpeercert() in this file.
728 """
729 pass
730
731 @property
732 def options(self):
733 # TODO: Well, crap.
734 #
735 # So this is the bit of the code that is the most likely to cause us
736 # trouble. Essentially we need to enumerate all of the SSL options that
737 # users might want to use and try to see if we can sensibly translate
738 # them, or whether we should just ignore them.
739 return self._options
740
741 @options.setter
742 def options(self, value):
743 # TODO: Update in line with above.
744 self._options = value
745
746 @property
747 def verify_mode(self):
748 return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE
749
750 @verify_mode.setter
751 def verify_mode(self, value):
752 self._verify = True if value == ssl.CERT_REQUIRED else False
753
754 def set_default_verify_paths(self):
755 # So, this has to do something a bit weird. Specifically, what it does
756 # is nothing.
757 #
758 # This means that, if we had previously had load_verify_locations
759 # called, this does not undo that. We need to do that because it turns
760 # out that the rest of the urllib3 code will attempt to load the
761 # default verify paths if it hasn't been told about any paths, even if
762 # the context itself was sometime earlier. We resolve that by just
763 # ignoring it.
764 pass
765
766 def load_default_certs(self):
767 return self.set_default_verify_paths()
768
769 def set_ciphers(self, ciphers):
770 # For now, we just require the default cipher string.
771 if ciphers != util.ssl_.DEFAULT_CIPHERS:
772 raise ValueError(
773 "SecureTransport doesn't support custom cipher strings"
774 )
775
776 def load_verify_locations(self, cafile=None, capath=None, cadata=None):
777 # OK, we only really support cadata and cafile.
778 if capath is not None:
779 raise ValueError(
780 "SecureTransport does not support cert directories"
781 )
782
783 self._trust_bundle = cafile or cadata
784
785 def load_cert_chain(self, certfile, keyfile=None, password=None):
786 self._client_cert = certfile
787 self._client_key = keyfile
788 self._client_cert_passphrase = password
789
790 def wrap_socket(self, sock, server_side=False,
791 do_handshake_on_connect=True, suppress_ragged_eofs=True,
792 server_hostname=None):
793 # So, what do we do here? Firstly, we assert some properties. This is a
794 # stripped down shim, so there is some functionality we don't support.
795 # See PEP 543 for the real deal.
796 assert not server_side
797 assert do_handshake_on_connect
798 assert suppress_ragged_eofs
799
800 # Ok, we're good to go. Now we want to create the wrapped socket object
801 # and store it in the appropriate place.
802 wrapped_socket = WrappedSocket(sock)
803
804 # Now we can handshake
805 wrapped_socket.handshake(
806 server_hostname, self._verify, self._trust_bundle,
807 self._min_version, self._max_version, self._client_cert,
808 self._client_key, self._client_key_passphrase
809 )
810 return wrapped_socket
diff --git a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/socks.py b/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/socks.py
deleted file mode 100644
index 6c99a75..0000000
--- a/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/urllib3/contrib/socks.py
+++ /dev/null
@@ -1,188 +0,0 @@
1# -*- coding: utf-8 -*-
2"""
3This module contains provisional support for SOCKS proxies from within
4urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and
5SOCKS5. To enable its functionality, either install PySocks or install this
6module with the ``socks`` extra.
7
8The SOCKS implementation supports the full range of urllib3 features. It also
9supports the following SOCKS features:
10
11- SOCKS4
12- SOCKS4a
13- SOCKS5
14- Usernames and passwords for the SOCKS proxy
15
16Known Limitations:
17
18- Currently PySocks does not support contacting remote websites via literal
19 IPv6 addresses. Any such connection attempt will fail. You must use a domain
20 name.
21- Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any
22 such connection attempt will fail.
23"""
24from __future__ import absolute_import
25
26try:
27 import socks
28except ImportError:
29 import warnings
30 from ..exceptions import DependencyWarning
31
32 warnings.warn((
33 'SOCKS support in urllib3 requires the installation of optional '
34 'dependencies: specifically, PySocks. For more information, see '
35 'https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies'
36 ),
37 DependencyWarning
38 )
39 raise
40
41from socket import error as SocketError, timeout as SocketTimeout
42
43from ..connection import (
44 HTTPConnection, HTTPSConnection
45)
46from ..connectionpool import (
47 HTTPConnectionPool, HTTPSConnectionPool
48)
49from ..exceptions import ConnectTimeoutError, NewConnectionError
50from ..poolmanager import PoolManager
51from ..util.url import parse_url
52
53try:
54 import ssl
55except ImportError:
56 ssl = None
57
58
59class SOCKSConnection(HTTPConnection):
60 """
61 A plain-text HTTP connection that connects via a SOCKS proxy.
62 """
63 def __init__(self, *args, **kwargs):
64 self._socks_options = kwargs.pop('_socks_options')
65 super(SOCKSConnection, self).__init__(*args, **kwargs)
66
67 def _new_conn(self):
68 """
69 Establish a new connection via the SOCKS proxy.
70 """
71 extra_kw = {}
72 if self.source_address:
73 extra_kw['source_address'] = self.source_address
74
75 if self.socket_options:
76 extra_kw['socket_options'] = self.socket_options
77
78 try:
79 conn = socks.create_connection(
80 (self.host, self.port),
81 proxy_type=self._socks_options['socks_version'],
82 proxy_addr=self._socks_options['proxy_host'],
83 proxy_port=self._socks_options['proxy_port'],
84 proxy_username=self._socks_options['username'],
85 proxy_password=self._socks_options['password'],
86 proxy_rdns=self._socks_options['rdns'],
87 timeout=self.timeout,
88 **extra_kw
89 )
90
91 except SocketTimeout as e:
92 raise ConnectTimeoutError(
93 self, "Connection to %s timed out. (connect timeout=%s)" %
94 (self.host, self.timeout))
95
96 except socks.ProxyError as e:
97 # This is fragile as hell, but it seems to be the only way to raise
98 # useful errors here.
99 if e.socket_err:
100 error = e.socket_err
101 if isinstance(error, SocketTimeout):
102 raise ConnectTimeoutError(
103 self,
104 "Connection to %s timed out. (connect timeout=%s)" %
105 (self.host, self.timeout)
106 )
107 else:
108 raise NewConnectionError(
109 self,
110 "Failed to establish a new connection: %s" % error
111 )
112 else:
113 raise NewConnectionError(
114 self,
115 "Failed to establish a new connection: %s" % e
116 )
117
118 except SocketError as e: # Defensive: PySocks should catch all these.
119 raise NewConnectionError(
120 self, "Failed to establish a new connection: %s" % e)
121
122 return conn
123
124
125# We don't need to duplicate the Verified/Unverified distinction from
126# urllib3/connection.py here because the HTTPSConnection will already have been
127# correctly set to either the Verified or Unverified form by that module. This
128# means the SOCKSHTTPSConnection will automatically be the correct type.
129class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):
130 pass
131
132
133class SOCKSHTTPConnectionPool(HTTPConnectionPool):
134 ConnectionCls = SOCKSConnection
135
136
137class SOCKSHTTPSConnectionPool(HTTPSConnectionPool):
138 ConnectionCls = SOCKSHTTPSConnection
139
140
141class SOCKSProxyManager(PoolManager):
142 """
143 A version of the urllib3 ProxyManager that routes connections via the
144 defined SOCKS proxy.
145 """
146 pool_classes_by_scheme = {
147 'http': SOCKSHTTPConnectionPool,
148 'https': SOCKSHTTPSConnectionPool,
149 }
150
151 def __init__(self, proxy_url, username=None, password=None,
152 num_pools=10, headers=None, **connection_pool_kw):
153 parsed = parse_url(proxy_url)
154
155 if parsed.scheme == 'socks5':
156 socks_version = socks.PROXY_TYPE_SOCKS5
157 rdns = False
158 elif parsed.scheme == 'socks5h':
159 socks_version = socks.PROXY_TYPE_SOCKS5
160 rdns = True
161 elif parsed.scheme == 'socks4':
162 socks_version = socks.PROXY_TYPE_SOCKS4
163 rdns = False
164 elif parsed.scheme == 'socks4a':
165 socks_version = socks.PROXY_TYPE_SOCKS4
166 rdns = True
167 else:
168 raise ValueError(
169 "Unable to determine SOCKS version from %s" % proxy_url
170 )
171
172 self.proxy_url = proxy_url
173
174 socks_options = {
175 'socks_version': socks_version,
176 'proxy_host': parsed.host,
177 'proxy_port': parsed.port,
178 'username': username,
179 'password': password,
180 'rdns': rdns
181 }
182 connection_pool_kw['_socks_options'] = socks_options
183
184 super(SOCKSProxyManager, self).__init__(
185 num_pools, headers, **connection_pool_kw
186 )
187
188 self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme