Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 88

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 215

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 216

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 217

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 218

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 219

Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 220
PK!j..rubyforgepublisher.rbnu[require 'rake/contrib/sshpublisher' module Rake class RubyForgePublisher < SshDirPublisher attr_reader :project, :proj_id, :user def initialize(projname, user) super( "#{user}@rubyforge.org", "/var/www/gforge-projects/#{projname}", "html") end end end PK!Jn $$ publisher.rbnu[# Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com) # All rights reserved. # :stopdoc: # Configuration information about an upload host system. # name :: Name of host system. # webdir :: Base directory for the web information for the # application. The application name (APP) is appended to # this directory before using. # pkgdir :: Directory on the host system where packages can be # placed. HostInfo = Struct.new(:name, :webdir, :pkgdir) # :startdoc: # Manage several publishers as a single entity. class CompositePublisher def initialize @publishers = [] end # Add a publisher to the composite. def add(pub) @publishers << pub end # Upload all the individual publishers. def upload @publishers.each { |p| p.upload } end end # Publish an entire directory to an existing remote directory using # SSH. class SshDirPublisher def initialize(host, remote_dir, local_dir) @host = host @remote_dir = remote_dir @local_dir = local_dir end def upload run %{scp -rq #{@local_dir}/* #{@host}:#{@remote_dir}} end end # Publish an entire directory to a fresh remote directory using SSH. class SshFreshDirPublisher < SshDirPublisher def upload run %{ssh #{@host} rm -rf #{@remote_dir}} rescue nil run %{ssh #{@host} mkdir #{@remote_dir}} super end end # Publish a list of files to an existing remote directory. class SshFilePublisher # Create a publisher using the give host information. def initialize(host, remote_dir, local_dir, *files) @host = host @remote_dir = remote_dir @local_dir = local_dir @files = files end # Upload the local directory to the remote directory. def upload @files.each do |fn| run %{scp -q #{@local_dir}/#{fn} #{@host}:#{@remote_dir}} end end end PK!4sys.rbnu[warn 'Sys has been deprecated in favor of FileUtils' #-- # Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com) # All rights reserved. #++ # begin require 'ftools' rescue LoadError end require 'rbconfig' ###################################################################### # Sys provides a number of file manipulation tools for the convenience # of writing Rakefiles. All commands in this module will announce # their activity on standard output if the $verbose flag is set # ($verbose = true is the default). You can control this by globally # setting $verbose or by using the +verbose+ and +quiet+ methods. # # Sys has been deprecated in favor of the FileUtils module available # in Ruby 1.8. # module Sys RUBY = RbConfig::CONFIG['ruby_install_name'] # Install all the files matching +wildcard+ into the +dest_dir+ # directory. The permission mode is set to +mode+. def install(wildcard, dest_dir, mode) Dir[wildcard].each do |fn| File.install(fn, dest_dir, mode, $verbose) end end # Run the system command +cmd+. def run(cmd) log cmd system(cmd) or fail "Command Failed: [#{cmd}]" end # Run a Ruby interpreter with the given arguments. def ruby(*args) run "#{RUBY} #{args.join(' ')}" end # Copy a single file from +file_name+ to +dest_file+. def copy(file_name, dest_file) log "Copying file #{file_name} to #{dest_file}" File.copy(file_name, dest_file) end # Copy all files matching +wildcard+ into the directory +dest_dir+. def copy_files(wildcard, dest_dir) for_matching_files(wildcard, dest_dir) { |from, to| copy(from, to) } end # Link +file_name+ to +dest_file+. def link(file_name, dest_file) log "Linking file #{file_name} to #{dest_file}" File.link(file_name, dest_file) end # Link all files matching +wildcard+ into the directory +dest_dir+. def link_files(wildcard, dest_dir) for_matching_files(wildcard, dest_dir) { |from, to| link(from, to) } end # Symlink +file_name+ to +dest_file+. def symlink(file_name, dest_file) log "Symlinking file #{file_name} to #{dest_file}" File.symlink(file_name, dest_file) end # Symlink all files matching +wildcard+ into the directory +dest_dir+. def symlink_files(wildcard, dest_dir) for_matching_files(wildcard, dest_dir) { |from, to| link(from, to) } end # Remove all files matching +wildcard+. If a matching file is a # directory, it must be empty to be removed. used +delete_all+ to # recursively delete directories. def delete(*wildcards) wildcards.each do |wildcard| Dir[wildcard].each do |fn| if File.directory?(fn) log "Deleting directory #{fn}" Dir.delete(fn) else log "Deleting file #{fn}" File.delete(fn) end end end end # Recursively delete all files and directories matching +wildcard+. def delete_all(*wildcards) wildcards.each do |wildcard| Dir[wildcard].each do |fn| next if ! File.exist?(fn) if File.directory?(fn) Dir["#{fn}/*"].each do |subfn| next if subfn=='.' || subfn=='..' delete_all(subfn) end log "Deleting directory #{fn}" Dir.delete(fn) else log "Deleting file #{fn}" File.delete(fn) end end end end # Make the directories given in +dirs+. def makedirs(*dirs) dirs.each do |fn| log "Making directory #{fn}" File.makedirs(fn) end end # Make +dir+ the current working directory for the duration of # executing the given block. def indir(dir) olddir = Dir.pwd Dir.chdir(dir) yield ensure Dir.chdir(olddir) end # Split a file path into individual directory names. # # For example: # split_all("a/b/c") => ['a', 'b', 'c'] def split_all(path) head, tail = File.split(path) return [tail] if head == '.' || tail == '/' return [head, tail] if head == '/' return split_all(head) + [tail] end # Write a message to standard error if $verbose is enabled. def log(msg) print " " if $trace && $verbose $stderr.puts msg if $verbose end # Perform a block with $verbose disabled. def quiet(&block) with_verbose(false, &block) end # Perform a block with $verbose enabled. def verbose(&block) with_verbose(true, &block) end # Perform a block with each file matching a set of wildcards. def for_files(*wildcards) wildcards.each do |wildcard| Dir[wildcard].each do |fn| yield(fn) end end end extend(self) private # ---------------------------------------------------------- def for_matching_files(wildcard, dest_dir) Dir[wildcard].each do |fn| dest_file = File.join(dest_dir, fn) parent = File.dirname(dest_file) makedirs(parent) if ! File.directory?(parent) yield(fn, dest_file) end end def with_verbose(v) oldverbose = $verbose $verbose = v yield ensure $verbose = oldverbose end end PK!ȉ`t__compositepublisher.rbnu[module Rake # Manage several publishers as a single entity. class CompositePublisher def initialize @publishers = [] end # Add a publisher to the composite. def add(pub) @publishers << pub end # Upload all the individual publishers. def upload @publishers.each { |p| p.upload } end end end PK!Vlsshpublisher.rbnu[require 'rake/dsl_definition' require 'rake/contrib/compositepublisher' module Rake # Publish an entire directory to an existing remote directory using # SSH. class SshDirPublisher include Rake::DSL def initialize(host, remote_dir, local_dir) @host = host @remote_dir = remote_dir @local_dir = local_dir end def upload sh %{scp -rq #{@local_dir}/* #{@host}:#{@remote_dir}} end end # Publish an entire directory to a fresh remote directory using SSH. class SshFreshDirPublisher < SshDirPublisher def upload sh %{ssh #{@host} rm -rf #{@remote_dir}} rescue nil sh %{ssh #{@host} mkdir #{@remote_dir}} super end end # Publish a list of files to an existing remote directory. class SshFilePublisher include Rake::DSL # Create a publisher using the give host information. def initialize(host, remote_dir, local_dir, *files) @host = host @remote_dir = remote_dir @local_dir = local_dir @files = files end # Upload the local directory to the remote directory. def upload @files.each do |fn| sh %{scp -q #{@local_dir}/#{fn} #{@host}:#{@remote_dir}} end end end end PK!¬P ftptools.rbnu[# = Tools for FTP uploading. # # This file is still under development and is not released for general # use. require 'date' require 'net/ftp' module Rake # :nodoc: #################################################################### # Note: Not released for general use. class FtpFile attr_reader :name, :size, :owner, :group, :time def self.date @date_class ||= Date end def self.time @time_class ||= Time end def initialize(path, entry) @path = path @mode, _, @owner, @group, size, d1, d2, d3, @name = entry.split(' ') @size = size.to_i @time = determine_time(d1, d2, d3) end def path File.join(@path, @name) end def directory? @mode[0] == ?d end def mode parse_mode(@mode) end def symlink? @mode[0] == ?l end private # -------------------------------------------------------- def parse_mode(m) result = 0 (1..9).each do |i| result = 2*result + ((m[i]==?-) ? 0 : 1) end result end def determine_time(d1, d2, d3) now = self.class.time.now if /:/ =~ d3 result = Time.parse("#{d1} #{d2} #{now.year} #{d3}") if result > now result = Time.parse("#{d1} #{d2} #{now.year-1} #{d3}") end else result = Time.parse("#{d1} #{d2} #{d3}") end result # elements = ParseDate.parsedate("#{d1} #{d2} #{d3}") # if elements[0].nil? # today = self.class.date.today # if elements[1] > today.month # elements[0] = today.year - 1 # else # elements[0] = today.year # end # end # elements = elements.collect { |el| el.nil? ? 0 : el } # Time.mktime(*elements[0,7]) end end #################################################################### # Manage the uploading of files to an FTP account. class FtpUploader # Log uploads to standard output when true. attr_accessor :verbose class << FtpUploader # Create an uploader and pass it to the given block as +up+. # When the block is complete, close the uploader. def connect(path, host, account, password) up = self.new(path, host, account, password) begin yield(up) ensure up.close end end end # Create an FTP uploader targeting the directory +path+ on +host+ # using the given account and password. +path+ will be the root # path of the uploader. def initialize(path, host, account, password) @created = Hash.new @path = path @ftp = Net::FTP.new(host, account, password) makedirs(@path) @ftp.chdir(@path) end # Create the directory +path+ in the uploader root path. def makedirs(path) route = [] File.split(path).each do |dir| route << dir current_dir = File.join(route) if @created[current_dir].nil? @created[current_dir] = true $stderr.puts "Creating Directory #{current_dir}" if @verbose @ftp.mkdir(current_dir) rescue nil end end end # Upload all files matching +wildcard+ to the uploader's root # path. def upload_files(wildcard) Dir[wildcard].each do |fn| upload(fn) end end # Close the uploader. def close @ftp.close end private # -------------------------------------------------------- # Upload a single file to the uploader's root path. def upload(file) $stderr.puts "Uploading #{file}" if @verbose dir = File.dirname(file) makedirs(dir) @ftp.putbinaryfile(file, file) unless File.directory?(file) end end end PK!socks.pynu[# -*- coding: utf-8 -*- """ This module contains provisional support for SOCKS proxies from within urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and SOCKS5. To enable its functionality, either install PySocks or install this module with the ``socks`` extra. The SOCKS implementation supports the full range of urllib3 features. It also supports the following SOCKS features: - SOCKS4 - SOCKS4a - SOCKS5 - Usernames and passwords for the SOCKS proxy Known Limitations: - Currently PySocks does not support contacting remote websites via literal IPv6 addresses. Any such connection attempt will fail. You must use a domain name. - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any such connection attempt will fail. """ from __future__ import absolute_import try: import socks except ImportError: import warnings from ..exceptions import DependencyWarning warnings.warn(( 'SOCKS support in urllib3 requires the installation of optional ' 'dependencies: specifically, PySocks. For more information, see ' 'https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies' ), DependencyWarning ) raise from socket import error as SocketError, timeout as SocketTimeout from ..connection import ( HTTPConnection, HTTPSConnection ) from ..connectionpool import ( HTTPConnectionPool, HTTPSConnectionPool ) from ..exceptions import ConnectTimeoutError, NewConnectionError from ..poolmanager import PoolManager from ..util.url import parse_url try: import ssl except ImportError: ssl = None class SOCKSConnection(HTTPConnection): """ A plain-text HTTP connection that connects via a SOCKS proxy. """ def __init__(self, *args, **kwargs): self._socks_options = kwargs.pop('_socks_options') super(SOCKSConnection, self).__init__(*args, **kwargs) def _new_conn(self): """ Establish a new connection via the SOCKS proxy. """ extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = socks.create_connection( (self.host, self.port), proxy_type=self._socks_options['socks_version'], proxy_addr=self._socks_options['proxy_host'], proxy_port=self._socks_options['proxy_port'], proxy_username=self._socks_options['username'], proxy_password=self._socks_options['password'], proxy_rdns=self._socks_options['rdns'], timeout=self.timeout, **extra_kw ) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout)) except socks.ProxyError as e: # This is fragile as hell, but it seems to be the only way to raise # useful errors here. if e.socket_err: error = e.socket_err if isinstance(error, SocketTimeout): raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout) ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % error ) else: raise NewConnectionError( self, "Failed to establish a new connection: %s" % e ) except SocketError as e: # Defensive: PySocks should catch all these. raise NewConnectionError( self, "Failed to establish a new connection: %s" % e) return conn # We don't need to duplicate the Verified/Unverified distinction from # urllib3/connection.py here because the HTTPSConnection will already have been # correctly set to either the Verified or Unverified form by that module. This # means the SOCKSHTTPSConnection will automatically be the correct type. class SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection): pass class SOCKSHTTPConnectionPool(HTTPConnectionPool): ConnectionCls = SOCKSConnection class SOCKSHTTPSConnectionPool(HTTPSConnectionPool): ConnectionCls = SOCKSHTTPSConnection class SOCKSProxyManager(PoolManager): """ A version of the urllib3 ProxyManager that routes connections via the defined SOCKS proxy. """ pool_classes_by_scheme = { 'http': SOCKSHTTPConnectionPool, 'https': SOCKSHTTPSConnectionPool, } def __init__(self, proxy_url, username=None, password=None, num_pools=10, headers=None, **connection_pool_kw): parsed = parse_url(proxy_url) if username is None and password is None and parsed.auth is not None: split = parsed.auth.split(':') if len(split) == 2: username, password = split if parsed.scheme == 'socks5': socks_version = socks.PROXY_TYPE_SOCKS5 rdns = False elif parsed.scheme == 'socks5h': socks_version = socks.PROXY_TYPE_SOCKS5 rdns = True elif parsed.scheme == 'socks4': socks_version = socks.PROXY_TYPE_SOCKS4 rdns = False elif parsed.scheme == 'socks4a': socks_version = socks.PROXY_TYPE_SOCKS4 rdns = True else: raise ValueError( "Unable to determine SOCKS version from %s" % proxy_url ) self.proxy_url = proxy_url socks_options = { 'socks_version': socks_version, 'proxy_host': parsed.host, 'proxy_port': parsed.port, 'username': username, 'password': password, 'rdns': rdns } connection_pool_kw['_socks_options'] = socks_options super(SOCKSProxyManager, self).__init__( num_pools, headers, **connection_pool_kw ) self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme PK! __init__.pynu[PK!_securetransport/__init__.pynu[PK!Y}DD_securetransport/bindings.pynu[""" This module uses ctypes to bind a whole bunch of functions and constants from SecureTransport. The goal here is to provide the low-level API to SecureTransport. These are essentially the C-level functions and constants, and they're pretty gross to work with. This code is a bastardised version of the code found in Will Bond's oscrypto library. An enormous debt is owed to him for blazing this trail for us. For that reason, this code should be considered to be covered both by urllib3's license and by oscrypto's: Copyright (c) 2015-2016 Will Bond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import platform from ctypes.util import find_library from ctypes import ( c_void_p, c_int32, c_char_p, c_size_t, c_byte, c_uint32, c_ulong, c_long, c_bool ) from ctypes import CDLL, POINTER, CFUNCTYPE security_path = find_library('Security') if not security_path: raise ImportError('The library Security could not be found') core_foundation_path = find_library('CoreFoundation') if not core_foundation_path: raise ImportError('The library CoreFoundation could not be found') version = platform.mac_ver()[0] version_info = tuple(map(int, version.split('.'))) if version_info < (10, 8): raise OSError( 'Only OS X 10.8 and newer are supported, not %s.%s' % ( version_info[0], version_info[1] ) ) Security = CDLL(security_path, use_errno=True) CoreFoundation = CDLL(core_foundation_path, use_errno=True) Boolean = c_bool CFIndex = c_long CFStringEncoding = c_uint32 CFData = c_void_p CFString = c_void_p CFArray = c_void_p CFMutableArray = c_void_p CFDictionary = c_void_p CFError = c_void_p CFType = c_void_p CFTypeID = c_ulong CFTypeRef = POINTER(CFType) CFAllocatorRef = c_void_p OSStatus = c_int32 CFDataRef = POINTER(CFData) CFStringRef = POINTER(CFString) CFArrayRef = POINTER(CFArray) CFMutableArrayRef = POINTER(CFMutableArray) CFDictionaryRef = POINTER(CFDictionary) CFArrayCallBacks = c_void_p CFDictionaryKeyCallBacks = c_void_p CFDictionaryValueCallBacks = c_void_p SecCertificateRef = POINTER(c_void_p) SecExternalFormat = c_uint32 SecExternalItemType = c_uint32 SecIdentityRef = POINTER(c_void_p) SecItemImportExportFlags = c_uint32 SecItemImportExportKeyParameters = c_void_p SecKeychainRef = POINTER(c_void_p) SSLProtocol = c_uint32 SSLCipherSuite = c_uint32 SSLContextRef = POINTER(c_void_p) SecTrustRef = POINTER(c_void_p) SSLConnectionRef = c_uint32 SecTrustResultType = c_uint32 SecTrustOptionFlags = c_uint32 SSLProtocolSide = c_uint32 SSLConnectionType = c_uint32 SSLSessionOption = c_uint32 try: Security.SecItemImport.argtypes = [ CFDataRef, CFStringRef, POINTER(SecExternalFormat), POINTER(SecExternalItemType), SecItemImportExportFlags, POINTER(SecItemImportExportKeyParameters), SecKeychainRef, POINTER(CFArrayRef), ] Security.SecItemImport.restype = OSStatus Security.SecCertificateGetTypeID.argtypes = [] Security.SecCertificateGetTypeID.restype = CFTypeID Security.SecIdentityGetTypeID.argtypes = [] Security.SecIdentityGetTypeID.restype = CFTypeID Security.SecKeyGetTypeID.argtypes = [] Security.SecKeyGetTypeID.restype = CFTypeID Security.SecCertificateCreateWithData.argtypes = [ CFAllocatorRef, CFDataRef ] Security.SecCertificateCreateWithData.restype = SecCertificateRef Security.SecCertificateCopyData.argtypes = [ SecCertificateRef ] Security.SecCertificateCopyData.restype = CFDataRef Security.SecCopyErrorMessageString.argtypes = [ OSStatus, c_void_p ] Security.SecCopyErrorMessageString.restype = CFStringRef Security.SecIdentityCreateWithCertificate.argtypes = [ CFTypeRef, SecCertificateRef, POINTER(SecIdentityRef) ] Security.SecIdentityCreateWithCertificate.restype = OSStatus Security.SecKeychainCreate.argtypes = [ c_char_p, c_uint32, c_void_p, Boolean, c_void_p, POINTER(SecKeychainRef) ] Security.SecKeychainCreate.restype = OSStatus Security.SecKeychainDelete.argtypes = [ SecKeychainRef ] Security.SecKeychainDelete.restype = OSStatus Security.SecPKCS12Import.argtypes = [ CFDataRef, CFDictionaryRef, POINTER(CFArrayRef) ] Security.SecPKCS12Import.restype = OSStatus SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t)) SSLWriteFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t)) Security.SSLSetIOFuncs.argtypes = [ SSLContextRef, SSLReadFunc, SSLWriteFunc ] Security.SSLSetIOFuncs.restype = OSStatus Security.SSLSetPeerID.argtypes = [ SSLContextRef, c_char_p, c_size_t ] Security.SSLSetPeerID.restype = OSStatus Security.SSLSetCertificate.argtypes = [ SSLContextRef, CFArrayRef ] Security.SSLSetCertificate.restype = OSStatus Security.SSLSetCertificateAuthorities.argtypes = [ SSLContextRef, CFTypeRef, Boolean ] Security.SSLSetCertificateAuthorities.restype = OSStatus Security.SSLSetConnection.argtypes = [ SSLContextRef, SSLConnectionRef ] Security.SSLSetConnection.restype = OSStatus Security.SSLSetPeerDomainName.argtypes = [ SSLContextRef, c_char_p, c_size_t ] Security.SSLSetPeerDomainName.restype = OSStatus Security.SSLHandshake.argtypes = [ SSLContextRef ] Security.SSLHandshake.restype = OSStatus Security.SSLRead.argtypes = [ SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t) ] Security.SSLRead.restype = OSStatus Security.SSLWrite.argtypes = [ SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t) ] Security.SSLWrite.restype = OSStatus Security.SSLClose.argtypes = [ SSLContextRef ] Security.SSLClose.restype = OSStatus Security.SSLGetNumberSupportedCiphers.argtypes = [ SSLContextRef, POINTER(c_size_t) ] Security.SSLGetNumberSupportedCiphers.restype = OSStatus Security.SSLGetSupportedCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), POINTER(c_size_t) ] Security.SSLGetSupportedCiphers.restype = OSStatus Security.SSLSetEnabledCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), c_size_t ] Security.SSLSetEnabledCiphers.restype = OSStatus Security.SSLGetNumberEnabledCiphers.argtype = [ SSLContextRef, POINTER(c_size_t) ] Security.SSLGetNumberEnabledCiphers.restype = OSStatus Security.SSLGetEnabledCiphers.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite), POINTER(c_size_t) ] Security.SSLGetEnabledCiphers.restype = OSStatus Security.SSLGetNegotiatedCipher.argtypes = [ SSLContextRef, POINTER(SSLCipherSuite) ] Security.SSLGetNegotiatedCipher.restype = OSStatus Security.SSLGetNegotiatedProtocolVersion.argtypes = [ SSLContextRef, POINTER(SSLProtocol) ] Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus Security.SSLCopyPeerTrust.argtypes = [ SSLContextRef, POINTER(SecTrustRef) ] Security.SSLCopyPeerTrust.restype = OSStatus Security.SecTrustSetAnchorCertificates.argtypes = [ SecTrustRef, CFArrayRef ] Security.SecTrustSetAnchorCertificates.restype = OSStatus Security.SecTrustSetAnchorCertificatesOnly.argstypes = [ SecTrustRef, Boolean ] Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus Security.SecTrustEvaluate.argtypes = [ SecTrustRef, POINTER(SecTrustResultType) ] Security.SecTrustEvaluate.restype = OSStatus Security.SecTrustGetCertificateCount.argtypes = [ SecTrustRef ] Security.SecTrustGetCertificateCount.restype = CFIndex Security.SecTrustGetCertificateAtIndex.argtypes = [ SecTrustRef, CFIndex ] Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef Security.SSLCreateContext.argtypes = [ CFAllocatorRef, SSLProtocolSide, SSLConnectionType ] Security.SSLCreateContext.restype = SSLContextRef Security.SSLSetSessionOption.argtypes = [ SSLContextRef, SSLSessionOption, Boolean ] Security.SSLSetSessionOption.restype = OSStatus Security.SSLSetProtocolVersionMin.argtypes = [ SSLContextRef, SSLProtocol ] Security.SSLSetProtocolVersionMin.restype = OSStatus Security.SSLSetProtocolVersionMax.argtypes = [ SSLContextRef, SSLProtocol ] Security.SSLSetProtocolVersionMax.restype = OSStatus Security.SecCopyErrorMessageString.argtypes = [ OSStatus, c_void_p ] Security.SecCopyErrorMessageString.restype = CFStringRef Security.SSLReadFunc = SSLReadFunc Security.SSLWriteFunc = SSLWriteFunc Security.SSLContextRef = SSLContextRef Security.SSLProtocol = SSLProtocol Security.SSLCipherSuite = SSLCipherSuite Security.SecIdentityRef = SecIdentityRef Security.SecKeychainRef = SecKeychainRef Security.SecTrustRef = SecTrustRef Security.SecTrustResultType = SecTrustResultType Security.SecExternalFormat = SecExternalFormat Security.OSStatus = OSStatus Security.kSecImportExportPassphrase = CFStringRef.in_dll( Security, 'kSecImportExportPassphrase' ) Security.kSecImportItemIdentity = CFStringRef.in_dll( Security, 'kSecImportItemIdentity' ) # CoreFoundation time! CoreFoundation.CFRetain.argtypes = [ CFTypeRef ] CoreFoundation.CFRetain.restype = CFTypeRef CoreFoundation.CFRelease.argtypes = [ CFTypeRef ] CoreFoundation.CFRelease.restype = None CoreFoundation.CFGetTypeID.argtypes = [ CFTypeRef ] CoreFoundation.CFGetTypeID.restype = CFTypeID CoreFoundation.CFStringCreateWithCString.argtypes = [ CFAllocatorRef, c_char_p, CFStringEncoding ] CoreFoundation.CFStringCreateWithCString.restype = CFStringRef CoreFoundation.CFStringGetCStringPtr.argtypes = [ CFStringRef, CFStringEncoding ] CoreFoundation.CFStringGetCStringPtr.restype = c_char_p CoreFoundation.CFStringGetCString.argtypes = [ CFStringRef, c_char_p, CFIndex, CFStringEncoding ] CoreFoundation.CFStringGetCString.restype = c_bool CoreFoundation.CFDataCreate.argtypes = [ CFAllocatorRef, c_char_p, CFIndex ] CoreFoundation.CFDataCreate.restype = CFDataRef CoreFoundation.CFDataGetLength.argtypes = [ CFDataRef ] CoreFoundation.CFDataGetLength.restype = CFIndex CoreFoundation.CFDataGetBytePtr.argtypes = [ CFDataRef ] CoreFoundation.CFDataGetBytePtr.restype = c_void_p CoreFoundation.CFDictionaryCreate.argtypes = [ CFAllocatorRef, POINTER(CFTypeRef), POINTER(CFTypeRef), CFIndex, CFDictionaryKeyCallBacks, CFDictionaryValueCallBacks ] CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef CoreFoundation.CFDictionaryGetValue.argtypes = [ CFDictionaryRef, CFTypeRef ] CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef CoreFoundation.CFArrayCreate.argtypes = [ CFAllocatorRef, POINTER(CFTypeRef), CFIndex, CFArrayCallBacks, ] CoreFoundation.CFArrayCreate.restype = CFArrayRef CoreFoundation.CFArrayCreateMutable.argtypes = [ CFAllocatorRef, CFIndex, CFArrayCallBacks ] CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef CoreFoundation.CFArrayAppendValue.argtypes = [ CFMutableArrayRef, c_void_p ] CoreFoundation.CFArrayAppendValue.restype = None CoreFoundation.CFArrayGetCount.argtypes = [ CFArrayRef ] CoreFoundation.CFArrayGetCount.restype = CFIndex CoreFoundation.CFArrayGetValueAtIndex.argtypes = [ CFArrayRef, CFIndex ] CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( CoreFoundation, 'kCFAllocatorDefault' ) CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll(CoreFoundation, 'kCFTypeArrayCallBacks') CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll( CoreFoundation, 'kCFTypeDictionaryKeyCallBacks' ) CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll( CoreFoundation, 'kCFTypeDictionaryValueCallBacks' ) CoreFoundation.CFTypeRef = CFTypeRef CoreFoundation.CFArrayRef = CFArrayRef CoreFoundation.CFStringRef = CFStringRef CoreFoundation.CFDictionaryRef = CFDictionaryRef except (AttributeError): raise ImportError('Error initializing ctypes') class CFConst(object): """ A class object that acts as essentially a namespace for CoreFoundation constants. """ kCFStringEncodingUTF8 = CFStringEncoding(0x08000100) class SecurityConst(object): """ A class object that acts as essentially a namespace for Security constants. """ kSSLSessionOptionBreakOnServerAuth = 0 kSSLProtocol2 = 1 kSSLProtocol3 = 2 kTLSProtocol1 = 4 kTLSProtocol11 = 7 kTLSProtocol12 = 8 kSSLClientSide = 1 kSSLStreamType = 0 kSecFormatPEMSequence = 10 kSecTrustResultInvalid = 0 kSecTrustResultProceed = 1 # This gap is present on purpose: this was kSecTrustResultConfirm, which # is deprecated. kSecTrustResultDeny = 3 kSecTrustResultUnspecified = 4 kSecTrustResultRecoverableTrustFailure = 5 kSecTrustResultFatalTrustFailure = 6 kSecTrustResultOtherError = 7 errSSLProtocol = -9800 errSSLWouldBlock = -9803 errSSLClosedGraceful = -9805 errSSLClosedNoNotify = -9816 errSSLClosedAbort = -9806 errSSLXCertChainInvalid = -9807 errSSLCrypto = -9809 errSSLInternal = -9810 errSSLCertExpired = -9814 errSSLCertNotYetValid = -9815 errSSLUnknownRootCert = -9812 errSSLNoRootCert = -9813 errSSLHostNameMismatch = -9843 errSSLPeerHandshakeFail = -9824 errSSLPeerUserCancelled = -9839 errSSLWeakPeerEphemeralDHKey = -9850 errSSLServerAuthCompleted = -9841 errSSLRecordOverflow = -9847 errSecVerifyFailed = -67808 errSecNoTrustSettings = -25263 errSecItemNotFound = -25300 errSecInvalidTrustSettings = -25262 # Cipher suites. We only pick the ones our default cipher string allows. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 = 0x00A3 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 = 0x00A2 TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014 TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 = 0x006A TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039 TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067 TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 = 0x0040 TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033 TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032 TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035 TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F TLS_AES_128_GCM_SHA256 = 0x1301 TLS_AES_256_GCM_SHA384 = 0x1302 TLS_CHACHA20_POLY1305_SHA256 = 0x1303 PK!"-X(X(:_securetransport/__pycache__/bindings.cpython-36.opt-1.pycnu[3 nf\D@sdZddlmZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZddlmZmZmZedZesxeded Zesed ejdZeeeejd ZedkredededfeeddZeeddZeZ eZ!e Z"eZ#eZ$eZ%eZ&eZ'eZ(eZ)e Z*ee)Z+eZ,eZ-ee#Z.ee$Z/ee%Z0ee&Z1ee'Z2eZ3eZ4eZ5eeZ6e Z7e Z8eeZ9e Z:eZ;eeZeeZ?eeZ@e ZAe ZBe ZCe ZDe ZEe ZFye.e/ee7ee8e:ee;eee geja_He-eja_Ie?ee>e gejb_He-ejb_Ie?ee gejc_de-ejc_Ie?ee>ee geje_He-eje_Ie?ee>gejf_He-ejf_Ie?ee=gejg_He-ejg_Ie?ee@gejh_He-ejh_Ie@e0geji_He-eji_Ie@e gejj_ke-ejj_Ie@eeBgejl_He-ejl_Ie@gejm_He!ejm_Ie@e!gejn_He6ejn_Ie,eDeEgejo_He?ejo_Ie?eFe gejp_He-ejp_Ie?e=gejq_He-ejq_Ie?e=gejr_He-ejr_Ie-egejO_He/ejO_IeTe_TeUe_Ue?e_?e=e_=e>e_>e9e_9e Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. )absolute_importN) find_library) c_void_pc_int32c_char_pc_size_tc_bytec_uint32c_ulongc_longc_bool)CDLLPOINTER CFUNCTYPESecurityz'The library Security could not be foundCoreFoundationz-The library CoreFoundation could not be found. z1Only OS X 10.8 and newer are supported, not %s.%sT)Z use_errnokSecImportExportPassphrasekSecImportItemIdentitykCFAllocatorDefaultkCFTypeArrayCallBackskCFTypeDictionaryKeyCallBackskCFTypeDictionaryValueCallBackszError initializing ctypesc@seZdZdZedZdS)CFConstz_ A class object that acts as essentially a namespace for CoreFoundation constants. iN)__name__ __module__ __qualname____doc__CFStringEncodingZkCFStringEncodingUTF8r"r"/usr/lib/python3.6/bindings.pyrsrc@s,eZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZd ZdZd Zd ZdZdDZdEZdFZdGZdHZdIZdJZdKZdLZdMZdNZdOZdPZ dQZ!dRZ"dSZ#dTZ$dUZ%dVZ&dWZ'dXZ(dYZ)d"Z*d#Z+d$Z,d%Z-d&Z.d'Z/d(Z0d)Z1d*Z2d+Z3d,Z4d-Z5d.Z6d/Z7d0Z8d1Z9d2Z:d3Z;d4Zd7Z?d8Z@d9ZAd:ZBd;ZCdZFd?ZGd@ZHdAZIdBZJdCS)Z SecurityConstzU A class object that acts as essentially a namespace for Security constants. rrrriH&iK&iM&iX&iN&iO&iQ&iR&iV&iW&iT&iU&is&i`&io&iz&iq&iw&iibibibi,i0i+i/i$i(i ikj98i#i'i ig@32=<5/iiiNiiiiiiiiiiiiiiiiiii iQi,iR)Krrrr Z"kSSLSessionOptionBreakOnServerAuthZ kSSLProtocol2Z kSSLProtocol3Z kTLSProtocol1ZkTLSProtocol11ZkTLSProtocol12ZkSSLClientSideZkSSLStreamTypeZkSecFormatPEMSequenceZkSecTrustResultInvalidZkSecTrustResultProceedZkSecTrustResultDenyZkSecTrustResultUnspecifiedZ&kSecTrustResultRecoverableTrustFailureZ kSecTrustResultFatalTrustFailureZkSecTrustResultOtherErrorZerrSSLProtocolZerrSSLWouldBlockZerrSSLClosedGracefulZerrSSLClosedNoNotifyZerrSSLClosedAbortZerrSSLXCertChainInvalidZ errSSLCryptoZerrSSLInternalZerrSSLCertExpiredZerrSSLCertNotYetValidZerrSSLUnknownRootCertZerrSSLNoRootCertZerrSSLHostNameMismatchZerrSSLPeerHandshakeFailZerrSSLPeerUserCancelledZerrSSLWeakPeerEphemeralDHKeyZerrSSLServerAuthCompletedZerrSSLRecordOverflowZerrSecVerifyFailedZerrSecNoTrustSettingsZerrSecItemNotFoundZerrSecInvalidTrustSettingsZ'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384Z%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384Z'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256Z%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256Z#TLS_DHE_DSS_WITH_AES_256_GCM_SHA384Z#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384Z#TLS_DHE_DSS_WITH_AES_128_GCM_SHA256Z#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256Z'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384Z%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384Z$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAZ"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256Z#TLS_DHE_DSS_WITH_AES_256_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_256_CBC_SHAZ TLS_DHE_DSS_WITH_AES_256_CBC_SHAZ'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256Z%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256Z$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAZ"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256Z#TLS_DHE_DSS_WITH_AES_128_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_128_CBC_SHAZ TLS_DHE_DSS_WITH_AES_128_CBC_SHAZTLS_RSA_WITH_AES_256_GCM_SHA384ZTLS_RSA_WITH_AES_128_GCM_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHA256ZTLS_RSA_WITH_AES_128_CBC_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHAZTLS_RSA_WITH_AES_128_CBC_SHAZTLS_AES_128_GCM_SHA256ZTLS_AES_256_GCM_SHA384ZTLS_CHACHA20_POLY1305_SHA256r"r"r"r#r$sr$)rr)r Z __future__rplatformZ ctypes.utilrZctypesrrrrrr r r r r rrZ security_path ImportErrorZcore_foundation_pathZmac_verversiontuplemapintsplit version_infoOSErrorrrZBooleanZCFIndexr!ZCFDataZCFStringZCFArrayZCFMutableArrayZ CFDictionaryZCFErrorZCFTypeZCFTypeIDZ CFTypeRefZCFAllocatorRefZOSStatusZ CFDataRefZ CFStringRefZ CFArrayRefZCFMutableArrayRefZCFDictionaryRefZCFArrayCallBacksZCFDictionaryKeyCallBacksZCFDictionaryValueCallBacksZSecCertificateRefZSecExternalFormatZSecExternalItemTypeZSecIdentityRefZSecItemImportExportFlagsZ SecItemImportExportKeyParametersZSecKeychainRefZ SSLProtocolZSSLCipherSuiteZ SSLContextRefZ SecTrustRefZSSLConnectionRefZSecTrustResultTypeZSecTrustOptionFlagsZSSLProtocolSideZSSLConnectionTypeZSSLSessionOptionZ SecItemImportZargtypesZrestypeZSecCertificateGetTypeIDZSecIdentityGetTypeIDZSecKeyGetTypeIDZSecCertificateCreateWithDataZSecCertificateCopyDataZSecCopyErrorMessageStringZ SecIdentityCreateWithCertificateZSecKeychainCreateZSecKeychainDeleteZSecPKCS12ImportZ SSLReadFuncZ SSLWriteFuncZ SSLSetIOFuncsZ SSLSetPeerIDZSSLSetCertificateZSSLSetCertificateAuthoritiesZSSLSetConnectionZSSLSetPeerDomainNameZ SSLHandshakeZSSLReadZSSLWriteZSSLCloseZSSLGetNumberSupportedCiphersZSSLGetSupportedCiphersZSSLSetEnabledCiphersZSSLGetNumberEnabledCiphersZargtypeZSSLGetEnabledCiphersZSSLGetNegotiatedCipherZSSLGetNegotiatedProtocolVersionZSSLCopyPeerTrustZSecTrustSetAnchorCertificatesZ!SecTrustSetAnchorCertificatesOnlyZ argstypesZSecTrustEvaluateZSecTrustGetCertificateCountZSecTrustGetCertificateAtIndexZSSLCreateContextZSSLSetSessionOptionZSSLSetProtocolVersionMinZSSLSetProtocolVersionMaxZin_dllrrZCFRetainZ CFReleaseZ CFGetTypeIDZCFStringCreateWithCStringZCFStringGetCStringPtrZCFStringGetCStringZ CFDataCreateZCFDataGetLengthZCFDataGetBytePtrZCFDictionaryCreateZCFDictionaryGetValueZ CFArrayCreateZCFArrayCreateMutableZCFArrayAppendValueZCFArrayGetCountZCFArrayGetValueAtIndexrrrrAttributeErrorobjectrr$r"r"r"r#s,  ,                                               PK!cl;_securetransport/__pycache__/low_level.cpython-36.opt-1.pycnu[3 nf\/@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z m Z ej dej ZddZdd Zd d Zdd d ZddZddZddZddZddZddZdS)a Low-level helpers for the SecureTransport bindings. These are Python functions that are not directly related to the high-level APIs but are necessary to get them to work. They include a whole bunch of low-level CoreFoundation messing about and memory management. The concerns in this module are almost entirely about trying to avoid memory leaks and providing appropriate and useful assistance to the higher-level code. N)SecurityCoreFoundationCFConsts;-----BEGIN CERTIFICATE----- (.*?) -----END CERTIFICATE-----cCstjtj|t|S)zv Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. )r CFDataCreatekCFAllocatorDefaultlen)Z bytestringr /usr/lib/python3.6/low_level.py_cf_data_from_bytessr cCsZt|}dd|D}dd|D}tj||}tj||}tjtj|||tjtjS)zK Given a list of Python tuples, create an associated CFDictionary. css|]}|dVqdS)rNr ).0tr r r ,sz-_cf_dictionary_from_tuples..css|]}|dVqdS)rNr )r r r r r r-s)rr CFTypeRefZCFDictionaryCreaterZkCFTypeDictionaryKeyCallBacksZkCFTypeDictionaryValueCallBacks)ZtuplesZdictionary_sizekeysvaluesZcf_keysZ cf_valuesr r r _cf_dictionary_from_tuples%srcCsntj|tjtj}tj|tj}|dkrXtjd}tj ||dtj}|sRt d|j }|dk rj|j d}|S)z Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. Niz'Error copying C string from CFStringRefzutf-8) ctypescastZPOINTERZc_void_prZCFStringGetCStringPtrrZkCFStringEncodingUTF8Zcreate_string_bufferZCFStringGetCStringOSErrorvaluedecode)rZvalue_as_void_pstringbufferresultr r r _cf_string_to_unicode;s"  rcCs\|dkr dStj|d}t|}tj||dks:|dkrBd|}|dkrPtj}||dS)z[ Checks the return code and throws an exception if there is an error to report rNz OSStatus %s)rZSecCopyErrorMessageStringrr CFReleasesslSSLError)errorZexception_classZcf_error_stringoutputr r r _assert_no_errorXs  r"c Cs|jdd}ddtj|D}|s.tjdtjtjdtj tj }|sTtjdydx^|D]V}t |}|svtjdt j tj|}tj||stjdtj||tj|q\WWntk rtj|YnX|S) z Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. s  cSsg|]}tj|jdqS)r)base64Z b64decodegroup)r matchr r r vsz(_cert_array_from_pem..zNo root certificates specifiedrzUnable to allocate memory!zUnable to build cert object!)replace _PEM_CERTS_REfinditerrrrCFArrayCreateMutablerrbyrefkCFTypeArrayCallBacksr rZSecCertificateCreateWithDatarCFArrayAppendValue Exception)Z pem_bundleZ der_certsZ cert_arrayZ der_bytesZcertdataZcertr r r _cert_array_from_pemms4         r0cCstj}tj||kS)z= Returns True if a given CFTypeRef is a certificate. )rZSecCertificateGetTypeIDr CFGetTypeID)itemexpectedr r r _is_certsr4cCstj}tj||kS)z; Returns True if a given CFTypeRef is an identity. )rZSecIdentityGetTypeIDrr1)r2r3r r r _is_identitysr5cCstjd}tj|ddjd}tj|dd}tj}tjj||j d}t j }t j |t ||ddtj|}t|||fS)a This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. (Nzutf-8F)osurandomr$Z b16encodertempfileZmkdtemppathjoinencoderZSecKeychainRefZSecKeychainCreaterrr,r")Z random_bytesfilenameZpasswordZ tempdirectoryZ keychain_pathkeychainstatusr r r _temporary_keychains  rAc Csg}g}d}t|d}|j}WdQRXztjtj|t|}tj}tj|ddddd|t j |}t |tj |} xdt | D]X} tj|| } t j| tj} t| rtj| |j| qt| rtj| |j| qWWd|rtj|tj|X||fS)z Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. Nrbr)openreadrrrrZ CFArrayRefrZ SecItemImportrr,r"ZCFArrayGetCountrangeZCFArrayGetValueAtIndexrrr4ZCFRetainappendr5r) r?r; certificates identitiesZ result_arrayfZ raw_filedataZfiledatarZ result_countindexr2r r r _load_items_from_filesH         rKc Gsg}g}dd|D}zx.|D]&}t||\}}|j||j|qW|stj}tj||dtj|}t||j|t j |j dt j t j dtjt j} x tj||D]} t j| | qW| Sxtj||D]} t j | qWXdS)z Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. css|]}|r|VqdS)Nr )r r;r r r r2sz*_load_client_cert_chain..rN)rKextendrZSecIdentityRefZ SecIdentityCreateWithCertificaterr,r"rFrrpopr+rr- itertoolschainr.) r?pathsrGrHZ file_pathZnew_identitiesZ new_certsZ new_identityr@Z trust_chainr2objr r r _load_client_cert_chains6      rR)N)__doc__r$rrNrer8rr:ZbindingsrrrcompileDOTALLr)r rrr"r0r4r5rArKrRr r r r  s(   .(;PK!cl5_securetransport/__pycache__/low_level.cpython-36.pycnu[3 nf\/@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z m Z ej dej ZddZdd Zd d Zdd d ZddZddZddZddZddZddZdS)a Low-level helpers for the SecureTransport bindings. These are Python functions that are not directly related to the high-level APIs but are necessary to get them to work. They include a whole bunch of low-level CoreFoundation messing about and memory management. The concerns in this module are almost entirely about trying to avoid memory leaks and providing appropriate and useful assistance to the higher-level code. N)SecurityCoreFoundationCFConsts;-----BEGIN CERTIFICATE----- (.*?) -----END CERTIFICATE-----cCstjtj|t|S)zv Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. )r CFDataCreatekCFAllocatorDefaultlen)Z bytestringr /usr/lib/python3.6/low_level.py_cf_data_from_bytessr cCsZt|}dd|D}dd|D}tj||}tj||}tjtj|||tjtjS)zK Given a list of Python tuples, create an associated CFDictionary. css|]}|dVqdS)rNr ).0tr r r ,sz-_cf_dictionary_from_tuples..css|]}|dVqdS)rNr )r r r r r r-s)rr CFTypeRefZCFDictionaryCreaterZkCFTypeDictionaryKeyCallBacksZkCFTypeDictionaryValueCallBacks)ZtuplesZdictionary_sizekeysvaluesZcf_keysZ cf_valuesr r r _cf_dictionary_from_tuples%srcCsntj|tjtj}tj|tj}|dkrXtjd}tj ||dtj}|sRt d|j }|dk rj|j d}|S)z Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. Niz'Error copying C string from CFStringRefzutf-8) ctypescastZPOINTERZc_void_prZCFStringGetCStringPtrrZkCFStringEncodingUTF8Zcreate_string_bufferZCFStringGetCStringOSErrorvaluedecode)rZvalue_as_void_pstringbufferresultr r r _cf_string_to_unicode;s"  rcCs\|dkr dStj|d}t|}tj||dks:|dkrBd|}|dkrPtj}||dS)z[ Checks the return code and throws an exception if there is an error to report rNz OSStatus %s)rZSecCopyErrorMessageStringrr CFReleasesslSSLError)errorZexception_classZcf_error_stringoutputr r r _assert_no_errorXs  r"c Cs|jdd}ddtj|D}|s.tjdtjtjdtj tj }|sTtjdydx^|D]V}t |}|svtjdt j tj|}tj||stjdtj||tj|q\WWntk rtj|YnX|S) z Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. s  cSsg|]}tj|jdqS)r)base64Z b64decodegroup)r matchr r r vsz(_cert_array_from_pem..zNo root certificates specifiedrzUnable to allocate memory!zUnable to build cert object!)replace _PEM_CERTS_REfinditerrrrCFArrayCreateMutablerrbyrefkCFTypeArrayCallBacksr rZSecCertificateCreateWithDatarCFArrayAppendValue Exception)Z pem_bundleZ der_certsZ cert_arrayZ der_bytesZcertdataZcertr r r _cert_array_from_pemms4         r0cCstj}tj||kS)z= Returns True if a given CFTypeRef is a certificate. )rZSecCertificateGetTypeIDr CFGetTypeID)itemexpectedr r r _is_certsr4cCstj}tj||kS)z; Returns True if a given CFTypeRef is an identity. )rZSecIdentityGetTypeIDrr1)r2r3r r r _is_identitysr5cCstjd}tj|ddjd}tj|dd}tj}tjj||j d}t j }t j |t ||ddtj|}t|||fS)a This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. (Nzutf-8F)osurandomr$Z b16encodertempfileZmkdtemppathjoinencoderZSecKeychainRefZSecKeychainCreaterrr,r")Z random_bytesfilenameZpasswordZ tempdirectoryZ keychain_pathkeychainstatusr r r _temporary_keychains  rAc Csg}g}d}t|d}|j}WdQRXztjtj|t|}tj}tj|ddddd|t j |}t |tj |} xdt | D]X} tj|| } t j| tj} t| rtj| |j| qt| rtj| |j| qWWd|rtj|tj|X||fS)z Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. Nrbr)openreadrrrrZ CFArrayRefrZ SecItemImportrr,r"ZCFArrayGetCountrangeZCFArrayGetValueAtIndexrrr4ZCFRetainappendr5r) r?r; certificates identitiesZ result_arrayfZ raw_filedataZfiledatarZ result_countindexr2r r r _load_items_from_filesH         rKc Gsg}g}dd|D}zx.|D]&}t||\}}|j||j|qW|stj}tj||dtj|}t||j|t j |j dt j t j dtjt j} x tj||D]} t j| | qW| Sxtj||D]} t j | qWXdS)z Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. css|]}|r|VqdS)Nr )r r;r r r r2sz*_load_client_cert_chain..rN)rKextendrZSecIdentityRefZ SecIdentityCreateWithCertificaterr,r"rFrrpopr+rr- itertoolschainr.) r?pathsrGrHZ file_pathZnew_identitiesZ new_certsZ new_identityr@Z trust_chainr2objr r r _load_client_cert_chains6      rR)N)__doc__r$rrNrer8rr:ZbindingsrrrcompileDOTALLr)r rrr"r0r4r5rArKrRr r r r  s(   .(;PK!"-X(X(4_securetransport/__pycache__/bindings.cpython-36.pycnu[3 nf\D@sdZddlmZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZddlmZmZmZedZesxeded Zesed ejdZeeeejd ZedkredededfeeddZeeddZeZ eZ!e Z"eZ#eZ$eZ%eZ&eZ'eZ(eZ)e Z*ee)Z+eZ,eZ-ee#Z.ee$Z/ee%Z0ee&Z1ee'Z2eZ3eZ4eZ5eeZ6e Z7e Z8eeZ9e Z:eZ;eeZeeZ?eeZ@e ZAe ZBe ZCe ZDe ZEe ZFye.e/ee7ee8e:ee;eee geja_He-eja_Ie?ee>e gejb_He-ejb_Ie?ee gejc_de-ejc_Ie?ee>ee geje_He-eje_Ie?ee>gejf_He-ejf_Ie?ee=gejg_He-ejg_Ie?ee@gejh_He-ejh_Ie@e0geji_He-eji_Ie@e gejj_ke-ejj_Ie@eeBgejl_He-ejl_Ie@gejm_He!ejm_Ie@e!gejn_He6ejn_Ie,eDeEgejo_He?ejo_Ie?eFe gejp_He-ejp_Ie?e=gejq_He-ejq_Ie?e=gejr_He-ejr_Ie-egejO_He/ejO_IeTe_TeUe_Ue?e_?e=e_=e>e_>e9e_9e Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. )absolute_importN) find_library) c_void_pc_int32c_char_pc_size_tc_bytec_uint32c_ulongc_longc_bool)CDLLPOINTER CFUNCTYPESecurityz'The library Security could not be foundCoreFoundationz-The library CoreFoundation could not be found. z1Only OS X 10.8 and newer are supported, not %s.%sT)Z use_errnokSecImportExportPassphrasekSecImportItemIdentitykCFAllocatorDefaultkCFTypeArrayCallBackskCFTypeDictionaryKeyCallBackskCFTypeDictionaryValueCallBackszError initializing ctypesc@seZdZdZedZdS)CFConstz_ A class object that acts as essentially a namespace for CoreFoundation constants. iN)__name__ __module__ __qualname____doc__CFStringEncodingZkCFStringEncodingUTF8r"r"/usr/lib/python3.6/bindings.pyrsrc@s,eZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZd ZdZd Zd ZdZdDZdEZdFZdGZdHZdIZdJZdKZdLZdMZdNZdOZdPZ dQZ!dRZ"dSZ#dTZ$dUZ%dVZ&dWZ'dXZ(dYZ)d"Z*d#Z+d$Z,d%Z-d&Z.d'Z/d(Z0d)Z1d*Z2d+Z3d,Z4d-Z5d.Z6d/Z7d0Z8d1Z9d2Z:d3Z;d4Zd7Z?d8Z@d9ZAd:ZBd;ZCdZFd?ZGd@ZHdAZIdBZJdCS)Z SecurityConstzU A class object that acts as essentially a namespace for Security constants. rrrriH&iK&iM&iX&iN&iO&iQ&iR&iV&iW&iT&iU&is&i`&io&iz&iq&iw&iibibibi,i0i+i/i$i(i ikj98i#i'i ig@32=<5/iiiNiiiiiiiiiiiiiiiiiii iQi,iR)Krrrr Z"kSSLSessionOptionBreakOnServerAuthZ kSSLProtocol2Z kSSLProtocol3Z kTLSProtocol1ZkTLSProtocol11ZkTLSProtocol12ZkSSLClientSideZkSSLStreamTypeZkSecFormatPEMSequenceZkSecTrustResultInvalidZkSecTrustResultProceedZkSecTrustResultDenyZkSecTrustResultUnspecifiedZ&kSecTrustResultRecoverableTrustFailureZ kSecTrustResultFatalTrustFailureZkSecTrustResultOtherErrorZerrSSLProtocolZerrSSLWouldBlockZerrSSLClosedGracefulZerrSSLClosedNoNotifyZerrSSLClosedAbortZerrSSLXCertChainInvalidZ errSSLCryptoZerrSSLInternalZerrSSLCertExpiredZerrSSLCertNotYetValidZerrSSLUnknownRootCertZerrSSLNoRootCertZerrSSLHostNameMismatchZerrSSLPeerHandshakeFailZerrSSLPeerUserCancelledZerrSSLWeakPeerEphemeralDHKeyZerrSSLServerAuthCompletedZerrSSLRecordOverflowZerrSecVerifyFailedZerrSecNoTrustSettingsZerrSecItemNotFoundZerrSecInvalidTrustSettingsZ'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384Z%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384Z'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256Z%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256Z#TLS_DHE_DSS_WITH_AES_256_GCM_SHA384Z#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384Z#TLS_DHE_DSS_WITH_AES_128_GCM_SHA256Z#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256Z'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384Z%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384Z$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAZ"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256Z#TLS_DHE_DSS_WITH_AES_256_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_256_CBC_SHAZ TLS_DHE_DSS_WITH_AES_256_CBC_SHAZ'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256Z%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256Z$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAZ"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256Z#TLS_DHE_DSS_WITH_AES_128_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_128_CBC_SHAZ TLS_DHE_DSS_WITH_AES_128_CBC_SHAZTLS_RSA_WITH_AES_256_GCM_SHA384ZTLS_RSA_WITH_AES_128_GCM_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHA256ZTLS_RSA_WITH_AES_128_CBC_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHAZTLS_RSA_WITH_AES_128_CBC_SHAZTLS_AES_128_GCM_SHA256ZTLS_AES_256_GCM_SHA384ZTLS_CHACHA20_POLY1305_SHA256r"r"r"r#r$sr$)rr)r Z __future__rplatformZ ctypes.utilrZctypesrrrrrr r r r r rrZ security_path ImportErrorZcore_foundation_pathZmac_verversiontuplemapintsplit version_infoOSErrorrrZBooleanZCFIndexr!ZCFDataZCFStringZCFArrayZCFMutableArrayZ CFDictionaryZCFErrorZCFTypeZCFTypeIDZ CFTypeRefZCFAllocatorRefZOSStatusZ CFDataRefZ CFStringRefZ CFArrayRefZCFMutableArrayRefZCFDictionaryRefZCFArrayCallBacksZCFDictionaryKeyCallBacksZCFDictionaryValueCallBacksZSecCertificateRefZSecExternalFormatZSecExternalItemTypeZSecIdentityRefZSecItemImportExportFlagsZ SecItemImportExportKeyParametersZSecKeychainRefZ SSLProtocolZSSLCipherSuiteZ SSLContextRefZ SecTrustRefZSSLConnectionRefZSecTrustResultTypeZSecTrustOptionFlagsZSSLProtocolSideZSSLConnectionTypeZSSLSessionOptionZ SecItemImportZargtypesZrestypeZSecCertificateGetTypeIDZSecIdentityGetTypeIDZSecKeyGetTypeIDZSecCertificateCreateWithDataZSecCertificateCopyDataZSecCopyErrorMessageStringZ SecIdentityCreateWithCertificateZSecKeychainCreateZSecKeychainDeleteZSecPKCS12ImportZ SSLReadFuncZ SSLWriteFuncZ SSLSetIOFuncsZ SSLSetPeerIDZSSLSetCertificateZSSLSetCertificateAuthoritiesZSSLSetConnectionZSSLSetPeerDomainNameZ SSLHandshakeZSSLReadZSSLWriteZSSLCloseZSSLGetNumberSupportedCiphersZSSLGetSupportedCiphersZSSLSetEnabledCiphersZSSLGetNumberEnabledCiphersZargtypeZSSLGetEnabledCiphersZSSLGetNegotiatedCipherZSSLGetNegotiatedProtocolVersionZSSLCopyPeerTrustZSecTrustSetAnchorCertificatesZ!SecTrustSetAnchorCertificatesOnlyZ argstypesZSecTrustEvaluateZSecTrustGetCertificateCountZSecTrustGetCertificateAtIndexZSSLCreateContextZSSLSetSessionOptionZSSLSetProtocolVersionMinZSSLSetProtocolVersionMaxZin_dllrrZCFRetainZ CFReleaseZ CFGetTypeIDZCFStringCreateWithCStringZCFStringGetCStringPtrZCFStringGetCStringZ CFDataCreateZCFDataGetLengthZCFDataGetBytePtrZCFDictionaryCreateZCFDictionaryGetValueZ CFArrayCreateZCFArrayCreateMutableZCFArrayAppendValueZCFArrayGetCountZCFArrayGetValueAtIndexrrrrAttributeErrorobjectrr$r"r"r"r#s,  ,                                               PK!5@qq4_securetransport/__pycache__/__init__.cpython-36.pycnu[3 nf\@sdS)Nrrr/usr/lib/python3.6/__init__.pysPK!5@qq:_securetransport/__pycache__/__init__.cpython-36.opt-1.pycnu[3 nf\@sdS)Nrrr/usr/lib/python3.6/__init__.pysPK!sK//_securetransport/low_level.pynu[""" Low-level helpers for the SecureTransport bindings. These are Python functions that are not directly related to the high-level APIs but are necessary to get them to work. They include a whole bunch of low-level CoreFoundation messing about and memory management. The concerns in this module are almost entirely about trying to avoid memory leaks and providing appropriate and useful assistance to the higher-level code. """ import base64 import ctypes import itertools import re import os import ssl import tempfile from .bindings import Security, CoreFoundation, CFConst # This regular expression is used to grab PEM data out of a PEM bundle. _PEM_CERTS_RE = re.compile( b"-----BEGIN CERTIFICATE-----\n(.*?)\n-----END CERTIFICATE-----", re.DOTALL ) def _cf_data_from_bytes(bytestring): """ Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. """ return CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring) ) def _cf_dictionary_from_tuples(tuples): """ Given a list of Python tuples, create an associated CFDictionary. """ dictionary_size = len(tuples) # We need to get the dictionary keys and values out in the same order. keys = (t[0] for t in tuples) values = (t[1] for t in tuples) cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys) cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values) return CoreFoundation.CFDictionaryCreate( CoreFoundation.kCFAllocatorDefault, cf_keys, cf_values, dictionary_size, CoreFoundation.kCFTypeDictionaryKeyCallBacks, CoreFoundation.kCFTypeDictionaryValueCallBacks, ) def _cf_string_to_unicode(value): """ Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. """ value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr( value_as_void_p, CFConst.kCFStringEncodingUTF8 ) if string is None: buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStringGetCString( value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8 ) if not result: raise OSError('Error copying C string from CFStringRef') string = buffer.value if string is not None: string = string.decode('utf-8') return string def _assert_no_error(error, exception_class=None): """ Checks the return code and throws an exception if there is an error to report """ if error == 0: return cf_error_string = Security.SecCopyErrorMessageString(error, None) output = _cf_string_to_unicode(cf_error_string) CoreFoundation.CFRelease(cf_error_string) if output is None or output == u'': output = u'OSStatus %s' % error if exception_class is None: exception_class = ssl.SSLError raise exception_class(output) def _cert_array_from_pem(pem_bundle): """ Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. """ # Normalize the PEM bundle's line endings. pem_bundle = pem_bundle.replace(b"\r\n", b"\n") der_certs = [ base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle) ] if not der_certs: raise ssl.SSLError("No root certificates specified") cert_array = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks) ) if not cert_array: raise ssl.SSLError("Unable to allocate memory!") try: for der_bytes in der_certs: certdata = _cf_data_from_bytes(der_bytes) if not certdata: raise ssl.SSLError("Unable to allocate memory!") cert = Security.SecCertificateCreateWithData( CoreFoundation.kCFAllocatorDefault, certdata ) CoreFoundation.CFRelease(certdata) if not cert: raise ssl.SSLError("Unable to build cert object!") CoreFoundation.CFArrayAppendValue(cert_array, cert) CoreFoundation.CFRelease(cert) except Exception: # We need to free the array before the exception bubbles further. # We only want to do that if an error occurs: otherwise, the caller # should free. CoreFoundation.CFRelease(cert_array) return cert_array def _is_cert(item): """ Returns True if a given CFTypeRef is a certificate. """ expected = Security.SecCertificateGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected def _is_identity(item): """ Returns True if a given CFTypeRef is an identity. """ expected = Security.SecIdentityGetTypeID() return CoreFoundation.CFGetTypeID(item) == expected def _temporary_keychain(): """ This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. """ # Unfortunately, SecKeychainCreate requires a path to a keychain. This # means we cannot use mkstemp to use a generic temporary file. Instead, # we're going to create a temporary directory and a filename to use there. # This filename will be 8 random bytes expanded into base64. We also need # some random bytes to password-protect the keychain we're creating, so we # ask for 40 random bytes. random_bytes = os.urandom(40) filename = base64.b16encode(random_bytes[:8]).decode('utf-8') password = base64.b16encode(random_bytes[8:]) # Must be valid UTF-8 tempdirectory = tempfile.mkdtemp() keychain_path = os.path.join(tempdirectory, filename).encode('utf-8') # We now want to create the keychain itself. keychain = Security.SecKeychainRef() status = Security.SecKeychainCreate( keychain_path, len(password), password, False, None, ctypes.byref(keychain) ) _assert_no_error(status) # Having created the keychain, we want to pass it off to the caller. return keychain, tempdirectory def _load_items_from_file(keychain, path): """ Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. """ certificates = [] identities = [] result_array = None with open(path, 'rb') as f: raw_filedata = f.read() try: filedata = CoreFoundation.CFDataCreate( CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata) ) result_array = CoreFoundation.CFArrayRef() result = Security.SecItemImport( filedata, # cert data None, # Filename, leaving it out for now None, # What the type of the file is, we don't care None, # what's in the file, we don't care 0, # import flags None, # key params, can include passphrase in the future keychain, # The keychain to insert into ctypes.byref(result_array) # Results ) _assert_no_error(result) # A CFArray is not very useful to us as an intermediary # representation, so we are going to extract the objects we want # and then free the array. We don't need to keep hold of keys: the # keychain already has them! result_count = CoreFoundation.CFArrayGetCount(result_array) for index in range(result_count): item = CoreFoundation.CFArrayGetValueAtIndex( result_array, index ) item = ctypes.cast(item, CoreFoundation.CFTypeRef) if _is_cert(item): CoreFoundation.CFRetain(item) certificates.append(item) elif _is_identity(item): CoreFoundation.CFRetain(item) identities.append(item) finally: if result_array: CoreFoundation.CFRelease(result_array) CoreFoundation.CFRelease(filedata) return (identities, certificates) def _load_client_cert_chain(keychain, *paths): """ Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. """ # Ok, the strategy. # # This relies on knowing that macOS will not give you a SecIdentityRef # unless you have imported a key into a keychain. This is a somewhat # artificial limitation of macOS (for example, it doesn't necessarily # affect iOS), but there is nothing inside Security.framework that lets you # get a SecIdentityRef without having a key in a keychain. # # So the policy here is we take all the files and iterate them in order. # Each one will use SecItemImport to have one or more objects loaded from # it. We will also point at a keychain that macOS can use to work with the # private key. # # Once we have all the objects, we'll check what we actually have. If we # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise, # we'll take the first certificate (which we assume to be our leaf) and # ask the keychain to give us a SecIdentityRef with that cert's associated # key. # # We'll then return a CFArray containing the trust chain: one # SecIdentityRef and then zero-or-more SecCertificateRef objects. The # responsibility for freeing this CFArray will be with the caller. This # CFArray must remain alive for the entire connection, so in practice it # will be stored with a single SSLSocket, along with the reference to the # keychain. certificates = [] identities = [] # Filter out bad paths. paths = (path for path in paths if path) try: for file_path in paths: new_identities, new_certs = _load_items_from_file( keychain, file_path ) identities.extend(new_identities) certificates.extend(new_certs) # Ok, we have everything. The question is: do we have an identity? If # not, we want to grab one from the first cert we have. if not identities: new_identity = Security.SecIdentityRef() status = Security.SecIdentityCreateWithCertificate( keychain, certificates[0], ctypes.byref(new_identity) ) _assert_no_error(status) identities.append(new_identity) # We now want to release the original certificate, as we no longer # need it. CoreFoundation.CFRelease(certificates.pop(0)) # We now need to build a new CFArray that holds the trust chain. trust_chain = CoreFoundation.CFArrayCreateMutable( CoreFoundation.kCFAllocatorDefault, 0, ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks), ) for item in itertools.chain(identities, certificates): # ArrayAppendValue does a CFRetain on the item. That's fine, # because the finally block will release our other refs to them. CoreFoundation.CFArrayAppendValue(trust_chain, item) return trust_chain finally: for obj in itertools.chain(identities, certificates): CoreFoundation.CFRelease(obj) PK!/_appengine_environ.pynu[""" This module provides means to detect the App Engine environment. """ import os def is_appengine(): return (is_local_appengine() or is_prod_appengine() or is_prod_appengine_mvms()) def is_appengine_sandbox(): return is_appengine() and not is_prod_appengine_mvms() def is_local_appengine(): return ('APPENGINE_RUNTIME' in os.environ and 'Development/' in os.environ['SERVER_SOFTWARE']) def is_prod_appengine(): return ('APPENGINE_RUNTIME' in os.environ and 'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and not is_prod_appengine_mvms()) def is_prod_appengine_mvms(): return os.environ.get('GAE_VM', False) == 'true' PK! evevsecuretransport.pynu[""" SecureTranport support for urllib3 via ctypes. This makes platform-native TLS available to urllib3 users on macOS without the use of a compiler. This is an important feature because the Python Package Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL that ships with macOS is not capable of doing TLSv1.2. The only way to resolve this is to give macOS users an alternative solution to the problem, and that solution is to use SecureTransport. We use ctypes here because this solution must not require a compiler. That's because pip is not allowed to require a compiler either. This is not intended to be a seriously long-term solution to this problem. The hope is that PEP 543 will eventually solve this issue for us, at which point we can retire this contrib module. But in the short term, we need to solve the impending tire fire that is Python on Mac without this kind of contrib module. So...here we are. To use this module, simply import and inject it:: import urllib3.contrib.securetransport urllib3.contrib.securetransport.inject_into_urllib3() Happy TLSing! """ from __future__ import absolute_import import contextlib import ctypes import errno import os.path import shutil import socket import ssl import threading import weakref from .. import util from ._securetransport.bindings import ( Security, SecurityConst, CoreFoundation ) from ._securetransport.low_level import ( _assert_no_error, _cert_array_from_pem, _temporary_keychain, _load_client_cert_chain ) try: # Platform-specific: Python 2 from socket import _fileobject except ImportError: # Platform-specific: Python 3 _fileobject = None from ..packages.backports.makefile import backport_makefile __all__ = ['inject_into_urllib3', 'extract_from_urllib3'] # SNI always works HAS_SNI = True orig_util_HAS_SNI = util.HAS_SNI orig_util_SSLContext = util.ssl_.SSLContext # This dictionary is used by the read callback to obtain a handle to the # calling wrapped socket. This is a pretty silly approach, but for now it'll # do. I feel like I should be able to smuggle a handle to the wrapped socket # directly in the SSLConnectionRef, but for now this approach will work I # guess. # # We need to lock around this structure for inserts, but we don't do it for # reads/writes in the callbacks. The reasoning here goes as follows: # # 1. It is not possible to call into the callbacks before the dictionary is # populated, so once in the callback the id must be in the dictionary. # 2. The callbacks don't mutate the dictionary, they only read from it, and # so cannot conflict with any of the insertions. # # This is good: if we had to lock in the callbacks we'd drastically slow down # the performance of this code. _connection_refs = weakref.WeakValueDictionary() _connection_ref_lock = threading.Lock() # Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over # for no better reason than we need *a* limit, and this one is right there. SSL_WRITE_BLOCKSIZE = 16384 # This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to # individual cipher suites. We need to do this because this is how # SecureTransport wants them. CIPHER_SUITES = [ SecurityConst.TLS_AES_256_GCM_SHA384, SecurityConst.TLS_CHACHA20_POLY1305_SHA256, SecurityConst.TLS_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SecurityConst.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SecurityConst.TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384, SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256, SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256, SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256, SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA, SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA, ] # Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of # TLSv1 and a high of TLSv1.2. For everything else, we pin to that version. _protocol_to_min_max = { ssl.PROTOCOL_SSLv23: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12), } if hasattr(ssl, "PROTOCOL_SSLv2"): _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = ( SecurityConst.kSSLProtocol2, SecurityConst.kSSLProtocol2 ) if hasattr(ssl, "PROTOCOL_SSLv3"): _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = ( SecurityConst.kSSLProtocol3, SecurityConst.kSSLProtocol3 ) if hasattr(ssl, "PROTOCOL_TLSv1"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = ( SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol1 ) if hasattr(ssl, "PROTOCOL_TLSv1_1"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = ( SecurityConst.kTLSProtocol11, SecurityConst.kTLSProtocol11 ) if hasattr(ssl, "PROTOCOL_TLSv1_2"): _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = ( SecurityConst.kTLSProtocol12, SecurityConst.kTLSProtocol12 ) if hasattr(ssl, "PROTOCOL_TLS"): _protocol_to_min_max[ssl.PROTOCOL_TLS] = _protocol_to_min_max[ssl.PROTOCOL_SSLv23] def inject_into_urllib3(): """ Monkey-patch urllib3 with SecureTransport-backed SSL-support. """ util.ssl_.SSLContext = SecureTransportContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_SECURETRANSPORT = True util.ssl_.IS_SECURETRANSPORT = True def extract_from_urllib3(): """ Undo monkey-patching by :func:`inject_into_urllib3`. """ util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_SECURETRANSPORT = False util.ssl_.IS_SECURETRANSPORT = False def _read_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport read callback. This is called by ST to request that data be returned from the socket. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket requested_length = data_length_pointer[0] timeout = wrapped_socket.gettimeout() error = None read_count = 0 try: while read_count < requested_length: if timeout is None or timeout >= 0: if not util.wait_for_read(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') remaining = requested_length - read_count buffer = (ctypes.c_char * remaining).from_address( data_buffer + read_count ) chunk_size = base_socket.recv_into(buffer, remaining) read_count += chunk_size if not chunk_size: if not read_count: return SecurityConst.errSSLClosedGraceful break except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = read_count if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = read_count if read_count != requested_length: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal def _write_callback(connection_id, data_buffer, data_length_pointer): """ SecureTransport write callback. This is called by ST to request that data actually be sent on the network. """ wrapped_socket = None try: wrapped_socket = _connection_refs.get(connection_id) if wrapped_socket is None: return SecurityConst.errSSLInternal base_socket = wrapped_socket.socket bytes_to_write = data_length_pointer[0] data = ctypes.string_at(data_buffer, bytes_to_write) timeout = wrapped_socket.gettimeout() error = None sent = 0 try: while sent < bytes_to_write: if timeout is None or timeout >= 0: if not util.wait_for_write(base_socket, timeout): raise socket.error(errno.EAGAIN, 'timed out') chunk_sent = base_socket.send(data) sent += chunk_sent # This has some needless copying here, but I'm not sure there's # much value in optimising this data path. data = data[chunk_sent:] except (socket.error) as e: error = e.errno if error is not None and error != errno.EAGAIN: data_length_pointer[0] = sent if error == errno.ECONNRESET or error == errno.EPIPE: return SecurityConst.errSSLClosedAbort raise data_length_pointer[0] = sent if sent != bytes_to_write: return SecurityConst.errSSLWouldBlock return 0 except Exception as e: if wrapped_socket is not None: wrapped_socket._exception = e return SecurityConst.errSSLInternal # We need to keep these two objects references alive: if they get GC'd while # in use then SecureTransport could attempt to call a function that is in freed # memory. That would be...uh...bad. Yeah, that's the word. Bad. _read_callback_pointer = Security.SSLReadFunc(_read_callback) _write_callback_pointer = Security.SSLWriteFunc(_write_callback) class WrappedSocket(object): """ API-compatibility wrapper for Python's OpenSSL wrapped socket object. Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage collector of PyPy. """ def __init__(self, socket): self.socket = socket self.context = None self._makefile_refs = 0 self._closed = False self._exception = None self._keychain = None self._keychain_dir = None self._client_cert_chain = None # We save off the previously-configured timeout and then set it to # zero. This is done because we use select and friends to handle the # timeouts, but if we leave the timeout set on the lower socket then # Python will "kindly" call select on that socket again for us. Avoid # that by forcing the timeout to zero. self._timeout = self.socket.gettimeout() self.socket.settimeout(0) @contextlib.contextmanager def _raise_on_error(self): """ A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. """ self._exception = None # We explicitly don't catch around this yield because in the unlikely # event that an exception was hit in the block we don't want to swallow # it. yield if self._exception is not None: exception, self._exception = self._exception, None self.close() raise exception def _set_ciphers(self): """ Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. """ ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers( self.context, ciphers, len(CIPHER_SUITES) ) _assert_no_error(result) def _custom_validate(self, verify, trust_bundle): """ Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. """ # If we disabled cert validation, just say: cool. if not verify: return # We want data in memory, so load it up. if os.path.isfile(trust_bundle): with open(trust_bundle, 'rb') as f: trust_bundle = f.read() cert_array = None trust = Security.SecTrustRef() try: # Get a CFArray that contains the certs we want. cert_array = _cert_array_from_pem(trust_bundle) # Ok, now the hard part. We want to get the SecTrustRef that ST has # created for this connection, shove our CAs into it, tell ST to # ignore everything else it knows, and then ask if it can build a # chain. This is a buuuunch of code. result = Security.SSLCopyPeerTrust( self.context, ctypes.byref(trust) ) _assert_no_error(result) if not trust: raise ssl.SSLError("Failed to copy trust reference") result = Security.SecTrustSetAnchorCertificates(trust, cert_array) _assert_no_error(result) result = Security.SecTrustSetAnchorCertificatesOnly(trust, True) _assert_no_error(result) trust_result = Security.SecTrustResultType() result = Security.SecTrustEvaluate( trust, ctypes.byref(trust_result) ) _assert_no_error(result) finally: if trust: CoreFoundation.CFRelease(trust) if cert_array is not None: CoreFoundation.CFRelease(cert_array) # Ok, now we can look at what the result was. successes = ( SecurityConst.kSecTrustResultUnspecified, SecurityConst.kSecTrustResultProceed ) if trust_result.value not in successes: raise ssl.SSLError( "certificate verify failed, error code: %d" % trust_result.value ) def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase): """ Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn't be needed in user code. """ # First, we do the initial bits of connection setup. We need to create # a context, set its I/O funcs, and set the connection reference. self.context = Security.SSLCreateContext( None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType ) result = Security.SSLSetIOFuncs( self.context, _read_callback_pointer, _write_callback_pointer ) _assert_no_error(result) # Here we need to compute the handle to use. We do this by taking the # id of self modulo 2**31 - 1. If this is already in the dictionary, we # just keep incrementing by one until we find a free space. with _connection_ref_lock: handle = id(self) % 2147483647 while handle in _connection_refs: handle = (handle + 1) % 2147483647 _connection_refs[handle] = self result = Security.SSLSetConnection(self.context, handle) _assert_no_error(result) # If we have a server hostname, we should set that too. if server_hostname: if not isinstance(server_hostname, bytes): server_hostname = server_hostname.encode('utf-8') result = Security.SSLSetPeerDomainName( self.context, server_hostname, len(server_hostname) ) _assert_no_error(result) # Setup the ciphers. self._set_ciphers() # Set the minimum and maximum TLS versions. result = Security.SSLSetProtocolVersionMin(self.context, min_version) _assert_no_error(result) result = Security.SSLSetProtocolVersionMax(self.context, max_version) _assert_no_error(result) # If there's a trust DB, we need to use it. We do that by telling # SecureTransport to break on server auth. We also do that if we don't # want to validate the certs at all: we just won't actually do any # authing in that case. if not verify or trust_bundle is not None: result = Security.SSLSetSessionOption( self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True ) _assert_no_error(result) # If there's a client cert, we need to use it. if client_cert: self._keychain, self._keychain_dir = _temporary_keychain() self._client_cert_chain = _load_client_cert_chain( self._keychain, client_cert, client_key ) result = Security.SSLSetCertificate( self.context, self._client_cert_chain ) _assert_no_error(result) while True: with self._raise_on_error(): result = Security.SSLHandshake(self.context) if result == SecurityConst.errSSLWouldBlock: raise socket.timeout("handshake timed out") elif result == SecurityConst.errSSLServerAuthCompleted: self._custom_validate(verify, trust_bundle) continue else: _assert_no_error(result) break def fileno(self): return self.socket.fileno() # Copy-pasted from Python 3.5 source code def _decref_socketios(self): if self._makefile_refs > 0: self._makefile_refs -= 1 if self._closed: self.close() def recv(self, bufsiz): buffer = ctypes.create_string_buffer(bufsiz) bytes_read = self.recv_into(buffer, bufsiz) data = buffer[:bytes_read] return data def recv_into(self, buffer, nbytes=None): # Read short on EOF. if self._closed: return 0 if nbytes is None: nbytes = len(buffer) buffer = (ctypes.c_char * nbytes).from_buffer(buffer) processed_bytes = ctypes.c_size_t(0) with self._raise_on_error(): result = Security.SSLRead( self.context, buffer, nbytes, ctypes.byref(processed_bytes) ) # There are some result codes that we want to treat as "not always # errors". Specifically, those are errSSLWouldBlock, # errSSLClosedGraceful, and errSSLClosedNoNotify. if (result == SecurityConst.errSSLWouldBlock): # If we didn't process any bytes, then this was just a time out. # However, we can get errSSLWouldBlock in situations when we *did* # read some data, and in those cases we should just read "short" # and return. if processed_bytes.value == 0: # Timed out, no data read. raise socket.timeout("recv timed out") elif result in (SecurityConst.errSSLClosedGraceful, SecurityConst.errSSLClosedNoNotify): # The remote peer has closed this connection. We should do so as # well. Note that we don't actually return here because in # principle this could actually be fired along with return data. # It's unlikely though. self.close() else: _assert_no_error(result) # Ok, we read and probably succeeded. We should return whatever data # was actually read. return processed_bytes.value def settimeout(self, timeout): self._timeout = timeout def gettimeout(self): return self._timeout def send(self, data): processed_bytes = ctypes.c_size_t(0) with self._raise_on_error(): result = Security.SSLWrite( self.context, data, len(data), ctypes.byref(processed_bytes) ) if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0: # Timed out raise socket.timeout("send timed out") else: _assert_no_error(result) # We sent, and probably succeeded. Tell them how much we sent. return processed_bytes.value def sendall(self, data): total_sent = 0 while total_sent < len(data): sent = self.send(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE]) total_sent += sent def shutdown(self): with self._raise_on_error(): Security.SSLClose(self.context) def close(self): # TODO: should I do clean shutdown here? Do I have to? if self._makefile_refs < 1: self._closed = True if self.context: CoreFoundation.CFRelease(self.context) self.context = None if self._client_cert_chain: CoreFoundation.CFRelease(self._client_cert_chain) self._client_cert_chain = None if self._keychain: Security.SecKeychainDelete(self._keychain) CoreFoundation.CFRelease(self._keychain) shutil.rmtree(self._keychain_dir) self._keychain = self._keychain_dir = None return self.socket.close() else: self._makefile_refs -= 1 def getpeercert(self, binary_form=False): # Urgh, annoying. # # Here's how we do this: # # 1. Call SSLCopyPeerTrust to get hold of the trust object for this # connection. # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf. # 3. To get the CN, call SecCertificateCopyCommonName and process that # string so that it's of the appropriate type. # 4. To get the SAN, we need to do something a bit more complex: # a. Call SecCertificateCopyValues to get the data, requesting # kSecOIDSubjectAltName. # b. Mess about with this dictionary to try to get the SANs out. # # This is gross. Really gross. It's going to be a few hundred LoC extra # just to repeat something that SecureTransport can *already do*. So my # operating assumption at this time is that what we want to do is # instead to just flag to urllib3 that it shouldn't do its own hostname # validation when using SecureTransport. if not binary_form: raise ValueError( "SecureTransport only supports dumping binary certs" ) trust = Security.SecTrustRef() certdata = None der_bytes = None try: # Grab the trust store. result = Security.SSLCopyPeerTrust( self.context, ctypes.byref(trust) ) _assert_no_error(result) if not trust: # Probably we haven't done the handshake yet. No biggie. return None cert_count = Security.SecTrustGetCertificateCount(trust) if not cert_count: # Also a case that might happen if we haven't handshaked. # Handshook? Handshaken? return None leaf = Security.SecTrustGetCertificateAtIndex(trust, 0) assert leaf # Ok, now we want the DER bytes. certdata = Security.SecCertificateCopyData(leaf) assert certdata data_length = CoreFoundation.CFDataGetLength(certdata) data_buffer = CoreFoundation.CFDataGetBytePtr(certdata) der_bytes = ctypes.string_at(data_buffer, data_length) finally: if certdata: CoreFoundation.CFRelease(certdata) if trust: CoreFoundation.CFRelease(trust) return der_bytes def _reuse(self): self._makefile_refs += 1 def _drop(self): if self._makefile_refs < 1: self.close() else: self._makefile_refs -= 1 if _fileobject: # Platform-specific: Python 2 def makefile(self, mode, bufsize=-1): self._makefile_refs += 1 return _fileobject(self, mode, bufsize, close=True) else: # Platform-specific: Python 3 def makefile(self, mode="r", buffering=None, *args, **kwargs): # We disable buffering with SecureTransport because it conflicts with # the buffering that ST does internally (see issue #1153 for more). buffering = 0 return backport_makefile(self, mode, buffering, *args, **kwargs) WrappedSocket.makefile = makefile class SecureTransportContext(object): """ I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. """ def __init__(self, protocol): self._min_version, self._max_version = _protocol_to_min_max[protocol] self._options = 0 self._verify = False self._trust_bundle = None self._client_cert = None self._client_key = None self._client_key_passphrase = None @property def check_hostname(self): """ SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. """ return True @check_hostname.setter def check_hostname(self, value): """ SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. """ pass @property def options(self): # TODO: Well, crap. # # So this is the bit of the code that is the most likely to cause us # trouble. Essentially we need to enumerate all of the SSL options that # users might want to use and try to see if we can sensibly translate # them, or whether we should just ignore them. return self._options @options.setter def options(self, value): # TODO: Update in line with above. self._options = value @property def verify_mode(self): return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE @verify_mode.setter def verify_mode(self, value): self._verify = True if value == ssl.CERT_REQUIRED else False def set_default_verify_paths(self): # So, this has to do something a bit weird. Specifically, what it does # is nothing. # # This means that, if we had previously had load_verify_locations # called, this does not undo that. We need to do that because it turns # out that the rest of the urllib3 code will attempt to load the # default verify paths if it hasn't been told about any paths, even if # the context itself was sometime earlier. We resolve that by just # ignoring it. pass def load_default_certs(self): return self.set_default_verify_paths() def set_ciphers(self, ciphers): # For now, we just require the default cipher string. if ciphers != util.ssl_.DEFAULT_CIPHERS: raise ValueError( "SecureTransport doesn't support custom cipher strings" ) def load_verify_locations(self, cafile=None, capath=None, cadata=None): # OK, we only really support cadata and cafile. if capath is not None: raise ValueError( "SecureTransport does not support cert directories" ) self._trust_bundle = cafile or cadata def load_cert_chain(self, certfile, keyfile=None, password=None): self._client_cert = certfile self._client_key = keyfile self._client_cert_passphrase = password def wrap_socket(self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None): # So, what do we do here? Firstly, we assert some properties. This is a # stripped down shim, so there is some functionality we don't support. # See PEP 543 for the real deal. assert not server_side assert do_handshake_on_connect assert suppress_ragged_eofs # Ok, we're good to go. Now we want to create the wrapped socket object # and store it in the appropriate place. wrapped_socket = WrappedSocket(sock) # Now we can handshake wrapped_socket.handshake( server_hostname, self._verify, self._trust_bundle, self._min_version, self._max_version, self._client_cert, self._client_key, self._client_key_passphrase ) return wrapped_socket PK!s{GEGE0__pycache__/securetransport.cpython-36.opt-1.pycnu[3 nf\ev)@sdZddlmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlmZmZmZddlmZmZmZmZydd l mZWn$ek rdZdd lmZYnXd d gZd ZejZejj Z!e j"Z#e j$Z%dZ&ej'ej(ej)ej*ej+ej,ej-ej.ej/ej0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:ej;ejej?ej@ejAejBejCejDejEejFejGg!ZHe jIejJejKfiZLeMe drejNejNfeLe jO<eMe drejPejPfeLe jQ<eMe drejJejJfeLe jR<eMe drejSejSfeLe jT<eMe dr$ejKejKfeLe jU<eMe dr@eLe jIeLe jV<dd ZWdd ZXddZYddZZej[eYZ\ej]eZZ^Gddde_Z`erd$ddZan d%d dZaeae`_aGd!d"d"e_ZbdS)&aU SecureTranport support for urllib3 via ctypes. This makes platform-native TLS available to urllib3 users on macOS without the use of a compiler. This is an important feature because the Python Package Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL that ships with macOS is not capable of doing TLSv1.2. The only way to resolve this is to give macOS users an alternative solution to the problem, and that solution is to use SecureTransport. We use ctypes here because this solution must not require a compiler. That's because pip is not allowed to require a compiler either. This is not intended to be a seriously long-term solution to this problem. The hope is that PEP 543 will eventually solve this issue for us, at which point we can retire this contrib module. But in the short term, we need to solve the impending tire fire that is Python on Mac without this kind of contrib module. So...here we are. To use this module, simply import and inject it:: import urllib3.contrib.securetransport urllib3.contrib.securetransport.inject_into_urllib3() Happy TLSing! )absolute_importN)util)Security SecurityConstCoreFoundation)_assert_no_error_cert_array_from_pem_temporary_keychain_load_client_cert_chain) _fileobject)backport_makefileinject_into_urllib3extract_from_urllib3Ti@PROTOCOL_SSLv2PROTOCOL_SSLv3PROTOCOL_TLSv1PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2 PROTOCOL_TLScCs(ttj_tt_ttj_dt_dtj_dS)zG Monkey-patch urllib3 with SecureTransport-backed SSL-support. TN)SecureTransportContextrssl_ SSLContextHAS_SNIIS_SECURETRANSPORTrr%/usr/lib/python3.6/securetransport.pyrs cCs(ttj_tt_ttj_dt_dtj_dS)z> Undo monkey-patching by :func:`inject_into_urllib3`. FN)orig_util_SSLContextrrrorig_util_HAS_SNIrrrrrrrs c Csxd}y8tj|}|dkr tjS|j}|d}|j}d}d}y|xv||kr|dksZ|dkrttj||sttjt j d||} t j | j ||} |j| | } || 7}| sB|stjSPqBWWnhtjk r"} zH| j }|dk o|t j kr||d<|t jks |t jkrtjSWYdd} ~ XnX||d<||krrrrsendallCszWrappedSocket.sendallc Cs$|jtj|jWdQRXdS)N)rLrZSSLCloserA)rIrrrshutdownIs zWrappedSocket.shutdowncCs|jdkrd|_|jr(tj|jd|_|jr@tj|jd|_|jrvtj|jtj|jt j |j d|_|_ |j j S|jd8_dS)NrT)rBrCrArr\rFrDrZSecKeychainDeleteshutilZrmtreerEr#rK)rIrrrrKMs        zWrappedSocket.closeFc Cs|s tdtj}d}d}zptj|jtj|}t||sBdStj|}|sTdStj |d}tj |}t j |}t j |} tj| |}Wd|rt j||rt j|X|S)Nz2SecureTransport only supports dumping binary certsr) ValueErrorrrXrYrAr(rZr ZSecTrustGetCertificateCountZSecTrustGetCertificateAtIndexZSecCertificateCopyDatarZCFDataGetLengthZCFDataGetBytePtrr;r\) rIZ binary_formraZcertdataZ der_bytesrPZ cert_countZleafZ data_lengthr3rrr getpeercert`s2       zWrappedSocket.getpeercertcCs|jd7_dS)Nr)rB)rIrrr_reuseszWrappedSocket._reusecCs&|jdkr|jn|jd8_dS)Nr)rBrK)rIrrr_drops  zWrappedSocket._drop)N)F)__name__ __module__ __qualname____doc__rJ contextlibcontextmanagerrLrQrbrkrlrmrnr*rHr$r<rsrtrKrwrxryrrrrr@!s& >Z ( >r@cCs|jd7_t|||ddS)NrT)rK)rBr )rImodebufsizerrrmakefilesrrcOsd}t|||f||S)Nr)r)rIr bufferingargskwargsrrrrsc@seZdZdZddZeddZejddZeddZejd dZed d Z e jd d Z d dZ ddZ ddZ dddZ dddZdddZdS)rz I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. cCs8t|\|_|_d|_d|_d|_d|_d|_d|_dS)NrF) _protocol_to_min_max _min_version _max_version_options_verify _trust_bundle _client_cert _client_key_client_key_passphrase)rIZprotocolrrrrJszSecureTransportContext.__init__cCsdS)z SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. Tr)rIrrrcheck_hostnamesz%SecureTransportContext.check_hostnamecCsdS)z SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. Nr)rIr]rrrrscCs|jS)N)r)rIrrroptionsszSecureTransportContext.optionscCs ||_dS)N)r)rIr]rrrrscCs|jr tjStjS)N)rr[ CERT_REQUIREDZ CERT_NONE)rIrrr verify_modesz"SecureTransportContext.verify_modecCs|tjkrdnd|_dS)NTF)r[rr)rIr]rrrrscCsdS)Nr)rIrrrset_default_verify_pathss z/SecureTransportContext.set_default_verify_pathscCs|jS)N)r)rIrrrload_default_certssz)SecureTransportContext.load_default_certscCs|tjjkrtddS)Nz5SecureTransport doesn't support custom cipher strings)rrZDEFAULT_CIPHERSrv)rIrOrrr set_cipherss z"SecureTransportContext.set_ciphersNcCs|dk rtd|p||_dS)Nz1SecureTransport does not support cert directories)rvr)rIZcafileZcapathZcadatarrrload_verify_locationssz,SecureTransportContext.load_verify_locationscCs||_||_||_dS)N)rrZ_client_cert_passphrase)rIZcertfileZkeyfileZpasswordrrrload_cert_chain sz&SecureTransportContext.load_cert_chainFTc Cs2t|}|j||j|j|j|j|j|j|j|S)N) r@rkrrrrrrr)rIZsockZ server_sideZdo_handshake_on_connectZsuppress_ragged_eofsrjr5rrr wrap_sockets    z"SecureTransportContext.wrap_socket)NNN)NN)FTTN)rzr{r|r}rJpropertyrsetterrrrrrrrrrrrrrs      r)r)rN)cr}Z __future__rr~r(r&Zos.pathrSrur#r[Z threadingweakrefrZ_securetransport.bindingsrrrZ_securetransport.low_levelr r r r r ImportErrorZpackages.backports.makefiler__all__rrrrrWeakValueDictionaryr ZLockrerrZTLS_AES_256_GCM_SHA384ZTLS_CHACHA20_POLY1305_SHA256ZTLS_AES_128_GCM_SHA256Z'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384Z%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384Z'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256Z%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256Z#TLS_DHE_DSS_WITH_AES_256_GCM_SHA384Z#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384Z#TLS_DHE_DSS_WITH_AES_128_GCM_SHA256Z#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256Z'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384Z%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384Z$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAZ"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256Z#TLS_DHE_DSS_WITH_AES_256_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_256_CBC_SHAZ TLS_DHE_DSS_WITH_AES_256_CBC_SHAZ'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256Z%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256Z$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAZ"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256Z#TLS_DHE_DSS_WITH_AES_128_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_128_CBC_SHAZ TLS_DHE_DSS_WITH_AES_128_CBC_SHAZTLS_RSA_WITH_AES_256_GCM_SHA384ZTLS_RSA_WITH_AES_128_GCM_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHA256ZTLS_RSA_WITH_AES_128_CBC_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHAZTLS_RSA_WITH_AES_128_CBC_SHArNZPROTOCOL_SSLv23Z kTLSProtocol1ZkTLSProtocol12rhasattrZ kSSLProtocol2rZ kSSLProtocol3rrZkTLSProtocol11rrrrrr:r?Z SSLReadFuncrcZ SSLWriteFuncrdobjectr@rrrrrrs          76     PK!s     PK!y23__pycache__/_appengine_environ.cpython-36.opt-1.pycnu[3 nf\@s8dZddlZddZddZddZd d Zd d ZdS) zB This module provides means to detect the App Engine environment. NcCstptptS)N)is_local_appengineis_prod_appengineis_prod_appengine_mvmsrr(/usr/lib/python3.6/_appengine_environ.py is_appenginesrcCsto t S)N)rrrrrris_appengine_sandboxsrcCsdtjkodtjdkS)NAPPENGINE_RUNTIMEz Development/SERVER_SOFTWARE)osenvironrrrrrs rcCs dtjkodtjdkot S)Nr zGoogle App Engine/r )r r rrrrrrs rcCstjjdddkS)NZGAE_VMFtrue)r r getrrrrrsr)__doc__r rrrrrrrrrs PK!y2-__pycache__/_appengine_environ.cpython-36.pycnu[3 nf\@s8dZddlZddZddZddZd d Zd d ZdS) zB This module provides means to detect the App Engine environment. NcCstptptS)N)is_local_appengineis_prod_appengineis_prod_appengine_mvmsrr(/usr/lib/python3.6/_appengine_environ.py is_appenginesrcCsto t S)N)rrrrrris_appengine_sandboxsrcCsdtjkodtjdkS)NAPPENGINE_RUNTIMEz Development/SERVER_SOFTWARE)osenvironrrrrrs rcCs dtjkodtjdkot S)Nr zGoogle App Engine/r )r r rrrrrrs rcCstjjdddkS)NZGAE_VMFtrue)r r getrrrrrsr)__doc__r rrrrrrrrrs PK!aX __pycache__/socks.cpython-36.pycnu[3 nf\@s(dZddlmZy ddlZWn6ek rRddlZddlmZejdeYnXddl m Z m Z ddlmZmZdd lmZmZdd lmZmZdd lmZdd lmZy ddlZWnek rdZYnXGd ddeZGdddeeZGdddeZGdddeZGdddeZdS)a This module contains provisional support for SOCKS proxies from within urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and SOCKS5. To enable its functionality, either install PySocks or install this module with the ``socks`` extra. The SOCKS implementation supports the full range of urllib3 features. It also supports the following SOCKS features: - SOCKS4 - SOCKS4a - SOCKS5 - Usernames and passwords for the SOCKS proxy Known Limitations: - Currently PySocks does not support contacting remote websites via literal IPv6 addresses. Any such connection attempt will fail. You must use a domain name. - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any such connection attempt will fail. )absolute_importN)DependencyWarningzSOCKS support in urllib3 requires the installation of optional dependencies: specifically, PySocks. For more information, see https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies)errortimeout)HTTPConnectionHTTPSConnection)HTTPConnectionPoolHTTPSConnectionPool)ConnectTimeoutErrorNewConnectionError) PoolManager) parse_urlcs(eZdZdZfddZddZZS)SOCKSConnectionzG A plain-text HTTP connection that connects via a SOCKS proxy. cs"|jd|_tt|j||dS)N_socks_options)poprsuperr__init__)selfargskwargs) __class__/usr/lib/python3.6/socks.pyr?s zSOCKSConnection.__init__cCsXi}|jr|j|d<|jr$|j|d<yTtj|j|jff|jd|jd|jd|jd|jd|jd|jd |}Wntk r}zt |d |j|jfWYd d }~Xntj k r"}zT|j r|j }t |trt |d |j|jfnt |d |nt |d |WYd d }~Xn2tk rR}zt |d |WYd d }~XnX|S) zA Establish a new connection via the SOCKS proxy. source_addresssocket_options socks_version proxy_host proxy_portusernamepasswordrdns)Z proxy_typeZ proxy_addrrZproxy_usernameZproxy_passwordZ proxy_rdnsrz0Connection to %s timed out. (connect timeout=%s)Nz(Failed to establish a new connection: %s)rrsocksZcreate_connectionhostportrr SocketTimeoutr Z ProxyErrorZ socket_err isinstancer SocketError)rZextra_kwZconnerrrr _new_connCsL       zSOCKSConnection._new_conn)__name__ __module__ __qualname____doc__rr) __classcell__rr)rrr;s rc@s eZdZdS)SOCKSHTTPSConnectionN)r*r+r,rrrrr/sr/c@seZdZeZdS)SOCKSHTTPConnectionPoolN)r*r+r,r ConnectionClsrrrrr0sr0c@seZdZeZdS)SOCKSHTTPSConnectionPoolN)r*r+r,r/r1rrrrr2sr2cs,eZdZdZeedZdfdd ZZS)SOCKSProxyManagerzh A version of the urllib3 ProxyManager that routes connections via the defined SOCKS proxy. )ZhttpZhttpsN c  st|}|dkrB|dkrB|jdk rB|jjd}t|dkrB|\}}|jdkrXtj} d} nN|jdkrntj} d} n8|jdkrtj} d} n"|jdkrtj} d} n td |||_ | |j |j ||| d } | |d <t t |j||f|t j|_dS) N:rZsocks5FZsocks5hTZsocks4Zsocks4az)Unable to determine SOCKS version from %s)rrrrr r!r)rZauthsplitlenschemer"ZPROXY_TYPE_SOCKS5ZPROXY_TYPE_SOCKS4 ValueError proxy_urlr#r$rr3rpool_classes_by_scheme) rr:rr Z num_poolsZheadersZconnection_pool_kwZparsedr6rr!Z socks_options)rrrrs<         zSOCKSProxyManager.__init__)NNr4N) r*r+r,r-r0r2r;rr.rr)rrr3s r3) r-Z __future__rr" ImportErrorwarnings exceptionsrwarnZsocketrr'rr%Z connectionrrZconnectionpoolr r r r Z poolmanagerr Zutil.urlrZsslrr/r0r2r3rrrrs2       FPK!I *__pycache__/appengine.cpython-36.opt-1.pycnu[3 nf\* @sdZddlmZddlZddlZddlZddlmZddlm Z m Z m Z m Z m Z mZddlmZddlmZdd lmZdd lmZd d lmZydd lmZWnek rdZYnXejeZGddde ZGddde Z GdddeZ!ej"Z"ej#Z#ej$Z$ej%Z%ej&Z&dS)aC This module provides a pool manager that uses Google App Engine's `URLFetch Service `_. Example usage:: from urllib3 import PoolManager from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox if is_appengine_sandbox(): # AppEngineManager uses AppEngine's URLFetch API behind the scenes http = AppEngineManager() else: # PoolManager uses a socket-level API behind the scenes http = PoolManager() r = http.request('GET', 'https://google.com/') There are `limitations `_ to the URLFetch service and it may not be the best choice for your application. There are three options for using urllib3 on Google App Engine: 1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is cost-effective in many circumstances as long as your usage is within the limitations. 2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets. Sockets also have `limitations and restrictions `_ and have a lower free quota than URLFetch. To use sockets, be sure to specify the following in your ``app.yaml``:: env_variables: GAE_USE_SOCKETS_HTTPLIB : 'true' 3. If you are using `App Engine Flexible `_, you can use the standard :class:`PoolManager` without any configuration or special environment variables. )absolute_importN)urljoin) HTTPError HTTPWarning MaxRetryError ProtocolError TimeoutErrorSSLError)RequestMethods) HTTPResponse)Timeout)Retry)_appengine_environ)urlfetchc@s eZdZdS)AppEnginePlatformWarningN)__name__ __module__ __qualname__rr/usr/lib/python3.6/appengine.pyrGsrc@s eZdZdS)AppEnginePlatformErrorN)rrrrrrrrKsrc@sXeZdZdZdddZddZdd Zddddejfd d Z d d Z ddZ ddZ dS)AppEngineManagera  Connection manager for Google App Engine sandbox applications. This manager uses the URLFetch service directly instead of using the emulated httplib, and is subject to URLFetch limitations as described in the App Engine documentation `here `_. Notably it will raise an :class:`AppEnginePlatformError` if: * URLFetch is not available. * If you attempt to use this on App Engine Flexible, as full socket support is available. * If a request size is more than 10 megabytes. * If a response size is more than 32 megabtyes. * If you use an unsupported request method such as OPTIONS. Beyond those cases, it will raise normal urllib3 errors. NTcCsNts tdtrtdtjdttj||||_||_ |pFt j |_ dS)Nz.URLFetch is not available in this environment.zUse normal urllib3.PoolManager instead of AppEngineManageron Managed VMs, as using URLFetch is not necessary in this environment.zurllib3 is using URLFetch on Google App Engine sandbox instead of sockets. To use sockets directly instead of URLFetch see https://urllib3.readthedocs.io/en/latest/reference/urllib3.contrib.html.) rris_prod_appengine_mvmswarningswarnrr __init__validate_certificateurlfetch_retriesrZDEFAULTretries)selfheadersr rrrrrrcs zAppEngineManager.__init__cCs|S)Nr)r!rrr __enter__{szAppEngineManager.__enter__cCsdS)NFr)r!exc_typeZexc_valZexc_tbrrr__exit__~szAppEngineManager.__exit__cKs|j||}yF|o |jdko |j} tj||||p2id|jo<| |j||jd} WnBtjk r} zt || WYdd} ~ Xntj k r} z$dt | krt d| t | WYdd} ~ Xntjk r} z(dt | krt||| dt | WYdd} ~ Xntjk r6} zt d| WYdd} ~ Xn`tjk rb} zt| WYdd} ~ Xn4tjk r} zt d || WYdd} ~ XnX|j| fd |i|} |o| j} | rr|jr|jrt||d n| jd krd }y|j||| |d}Wn*tk r.|jr*t||d | SX|j| tjd|| t|| }|j||||f|||d|St| jd}|j || j|r|j||| |d}tjd||j!| |j||f|||||d|S| S)NrF)Zpayloadmethodr"Zallow_truncatedfollow_redirectsZdeadlinerz too largezOURLFetch request too large, URLFetch only supports requests up to 10mb in size.zToo many redirects)reasonzPURLFetch response too large, URLFetch only supportsresponses up to 32mb in size.z$URLFetch does not support method: %sr ztoo many redirectsi/ZGET)responseZ_poolzRedirecting %s -> %s)r redirecttimeoutz Retry-Afterz Retry: %s)bodyr"r r*r+)" _get_retriesr*totalrZfetchr_get_absolute_timeoutrZDeadlineExceededErrorr ZInvalidURLErrorstrrrZ DownloadErrorrZResponseTooLargeErrorZSSLCertificateErrorr ZInvalidMethodError#_urlfetch_response_to_http_responseZget_redirect_locationZraise_on_redirectstatusZ incrementZsleep_for_retrylogdebugrurlopenboolZ getheaderZis_retryZsleep)r!r&Zurlr,r"r r*r+ response_kwr'r)eZ http_responseZredirect_locationZ redirect_urlZhas_retry_afterrrrr5s           zAppEngineManager.urlopencKstr"|jjd}|dkr"|jd=|jjd}|dkrZ|jd}|jddj||jd<tftj|j |j |j|j d|}tftj|j |j|j |d|S)Nzcontent-encodingZdeflateztransfer-encodingZchunked,)r,msgr"r2)r,r"r2original_response) is_prod_appenginer"getsplitremovejoinr ioBytesIOZcontentZ header_msgZ status_code)r!Z urlfetch_respr7Zcontent_encodingZtransfer_encodingZ encodingsr;rrrr1s*      z4AppEngineManager._urlfetch_response_to_http_responsecCsB|tjkrdSt|tr>|jdk s,|jdk r8tjdt|jS|S)NzdURLFetch does not support granular timeout settings, reverting to total or default URLFetch timeout.) r DEFAULT_TIMEOUT isinstanceZ_readZ_connectrrrr.)r!r+rrrr/s  z&AppEngineManager._get_absolute_timeoutcCs>t|tstj|||jd}|js.|js.|jr:tjdt |S)N)r*defaultzhURLFetch only supports total retries and does not recognize connect, read, or redirect retry parameters.) rDrZfrom_intr Zconnectreadr*rrr)r!r r*rrrr- s zAppEngineManager._get_retries)NNTT) rrr__doc__rr#r%r rCr5r1r/r-rrrrrOs Z$ r)'rGZ __future__rrAZloggingrZpackages.six.moves.urllib.parser exceptionsrrrrr r Zrequestr r)r Z util.timeoutr Z util.retryrrZgoogle.appengine.apir ImportErrorZ getLoggerrr3rrrZ is_appengineZis_appengine_sandboxZis_local_appenginer<rrrrr's2         OPK!aX&__pycache__/socks.cpython-36.opt-1.pycnu[3 nf\@s(dZddlmZy ddlZWn6ek rRddlZddlmZejdeYnXddl m Z m Z ddlmZmZdd lmZmZdd lmZmZdd lmZdd lmZy ddlZWnek rdZYnXGd ddeZGdddeeZGdddeZGdddeZGdddeZdS)a This module contains provisional support for SOCKS proxies from within urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and SOCKS5. To enable its functionality, either install PySocks or install this module with the ``socks`` extra. The SOCKS implementation supports the full range of urllib3 features. It also supports the following SOCKS features: - SOCKS4 - SOCKS4a - SOCKS5 - Usernames and passwords for the SOCKS proxy Known Limitations: - Currently PySocks does not support contacting remote websites via literal IPv6 addresses. Any such connection attempt will fail. You must use a domain name. - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any such connection attempt will fail. )absolute_importN)DependencyWarningzSOCKS support in urllib3 requires the installation of optional dependencies: specifically, PySocks. For more information, see https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies)errortimeout)HTTPConnectionHTTPSConnection)HTTPConnectionPoolHTTPSConnectionPool)ConnectTimeoutErrorNewConnectionError) PoolManager) parse_urlcs(eZdZdZfddZddZZS)SOCKSConnectionzG A plain-text HTTP connection that connects via a SOCKS proxy. cs"|jd|_tt|j||dS)N_socks_options)poprsuperr__init__)selfargskwargs) __class__/usr/lib/python3.6/socks.pyr?s zSOCKSConnection.__init__cCsXi}|jr|j|d<|jr$|j|d<yTtj|j|jff|jd|jd|jd|jd|jd|jd|jd |}Wntk r}zt |d |j|jfWYd d }~Xntj k r"}zT|j r|j }t |trt |d |j|jfnt |d |nt |d |WYd d }~Xn2tk rR}zt |d |WYd d }~XnX|S) zA Establish a new connection via the SOCKS proxy. source_addresssocket_options socks_version proxy_host proxy_portusernamepasswordrdns)Z proxy_typeZ proxy_addrrZproxy_usernameZproxy_passwordZ proxy_rdnsrz0Connection to %s timed out. (connect timeout=%s)Nz(Failed to establish a new connection: %s)rrsocksZcreate_connectionhostportrr SocketTimeoutr Z ProxyErrorZ socket_err isinstancer SocketError)rZextra_kwZconnerrrr _new_connCsL       zSOCKSConnection._new_conn)__name__ __module__ __qualname____doc__rr) __classcell__rr)rrr;s rc@s eZdZdS)SOCKSHTTPSConnectionN)r*r+r,rrrrr/sr/c@seZdZeZdS)SOCKSHTTPConnectionPoolN)r*r+r,r ConnectionClsrrrrr0sr0c@seZdZeZdS)SOCKSHTTPSConnectionPoolN)r*r+r,r/r1rrrrr2sr2cs,eZdZdZeedZdfdd ZZS)SOCKSProxyManagerzh A version of the urllib3 ProxyManager that routes connections via the defined SOCKS proxy. )ZhttpZhttpsN c  st|}|dkrB|dkrB|jdk rB|jjd}t|dkrB|\}}|jdkrXtj} d} nN|jdkrntj} d} n8|jdkrtj} d} n"|jdkrtj} d} n td |||_ | |j |j ||| d } | |d <t t |j||f|t j|_dS) N:rZsocks5FZsocks5hTZsocks4Zsocks4az)Unable to determine SOCKS version from %s)rrrrr r!r)rZauthsplitlenschemer"ZPROXY_TYPE_SOCKS5ZPROXY_TYPE_SOCKS4 ValueError proxy_urlr#r$rr3rpool_classes_by_scheme) rr:rr Z num_poolsZheadersZconnection_pool_kwZparsedr6rr!Z socks_options)rrrrs<         zSOCKSProxyManager.__init__)NNr4N) r*r+r,r-r0r2r;rr.rr)rrr3s r3) r-Z __future__rr" ImportErrorwarnings exceptionsrwarnZsocketrr'rr%Z connectionrrZconnectionpoolr r r r Z poolmanagerr Zutil.urlrZsslrr/r0r2r3rrrrs2       FPK!/ug8g8*__pycache__/pyopenssl.cpython-36.opt-1.pycnu[3 nf\=@sddZddlmZddlZddlmZddlmZ ddl m Z yddl m Z Wn$ek rpGdd d eZ YnXdd lmZmZdd lmZydd lmZWn$ek rdZd dlmZYnXddlZddlZd dlmZddlZd dlmZddgZ dZ!ej"ej#j$ej%ej#j&iZ'e(edr@e(ej#dr@ej#j)e'ej*<e(edrhe(ej#drhej#j+e'ej,<ye'j-ej.ej#j/iWne0k rYnXej1ej#j2ej3ej#j4ej5ej#j4ej#j6iZ7e8dde7j9DZ:dZ;ej!ZZ?ej@eAZBddZCddZDddZEdd ZFd!d"ZGGd#d$d$eHZIer>d-d&d'ZJneZJeJeI_JGd(d)d)eHZKd*d+ZLdS).ab SSL with SNI_-support for Python 2. Follow these instructions if you would like to verify SSL certificates in Python 2. Note, the default libraries do *not* do certificate checking; you need to do additional work to validate certificates yourself. This needs the following packages installed: * pyOpenSSL (tested with 16.0.0) * cryptography (minimum 1.3.4, from pyopenssl) * idna (minimum 2.0, from cryptography) However, pyopenssl depends on cryptography, which depends on idna, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. Activating this module also has the positive side effect of disabling SSL/TLS compression in Python 2 (see `CRIME attack`_). If you want to configure the default list of supported cipher suites, you can set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit) )absolute_importN)x509)backend) _Certificate)UnsupportedExtensionc@s eZdZdS)rN)__name__ __module__ __qualname__r r /usr/lib/python3.6/pyopenssl.pyr6sr)timeouterror)BytesIO) _fileobject)backport_makefile)six)utilinject_into_urllib3extract_from_urllib3TPROTOCOL_TLSv1_1TLSv1_1_METHODPROTOCOL_TLSv1_2TLSv1_2_METHODccs|]\}}||fVqdS)Nr ).0kvr r r fsri@cCs.tttj_tt_ttj_dt_dtj_dS)z7Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.TN)_validate_dependencies_metPyOpenSSLContextrssl_ SSLContextHAS_SNI IS_PYOPENSSLr r r r rss cCs(ttj_tt_ttj_dt_dtj_dS)z4Undo monkey-patching by :func:`inject_into_urllib3`.FN)orig_util_SSLContextrr r!orig_util_HAS_SNIr"r#r r r r rs cCsRddlm}t|dddkr$tdddlm}|}t|dddkrNtddS) z{ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. r) Extensionsget_extension_for_classNzX'cryptography' module missing required functionality. Try upgrading to v1.3.4 or newer.)X509_x509zS'pyOpenSSL' module missing required functionality. Try upgrading to v0.14 or newer.)Zcryptography.x509.extensionsr&getattr ImportErrorZOpenSSL.cryptor()r&r(rr r r rs  rcCs@dd}d|kr|S||}|dkr(dStjdkr<|jd}|S) a% Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. c Sslddl}yFx:dD]2}|j|r|t|d}|jd|j|SqW|j|S|jjk rfdSXdS)z Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. rN*..ascii)r,r-)idna startswithlenencodeZcoreZ IDNAError)namer/prefixr r r idna_encodes   z'_dnsname_to_stdlib..idna_encode:Nrzutf-8)r7r)sys version_infodecode)r3r5r r r _dnsname_to_stdlibs   r;cCst|dr|j}n tt|j}y|jjtjj }WnLtj k rJgStj t tj tfk r}ztjd|gSd}~XnXddtt|jtjD}|jdd|jtjD|S)zU Given an PyOpenSSL certificate, provides all the subject alternative names. to_cryptographyzA problem was encountered with the certificate that prevented urllib3 from finding the SubjectAlternativeName field. This can affect certificate validation. The error was %sNcSsg|]}|dk rd|fqS)NZDNSr )rr3r r r sz%get_subj_alt_name..css|]}dt|fVqdS)z IP AddressN)str)rr3r r r rsz$get_subj_alt_name..)hasattrr<ropenssl_backendr) extensionsr'rZSubjectAlternativeNamevalueZExtensionNotFoundZDuplicateExtensionrZUnsupportedGeneralNameType UnicodeErrorlogZwarningmapr;Zget_values_for_typeZDNSNameextendZ IPAddress)Z peer_certZcertZextenamesr r r get_subj_alt_names&    rIc@s|eZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ d ddZddZddZdS)! WrappedSocketzAPI-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. TcCs"||_||_||_d|_d|_dS)NrF) connectionsocketsuppress_ragged_eofs_makefile_refs_closed)selfrKrLrMr r r __init__s zWrappedSocket.__init__cCs |jjS)N)rLfileno)rPr r r rRszWrappedSocket.filenocCs*|jdkr|jd8_|jr&|jdS)Nr)rNrOclose)rPr r r _decref_socketios s zWrappedSocket._decref_socketioscOsy|jj||}Wntjjk rX}z&|jr<|jdkrZeroReturnError get_shutdownRECEIVED_SHUTDOWN WantReadErrorr wait_for_readrL gettimeoutr )rPr]kwargsdatarGr r r rYs zWrappedSocket.recvcOsy|jj||Stjjk rT}z&|jr8|jdkr8dStt|WYdd}~Xn~tjj k r}z|jj tjj kr~dSWYdd}~XnBtjj k rt j|j|jjstdn |j||SYnXdS)NrSUnexpected EOFrzThe read operation timed outrX)rXrg)rK recv_intorZr[r\rMr]r^r>r_r`rarbrrcrLrdr )rPr]rerGr r r rh's zWrappedSocket.recv_intocCs |jj|S)N)rL settimeout)rPr r r r ri:szWrappedSocket.settimeoutcCs|xvy |jj|Stjjk rBtj|j|jjs)rPrfrGr r r _send_until_done=s zWrappedSocket._send_until_donecCs8d}x.|t|kr2|j|||t}||7}qWdS)Nr)r1rkSSL_WRITE_BLOCKSIZE)rPrfZ total_sentZsentr r r sendallHszWrappedSocket.sendallcCs|jjdS)N)rKshutdown)rPr r r rnNszWrappedSocket.shutdownc CsH|jdkr6yd|_|jjStjjk r2dSXn|jd8_dS)NrST)rNrOrKrTrZr[Error)rPr r r rTRs  zWrappedSocket.closeFcCsD|jj}|s|S|r(tjjtjj|Sd|jjffft|dS)NZ commonName)ZsubjectZsubjectAltName) rKZget_peer_certificaterZZcryptoZdump_certificateZ FILETYPE_ASN1Z get_subjectZCNrI)rPZ binary_formrr r r getpeercert\s zWrappedSocket.getpeercertcCs|jd7_dS)NrS)rN)rPr r r _reusenszWrappedSocket._reusecCs&|jdkr|jn|jd8_dS)NrS)rNrT)rPr r r _dropqs  zWrappedSocket._dropN)T)F)rrr __doc__rQrRrUrYrhrirkrmrnrTrprqrrr r r r rJs   rJrScCs|jd7_t|||ddS)NrST)rT)rNr)rPmodebufsizer r r makefileysrvc@szeZdZdZddZeddZejddZeddZejd dZd d Z d d Z dddZ dddZ dddZ dS)rz I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. cCs*t||_tjj|j|_d|_d|_dS)NrF)_openssl_versionsprotocolrZr[ZContext_ctx_optionsZcheck_hostname)rPrxr r r rQs zPyOpenSSLContext.__init__cCs|jS)N)rz)rPr r r optionsszPyOpenSSLContext.optionscCs||_|jj|dS)N)rzryZ set_options)rPrBr r r r{scCst|jjS)N)_openssl_to_stdlib_verifyryZget_verify_mode)rPr r r verify_modeszPyOpenSSLContext.verify_modecCs|jjt|tdS)N)ryZ set_verify_stdlib_to_openssl_verify_verify_callback)rPrBr r r r}scCs|jjdS)N)ryset_default_verify_paths)rPr r r rsz)PyOpenSSLContext.set_default_verify_pathscCs&t|tjr|jd}|jj|dS)Nzutf-8) isinstancer text_typer2ryZset_cipher_list)rPZciphersr r r set_cipherss  zPyOpenSSLContext.set_ciphersNcCsN|dk r|jd}|dk r$|jd}|jj|||dk rJ|jjt|dS)Nzutf-8)r2ryload_verify_locationsr)rPZcafileZcapathZcadatar r r rs  z&PyOpenSSLContext.load_verify_locationscs<|jj|dk r(|jjfdd|jj|p4|dS)NcsS)Nr )Z max_lengthZ prompt_twiceZuserdata)passwordr r sz2PyOpenSSLContext.load_cert_chain..)ryZuse_certificate_chain_fileZ set_passwd_cbZuse_privatekey_file)rPZcertfileZkeyfilerr )rr load_cert_chains z PyOpenSSLContext.load_cert_chainFTcCstjj|j|}t|tjr&|jd}|dk r8|j||j xxy |j Wndtjj k rt j ||jsztdwBYn4tjjk r}ztjd|WYdd}~XnXPqBWt||S)Nzutf-8zselect timed outzbad handshake: %r)rZr[Z Connectionryrrrr2Zset_tlsext_host_nameZset_connect_stateZ do_handshakerbrrcrdr rosslZSSLErrorrJ)rPZsockZ server_sideZdo_handshake_on_connectrMZserver_hostnamecnxrGr r r wrap_sockets"     zPyOpenSSLContext.wrap_socket)NNN)NN)FTTN)rrr rsrQpropertyr{setterr}rrrrrr r r r rs   rcCs|dkS)Nrr )rrZerr_noZ err_depthZ return_coder r r rsrrX)rX)MrsZ __future__rZ OpenSSL.SSLrZZ cryptographyrZ$cryptography.hazmat.backends.opensslrr@Z)cryptography.hazmat.backends.openssl.x509rZcryptography.x509rr+ ExceptionrLr r r^iorrZpackages.backports.makefilerZloggingrZpackagesrr8r__all__r"ZPROTOCOL_SSLv23r[Z SSLv23_METHODZPROTOCOL_TLSv1Z TLSv1_METHODrwr?rrrrupdateZPROTOCOL_SSLv3Z SSLv3_METHODAttributeErrorZ CERT_NONEZ VERIFY_NONEZ CERT_OPTIONALZ VERIFY_PEERZ CERT_REQUIREDZVERIFY_FAIL_IF_NO_PEER_CERTr~dictitemsr|rlr%r r!r$Z getLoggerrrDrrrr;rIobjectrJrvrrr r r r +sn             )4~ RPK!/ug8g8$__pycache__/pyopenssl.cpython-36.pycnu[3 nf\=@sddZddlmZddlZddlmZddlmZ ddl m Z yddl m Z Wn$ek rpGdd d eZ YnXdd lmZmZdd lmZydd lmZWn$ek rdZd dlmZYnXddlZddlZd dlmZddlZd dlmZddgZ dZ!ej"ej#j$ej%ej#j&iZ'e(edr@e(ej#dr@ej#j)e'ej*<e(edrhe(ej#drhej#j+e'ej,<ye'j-ej.ej#j/iWne0k rYnXej1ej#j2ej3ej#j4ej5ej#j4ej#j6iZ7e8dde7j9DZ:dZ;ej!ZZ?ej@eAZBddZCddZDddZEdd ZFd!d"ZGGd#d$d$eHZIer>d-d&d'ZJneZJeJeI_JGd(d)d)eHZKd*d+ZLdS).ab SSL with SNI_-support for Python 2. Follow these instructions if you would like to verify SSL certificates in Python 2. Note, the default libraries do *not* do certificate checking; you need to do additional work to validate certificates yourself. This needs the following packages installed: * pyOpenSSL (tested with 16.0.0) * cryptography (minimum 1.3.4, from pyopenssl) * idna (minimum 2.0, from cryptography) However, pyopenssl depends on cryptography, which depends on idna, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. Activating this module also has the positive side effect of disabling SSL/TLS compression in Python 2 (see `CRIME attack`_). If you want to configure the default list of supported cipher suites, you can set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit) )absolute_importN)x509)backend) _Certificate)UnsupportedExtensionc@s eZdZdS)rN)__name__ __module__ __qualname__r r /usr/lib/python3.6/pyopenssl.pyr6sr)timeouterror)BytesIO) _fileobject)backport_makefile)six)utilinject_into_urllib3extract_from_urllib3TPROTOCOL_TLSv1_1TLSv1_1_METHODPROTOCOL_TLSv1_2TLSv1_2_METHODccs|]\}}||fVqdS)Nr ).0kvr r r fsri@cCs.tttj_tt_ttj_dt_dtj_dS)z7Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.TN)_validate_dependencies_metPyOpenSSLContextrssl_ SSLContextHAS_SNI IS_PYOPENSSLr r r r rss cCs(ttj_tt_ttj_dt_dtj_dS)z4Undo monkey-patching by :func:`inject_into_urllib3`.FN)orig_util_SSLContextrr r!orig_util_HAS_SNIr"r#r r r r rs cCsRddlm}t|dddkr$tdddlm}|}t|dddkrNtddS) z{ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. r) Extensionsget_extension_for_classNzX'cryptography' module missing required functionality. Try upgrading to v1.3.4 or newer.)X509_x509zS'pyOpenSSL' module missing required functionality. Try upgrading to v0.14 or newer.)Zcryptography.x509.extensionsr&getattr ImportErrorZOpenSSL.cryptor()r&r(rr r r rs  rcCs@dd}d|kr|S||}|dkr(dStjdkr<|jd}|S) a% Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. c Sslddl}yFx:dD]2}|j|r|t|d}|jd|j|SqW|j|S|jjk rfdSXdS)z Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. rN*..ascii)r,r-)idna startswithlenencodeZcoreZ IDNAError)namer/prefixr r r idna_encodes   z'_dnsname_to_stdlib..idna_encode:Nrzutf-8)r7r)sys version_infodecode)r3r5r r r _dnsname_to_stdlibs   r;cCst|dr|j}n tt|j}y|jjtjj }WnLtj k rJgStj t tj tfk r}ztjd|gSd}~XnXddtt|jtjD}|jdd|jtjD|S)zU Given an PyOpenSSL certificate, provides all the subject alternative names. to_cryptographyzA problem was encountered with the certificate that prevented urllib3 from finding the SubjectAlternativeName field. This can affect certificate validation. The error was %sNcSsg|]}|dk rd|fqS)NZDNSr )rr3r r r sz%get_subj_alt_name..css|]}dt|fVqdS)z IP AddressN)str)rr3r r r rsz$get_subj_alt_name..)hasattrr<ropenssl_backendr) extensionsr'rZSubjectAlternativeNamevalueZExtensionNotFoundZDuplicateExtensionrZUnsupportedGeneralNameType UnicodeErrorlogZwarningmapr;Zget_values_for_typeZDNSNameextendZ IPAddress)Z peer_certZcertZextenamesr r r get_subj_alt_names&    rIc@s|eZdZdZdddZddZddZd d Zd d Zd dZ ddZ ddZ ddZ ddZ d ddZddZddZdS)! WrappedSocketzAPI-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. TcCs"||_||_||_d|_d|_dS)NrF) connectionsocketsuppress_ragged_eofs_makefile_refs_closed)selfrKrLrMr r r __init__s zWrappedSocket.__init__cCs |jjS)N)rLfileno)rPr r r rRszWrappedSocket.filenocCs*|jdkr|jd8_|jr&|jdS)Nr)rNrOclose)rPr r r _decref_socketios s zWrappedSocket._decref_socketioscOsy|jj||}Wntjjk rX}z&|jr<|jdkrZeroReturnError get_shutdownRECEIVED_SHUTDOWN WantReadErrorr wait_for_readrL gettimeoutr )rPr]kwargsdatarGr r r rYs zWrappedSocket.recvcOsy|jj||Stjjk rT}z&|jr8|jdkr8dStt|WYdd}~Xn~tjj k r}z|jj tjj kr~dSWYdd}~XnBtjj k rt j|j|jjstdn |j||SYnXdS)NrSUnexpected EOFrzThe read operation timed outrX)rXrg)rK recv_intorZr[r\rMr]r^r>r_r`rarbrrcrLrdr )rPr]rerGr r r rh's zWrappedSocket.recv_intocCs |jj|S)N)rL settimeout)rPr r r r ri:szWrappedSocket.settimeoutcCs|xvy |jj|Stjjk rBtj|j|jjs)rPrfrGr r r _send_until_done=s zWrappedSocket._send_until_donecCs8d}x.|t|kr2|j|||t}||7}qWdS)Nr)r1rkSSL_WRITE_BLOCKSIZE)rPrfZ total_sentZsentr r r sendallHszWrappedSocket.sendallcCs|jjdS)N)rKshutdown)rPr r r rnNszWrappedSocket.shutdownc CsH|jdkr6yd|_|jjStjjk r2dSXn|jd8_dS)NrST)rNrOrKrTrZr[Error)rPr r r rTRs  zWrappedSocket.closeFcCsD|jj}|s|S|r(tjjtjj|Sd|jjffft|dS)NZ commonName)ZsubjectZsubjectAltName) rKZget_peer_certificaterZZcryptoZdump_certificateZ FILETYPE_ASN1Z get_subjectZCNrI)rPZ binary_formrr r r getpeercert\s zWrappedSocket.getpeercertcCs|jd7_dS)NrS)rN)rPr r r _reusenszWrappedSocket._reusecCs&|jdkr|jn|jd8_dS)NrS)rNrT)rPr r r _dropqs  zWrappedSocket._dropN)T)F)rrr __doc__rQrRrUrYrhrirkrmrnrTrprqrrr r r r rJs   rJrScCs|jd7_t|||ddS)NrST)rT)rNr)rPmodebufsizer r r makefileysrvc@szeZdZdZddZeddZejddZeddZejd dZd d Z d d Z dddZ dddZ dddZ dS)rz I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. cCs*t||_tjj|j|_d|_d|_dS)NrF)_openssl_versionsprotocolrZr[ZContext_ctx_optionsZcheck_hostname)rPrxr r r rQs zPyOpenSSLContext.__init__cCs|jS)N)rz)rPr r r optionsszPyOpenSSLContext.optionscCs||_|jj|dS)N)rzryZ set_options)rPrBr r r r{scCst|jjS)N)_openssl_to_stdlib_verifyryZget_verify_mode)rPr r r verify_modeszPyOpenSSLContext.verify_modecCs|jjt|tdS)N)ryZ set_verify_stdlib_to_openssl_verify_verify_callback)rPrBr r r r}scCs|jjdS)N)ryset_default_verify_paths)rPr r r rsz)PyOpenSSLContext.set_default_verify_pathscCs&t|tjr|jd}|jj|dS)Nzutf-8) isinstancer text_typer2ryZset_cipher_list)rPZciphersr r r set_cipherss  zPyOpenSSLContext.set_ciphersNcCsN|dk r|jd}|dk r$|jd}|jj|||dk rJ|jjt|dS)Nzutf-8)r2ryload_verify_locationsr)rPZcafileZcapathZcadatar r r rs  z&PyOpenSSLContext.load_verify_locationscs<|jj|dk r(|jjfdd|jj|p4|dS)NcsS)Nr )Z max_lengthZ prompt_twiceZuserdata)passwordr r sz2PyOpenSSLContext.load_cert_chain..)ryZuse_certificate_chain_fileZ set_passwd_cbZuse_privatekey_file)rPZcertfileZkeyfilerr )rr load_cert_chains z PyOpenSSLContext.load_cert_chainFTcCstjj|j|}t|tjr&|jd}|dk r8|j||j xxy |j Wndtjj k rt j ||jsztdwBYn4tjjk r}ztjd|WYdd}~XnXPqBWt||S)Nzutf-8zselect timed outzbad handshake: %r)rZr[Z Connectionryrrrr2Zset_tlsext_host_nameZset_connect_stateZ do_handshakerbrrcrdr rosslZSSLErrorrJ)rPZsockZ server_sideZdo_handshake_on_connectrMZserver_hostnamecnxrGr r r wrap_sockets"     zPyOpenSSLContext.wrap_socket)NNN)NN)FTTN)rrr rsrQpropertyr{setterr}rrrrrr r r r rs   rcCs|dkS)Nrr )rrZerr_noZ err_depthZ return_coder r r rsrrX)rX)MrsZ __future__rZ OpenSSL.SSLrZZ cryptographyrZ$cryptography.hazmat.backends.opensslrr@Z)cryptography.hazmat.backends.openssl.x509rZcryptography.x509rr+ ExceptionrLr r r^iorrZpackages.backports.makefilerZloggingrZpackagesrr8r__all__r"ZPROTOCOL_SSLv23r[Z SSLv23_METHODZPROTOCOL_TLSv1Z TLSv1_METHODrwr?rrrrupdateZPROTOCOL_SSLv3Z SSLv3_METHODAttributeErrorZ CERT_NONEZ VERIFY_NONEZ CERT_OPTIONALZ VERIFY_PEERZ CERT_REQUIREDZVERIFY_FAIL_IF_NO_PEER_CERTr~dictitemsr|rlr%r r!r$Z getLoggerrrDrrrr;rIobjectrJrvrrr r r r +sn             )4~ RPK!6QEE*__pycache__/securetransport.cpython-36.pycnu[3 nf\ev)@sdZddlmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlmZmZmZddlmZmZmZmZydd l mZWn$ek rdZdd lmZYnXd d gZd ZejZejj Z!e j"Z#e j$Z%dZ&ej'ej(ej)ej*ej+ej,ej-ej.ej/ej0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:ej;ejej?ej@ejAejBejCejDejEejFejGg!ZHe jIejJejKfiZLeMe drejNejNfeLe jO<eMe drejPejPfeLe jQ<eMe drejJejJfeLe jR<eMe drejSejSfeLe jT<eMe dr$ejKejKfeLe jU<eMe dr@eLe jIeLe jV<dd ZWdd ZXddZYddZZej[eYZ\ej]eZZ^Gddde_Z`erd$ddZan d%d dZaeae`_aGd!d"d"e_ZbdS)&aU SecureTranport support for urllib3 via ctypes. This makes platform-native TLS available to urllib3 users on macOS without the use of a compiler. This is an important feature because the Python Package Index is moving to become a TLSv1.2-or-higher server, and the default OpenSSL that ships with macOS is not capable of doing TLSv1.2. The only way to resolve this is to give macOS users an alternative solution to the problem, and that solution is to use SecureTransport. We use ctypes here because this solution must not require a compiler. That's because pip is not allowed to require a compiler either. This is not intended to be a seriously long-term solution to this problem. The hope is that PEP 543 will eventually solve this issue for us, at which point we can retire this contrib module. But in the short term, we need to solve the impending tire fire that is Python on Mac without this kind of contrib module. So...here we are. To use this module, simply import and inject it:: import urllib3.contrib.securetransport urllib3.contrib.securetransport.inject_into_urllib3() Happy TLSing! )absolute_importN)util)Security SecurityConstCoreFoundation)_assert_no_error_cert_array_from_pem_temporary_keychain_load_client_cert_chain) _fileobject)backport_makefileinject_into_urllib3extract_from_urllib3Ti@PROTOCOL_SSLv2PROTOCOL_SSLv3PROTOCOL_TLSv1PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2 PROTOCOL_TLScCs(ttj_tt_ttj_dt_dtj_dS)zG Monkey-patch urllib3 with SecureTransport-backed SSL-support. TN)SecureTransportContextrssl_ SSLContextHAS_SNIIS_SECURETRANSPORTrr%/usr/lib/python3.6/securetransport.pyrs cCs(ttj_tt_ttj_dt_dtj_dS)z> Undo monkey-patching by :func:`inject_into_urllib3`. FN)orig_util_SSLContextrrrorig_util_HAS_SNIrrrrrrrs c Csxd}y8tj|}|dkr tjS|j}|d}|j}d}d}y|xv||kr|dksZ|dkrttj||sttjt j d||} t j | j ||} |j| | } || 7}| sB|stjSPqBWWnhtjk r"} zH| j }|dk o|t j kr||d<|t jks |t jkrtjSWYdd} ~ XnX||d<||krrrrsendallCszWrappedSocket.sendallc Cs$|jtj|jWdQRXdS)N)rLrZSSLCloserA)rIrrrshutdownIs zWrappedSocket.shutdowncCs|jdkrd|_|jr(tj|jd|_|jr@tj|jd|_|jrvtj|jtj|jt j |j d|_|_ |j j S|jd8_dS)NrT)rBrCrArr\rFrDrZSecKeychainDeleteshutilZrmtreerEr#rK)rIrrrrKMs        zWrappedSocket.closeFc Cs|s tdtj}d}d}ztj|jtj|}t||sBdStj|}|sTdStj |d}|sht tj |}|szt t j |}t j|} tj| |}Wd|rt j||rt j|X|S)Nz2SecureTransport only supports dumping binary certsr) ValueErrorrrXrYrAr(rZr ZSecTrustGetCertificateCountZSecTrustGetCertificateAtIndexAssertionErrorZSecCertificateCopyDatarZCFDataGetLengthZCFDataGetBytePtrr;r\) rIZ binary_formraZcertdataZ der_bytesrPZ cert_countZleafZ data_lengthr3rrr getpeercert`s6       zWrappedSocket.getpeercertcCs|jd7_dS)Nr)rB)rIrrr_reuseszWrappedSocket._reusecCs&|jdkr|jn|jd8_dS)Nr)rBrK)rIrrr_drops  zWrappedSocket._drop)N)F)__name__ __module__ __qualname____doc__rJ contextlibcontextmanagerrLrQrbrkrlrmrnr*rHr$r<rsrtrKrxryrzrrrrr@!s& >Z ( >r@cCs|jd7_t|||ddS)NrT)rK)rBr )rImodebufsizerrrmakefilesrrcOsd}t|||f||S)Nr)r)rIr bufferingargskwargsrrrrsc@seZdZdZddZeddZejddZeddZejd dZed d Z e jd d Z d dZ ddZ ddZ dddZ dddZdddZdS)rz I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. cCs8t|\|_|_d|_d|_d|_d|_d|_d|_dS)NrF) _protocol_to_min_max _min_version _max_version_options_verify _trust_bundle _client_cert _client_key_client_key_passphrase)rIZprotocolrrrrJszSecureTransportContext.__init__cCsdS)z SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. Tr)rIrrrcheck_hostnamesz%SecureTransportContext.check_hostnamecCsdS)z SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. Nr)rIr]rrrrscCs|jS)N)r)rIrrroptionsszSecureTransportContext.optionscCs ||_dS)N)r)rIr]rrrrscCs|jr tjStjS)N)rr[ CERT_REQUIREDZ CERT_NONE)rIrrr verify_modesz"SecureTransportContext.verify_modecCs|tjkrdnd|_dS)NTF)r[rr)rIr]rrrrscCsdS)Nr)rIrrrset_default_verify_pathss z/SecureTransportContext.set_default_verify_pathscCs|jS)N)r)rIrrrload_default_certssz)SecureTransportContext.load_default_certscCs|tjjkrtddS)Nz5SecureTransport doesn't support custom cipher strings)rrZDEFAULT_CIPHERSrv)rIrOrrr set_cipherss z"SecureTransportContext.set_ciphersNcCs|dk rtd|p||_dS)Nz1SecureTransport does not support cert directories)rvr)rIZcafileZcapathZcadatarrrload_verify_locationssz,SecureTransportContext.load_verify_locationscCs||_||_||_dS)N)rrZ_client_cert_passphrase)rIZcertfileZkeyfileZpasswordrrrload_cert_chain sz&SecureTransportContext.load_cert_chainFTc CsL| s t|st|stt|}|j||j|j|j|j|j|j|j |S)N) rwr@rkrrrrrrr)rIZsockZ server_sideZdo_handshake_on_connectZsuppress_ragged_eofsrjr5rrr wrap_sockets    z"SecureTransportContext.wrap_socket)NNN)NN)FTTN)r{r|r}r~rJpropertyrsetterrrrrrrrrrrrrrs      r)r)rN)cr~Z __future__rrr(r&Zos.pathrSrur#r[Z threadingweakrefrZ_securetransport.bindingsrrrZ_securetransport.low_levelr r r r r ImportErrorZpackages.backports.makefiler__all__rrrrrWeakValueDictionaryr ZLockrerrZTLS_AES_256_GCM_SHA384ZTLS_CHACHA20_POLY1305_SHA256ZTLS_AES_128_GCM_SHA256Z'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384Z%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384Z'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256Z%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256Z#TLS_DHE_DSS_WITH_AES_256_GCM_SHA384Z#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384Z#TLS_DHE_DSS_WITH_AES_128_GCM_SHA256Z#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256Z'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384Z%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384Z$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAZ"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256Z#TLS_DHE_DSS_WITH_AES_256_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_256_CBC_SHAZ TLS_DHE_DSS_WITH_AES_256_CBC_SHAZ'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256Z%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256Z$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAZ"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAZ#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256Z#TLS_DHE_DSS_WITH_AES_128_CBC_SHA256Z TLS_DHE_RSA_WITH_AES_128_CBC_SHAZ TLS_DHE_DSS_WITH_AES_128_CBC_SHAZTLS_RSA_WITH_AES_256_GCM_SHA384ZTLS_RSA_WITH_AES_128_GCM_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHA256ZTLS_RSA_WITH_AES_128_CBC_SHA256ZTLS_RSA_WITH_AES_256_CBC_SHAZTLS_RSA_WITH_AES_128_CBC_SHArNZPROTOCOL_SSLv23Z kTLSProtocol1ZkTLSProtocol12rhasattrZ kSSLProtocol2rZ kSSLProtocol3rrZkTLSProtocol11rrrrrr:r?Z SSLReadFuncrcZ SSLWriteFuncrdobjectr@rrrrrrs          76     PK!s     PK!I $__pycache__/appengine.cpython-36.pycnu[3 nf\* @sdZddlmZddlZddlZddlZddlmZddlm Z m Z m Z m Z m Z mZddlmZddlmZdd lmZdd lmZd d lmZydd lmZWnek rdZYnXejeZGddde ZGddde Z GdddeZ!ej"Z"ej#Z#ej$Z$ej%Z%ej&Z&dS)aC This module provides a pool manager that uses Google App Engine's `URLFetch Service `_. Example usage:: from urllib3 import PoolManager from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox if is_appengine_sandbox(): # AppEngineManager uses AppEngine's URLFetch API behind the scenes http = AppEngineManager() else: # PoolManager uses a socket-level API behind the scenes http = PoolManager() r = http.request('GET', 'https://google.com/') There are `limitations `_ to the URLFetch service and it may not be the best choice for your application. There are three options for using urllib3 on Google App Engine: 1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is cost-effective in many circumstances as long as your usage is within the limitations. 2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets. Sockets also have `limitations and restrictions `_ and have a lower free quota than URLFetch. To use sockets, be sure to specify the following in your ``app.yaml``:: env_variables: GAE_USE_SOCKETS_HTTPLIB : 'true' 3. If you are using `App Engine Flexible `_, you can use the standard :class:`PoolManager` without any configuration or special environment variables. )absolute_importN)urljoin) HTTPError HTTPWarning MaxRetryError ProtocolError TimeoutErrorSSLError)RequestMethods) HTTPResponse)Timeout)Retry)_appengine_environ)urlfetchc@s eZdZdS)AppEnginePlatformWarningN)__name__ __module__ __qualname__rr/usr/lib/python3.6/appengine.pyrGsrc@s eZdZdS)AppEnginePlatformErrorN)rrrrrrrrKsrc@sXeZdZdZdddZddZdd Zddddejfd d Z d d Z ddZ ddZ dS)AppEngineManagera  Connection manager for Google App Engine sandbox applications. This manager uses the URLFetch service directly instead of using the emulated httplib, and is subject to URLFetch limitations as described in the App Engine documentation `here `_. Notably it will raise an :class:`AppEnginePlatformError` if: * URLFetch is not available. * If you attempt to use this on App Engine Flexible, as full socket support is available. * If a request size is more than 10 megabytes. * If a response size is more than 32 megabtyes. * If you use an unsupported request method such as OPTIONS. Beyond those cases, it will raise normal urllib3 errors. NTcCsNts tdtrtdtjdttj||||_||_ |pFt j |_ dS)Nz.URLFetch is not available in this environment.zUse normal urllib3.PoolManager instead of AppEngineManageron Managed VMs, as using URLFetch is not necessary in this environment.zurllib3 is using URLFetch on Google App Engine sandbox instead of sockets. To use sockets directly instead of URLFetch see https://urllib3.readthedocs.io/en/latest/reference/urllib3.contrib.html.) rris_prod_appengine_mvmswarningswarnrr __init__validate_certificateurlfetch_retriesrZDEFAULTretries)selfheadersr rrrrrrcs zAppEngineManager.__init__cCs|S)Nr)r!rrr __enter__{szAppEngineManager.__enter__cCsdS)NFr)r!exc_typeZexc_valZexc_tbrrr__exit__~szAppEngineManager.__exit__cKs|j||}yF|o |jdko |j} tj||||p2id|jo<| |j||jd} WnBtjk r} zt || WYdd} ~ Xntj k r} z$dt | krt d| t | WYdd} ~ Xntjk r} z(dt | krt||| dt | WYdd} ~ Xntjk r6} zt d| WYdd} ~ Xn`tjk rb} zt| WYdd} ~ Xn4tjk r} zt d || WYdd} ~ XnX|j| fd |i|} |o| j} | rr|jr|jrt||d n| jd krd }y|j||| |d}Wn*tk r.|jr*t||d | SX|j| tjd|| t|| }|j||||f|||d|St| jd}|j || j|r|j||| |d}tjd||j!| |j||f|||||d|S| S)NrF)Zpayloadmethodr"Zallow_truncatedfollow_redirectsZdeadlinerz too largezOURLFetch request too large, URLFetch only supports requests up to 10mb in size.zToo many redirects)reasonzPURLFetch response too large, URLFetch only supportsresponses up to 32mb in size.z$URLFetch does not support method: %sr ztoo many redirectsi/ZGET)responseZ_poolzRedirecting %s -> %s)r redirecttimeoutz Retry-Afterz Retry: %s)bodyr"r r*r+)" _get_retriesr*totalrZfetchr_get_absolute_timeoutrZDeadlineExceededErrorr ZInvalidURLErrorstrrrZ DownloadErrorrZResponseTooLargeErrorZSSLCertificateErrorr ZInvalidMethodError#_urlfetch_response_to_http_responseZget_redirect_locationZraise_on_redirectstatusZ incrementZsleep_for_retrylogdebugrurlopenboolZ getheaderZis_retryZsleep)r!r&Zurlr,r"r r*r+ response_kwr'r)eZ http_responseZredirect_locationZ redirect_urlZhas_retry_afterrrrr5s           zAppEngineManager.urlopencKstr"|jjd}|dkr"|jd=|jjd}|dkrZ|jd}|jddj||jd<tftj|j |j |j|j d|}tftj|j |j|j |d|S)Nzcontent-encodingZdeflateztransfer-encodingZchunked,)r,msgr"r2)r,r"r2original_response) is_prod_appenginer"getsplitremovejoinr ioBytesIOZcontentZ header_msgZ status_code)r!Z urlfetch_respr7Zcontent_encodingZtransfer_encodingZ encodingsr;rrrr1s*      z4AppEngineManager._urlfetch_response_to_http_responsecCsB|tjkrdSt|tr>|jdk s,|jdk r8tjdt|jS|S)NzdURLFetch does not support granular timeout settings, reverting to total or default URLFetch timeout.) r DEFAULT_TIMEOUT isinstanceZ_readZ_connectrrrr.)r!r+rrrr/s  z&AppEngineManager._get_absolute_timeoutcCs>t|tstj|||jd}|js.|js.|jr:tjdt |S)N)r*defaultzhURLFetch only supports total retries and does not recognize connect, read, or redirect retry parameters.) rDrZfrom_intr Zconnectreadr*rrr)r!r r*rrrr- s zAppEngineManager._get_retries)NNTT) rrr__doc__rr#r%r rCr5r1r/r-rrrrrOs Z$ r)'rGZ __future__rrAZloggingrZpackages.six.moves.urllib.parser exceptionsrrrrr r Zrequestr r)r Z util.timeoutr Z util.retryrrZgoogle.appengine.apir ImportErrorZ getLoggerrr3rrrZ is_appengineZis_appengine_sandboxZis_local_appenginer<rrrrr's2         OPK!5@qq#__pycache__/__init__.cpython-36.pycnu[3 nf\@sdS)Nrrr/usr/lib/python3.6/__init__.pysPK!5@qq)__pycache__/__init__.cpython-36.opt-1.pycnu[3 nf\@sdS)Nrrr/usr/lib/python3.6/__init__.pysPK!Jkk ntlmpool.pynu[""" NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 """ from __future__ import absolute_import from logging import getLogger from ntlm import ntlm from .. import HTTPSConnectionPool from ..packages.six.moves.http_client import HTTPSConnection log = getLogger(__name__) class NTLMConnectionPool(HTTPSConnectionPool): """ Implements an NTLM authentication version of an urllib3 connection pool """ scheme = 'https' def __init__(self, user, pw, authurl, *args, **kwargs): """ authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\\username format. pw is the password for the user. """ super(NTLMConnectionPool, self).__init__(*args, **kwargs) self.authurl = authurl self.rawuser = user user_parts = user.split('\\', 1) self.domain = user_parts[0].upper() self.user = user_parts[1] self.pw = pw def _new_conn(self): # Performs the NTLM handshake that secures the connection. The socket # must be kept open while requests are performed. self.num_connections += 1 log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s', self.num_connections, self.host, self.authurl) headers = {'Connection': 'Keep-Alive'} req_header = 'Authorization' resp_header = 'www-authenticate' conn = HTTPSConnection(host=self.host, port=self.port) # Send negotiation message headers[req_header] = ( 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser)) log.debug('Request headers: %s', headers) conn.request('GET', self.authurl, None, headers) res = conn.getresponse() reshdr = dict(res.getheaders()) log.debug('Response status: %s %s', res.status, res.reason) log.debug('Response headers: %s', reshdr) log.debug('Response data: %s [...]', res.read(100)) # Remove the reference to the socket, so that it can not be closed by # the response object (we want to keep the socket open) res.fp = None # Server should respond with a challenge message auth_header_values = reshdr[resp_header].split(', ') auth_header_value = None for s in auth_header_values: if s[:5] == 'NTLM ': auth_header_value = s[5:] if auth_header_value is None: raise Exception('Unexpected %s response header: %s' % (resp_header, reshdr[resp_header])) # Send authentication message ServerChallenge, NegotiateFlags = \ ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value) auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags) headers[req_header] = 'NTLM %s' % auth_msg log.debug('Request headers: %s', headers) conn.request('GET', self.authurl, None, headers) res = conn.getresponse() log.debug('Response status: %s %s', res.status, res.reason) log.debug('Response headers: %s', dict(res.getheaders())) log.debug('Response data: %s [...]', res.read()[:100]) if res.status != 200: if res.status == 401: raise Exception('Server rejected request: wrong ' 'username or password') raise Exception('Wrong server response: %s %s' % (res.status, res.reason)) res.fp = None log.debug('Connection established') return conn def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True): if headers is None: headers = {} headers['Connection'] = 'Keep-Alive' return super(NTLMConnectionPool, self).urlopen(method, url, body, headers, retries, redirect, assert_same_host) PK!D# == pyopenssl.pynu[""" SSL with SNI_-support for Python 2. Follow these instructions if you would like to verify SSL certificates in Python 2. Note, the default libraries do *not* do certificate checking; you need to do additional work to validate certificates yourself. This needs the following packages installed: * pyOpenSSL (tested with 16.0.0) * cryptography (minimum 1.3.4, from pyopenssl) * idna (minimum 2.0, from cryptography) However, pyopenssl depends on cryptography, which depends on idna, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. Activating this module also has the positive side effect of disabling SSL/TLS compression in Python 2 (see `CRIME attack`_). If you want to configure the default list of supported cipher suites, you can set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit) """ from __future__ import absolute_import import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend from cryptography.hazmat.backends.openssl.x509 import _Certificate try: from cryptography.x509 import UnsupportedExtension except ImportError: # UnsupportedExtension is gone in cryptography >= 2.1.0 class UnsupportedExtension(Exception): pass from socket import timeout, error as SocketError from io import BytesIO try: # Platform-specific: Python 2 from socket import _fileobject except ImportError: # Platform-specific: Python 3 _fileobject = None from ..packages.backports.makefile import backport_makefile import logging import ssl from ..packages import six import sys from .. import util __all__ = ['inject_into_urllib3', 'extract_from_urllib3'] # SNI always works. HAS_SNI = True # Map from urllib3 to PyOpenSSL compatible parameter-values. _openssl_versions = { ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, } if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'): _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'): _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD try: _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD}) except AttributeError: pass _stdlib_to_openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } _openssl_to_stdlib_verify = dict( (v, k) for k, v in _stdlib_to_openssl_verify.items() ) # OpenSSL will only write 16K at a time SSL_WRITE_BLOCKSIZE = 16384 orig_util_HAS_SNI = util.HAS_SNI orig_util_SSLContext = util.ssl_.SSLContext log = logging.getLogger(__name__) def inject_into_urllib3(): 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.' _validate_dependencies_met() util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSSL = True def extract_from_urllib3(): 'Undo monkey-patching by :func:`inject_into_urllib3`.' util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_PYOPENSSL = False util.ssl_.IS_PYOPENSSL = False def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Extensions, "get_extension_for_class", None) is None: raise ImportError("'cryptography' module missing required functionality. " "Try upgrading to v1.3.4 or newer.") # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 # attribute is only present on those versions. from OpenSSL.crypto import X509 x509 = X509() if getattr(x509, "_x509", None) is None: raise ImportError("'pyOpenSSL' module missing required functionality. " "Try upgrading to v0.14 or newer.") def _dnsname_to_stdlib(name): """ Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. """ def idna_encode(name): """ Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. """ import idna try: for prefix in [u'*.', u'.']: if name.startswith(prefix): name = name[len(prefix):] return prefix.encode('ascii') + idna.encode(name) return idna.encode(name) except idna.core.IDNAError: return None if ':' in name: return name name = idna_encode(name) if name is None: return None elif sys.version_info >= (3, 0): name = name.decode('utf-8') return name def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is technically using private APIs, but should work across all # relevant versions before PyOpenSSL got a proper API for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. # We also want to skip over names which cannot be idna encoded. names = [ ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName)) if name is not None ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names class WrappedSocket(object): '''API-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. ''' def __init__(self, connection, socket, suppress_ragged_eofs=True): self.connection = connection self.socket = socket self.suppress_ragged_eofs = suppress_ragged_eofs self._makefile_refs = 0 self._closed = False def fileno(self): return self.socket.fileno() # Copy-pasted from Python 3.5 source code def _decref_socketios(self): if self._makefile_refs > 0: self._makefile_refs -= 1 if self._closed: self.close() def recv(self, *args, **kwargs): try: data = self.connection.recv(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else: raise except OpenSSL.SSL.WantReadError: if not util.wait_for_read(self.socket, self.socket.gettimeout()): raise timeout('The read operation timed out') else: return self.recv(*args, **kwargs) else: return data def recv_into(self, *args, **kwargs): try: return self.connection.recv_into(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else: raise except OpenSSL.SSL.WantReadError: if not util.wait_for_read(self.socket, self.socket.gettimeout()): raise timeout('The read operation timed out') else: return self.recv_into(*args, **kwargs) def settimeout(self, timeout): return self.socket.settimeout(timeout) def _send_until_done(self, data): while True: try: return self.connection.send(data) except OpenSSL.SSL.WantWriteError: if not util.wait_for_write(self.socket, self.socket.gettimeout()): raise timeout() continue except OpenSSL.SSL.SysCallError as e: raise SocketError(str(e)) def sendall(self, data): total_sent = 0 while total_sent < len(data): sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE]) total_sent += sent def shutdown(self): # FIXME rethrow compatible exceptions should we ever use this self.connection.shutdown() def close(self): if self._makefile_refs < 1: try: self._closed = True return self.connection.close() except OpenSSL.SSL.Error: return else: self._makefile_refs -= 1 def getpeercert(self, binary_form=False): x509 = self.connection.get_peer_certificate() if not x509: return x509 if binary_form: return OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_ASN1, x509) return { 'subject': ( (('commonName', x509.get_subject().CN),), ), 'subjectAltName': get_subj_alt_name(x509) } def _reuse(self): self._makefile_refs += 1 def _drop(self): if self._makefile_refs < 1: self.close() else: self._makefile_refs -= 1 if _fileobject: # Platform-specific: Python 2 def makefile(self, mode, bufsize=-1): self._makefile_refs += 1 return _fileobject(self, mode, bufsize, close=True) else: # Platform-specific: Python 3 makefile = backport_makefile WrappedSocket.makefile = makefile class PyOpenSSLContext(object): """ I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. """ def __init__(self, protocol): self.protocol = _openssl_versions[protocol] self._ctx = OpenSSL.SSL.Context(self.protocol) self._options = 0 self.check_hostname = False @property def options(self): return self._options @options.setter def options(self, value): self._options = value self._ctx.set_options(value) @property def verify_mode(self): return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify( _stdlib_to_openssl_verify[value], _verify_callback ) def set_default_verify_paths(self): self._ctx.set_default_verify_paths() def set_ciphers(self, ciphers): if isinstance(ciphers, six.text_type): ciphers = ciphers.encode('utf-8') self._ctx.set_cipher_list(ciphers) def load_verify_locations(self, cafile=None, capath=None, cadata=None): if cafile is not None: cafile = cafile.encode('utf-8') if capath is not None: capath = capath.encode('utf-8') self._ctx.load_verify_locations(cafile, capath) if cadata is not None: self._ctx.load_verify_locations(BytesIO(cadata)) def load_cert_chain(self, certfile, keyfile=None, password=None): self._ctx.use_certificate_chain_file(certfile) if password is not None: self._ctx.set_passwd_cb(lambda max_length, prompt_twice, userdata: password) self._ctx.use_privatekey_file(keyfile or certfile) def wrap_socket(self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None): cnx = OpenSSL.SSL.Connection(self._ctx, sock) if isinstance(server_hostname, six.text_type): # Platform-specific: Python 3 server_hostname = server_hostname.encode('utf-8') if server_hostname is not None: cnx.set_tlsext_host_name(server_hostname) cnx.set_connect_state() while True: try: cnx.do_handshake() except OpenSSL.SSL.WantReadError: if not util.wait_for_read(sock, sock.gettimeout()): raise timeout('select timed out') continue except OpenSSL.SSL.Error as e: raise ssl.SSLError('bad handshake: %r' % e) break return WrappedSocket(cnx, sock) def _verify_callback(cnx, x509, err_no, err_depth, return_code): return err_no == 0 PK!** appengine.pynu[""" This module provides a pool manager that uses Google App Engine's `URLFetch Service `_. Example usage:: from urllib3 import PoolManager from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox if is_appengine_sandbox(): # AppEngineManager uses AppEngine's URLFetch API behind the scenes http = AppEngineManager() else: # PoolManager uses a socket-level API behind the scenes http = PoolManager() r = http.request('GET', 'https://google.com/') There are `limitations `_ to the URLFetch service and it may not be the best choice for your application. There are three options for using urllib3 on Google App Engine: 1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is cost-effective in many circumstances as long as your usage is within the limitations. 2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets. Sockets also have `limitations and restrictions `_ and have a lower free quota than URLFetch. To use sockets, be sure to specify the following in your ``app.yaml``:: env_variables: GAE_USE_SOCKETS_HTTPLIB : 'true' 3. If you are using `App Engine Flexible `_, you can use the standard :class:`PoolManager` without any configuration or special environment variables. """ from __future__ import absolute_import import io import logging import warnings from ..packages.six.moves.urllib.parse import urljoin from ..exceptions import ( HTTPError, HTTPWarning, MaxRetryError, ProtocolError, TimeoutError, SSLError ) from ..request import RequestMethods from ..response import HTTPResponse from ..util.timeout import Timeout from ..util.retry import Retry from . import _appengine_environ try: from google.appengine.api import urlfetch except ImportError: urlfetch = None log = logging.getLogger(__name__) class AppEnginePlatformWarning(HTTPWarning): pass class AppEnginePlatformError(HTTPError): pass class AppEngineManager(RequestMethods): """ Connection manager for Google App Engine sandbox applications. This manager uses the URLFetch service directly instead of using the emulated httplib, and is subject to URLFetch limitations as described in the App Engine documentation `here `_. Notably it will raise an :class:`AppEnginePlatformError` if: * URLFetch is not available. * If you attempt to use this on App Engine Flexible, as full socket support is available. * If a request size is more than 10 megabytes. * If a response size is more than 32 megabtyes. * If you use an unsupported request method such as OPTIONS. Beyond those cases, it will raise normal urllib3 errors. """ def __init__(self, headers=None, retries=None, validate_certificate=True, urlfetch_retries=True): if not urlfetch: raise AppEnginePlatformError( "URLFetch is not available in this environment.") if is_prod_appengine_mvms(): raise AppEnginePlatformError( "Use normal urllib3.PoolManager instead of AppEngineManager" "on Managed VMs, as using URLFetch is not necessary in " "this environment.") warnings.warn( "urllib3 is using URLFetch on Google App Engine sandbox instead " "of sockets. To use sockets directly instead of URLFetch see " "https://urllib3.readthedocs.io/en/latest/reference/urllib3.contrib.html.", AppEnginePlatformWarning) RequestMethods.__init__(self, headers) self.validate_certificate = validate_certificate self.urlfetch_retries = urlfetch_retries self.retries = retries or Retry.DEFAULT def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # Return False to re-raise any potential exceptions return False def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT, **response_kw): retries = self._get_retries(retries, redirect) try: follow_redirects = ( redirect and retries.redirect != 0 and retries.total) response = urlfetch.fetch( url, payload=body, method=method, headers=headers or {}, allow_truncated=False, follow_redirects=self.urlfetch_retries and follow_redirects, deadline=self._get_absolute_timeout(timeout), validate_certificate=self.validate_certificate, ) except urlfetch.DeadlineExceededError as e: raise TimeoutError(self, e) except urlfetch.InvalidURLError as e: if 'too large' in str(e): raise AppEnginePlatformError( "URLFetch request too large, URLFetch only " "supports requests up to 10mb in size.", e) raise ProtocolError(e) except urlfetch.DownloadError as e: if 'Too many redirects' in str(e): raise MaxRetryError(self, url, reason=e) raise ProtocolError(e) except urlfetch.ResponseTooLargeError as e: raise AppEnginePlatformError( "URLFetch response too large, URLFetch only supports" "responses up to 32mb in size.", e) except urlfetch.SSLCertificateError as e: raise SSLError(e) except urlfetch.InvalidMethodError as e: raise AppEnginePlatformError( "URLFetch does not support method: %s" % method, e) http_response = self._urlfetch_response_to_http_response( response, retries=retries, **response_kw) # Handle redirect? redirect_location = redirect and http_response.get_redirect_location() if redirect_location: # Check for redirect response if (self.urlfetch_retries and retries.raise_on_redirect): raise MaxRetryError(self, url, "too many redirects") else: if http_response.status == 303: method = 'GET' try: retries = retries.increment(method, url, response=http_response, _pool=self) except MaxRetryError: if retries.raise_on_redirect: raise MaxRetryError(self, url, "too many redirects") return http_response retries.sleep_for_retry(http_response) log.debug("Redirecting %s -> %s", url, redirect_location) redirect_url = urljoin(url, redirect_location) return self.urlopen( method, redirect_url, body, headers, retries=retries, redirect=redirect, timeout=timeout, **response_kw) # Check if we should retry the HTTP response. has_retry_after = bool(http_response.getheader('Retry-After')) if retries.is_retry(method, http_response.status, has_retry_after): retries = retries.increment( method, url, response=http_response, _pool=self) log.debug("Retry: %s", url) retries.sleep(http_response) return self.urlopen( method, url, body=body, headers=headers, retries=retries, redirect=redirect, timeout=timeout, **response_kw) return http_response def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw): if is_prod_appengine(): # Production GAE handles deflate encoding automatically, but does # not remove the encoding header. content_encoding = urlfetch_resp.headers.get('content-encoding') if content_encoding == 'deflate': del urlfetch_resp.headers['content-encoding'] transfer_encoding = urlfetch_resp.headers.get('transfer-encoding') # We have a full response's content, # so let's make sure we don't report ourselves as chunked data. if transfer_encoding == 'chunked': encodings = transfer_encoding.split(",") encodings.remove('chunked') urlfetch_resp.headers['transfer-encoding'] = ','.join(encodings) original_response = HTTPResponse( # In order for decoding to work, we must present the content as # a file-like object. body=io.BytesIO(urlfetch_resp.content), msg=urlfetch_resp.header_msg, headers=urlfetch_resp.headers, status=urlfetch_resp.status_code, **response_kw ) return HTTPResponse( body=io.BytesIO(urlfetch_resp.content), headers=urlfetch_resp.headers, status=urlfetch_resp.status_code, original_response=original_response, **response_kw ) def _get_absolute_timeout(self, timeout): if timeout is Timeout.DEFAULT_TIMEOUT: return None # Defer to URLFetch's default. if isinstance(timeout, Timeout): if timeout._read is not None or timeout._connect is not None: warnings.warn( "URLFetch does not support granular timeout settings, " "reverting to total or default URLFetch timeout.", AppEnginePlatformWarning) return timeout.total return timeout def _get_retries(self, retries, redirect): if not isinstance(retries, Retry): retries = Retry.from_int( retries, redirect=redirect, default=self.retries) if retries.connect or retries.read or retries.redirect: warnings.warn( "URLFetch only supports total retries and does not " "recognize connect, read, or redirect retry parameters.", AppEnginePlatformWarning) return retries # Alias methods from _appengine_environ to maintain public API interface. is_appengine = _appengine_environ.is_appengine is_appengine_sandbox = _appengine_environ.is_appengine_sandbox is_local_appengine = _appengine_environ.is_local_appengine is_prod_appengine = _appengine_environ.is_prod_appengine is_prod_appengine_mvms = _appengine_environ.is_prod_appengine_mvms PK!i/kk%__pycache__/pyopenssl.cpython-312.pycnu[ @gK UdZddlmZddlZddlmZ ddlmZddl Z ddl Z ddl Z ddlmZdd lmZdd lmZd d lmZe j*rdd lmZddgZej2j4ej6j8ej2j:ej6j8e j<ej6j>iZ de!d<e"e dr6e"ej6dr#ej6jFe e jH<e"e dr6e"ej6dr#ej6jJe e jL<e jNej6jPe jRej6jTe jVej6jTej6jXziZ-e-j]Dcic]\}}|| c}}Z/e0ej6dde0ej6ddzZ1de!d<e0ej6ddZ2de!d<e0ej6ddZ3de!d<e0ej6ddZ4de!d<e0ej6d dZ5de!d!<e jljne1e jljpe1e jljre1e2ze jljte1e2ze3ze jljve1e2ze3ze4ze jljxe1e2ze3ze4ziZ=de!d"<e jljne1e2ze3ze4ze5ze jljpe1e3ze4ze5ze jljre1e4ze5ze jljte1e5ze jljve1e jljxe1iZ>de!d#<d$Z?ej2jZAe jeCZDd/d%ZEd/d&ZFd/d'ZGd0d(ZHd1d)ZIGd*d+ZJejeJ_KGd,d-ZL d2d.ZMy#e $rGdde ZY8wxYwcc}}w)3a Module for using pyOpenSSL as a TLS backend. This module was relevant before the standard library ``ssl`` module supported SNI, but now that we've dropped support for Python 2.7 all relevant Python versions support SNI so **this module is no longer recommended**. This needs the following packages installed: * `pyOpenSSL`_ (tested with 16.0.0) * `cryptography`_ (minimum 1.3.4, from pyopenssl) * `idna`_ (minimum 2.0) However, pyOpenSSL depends on cryptography, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: .. code-block:: bash $ python -m pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this: .. code-block:: python try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass .. _pyopenssl: https://www.pyopenssl.org .. _cryptography: https://cryptography.io .. _idna: https://github.com/kjd/idna ) annotationsN)x509)UnsupportedExtensionc eZdZy)rN)__name__ __module__ __qualname__H/opt/hc_python/lib/python3.12/site-packages/urllib3/contrib/pyopenssl.pyrr2s r r)BytesIO)socket)timeout)utilX509inject_into_urllib3extract_from_urllib3zdict[int, int]_openssl_versionsPROTOCOL_TLSv1_1TLSv1_1_METHODPROTOCOL_TLSv1_2TLSv1_2_METHOD OP_NO_SSLv2 OP_NO_SSLv3int_OP_NO_SSLv2_OR_SSLv3 OP_NO_TLSv1 _OP_NO_TLSv1 OP_NO_TLSv1_1_OP_NO_TLSv1_1 OP_NO_TLSv1_2_OP_NO_TLSv1_2 OP_NO_TLSv1_3_OP_NO_TLSv1_3_openssl_to_ssl_minimum_version_openssl_to_ssl_maximum_versioni@cttt_ttj_dt_dtj_y)z7Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.TN)_validate_dependencies_metPyOpenSSLContextr SSLContextssl_ IS_PYOPENSSLr r r rrs1 &DO+DIID!DIIr ctt_ttj_dt_dtj_y)z4Undo monkey-patching by :func:`inject_into_urllib3`.FN)orig_util_SSLContextrr,r-r.r r r rrs++DO/DIID"DIIr cddlm}t|dd tdddlm}|}t|dd tdy) z{ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. r) Extensionsget_extension_for_classNzX'cryptography' module missing required functionality. Try upgrading to v1.3.4 or newer.r_x509zS'pyOpenSSL' module missing required functionality. Try upgrading to v0.14 or newer.)cryptography.x509.extensionsr2getattr ImportErrorOpenSSL.cryptor)r2rrs r r*r*s[ 8z4d;C 0  $ 6DtWd#+ /  ,r cNdd}d|vr|S||}|y|jdS)a% Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). If the name cannot be idna-encoded then we return None signalling that the name given should be skipped. cddl} dD]F}|j|s|t|d}|jd|j|zcS|j|S#|jj $rYywxYw)z Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. rN)z*..ascii)idna startswithlenencodecore IDNAError)namer=prefixs r idna_encodez'_dnsname_to_stdlib..idna_encodes|  %??6*F .D!==1DKK4EEE&;;t$ $yy""  sA"2A"A""A>=A>:Nutf-8)rCstrreturn bytes | None)decode)rCrE encoded_names r _dnsname_to_stdlibrMs9$ d{ t$L   w ''r cN|j} |jjtjj }tt|jtj Dcgc]}|d|f }}|j#d|jtj$D|S#tj $rgcYStjttjtf$r"}tjd|gcYd}~Sd}~wwxYwcc}w)zU Given an PyOpenSSL certificate, provides all the subject alternative names. zA problem was encountered with the certificate that prevented urllib3 from finding the SubjectAlternativeName field. This can affect certificate validation. The error was %sNDNSc36K|]}dt|fyw)z IP AddressN)rH).0rCs r z$get_subj_alt_name.. s.Uds4y!.Us)to_cryptography extensionsr3rSubjectAlternativeNamevalueExtensionNotFoundDuplicateExtensionrUnsupportedGeneralNameType UnicodeErrorlogwarningmaprMget_values_for_typeDNSNameextend IPAddress) peer_certcertexterCnamess r get_subj_alt_namergs  $ $ &Doo55d6Q6QRXX:*C,C,CDLL,QR RD    R    LL.1.E.Ednn.U LG  ! !   ''    >    . s)3B:4 D":D,D=DDDceZdZdZ d ddZddZddZddZddZddZ ddZ dd Z dd Z dd Z dd Z d dd ZddZddZy) WrappedSocketz@API-compatibility wrapper for Python OpenSSL's Connection-class.cJ||_||_||_d|_d|_yNrF) connectionrsuppress_ragged_eofs_io_refs_closed)selfrlrrms r __init__zWrappedSocket.__init__s( % $8!  r c6|jjSN)rfilenorps r rtzWrappedSocket.fileno!s{{!!##r c|jdkDr|xjdzc_|jr|jyy)Nr)rnrocloserus r _decref_socketioszWrappedSocket._decref_socketios%s1 ==1  MMQ M << JJL r c  |jj|i|}|S#tjj$rH}|j r|j dk(rYd}~yt|j dt||d}~wtjj$r9|jjtjjk(rYytjj$r`}tj|j|jj!s t#d||j|i|cYd}~Sd}~wtjj$$r}t'j(d||d}~wwxYw)NzUnexpected EOFr rThe read operation timed out read error: )rlrecvOpenSSLSSL SysCallErrorrmargsOSErrorrHZeroReturnError get_shutdownRECEIVED_SHUTDOWN WantReadErrorr wait_for_readr gettimeoutrErrorsslSSLError)rprkwargsdatares r rzWrappedSocket.recv+s4 '4??''88D*K){{'' 8((QVV7M-MaffQiQ0a7{{** ++-1N1NN{{(( 2%%dkk4;;3I3I3KL<=1D tyy$1&11{{   <,,aU34! ; #A>>AF F 2AE F  F -FF c8|jj|Srs)r settimeout)rprs r rzWrappedSocket.settimeout[s{{%%g..r c |jj|S#tjj$rM}t j |j|jjs t|Yd}~d}~wtjj$r(}t|jdt||d}~wwxYwNr)rlsendrrWantWriteErrorrwait_for_writerrrrrrrH)rprres r _send_until_donezWrappedSocket._send_until_done^s 8++D11;;-- **4;; 8N8N8PQ!)*;;++ 8affQiQ0a7 8s!C AB C ##CC cd}|t|kr0|j|||tz}||z }|t|kr/yyr)r?rSSL_WRITE_BLOCKSIZE)rpr total_sentsents r sendallzWrappedSocket.sendallisM 3t9$((Z*/B"BCD $ J 3t9$r c |jjy#tjj$r}t j d||d}~wwxYw)Nzshutdown error: )rlshutdownrrrrr)rphowres r rzWrappedSocket.shutdownqsM @ OO $ $ &{{   @,,!1!78a ? @sAAAcRd|_|jdkr|jyy)NTr)rorn _real_closerus r rxzWrappedSocket.closews& ==A      r c~ |jjS#tjj$rYywxYwrs)rlrxrrrrus r rzWrappedSocket._real_close|s6 ??((* *{{     s <<c|jj}|s|S|r8tjj tjj |Sd|j jffft|dS)N commonName)subjectsubjectAltName) rlget_peer_certificatercryptodump_certificate FILETYPE_ASN1 get_subjectCNrg)rp binary_formrs r getpeercertzWrappedSocket.getpeercertsw335K >>227>>3O3OQUV V'(8(8(8(:(=(=>@B/5  r c6|jjSrs)rlget_protocol_version_namerus r versionzWrappedSocket.versions88::r c^|jj}|r|jSdSrs)rlget_alpn_proto_negotiatedrK)rp alpn_protos r selected_alpn_protocolz$WrappedSocket.selected_alpn_protocols*__>>@ &0z  ":d:r N)T)rlOpenSSL.SSL.Connectionr socket_clsrmboolrINonerIrrIr)r typing.AnyrrrIbytes)rrrrrIr)rfloatrIr)rrrIr)rrrIr)rrrIr)F)rrrIz"dict[str, list[typing.Any]] | None)rIrH)rI str | None)rrr __doc__rqrtryrrrrrrrxrrrrr r r ririsJ &* *  #   $ 2<./ 8@  #(  + ;;r riczeZdZdZddZeddZejddZeddZejddZddZ ddZ d dd Z d dd Z dd Z d dd ZddZeddZejd dZeddZejd!dZy )"r+z I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. ct||_tjj |j|_d|_d|_tjj|_ tjj|_ yrk)rprotocolrrContext_ctx_optionscheck_hostnamer TLSVersionMINIMUM_SUPPORTED_minimum_versionMAXIMUM_SUPPORTED_maximum_version)rprs r rqzPyOpenSSLContext.__init__s[)(3 KK'' 6  #%(^^%E%E%(^^%E%Er c|jSrs)rrus r optionszPyOpenSSLContext.optionss }}r c2||_|jyrs)r_set_ctx_optionsrprVs r rzPyOpenSSLContext.optionss  r cDt|jjSrs)_openssl_to_stdlib_verifyrget_verify_moderus r verify_modezPyOpenSSLContext.verify_modes()B)B)DEEr cR|jjt|tyrs)r set_verify_stdlib_to_openssl_verify_verify_callbackrs r rzPyOpenSSLContext.verify_modes 6u=?OPr c8|jjyrs)rset_default_verify_pathsrus r rz)PyOpenSSLContext.set_default_verify_pathss **,r c|t|tr|jd}|jj |y)NrG) isinstancerHr@rset_cipher_list)rpcipherss r set_cipherszPyOpenSSLContext.set_cipherss, gs #nnW-G !!'*r NcT||jd}||jd} |jj|||%|jjt|yy#tj j $r}tjd||d}~wwxYw)NrGz%unable to load trusted certificates: ) r@rload_verify_locationsr rrrrr)rpcafilecapathcadatares r rz&PyOpenSSLContext.load_verify_locationss  ]]7+F  ]]7+F U II + +FF ;! //@"{{   U,,!FqeLMST T UsAA,,B' B""B'cz |jj|?ttsj d|jj fd|jj |xs|y#tjj$r}tjd||d}~wwxYw)NrGcSrsr )_passwords r z2PyOpenSSLContext.load_cert_chain..s8r z"Unable to load certificate chain: ) ruse_certificate_chain_filerrr@ set_passwd_cbuse_privatekey_filerrrrr)rpcertfilekeyfilerres ` r load_cert_chainz PyOpenSSLContext.load_cert_chains  R II 0 0 :#!(E2'w7H ''(;< II ) )'*=X >{{   R,,!CA5IJPQ Q RsA;A??B:B55B:c|Dcgc]"}tjj|d$}}|jj|Scc}w)Nr<)rto_bytesrset_alpn_protos)rp protocolsps r set_alpn_protocolsz#PyOpenSSLContext.set_alpn_protocolssB=FGYTYY''73Y Gyy((33Hs'A ctjj|j|}|rQtj j |s2t|tr|jd}|j||j |j t)||S#tjj$r:}t j||js t!d|Yd}~qd}~wtjj"$r}t%j&d||d}~wwxYw)NrGzselect timed outzbad handshake: )rr Connectionrrr- is_ipaddressrrHr@set_tlsext_host_nameset_connect_state do_handshakerrrrrrrri)rpsock server_sidedo_handshake_on_connectrmserver_hostnamecnxres r wrap_socketzPyOpenSSLContext.wrap_socketskk$$TYY5 499#9#9/#J/3/"1"8"8"A  $ $_ 5  C  " S$'';;,, ))$0AB!"451<;;$$ Cll_QE#:;B Cs$B--D= 0C?? D=D88D=c|jj|jt|jzt |j zyrs)r set_optionsrr'rr(rrus r rz!PyOpenSSLContext._set_ctx_options sC  MM-d.C.CD E-d.C.CD E r c|jSrs)rrus r minimum_versionz PyOpenSSLContext.minimum_version$$$r c2||_|jyrs)rr)rprs r rz PyOpenSSLContext.minimum_version / r c|jSrs)rrus r maximum_versionz PyOpenSSLContext.maximum_versionr r c2||_|jyrs)rr)rpr s r r z PyOpenSSLContext.maximum_versionr r )rrrIrr)rVrrIr)rVzssl.VerifyModerIrr)rz bytes | strrIr)NNN)rrrrrrJrIr)NN)rrHrrrrrIr)rzlist[bytes | str]rIr)FTTN) rrrrrrrmrrzbytes | str | NonerIri)rrrIr)r rrIr)rrr rrqpropertyrsetterrrrrrrrrrr r r r r+r+s F ^^  FFQQ-+"!# UUU U  U(## RRR R  R 4"(,%).2 ((("& ( # ( , ( (> %%  %%  r r+c |dk(Srr )rrerr_no err_depth return_codes r rr#s Q;r r)rCrHrIr)rbrrIzlist[tuple[str, str]]) rrrrrrrrrrrIr)Nr __future__r OpenSSL.SSLr cryptographyrcryptography.x509rr7 Exceptionloggingrtypingior rrrr TYPE_CHECKINGr8r__all__r- PROTOCOL_TLSr SSLv23_METHODPROTOCOL_TLS_CLIENTPROTOCOL_TLSv1 TLSv1_METHODr__annotations__hasattrrrrr CERT_NONE VERIFY_NONE CERT_OPTIONAL VERIFY_PEER CERT_REQUIREDVERIFY_FAIL_IF_NO_PEER_CERTritemsrr6rr r"r$r&rrTLSv1TLSv1_1TLSv1_2TLSv1_3rr'r(rr,r0 getLoggerrr[rrr*rMrgrimakefiler+r)kvs00r r6sK&P# 6 ' # !"8 9 IIGKK55II!!7;;#<#< 00%>  3"# =M(N.5kk.H.Hc**+ 3"# =M(N.5kk.H.Hc**+MM7;;**w{{..w{{.. kk--. /H.M.M.OP.OdaQT.OP%W[[-Cg KKGsGKK: c:gkk?A>>gkk?A>>gkk?A>>NN$$&;NN/NN1L@NN1L@>QNN ,~=NNN$$ ,~=N 3 NN$$          NN.?.PNN1NB^SNN1NBNN1NN$$&;3$yy++g!"# 4&(R-`E;E;P$,, C C L        g  y  RQsQ QQQPK!;H$__pycache__/__init__.cpython-312.pycnu[ @gy)NrG/opt/hc_python/lib/python3.12/site-packages/urllib3/contrib/__init__.pyrsrPK!!__pycache__/socks.cpython-312.pycnu[ @g}dZddlmZ ddlZddl Z ddl m Z ddl mZmZdd lmZmZdd lmZmZdd lmZdd lmZ ddlZGd de j4ZGddeZGddeeZGddeZGddeZGddeZ y#e$rddlZddlmZejdewxYw#e$rdZY~wxYw)a This module contains provisional support for SOCKS proxies from within urllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and SOCKS5. To enable its functionality, either install PySocks or install this module with the ``socks`` extra. The SOCKS implementation supports the full range of urllib3 features. It also supports the following SOCKS features: - SOCKS4A (``proxy_url='socks4a://...``) - SOCKS4 (``proxy_url='socks4://...``) - SOCKS5 with remote DNS (``proxy_url='socks5h://...``) - SOCKS5 with local DNS (``proxy_url='socks5://...``) - Usernames and passwords for the SOCKS proxy .. note:: It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in your ``proxy_url`` to ensure that DNS resolution is done from the remote server instead of client-side when connecting to a domain name. SOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5 supports IPv4, IPv6, and domain names. When connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url`` will be sent as the ``userid`` section of the SOCKS request: .. code-block:: python proxy_url="socks4a://@proxy-host" When connecting to a SOCKS5 proxy the ``username`` and ``password`` portion of the ``proxy_url`` will be sent as the username/password to authenticate with the proxy: .. code-block:: python proxy_url="socks5h://:@proxy-host" ) annotationsN)DependencyWarningzSOCKS support in urllib3 requires the installation of optional dependencies: specifically, PySocks. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#socks-proxies)timeout)HTTPConnectionHTTPSConnection)HTTPConnectionPoolHTTPSConnectionPool)ConnectTimeoutErrorNewConnectionError) PoolManager) parse_urlcJeZdZUded<ded<ded<ded<ded<ded <y ) _TYPE_SOCKS_OPTIONSint socks_version str | None proxy_host proxy_portusernamepasswordboolrdnsN)__name__ __module__ __qualname____annotations__D/opt/hc_python/lib/python3.12/site-packages/urllib3/contrib/socks.pyrrKs% Jrrc<eZdZdZ dfd ZddZxZS)SOCKSConnectionzG A plain-text HTTP connection that connects via a SOCKS proxy. c2||_t||i|y)N)_socks_optionssuper__init__)selfr$argskwargs __class__s r r&zSOCKSConnection.__init__Ys - $)&)rc Di}|jr|j|d<|jr|j|d< tj|j|j ff|j d|j d|j d|j d|j d|j d|jd |}|S#t$r-}t|d |jd |jd |d }~wtj$rt}|jrS|j}t|tr(t|d |jd |jd |t|d|t|d||d }~wt$r}t|d||d }~wwxYw)zA Establish a new connection via the SOCKS proxy. source_addresssocket_optionsrrrrrr) proxy_type proxy_addrrproxy_usernameproxy_password proxy_rdnsrzConnection to z timed out. (connect timeout=)Nz&Failed to establish a new connection: )r,r-sockscreate_connectionhostportr$r SocketTimeoutr ProxyError socket_err isinstancer OSError)r'extra_kwconneerrors r _new_connzSOCKSConnection._new_connbs+-   )-)<)#22:>..v6   DX A %  +HVWX   || e]3-( 3PQUQ]Q]P^^_`- FugN)B1#F $>qcB  s1B C F(C99FA/E>> F FF)r$rr( typing.Anyr)rBreturnNone)rCzsocks.socksocket)rrr__doc__r&rA __classcell__r*s@r r"r"Ts8*+** *  *8rr"c eZdZy)SOCKSHTTPSConnectionN)rrrrrr rIrIsrrIceZdZeZy)SOCKSHTTPConnectionPoolN)rrrr" ConnectionClsrrr rKrKs#MrrKceZdZeZy)SOCKSHTTPSConnectionPoolN)rrrrIrLrrr rNrNs(MrrNcNeZdZdZeedZ d dfd ZxZS)SOCKSProxyManagerzh A version of the urllib3 ProxyManager that routes connections via the defined SOCKS proxy. )httphttpsc bt|}|<|:|j.|jjd}t|dk(r|\}}|jdk(rt j } d} nt|jdk(rt j } d} nR|jdk(rt j} d} n0|jdk(rt j} d} ntd |||_ | |j|j||| d } | |d <t |4||fi|tj|_y) N:rsocks5Fsocks5hTsocks4socks4az'Unable to determine SOCKS version from )rrrrrrr$)rauthsplitlenschemer4PROXY_TYPE_SOCKS5PROXY_TYPE_SOCKS4 ValueError proxy_urlr6r7r%r&rPpool_classes_by_scheme) r'r`rr num_poolsheadersconnection_pool_kwparsedrZrr socks_optionsr*s r r&zSOCKSProxyManager.__init__s*9%   0V[[5LKK%%c*E5zQ%*"( ==H $!33MD ]]i '!33MD ]]h &!33MD ]]i '!33MDFykRS S"+ ++ ++    0=+, GB/AB&7&N&N#r)NN N) r`strrrrrrbrrcztyping.Mapping[str, str] | NonerdrB) rrrrErKrNrar&rFrGs@r rPrPsr () $#37 ,O,O,O ,O  ,O 1 ,O),O,OrrP)!rE __future__rr4 ImportErrorwarnings exceptionsrwarntypingsocketrr8 connectionrrconnectionpoolr r r r poolmanagerr util.urlrssl TypedDictrr"rIrKrNrPrrr rvs&P#  +8D@%  &**FnFZ ?O $0$)2)7O 7OA  .HMM Y     4 CsBB6$B36C?CPK!л&&emscripten/response.pynu[from __future__ import annotations import json as _json import logging import typing from contextlib import contextmanager from dataclasses import dataclass from http.client import HTTPException as HTTPException from io import BytesIO, IOBase from ...exceptions import InvalidHeader, TimeoutError from ...response import BaseHTTPResponse from ...util.retry import Retry from .request import EmscriptenRequest if typing.TYPE_CHECKING: from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection log = logging.getLogger(__name__) @dataclass class EmscriptenResponse: status_code: int headers: dict[str, str] body: IOBase | bytes request: EmscriptenRequest class EmscriptenHttpResponseWrapper(BaseHTTPResponse): def __init__( self, internal_response: EmscriptenResponse, url: str | None = None, connection: BaseHTTPConnection | BaseHTTPSConnection | None = None, ): self._pool = None # set by pool class self._body = None self._response = internal_response self._url = url self._connection = connection self._closed = False super().__init__( headers=internal_response.headers, status=internal_response.status_code, request_url=url, version=0, version_string="HTTP/?", reason="", decode_content=True, ) self.length_remaining = self._init_length(self._response.request.method) self.length_is_certain = False @property def url(self) -> str | None: return self._url @url.setter def url(self, url: str | None) -> None: self._url = url @property def connection(self) -> BaseHTTPConnection | BaseHTTPSConnection | None: return self._connection @property def retries(self) -> Retry | None: return self._retries @retries.setter def retries(self, retries: Retry | None) -> None: # Override the request_url if retries has a redirect location. self._retries = retries def stream( self, amt: int | None = 2**16, decode_content: bool | None = None ) -> typing.Generator[bytes]: """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ while True: data = self.read(amt=amt, decode_content=decode_content) if data: yield data else: break def _init_length(self, request_method: str | None) -> int | None: length: int | None content_length: str | None = self.headers.get("content-length") if content_length is not None: try: # RFC 7230 section 3.3.2 specifies multiple content lengths can # be sent in a single Content-Length header # (e.g. Content-Length: 42, 42). This line ensures the values # are all valid ints and that as long as the `set` length is 1, # all values are the same. Otherwise, the header is invalid. lengths = {int(val) for val in content_length.split(",")} if len(lengths) > 1: raise InvalidHeader( "Content-Length contained multiple " "unmatching values (%s)" % content_length ) length = lengths.pop() except ValueError: length = None else: if length < 0: length = None else: # if content_length is None length = None # Check for responses that shouldn't include a body if ( self.status in (204, 304) or 100 <= self.status < 200 or request_method == "HEAD" ): length = 0 return length def read( self, amt: int | None = None, decode_content: bool | None = None, # ignored because browser decodes always cache_content: bool = False, ) -> bytes: if ( self._closed or self._response is None or (isinstance(self._response.body, IOBase) and self._response.body.closed) ): return b"" with self._error_catcher(): # body has been preloaded as a string by XmlHttpRequest if not isinstance(self._response.body, IOBase): self.length_remaining = len(self._response.body) self.length_is_certain = True # wrap body in IOStream self._response.body = BytesIO(self._response.body) if amt is not None and amt >= 0: # don't cache partial content cache_content = False data = self._response.body.read(amt) if self.length_remaining is not None: self.length_remaining = max(self.length_remaining - len(data), 0) if (self.length_is_certain and self.length_remaining == 0) or len( data ) < amt: # definitely finished reading, close response stream self._response.body.close() return typing.cast(bytes, data) else: # read all we can (and cache it) data = self._response.body.read() if cache_content: self._body = data if self.length_remaining is not None: self.length_remaining = max(self.length_remaining - len(data), 0) if len(data) == 0 or ( self.length_is_certain and self.length_remaining == 0 ): # definitely finished reading, close response stream self._response.body.close() return typing.cast(bytes, data) def read_chunked( self, amt: int | None = None, decode_content: bool | None = None, ) -> typing.Generator[bytes]: # chunked is handled by browser while True: bytes = self.read(amt, decode_content) if not bytes: break yield bytes def release_conn(self) -> None: if not self._pool or not self._connection: return None self._pool._put_conn(self._connection) self._connection = None def drain_conn(self) -> None: self.close() @property def data(self) -> bytes: if self._body: return self._body else: return self.read(cache_content=True) def json(self) -> typing.Any: """ Deserializes the body of the HTTP response as a Python object. The body of the HTTP response must be encoded using UTF-8, as per `RFC 8529 Section 8.1 `_. To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to your custom decoder instead. If the body of the HTTP response is not decodable to UTF-8, a `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a valid JSON document, a `json.JSONDecodeError` will be raised. Read more :ref:`here `. :returns: The body of the HTTP response as a Python object. """ data = self.data.decode("utf-8") return _json.loads(data) def close(self) -> None: if not self._closed: if isinstance(self._response.body, IOBase): self._response.body.close() if self._connection: self._connection.close() self._connection = None self._closed = True @contextmanager def _error_catcher(self) -> typing.Generator[None]: """ Catch Emscripten specific exceptions thrown by fetch.py, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ from .fetch import _RequestError, _TimeoutError # avoid circular import clean_exit = False try: yield # If no exception is thrown, we should avoid cleaning up # unnecessarily. clean_exit = True except _TimeoutError as e: raise TimeoutError(str(e)) except _RequestError as e: raise HTTPException(str(e)) finally: # If we didn't terminate cleanly, we need to throw away our # connection. if not clean_exit: # The response may not be closed but we're not going to use it # anymore so close it now if ( isinstance(self._response.body, IOBase) and not self._response.body.closed ): self._response.body.close() # release the connection back to the pool self.release_conn() else: # If we have read everything from the response stream, # return the connection back to the pool. if ( isinstance(self._response.body, IOBase) and self._response.body.closed ): self.release_conn() PK!ﱮ''1emscripten/__pycache__/connection.cpython-312.pycnu[ @gC"rUddlmZddlZddlZddlmZddlmZddlmZddl m Z m Z m Z ddl mZdd lmZdd lmZdd lmZmZdd lmZd dlmZmZmZmZd dlmZd dlmZm Z ejBrddlm"Z"m#Z#GddZ$Gdde$Z%ejBre$ddZ&de'd<e%ddZ(de'd<yy)) annotationsN) HTTPException)ResponseNotReady) _TYPE_BODY)HTTPConnection ProxyConfigport_by_scheme) TimeoutError)BaseHTTPResponse)_TYPE_SOCKET_OPTIONS)_DEFAULT_TIMEOUT _TYPE_TIMEOUT)Url) _RequestError _TimeoutError send_requestsend_streaming_request)EmscriptenRequest)EmscriptenHttpResponseWrapperEmscriptenResponse)BaseHTTPConnectionBaseHTTPSConnectionceZdZUedZded<ded<ded<ded <d ed <d ed <d ed<ded<ded<ded<dZded<dZded<ded< d*edddddd d+dZ d, d-d Z d.d!Z d/dd"d"d"d# d0d$Z d1d%Z d.d&Zed2d'Zed2d(Zed2d)Zy)3EmscriptenHTTPConnectionhttpztyping.ClassVar[int] default_portz%typing.ClassVar[_TYPE_SOCKET_OPTIONS]default_socket_optionsz None | floattimeoutstrhostintport blocksizetuple[str, int] | Nonesource_address_TYPE_SOCKET_OPTIONS | Nonesocket_options Url | NoneproxyProxyConfig | None proxy_configFbool is_verifiedNz bool | Noneproxy_is_verifiedzEmscriptenResponse | None _responsei )r r'r%r)r+r-c||_||_t|tr|nd|_d|_d|_d|_d|_d|_ ||_ d|_ d|_ d|_ y)NgrTF)r"r$ isinstancefloatr scheme_closedr1r+r-r%r'r)r/) selfr"r$r r'r%r)r+r-s T/opt/hc_python/lib/python3.12/site-packages/urllib3/contrib/emscripten/connection.py__init__z!EmscriptenHTTPConnection.__init__-si  ",We"rCrDrErFrequestkves r8rRz EmscriptenHTTPConnection.requestTs >># [[MTYYKq > %0"&..NN**..  #$ $r:c d|_d|_y)NT)r6r1rAs r8closezEmscriptenHTTPConnection.closes r:c|jS)zWhether the connection either is brand new or has been previously closed. If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` properties must be False. )r6rAs r8 is_closedz"EmscriptenHTTPConnection.is_closeds ||r:cy)zLWhether the connection is actively connected to any origin (proxy or target)Tr=rAs r8 is_connectedz%EmscriptenHTTPConnection.is_connectedsr:cy)zWhether the connection has successfully connected to its proxy. This returns False if no proxy is in use. Used to determine whether errors are coming from the proxy layer or from tunnelling to the target origin. Fr=rAs r8has_connected_to_proxyz/EmscriptenHTTPConnection.has_connected_to_proxys r:r)r"r!r$r#r rr'r&r%r#r)r(r+r*r-r,returnNone)rNr) r"r!r$ int | Noner>typing.Mapping[str, str] | Noner5r!rcrd)rcrd)NN)rKr!rJr!rQz_TYPE_BODY | Noner>rfrCr.rDr.rEr.rFr.rcrd)rcr )rcr.)__name__ __module__ __qualname__r r__annotations__r/r0rr9r?rBrRrYr[propertyr]r_rar=r:r8rrs)7)?L&?AA  I IN**// $$K%){)(( ! "2156: +/!!!  ! / !!4!!)! !<37    1       #'37 &2 $#'+&2&2&2 &2 1 &2&2&2&2!%&2 &2P%r:rceZdZUedZdZded<dZded<dZded<dZ ded <ded <ded <ded <d ed<dZ ded<dZ ded<dZ ded<ded<dZ ded< deddej ddddddddddddddddd dfdZ d ddZxZS)EmscriptenHTTPSConnectionhttpsNint | str | None cert_reqs str | Noneca_certs ca_cert_dirNone | str | bytes ca_cert_data cert_filekey_file key_passwordtyping.Any | None ssl_context ssl_versionressl_minimum_versionssl_maximum_version"None | str | typing.Literal[False]assert_hostnameassert_fingerprinti@)r r'r%r)r+r-rprrserver_hostnamerzrrrsrur|r}r{rvrwrxc t|||||||||d|_||_||_||_| |_| |_| |_| |_ ||_ ||_ ||_ |xrtjj||_|xrtjj||_||_d|_d|_y)N)r$r r'r%r)r+r-rnT)superr9r5rwrvrxrzrrrr{r|r}ospath expanduserrrrsrurpr/)r7r"r$r r'r%r)r+r-rprrrrzrrrsrur|r}r{rvrwrx __class__s r8r9z"EmscriptenHTTPSConnection.__init__s8  ))%     "(&.."4&#6 #6  ARWW%7%7%A &J277+=+=k+J( r:c yr<r=) r7rwrvrprxrrrrrsrus r8set_certz"EmscriptenHTTPSConnection.set_certs r:rb).r"r!r$r#r rr'r&r%r#r)zNone | _TYPE_SOCKET_OPTIONSr+r*r-r,rprorr~rrqrrqrzryrrrqrsrqrurtr|rer}rer{rorvrqrwrqrxrqrcrd) NNNNNNNNN)rwrqrvrqrprorxrqrrrqrr~rrqrsrqrurtrcrd)rgrhrir rrprjrrrsrur{r|r}rrrrr9r __classcell__)rs@r8rmrms?!'*L"&I&Hj"K"'+L$+""$(K!(&**&**77%) ) : "215  1 1 +/&*>B)-&*)-#"&+/*.*.(, $##'5: : :  : / : :  (: : ): $: <: ': $!: "'#: $%: & ': ()): *(+: ,(-: .&/: 01: 23: 4!5: 6 7: | $ $&*#'#>B)-"&+/      $  !    <  '     )     r:rmr_supports_http_protocolr_supports_https_protocol)) __future__rrtyping http.clientrr_base_connectionrrXrr r exceptionsr responser util.connectionr util.timeoutrrutil.urlrfetchrrrrrRrrr TYPE_CHECKINGrrrrmrrjrr=r:r8rs" 7(*EE&(3;UU&G KDDNY 8Y z 2J2q2Q/Q4MbRS4T1Tr:PK!D5i1i1/emscripten/__pycache__/response.cpython-312.pycnu[ @g&ddlmZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z mZddlmZmZdd lmZdd lmZd d lmZej0rdd lmZmZej8eZe GddZGddeZ y)) annotationsN)contextmanager) dataclass) HTTPException)BytesIOIOBase) InvalidHeader TimeoutError)BaseHTTPResponse)Retry)EmscriptenRequest)BaseHTTPConnectionBaseHTTPSConnectionc6eZdZUded<ded<ded<ded<y ) EmscriptenResponseint status_codezdict[str, str]headerszIOBase | bytesbodyrrequestN)__name__ __module__ __qualname____annotations__R/opt/hc_python/lib/python3.12/site-packages/urllib3/contrib/emscripten/response.pyrrs   rrcJeZdZ d dfd ZeddZej ddZeddZeddZej ddZ d ddZ ddZ d dd Z d dd Z dd Z dd Zedd ZddZddZed dZxZS)!EmscriptenHttpResponseWrapperc $d|_d|_||_||_||_d|_t ||j|j|dddd|j|jjj|_ d|_y)NFrzHTTP/?T)rstatus request_urlversionversion_stringreasondecode_content)_pool_body _response_url _connection_closedsuper__init__rr _init_lengthrmethodlength_remaininglength_is_certain)selfinternal_responseurl connection __class__s rr1z&EmscriptenHttpResponseWrapper.__init__s   * %  %--$00#  !% 1 1$..2H2H2O2O P!&rc|jSNr-r6s rr8z!EmscriptenHttpResponseWrapper.url7s yyrc||_yr<r=)r6r8s rr8z!EmscriptenHttpResponseWrapper.url;s  rc|jSr<)r.r>s rr9z(EmscriptenHttpResponseWrapper.connection?src|jSr<_retriesr>s rretriesz%EmscriptenHttpResponseWrapper.retriesCs }}rc||_yr<rB)r6rDs rrDz%EmscriptenHttpResponseWrapper.retriesGs   rc#DK |j||}|r|nyw)a_ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. )amtr)Nread)r6rGr)datas rstreamz$EmscriptenHttpResponseWrapper.streamLs-$99^9DD  s c|jjd}|\ |jdDchc] }t|}}t |dkDrt d|z|j }|dkrd}nd}|jdvsd|jcxkrdksn|d k(rd}|Scc}w#t$rd}Y@wxYw) Nzcontent-length,rz8Content-Length contained multiple unmatching values (%s)r)i0dHEAD) rgetsplitrlenr pop ValueErrorr$)r6request_methodcontent_lengthvallengthslengths rr2z*EmscriptenHttpResponseWrapper._init_lengthfs%)\\%5%56F%G  % " 0>/C/CC/HI/H3s8/HIw>..7DNN**t/D/D/INN''--/{{5$/=# " "s.EJ =CJ  Jc#@K |j||}|sy|wr<rH)r6rGr)rds r read_chunkedz*EmscriptenHttpResponseWrapper.read_chunkeds+ IIc>2EK sc|jr |jsy|jj|jd|_yr<)r*r. _put_connr>s r release_connz*EmscriptenHttpResponseWrapper.release_conns4zz!1!1 T--.rc$|jyr<)rar>s r drain_connz(EmscriptenHttpResponseWrapper.drain_conns  rcV|jr |jS|jdS)NT)re)r+rIr>s rrJz"EmscriptenHttpResponseWrapper.datas$ :::: 99490 0rcb|jjd}tj|S)a Deserializes the body of the HTTP response as a Python object. The body of the HTTP response must be encoded using UTF-8, as per `RFC 8529 Section 8.1 `_. To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to your custom decoder instead. If the body of the HTTP response is not decodable to UTF-8, a `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a valid JSON document, a `json.JSONDecodeError` will be raised. Read more :ref:`here `. :returns: The body of the HTTP response as a Python object. zutf-8)rJdecode_jsonloads)r6rJs rjsonz"EmscriptenHttpResponseWrapper.jsons'$yy({{4  rc|js}t|jjtr$|jjj |j r!|j j d|_d|_yy)NT)r/r]r,rrrar.r>s rraz#EmscriptenHttpResponseWrapper.closesb||$..--v6##))+  &&(#' DL rc#Kddlm}m}d} dd} |syt |jjtrD|jjjs$|jjj|jyt |jjtr2|jjjr|jyyy#|$r}tt |d}~w|$r}t t |d}~wwxYw#|syt |jjtrD|jjjs$|jjj|jwt |jjtr2|jjjr|jwwwxYww)z Catch Emscripten specific exceptions thrown by fetch.py, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. r) _RequestError _TimeoutErrorFNT) fetchrurvr strrr]r,rrr^rarj)r6rurv clean_exites rr_z,EmscriptenHttpResponseWrapper._error_catchersv 8  ( Jt~~22F; NN//66NN''--/!!# t~~22F;++22%%'3<+ 's1v& & (A' ' ( t~~22F; NN//66NN''--/!!# t~~22F;++22%%'3rso" %!65(& Kg!  ($4(rPK!1{ tt.emscripten/__pycache__/request.cpython-312.pycnu[ @g6JddlmZddlmZmZddlmZeGddZy)) annotations) dataclassfield) _TYPE_BODYceZdZUded<ded<dZded<dZded<ee Zd ed <d Z d ed<dZ ded<ddZ ddZ y)EmscriptenRequeststrmethodurlNzdict[str, str] | Noneparams_TYPE_BODY | Nonebody)default_factoryzdict[str, str]headersrfloattimeoutTbooldecode_contentc>||j|j<yN)r capitalize)selfnamevalues Q/opt/hc_python/lib/python3.12/site-packages/urllib3/contrib/emscripten/request.py set_headerzEmscriptenRequest.set_headers*/ T__&'c||_yr)r)rrs rset_bodyzEmscriptenRequest.set_bodys  r)rr rr returnNone)rrr!r") __name__ __module__ __qualname____annotations__r rrdictrrrrr rrr r sO K H$(F !("D "#D9G^9GUND0rr N) __future__r dataclassesrr_base_connectionrr r(rrr,s'"(*     rPK!ζll/emscripten/__pycache__/__init__.cpython-312.pycnu[ @g@ddlmZddlZddlmZmZddlmZm Z ddZ y) ) annotationsN)HTTPConnectionPoolHTTPSConnectionPool)EmscriptenHTTPConnectionEmscriptenHTTPSConnectionctt_tt_tt j _tt j _y)N) rr ConnectionClsr rurllib3 connectionHTTPConnectionHTTPSConnectionR/opt/hc_python/lib/python3.12/site-packages/urllib3/contrib/emscripten/__init__.pyinject_into_urllib3r s3(@$(A%(@G%)BG&r)returnNone) __future__rurllib3.connectionr connectionpoolrrr rr rrrrrs"EKCrPK!(|Zmm,emscripten/__pycache__/fetch.cpython-312.pycnu[ @gSYUdZddlmZddlZddlZddlmZddlmZddl m Z m Z ddl Z ddl mZmZmZmZe rddlmZd d lmZd d lmZ d Zd ZdZdZdZeej=dj?dZ Gdde!Z"Gdde"Z#Gdde"Z$d2dZ%GddejLZ'GddZ(Gdd ejLZ)d3d!Z*d3d"Z+d3d#Z,d3d$Z-dZ.d%e/d&<e-re+re*se,se(Z.ndZ.d'Z0d4d(Z1d)a2d5d*Z3d)a4d5d+Z5d6d,Z6 d7d-Z7 d8d.Z8d3d/Z9d9d0Z:d3d1Z;y):a Support for streaming http requests in emscripten. A few caveats - If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md *and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case timeouts and streaming should just work. Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming. This approach has several caveats: Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed. Streaming only works if you're running pyodide in a web worker. Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch operation, so it requires that you have crossOriginIsolation enabled, by serving over https (or from localhost) with the two headers below set: Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole request into a buffer and then returning it. it shows a warning in the JavaScript console in this case. Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch. NB: in this code, there are a lot of JavaScript objects. They are named js_* to make it clear what type of object they are. ) annotationsN)Parser)files) TYPE_CHECKINGAny)JsArray JsExceptionJsProxyto_js)Buffer)EmscriptenRequest)EmscriptenResponse)z user-agentzemscripten_fetch_worker.jszutf-8)encodingc6eZdZ dddd dfdZxZS) _RequestErrorNrequestresponsecb||_||_||_t||jyN)rrmessagesuper__init__)selfrrr __class__s O/opt/hc_python/lib/python3.12/site-packages/urllib3/contrib/emscripten/fetch.pyrz_RequestError.__init__Ns+     &r)rz str | NonerEmscriptenRequest | NonerEmscriptenResponse | None)__name__ __module__ __qualname__r __classcell__r s@r!rrMs;# '-1.2 ' '* ' , ' 'r"rc eZdZy)_StreamingErrorNr%r&r'r"r!r+r+[r"r+c eZdZy) _TimeoutErrorNr,r-r"r!r0r0_r.r"r0cLt|tjjS)N)dict_converter)r jsObject fromEntries)dict_vals r!_obj_from_dictr7cs "))*?*? @@r"ceZdZ d dZd dZd dZed dZd fd Zd dZ d dZ d dZ d d Z xZ S) _ReadStreamc||_||_d|_d|_||_||_|dkDrt d|znd|_d|_d|_ ||_ y)NrTF) int_buffer byte_bufferread_posread_len connection_idworkerinttimeoutis_live _is_closedr)rr<r=rCrAr@rs r!rz_ReadStream.__init__hs]%&  * .5ks4'>*t  18 r"c$|jyrclosers r!__del__z_ReadStream.__del__|  r"c|jSrrErIs r! is_closedz_ReadStream.is_closed r"c"|jSrrNrIs r!closedz_ReadStream.closed~~r"c|jryd|_d|_d|_d|_d|_d|_|jr7|jjtd|jid|_t|5y)NrTrHF)rNr?r>r<r=rErrDrA postMessager7r@rrHrr s r!rHz_ReadStream.closest >>     << KK # #NGT=O=O3P$Q R DL  r"cyNTr-rIs r!readablez_ReadStream.readabler"cyNFr-rIs r!writablez_ReadStream.writabler"cyr\r-rIs r!seekablez_ReadStream.seekabler^r"cb|jstd|jd|jdk(rYtj j |jdt|jjtd|jitj j|jdt|jdk(rt|jd}|dkDr||_d|_n|t k(rs|jd}tj"j%}|j'|j(j+d|}td||jdd|_|j/yt1|jt3t5|}|j(j7|j|j|zj9}|t5|d||xj|zc_|xj|z c_|S) Nz,No buffer for stream in _ReadStream.readintorrgetMorez timed-outr Exception thrown in fetch: F)r<r+rr?r3Atomicsstore ERROR_TIMEOUTrArUr7r@waitrCr0r>ERROR_EXCEPTION TextDecodernewdecoder=slicerDrHminlen memoryviewsubarrayto_py)rbyte_objdata_len string_len js_decoderjson_str ret_lengthrps r!readintoz_ReadStream.readintos!>   ==A  JJ  T__a ? KK # #NIt?Q?Q3R$S T M4<<P$#q)H!| ( ! _,!__Q/ ^^//1 %,,T-=-=-C-CAz-RS%1(< LL! %  Jx,@(AB ##,, MM4==:5 %' .6 8Qz* #  # r") r<rr=rrCfloatrAr r@rBrrreturnNoner{boolrrr r{rB)r%r&r'rrJrNpropertyrRrHrYr]r`rxr(r)s@r!r9r9gsy999 9  9  9#9(   ,r"r9ceZdZddZddZy)_StreamingFetchercd_tjjt t gdt ddi}dfd }tjj|}tjjj|_ tjjj|_ y)NF)create_pyproxiestypezapplication/javascriptchdfd }dfd }|j_|j_y)Nc$d_|yrX)streaming_ready)e js_resolve_fnrs r!onMsgzC_StreamingFetcher.__init__..promise_resolver..onMsgs'+$a r"c|yrr-)r js_reject_fns r!onErrzC_StreamingFetcher.__init__..promise_resolver..onErrs Qr")rr r{r|) js_worker onmessageonerror)rrrrrs`` r!promise_resolverz4_StreamingFetcher.__init__..promise_resolvers' ! (-DNN $%*DNN "r")rr rr r{r|)rr3Blobrjr _STREAMING_WORKER_CODEr7URLcreateObjectURL globalThisWorkerrPromisejs_worker_ready_promise)r js_data_blobr js_data_urls` r!rz_StreamingFetcher.__init__s$ww{{ )*U C F$<= > +ff,,\: --11+>')}}'<'<'@'@AQ'R$r"c |jjDcic]\}}|tvs||}}}|j}|t ||j d}|j dkDrtd|j znd}tjjd}tjj|} tjj|d} tjj| dttjj!| dtj"j|j$tj&j(} |j*j-t/|| |dtjj1| dt|| dtk(rt3d|d| dt4k(r| d } tj6j} | j9| j;d| }t=j>|}tA||d |d tC| | |j |j*|d | S| dtDk(rU| d } tj6j} | j9| j;d| }tGd||dtGd| d|dcc}}w)N)headersbodymethodrr;i)bufferurl fetchParamsz'Timeout connecting to streaming requestrr statusr connectionID)r status_coderrrcz%Unknown status from worker in fetch: )$ritemsHEADERS_TO_IGNORErr rrCrBr3SharedArrayBufferrj Int32Array Uint8ArrayrdrerfnotifyrrlocationhrefrrUr7rgr0SUCCESS_HEADERrirkrljsonloadsrr9rhr+)rrkvrr fetch_datarCjs_shared_buffer js_int_bufferjs_byte_bufferjs_absolute_urlrtrurv response_objs r!sendz_StreamingFetcher.sends$__224 4TQAR8RAqD4  ||!(%+X 1811D#dW__,-$//33G< ))*:; **+;Q? =9 -+&&**W[["++>CC "" .*#-    q-A  } ,9  1  /'q)J++-J"(()=)=a)LMH::h/L%(2$Y/ !"OONN 0   1  0&q)J++-J!(()=)=a)LMH!-hZ8'TX "7 a8H7IJ C s K&K&Nrzrrr{r)r%r&r'rrr-r"r!rrsS0Fr"rceZdZdZ d dZd dZddZeddZd fd Z ddZ ddZ dd Z dd Z dd ZxZS)_JSPIReadStreamaF A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch response. This requires support for WebAssembly JavaScript Promise Integration in the containing browser, and for pyodide to be launched via runPythonAsync. :param js_read_stream: The JavaScript stream reader :param timeout: Timeout in seconds :param request: The request we're handling :param response: The response this stream relates to :param js_abort_controller: A JavaScript AbortController object, used for timeouts c||_||_d|_d|_||_||_d|_d|_||_y)NFr) js_read_streamrCrE_is_donerrcurrent_buffercurrent_buffer_posjs_abort_controller)rrrCrrrs r!rz_JSPIReadStream.__init__FsG-  18 3; ""##6 r"c$|jyrrGrIs r!rJz_JSPIReadStream.__del__XrKr"c|jSrrMrIs r!rNz_JSPIReadStream.is_closed\rOr"c"|jSrrQrIs r!rRz_JSPIReadStream.closed`rSr"c|jryd|_d|_|jj d|_d|_d|_d|_d|_t|)y)NrT) rNr?r>rcancelrErrrrrHrVs r!rHz_JSPIReadStream.closeds] >>     ""$"     r"cyrXr-rIs r!rYz_JSPIReadStream.readableqrZr"cyr\r-rIs r!r]z_JSPIReadStream.writabletr^r"cyr\r-rIs r!r`z_JSPIReadStream.seekablewr^r"ct|jj|j|j|j |j }|jrd|_y|jj|_ d|_ y)NrTFr) _run_sync_with_timeoutrreadrCrrrdonervaluerqrr)r result_jss r!_get_next_bufferz _JSPIReadStream._get_next_bufferzso*    $ $ & LL  $ $LL]]   >> DM"+//"7"7"9D &'D #r"c|j-|jr |j|jytt |t |j|j z }|j|j |j |z|d||xj |z c_|j t |jk(rd|_|S)Nr)rrrHrmrnr)rrrrws r!rxz_JSPIReadStream.readintos    &((*d.A.A.I  M3t223d6M6MM "&!4!4  # #d&=&= &J" : :-  " "c$*=*=&> >"&D r") rrrCryrrrrrrrzr}r)r%r&r'__doc__rrJrNrrRrHrYr]r`rrxr(r)s@r!rr0sy*777# 7 % 7 ! 7$    r"rcttdxr3ttdxr!tjtjk(S)Nwindowr)hasattrr3rrr-r"r!is_in_browser_main_threadrs- 2x QWR%8 QRWW =QQr"cFttdxrtjS)NcrossOriginIsolated)rr3rr-r"r!is_cross_origin_isolatedrs 2, - H"2H2HHr"cttdxrittjdxrMttjjdxr'tjjjdk(S)Nprocessreleasenamenode)rr3rrrr-r"r! is_in_noders\I . BJJ * . BJJ&& / . JJ   # #v - r"cFttdxrttdS)Nrr)rr3r-r"r!is_worker_availablers 2x 8WR%88r"z_StreamingFetcher | None_fetcherzurllib3 only works in Node.js with pyodide.runPythonAsync and requires the flag --experimental-wasm-stack-switching in versions of node <24.ctr t|dStrtt|dt rt rt j|Sty)NTrrr) has_jspisend_jspi_requestrrNODE_JSPI_ERRORrrr_show_streaming_warningrs r!send_streaming_requestrsQz $// #  O%}}W%%!r"FcXts$dad}tjj|yy)NTz8Warning: Timeout is not available on main browser thread)_SHOWN_TIMEOUT_WARNINGr3consolewarn)rs r!_show_timeout_warningrs% !!%L   "r"ctsZdad}ts|dz }tr|dz }ts|dz }t dur|dz }dd lm}|j|yy) NTz%Can't stream HTTP requests because: z$ Page is not cross-origin isolated z+ Python is running in main browser thread z> Worker or Blob classes are not available in this environment.Fz Streaming fetch worker isn't ready. If you want to be sure that streaming fetch is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`r)r)_SHOWN_STREAMING_WARNINGrrrrr3rr)rrs r!rrss ##' :') > >G $ & E EG"$ W WG   % e eG W $r"ctr t|dStrtt|d t j j}ts1d|_ |jrEt|jdz|_ n'|jd|jr t|j|j|j d|j"j%D].\}}|j't(vs|j+||0|j-t/|j0t3t5j7|j9}ts)|j:j=j?}n|j:jAd}tC|jD|||S#tF$rh}|jHdk(rtK|jL| |jHd k(rt|jL| t|jL| d}~wwxYw) NFr arraybufferr;ztext/plain; charset=ISO-8859-15z ISO-8859-15rrrr TimeoutErrorr NetworkError)'rrrrrr3XMLHttpRequestrjr responseTyperCrBoverrideMimeTyperopenrrrrlowerrsetRequestHeaderrr rdictrparsestrgetAllResponseHeadersrrqtobytesencoderrr rr0r)rjs_xhrrrrrerrs r! send_requestrsz %00 #  %>""&&((*"/F !$W__t%;!<  # #$E F&' GNNGKK7"??002KD%zz|#44''e43  E',,'(vx(()E)E)GHI(*??((*224D??))-8D! wT7   > 88~ % W= = XX ' W= =  W= =>s CG!CG!! I*A#I  Ic|j}tjj}|jj Dcic]\}}|t vs||}}}|j}|t||j|jd}tj|jt|} t| |||d} i}| jj} | j!} t#| ddrn2t%| j&d|t%| j&d<P| j(} d}t+| |d| }|r6| jV| jj-}t/|||||}n,t| j1||||j3}||_|Scc}}w) a7 Send a request using WebAssembly JavaScript Promise Integration to wrap the asynchronous JavaScript fetch api (experimental). :param request: Request to send :param streaming: Whether to stream the response :return: The response object :rtype: EmscriptenResponse )rrrsignalNrrFr rr"r)rCr3AbortControllerrjrrrrr rr fetchrr7rentriesnextgetattrstrrrr getReaderr arrayBufferrq)r streamingrCrrrrreq_bodyrfetcher_promise_js response_js header_iter iter_value_jsrrrbody_stream_jss r!rr&s ooG,,002 ' 5 5 7V 711DU;Uq!t 7GV||Hh..%,, J'++~j/IJ) KG%%--/K #((* =&% 0 36}7J7J17M3NGC ++A./ 0  $$K!$D!sGH    '(--779N"(H{==  % % * *+> ?Wt^AT &(    OOH %  Y 88| #+Wx   WxX X Y   OOH % s$ A** B-35B((B--B00C cR ddlm}m}t|S#t$rYywxYw)a Return true if jspi can be used. This requires both browser support and also WebAssembly to be in the correct state - i.e. that the javascript call into python was async not sync. :return: True if jspi can be used. :rtype: bool r can_run_syncrF)rr%rr~ ImportErrorr$s r!rrs)6LN## s  &&c0trtjSyr)rrr-r"r!rrs'''r"cNKtrtjd{yy7w)NTF)rrr-r"r!wait_for_streaming_readyr)s#.... /s %#%)r6zdict[str, Any]r{r r})rrr{r$rzr)rrrr~r{r) r!rrCryrrrr#rr$r{r)r{z bool | None)r7s"H# %% (&($   + X*+YY  'I ' m  M Ad",,dN__DhbllhXRI9&* ")(A(C \ "HH"!!&.>bF F+/FFR3& 3& 3&3&& 3& ( 3&  3&l&r"PK!Rh66emscripten/request.pynu[from __future__ import annotations from dataclasses import dataclass, field from ..._base_connection import _TYPE_BODY @dataclass class EmscriptenRequest: method: str url: str params: dict[str, str] | None = None body: _TYPE_BODY | None = None headers: dict[str, str] = field(default_factory=dict) timeout: float = 0 decode_content: bool = True def set_header(self, name: str, value: str) -> None: self.headers[name.capitalize()] = value def set_body(self, body: _TYPE_BODY | None) -> None: self.body = body PK!KGG%emscripten/emscripten_fetch_worker.jsnu[let Status = { SUCCESS_HEADER: -1, SUCCESS_EOF: -2, ERROR_TIMEOUT: -3, ERROR_EXCEPTION: -4, }; let connections = {}; let nextConnectionID = 1; const encoder = new TextEncoder(); self.addEventListener("message", async function (event) { if (event.data.close) { let connectionID = event.data.close; delete connections[connectionID]; return; } else if (event.data.getMore) { let connectionID = event.data.getMore; let { curOffset, value, reader, intBuffer, byteBuffer } = connections[connectionID]; // if we still have some in buffer, then just send it back straight away if (!value || curOffset >= value.length) { // read another buffer if required try { let readResponse = await reader.read(); if (readResponse.done) { // read everything - clear connection and return delete connections[connectionID]; Atomics.store(intBuffer, 0, Status.SUCCESS_EOF); Atomics.notify(intBuffer, 0); // finished reading successfully // return from event handler return; } curOffset = 0; connections[connectionID].value = readResponse.value; value = readResponse.value; } catch (error) { console.log("Request exception:", error); let errorBytes = encoder.encode(error.message); let written = errorBytes.length; byteBuffer.set(errorBytes); intBuffer[1] = written; Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); Atomics.notify(intBuffer, 0); } } // send as much buffer as we can let curLen = value.length - curOffset; if (curLen > byteBuffer.length) { curLen = byteBuffer.length; } byteBuffer.set(value.subarray(curOffset, curOffset + curLen), 0); Atomics.store(intBuffer, 0, curLen); // store current length in bytes Atomics.notify(intBuffer, 0); curOffset += curLen; connections[connectionID].curOffset = curOffset; return; } else { // start fetch let connectionID = nextConnectionID; nextConnectionID += 1; const intBuffer = new Int32Array(event.data.buffer); const byteBuffer = new Uint8Array(event.data.buffer, 8); try { const response = await fetch(event.data.url, event.data.fetchParams); // return the headers first via textencoder var headers = []; for (const pair of response.headers.entries()) { headers.push([pair[0], pair[1]]); } let headerObj = { headers: headers, status: response.status, connectionID, }; const headerText = JSON.stringify(headerObj); let headerBytes = encoder.encode(headerText); let written = headerBytes.length; byteBuffer.set(headerBytes); intBuffer[1] = written; // make a connection connections[connectionID] = { reader: response.body.getReader(), intBuffer: intBuffer, byteBuffer: byteBuffer, value: undefined, curOffset: 0, }; // set header ready Atomics.store(intBuffer, 0, Status.SUCCESS_HEADER); Atomics.notify(intBuffer, 0); // all fetching after this goes through a new postmessage call with getMore // this allows for parallel requests } catch (error) { console.log("Request exception:", error); let errorBytes = encoder.encode(error.message); let written = errorBytes.length; byteBuffer.set(errorBytes); intBuffer[1] = written; Atomics.store(intBuffer, 0, Status.ERROR_EXCEPTION); Atomics.notify(intBuffer, 0); } } }); self.postMessage({ inited: true }); PK!1C"C"emscripten/connection.pynu[from __future__ import annotations import os import typing # use http.client.HTTPException for consistency with non-emscripten from http.client import HTTPException as HTTPException # noqa: F401 from http.client import ResponseNotReady from ..._base_connection import _TYPE_BODY from ...connection import HTTPConnection, ProxyConfig, port_by_scheme from ...exceptions import TimeoutError from ...response import BaseHTTPResponse from ...util.connection import _TYPE_SOCKET_OPTIONS from ...util.timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT from ...util.url import Url from .fetch import _RequestError, _TimeoutError, send_request, send_streaming_request from .request import EmscriptenRequest from .response import EmscriptenHttpResponseWrapper, EmscriptenResponse if typing.TYPE_CHECKING: from ..._base_connection import BaseHTTPConnection, BaseHTTPSConnection class EmscriptenHTTPConnection: default_port: typing.ClassVar[int] = port_by_scheme["http"] default_socket_options: typing.ClassVar[_TYPE_SOCKET_OPTIONS] timeout: None | (float) host: str port: int blocksize: int source_address: tuple[str, int] | None socket_options: _TYPE_SOCKET_OPTIONS | None proxy: Url | None proxy_config: ProxyConfig | None is_verified: bool = False proxy_is_verified: bool | None = None _response: EmscriptenResponse | None def __init__( self, host: str, port: int = 0, *, timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, source_address: tuple[str, int] | None = None, blocksize: int = 8192, socket_options: _TYPE_SOCKET_OPTIONS | None = None, proxy: Url | None = None, proxy_config: ProxyConfig | None = None, ) -> None: self.host = host self.port = port self.timeout = timeout if isinstance(timeout, float) else 0.0 self.scheme = "http" self._closed = True self._response = None # ignore these things because we don't # have control over that stuff self.proxy = None self.proxy_config = None self.blocksize = blocksize self.source_address = None self.socket_options = None self.is_verified = False def set_tunnel( self, host: str, port: int | None = 0, headers: typing.Mapping[str, str] | None = None, scheme: str = "http", ) -> None: pass def connect(self) -> None: pass def request( self, method: str, url: str, body: _TYPE_BODY | None = None, headers: typing.Mapping[str, str] | None = None, # We know *at least* botocore is depending on the order of the # first 3 parameters so to be safe we only mark the later ones # as keyword-only to ensure we have space to extend. *, chunked: bool = False, preload_content: bool = True, decode_content: bool = True, enforce_content_length: bool = True, ) -> None: self._closed = False if url.startswith("/"): # no scheme / host / port included, make a full url url = f"{self.scheme}://{self.host}:{self.port}" + url request = EmscriptenRequest( url=url, method=method, timeout=self.timeout if self.timeout else 0, decode_content=decode_content, ) request.set_body(body) if headers: for k, v in headers.items(): request.set_header(k, v) self._response = None try: if not preload_content: self._response = send_streaming_request(request) if self._response is None: self._response = send_request(request) except _TimeoutError as e: raise TimeoutError(e.message) from e except _RequestError as e: raise HTTPException(e.message) from e def getresponse(self) -> BaseHTTPResponse: if self._response is not None: return EmscriptenHttpResponseWrapper( internal_response=self._response, url=self._response.request.url, connection=self, ) else: raise ResponseNotReady() def close(self) -> None: self._closed = True self._response = None @property def is_closed(self) -> bool: """Whether the connection either is brand new or has been previously closed. If this property is True then both ``is_connected`` and ``has_connected_to_proxy`` properties must be False. """ return self._closed @property def is_connected(self) -> bool: """Whether the connection is actively connected to any origin (proxy or target)""" return True @property def has_connected_to_proxy(self) -> bool: """Whether the connection has successfully connected to its proxy. This returns False if no proxy is in use. Used to determine whether errors are coming from the proxy layer or from tunnelling to the target origin. """ return False class EmscriptenHTTPSConnection(EmscriptenHTTPConnection): default_port = port_by_scheme["https"] # all this is basically ignored, as browser handles https cert_reqs: int | str | None = None ca_certs: str | None = None ca_cert_dir: str | None = None ca_cert_data: None | str | bytes = None cert_file: str | None key_file: str | None key_password: str | None ssl_context: typing.Any | None ssl_version: int | str | None = None ssl_minimum_version: int | None = None ssl_maximum_version: int | None = None assert_hostname: None | str | typing.Literal[False] assert_fingerprint: str | None = None def __init__( self, host: str, port: int = 0, *, timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT, source_address: tuple[str, int] | None = None, blocksize: int = 16384, socket_options: ( None | _TYPE_SOCKET_OPTIONS ) = HTTPConnection.default_socket_options, proxy: Url | None = None, proxy_config: ProxyConfig | None = None, cert_reqs: int | str | None = None, assert_hostname: None | str | typing.Literal[False] = None, assert_fingerprint: str | None = None, server_hostname: str | None = None, ssl_context: typing.Any | None = None, ca_certs: str | None = None, ca_cert_dir: str | None = None, ca_cert_data: None | str | bytes = None, ssl_minimum_version: int | None = None, ssl_maximum_version: int | None = None, ssl_version: int | str | None = None, # Deprecated cert_file: str | None = None, key_file: str | None = None, key_password: str | None = None, ) -> None: super().__init__( host, port=port, timeout=timeout, source_address=source_address, blocksize=blocksize, socket_options=socket_options, proxy=proxy, proxy_config=proxy_config, ) self.scheme = "https" self.key_file = key_file self.cert_file = cert_file self.key_password = key_password self.ssl_context = ssl_context self.server_hostname = server_hostname self.assert_hostname = assert_hostname self.assert_fingerprint = assert_fingerprint self.ssl_version = ssl_version self.ssl_minimum_version = ssl_minimum_version self.ssl_maximum_version = ssl_maximum_version self.ca_certs = ca_certs and os.path.expanduser(ca_certs) self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir) self.ca_cert_data = ca_cert_data self.cert_reqs = None # The browser will automatically verify all requests. # We have no control over that setting. self.is_verified = True def set_cert( self, key_file: str | None = None, cert_file: str | None = None, cert_reqs: int | str | None = None, key_password: str | None = None, ca_certs: str | None = None, assert_hostname: None | str | typing.Literal[False] = None, assert_fingerprint: str | None = None, ca_cert_dir: str | None = None, ca_cert_data: None | str | bytes = None, ) -> None: pass # verify that this class implements BaseHTTP(s) connection correctly if typing.TYPE_CHECKING: _supports_http_protocol: BaseHTTPConnection = EmscriptenHTTPConnection("", 0) _supports_https_protocol: BaseHTTPSConnection = EmscriptenHTTPSConnection("", 0) PK!nSYSYemscripten/fetch.pynu[""" Support for streaming http requests in emscripten. A few caveats - If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md *and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case timeouts and streaming should just work. Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming. This approach has several caveats: Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed. Streaming only works if you're running pyodide in a web worker. Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch operation, so it requires that you have crossOriginIsolation enabled, by serving over https (or from localhost) with the two headers below set: Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole request into a buffer and then returning it. it shows a warning in the JavaScript console in this case. Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch. NB: in this code, there are a lot of JavaScript objects. They are named js_* to make it clear what type of object they are. """ from __future__ import annotations import io import json from email.parser import Parser from importlib.resources import files from typing import TYPE_CHECKING, Any import js # type: ignore[import-not-found] from pyodide.ffi import ( # type: ignore[import-not-found] JsArray, JsException, JsProxy, to_js, ) if TYPE_CHECKING: from typing_extensions import Buffer from .request import EmscriptenRequest from .response import EmscriptenResponse """ There are some headers that trigger unintended CORS preflight requests. See also https://github.com/koenvo/pyodide-http/issues/22 """ HEADERS_TO_IGNORE = ("user-agent",) SUCCESS_HEADER = -1 SUCCESS_EOF = -2 ERROR_TIMEOUT = -3 ERROR_EXCEPTION = -4 _STREAMING_WORKER_CODE = ( files(__package__) .joinpath("emscripten_fetch_worker.js") .read_text(encoding="utf-8") ) class _RequestError(Exception): def __init__( self, message: str | None = None, *, request: EmscriptenRequest | None = None, response: EmscriptenResponse | None = None, ): self.request = request self.response = response self.message = message super().__init__(self.message) class _StreamingError(_RequestError): pass class _TimeoutError(_RequestError): pass def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy: return to_js(dict_val, dict_converter=js.Object.fromEntries) class _ReadStream(io.RawIOBase): def __init__( self, int_buffer: JsArray, byte_buffer: JsArray, timeout: float, worker: JsProxy, connection_id: int, request: EmscriptenRequest, ): self.int_buffer = int_buffer self.byte_buffer = byte_buffer self.read_pos = 0 self.read_len = 0 self.connection_id = connection_id self.worker = worker self.timeout = int(1000 * timeout) if timeout > 0 else None self.is_live = True self._is_closed = False self.request: EmscriptenRequest | None = request def __del__(self) -> None: self.close() # this is compatible with _base_connection def is_closed(self) -> bool: return self._is_closed # for compatibility with RawIOBase @property def closed(self) -> bool: return self.is_closed() def close(self) -> None: if self.is_closed(): return self.read_len = 0 self.read_pos = 0 self.int_buffer = None self.byte_buffer = None self._is_closed = True self.request = None if self.is_live: self.worker.postMessage(_obj_from_dict({"close": self.connection_id})) self.is_live = False super().close() def readable(self) -> bool: return True def writable(self) -> bool: return False def seekable(self) -> bool: return False def readinto(self, byte_obj: Buffer) -> int: if not self.int_buffer: raise _StreamingError( "No buffer for stream in _ReadStream.readinto", request=self.request, response=None, ) if self.read_len == 0: # wait for the worker to send something js.Atomics.store(self.int_buffer, 0, ERROR_TIMEOUT) self.worker.postMessage(_obj_from_dict({"getMore": self.connection_id})) if ( js.Atomics.wait(self.int_buffer, 0, ERROR_TIMEOUT, self.timeout) == "timed-out" ): raise _TimeoutError data_len = self.int_buffer[0] if data_len > 0: self.read_len = data_len self.read_pos = 0 elif data_len == ERROR_EXCEPTION: string_len = self.int_buffer[1] # decode the error string js_decoder = js.TextDecoder.new() json_str = js_decoder.decode(self.byte_buffer.slice(0, string_len)) raise _StreamingError( f"Exception thrown in fetch: {json_str}", request=self.request, response=None, ) else: # EOF, free the buffers and return zero # and free the request self.is_live = False self.close() return 0 # copy from int32array to python bytes ret_length = min(self.read_len, len(memoryview(byte_obj))) subarray = self.byte_buffer.subarray( self.read_pos, self.read_pos + ret_length ).to_py() memoryview(byte_obj)[0:ret_length] = subarray self.read_len -= ret_length self.read_pos += ret_length return ret_length class _StreamingFetcher: def __init__(self) -> None: # make web-worker and data buffer on startup self.streaming_ready = False js_data_blob = js.Blob.new( to_js([_STREAMING_WORKER_CODE], create_pyproxies=False), _obj_from_dict({"type": "application/javascript"}), ) def promise_resolver(js_resolve_fn: JsProxy, js_reject_fn: JsProxy) -> None: def onMsg(e: JsProxy) -> None: self.streaming_ready = True js_resolve_fn(e) def onErr(e: JsProxy) -> None: js_reject_fn(e) # Defensive: never happens in ci self.js_worker.onmessage = onMsg self.js_worker.onerror = onErr js_data_url = js.URL.createObjectURL(js_data_blob) self.js_worker = js.globalThis.Worker.new(js_data_url) self.js_worker_ready_promise = js.globalThis.Promise.new(promise_resolver) def send(self, request: EmscriptenRequest) -> EmscriptenResponse: headers = { k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE } body = request.body fetch_data = {"headers": headers, "body": to_js(body), "method": request.method} # start the request off in the worker timeout = int(1000 * request.timeout) if request.timeout > 0 else None js_shared_buffer = js.SharedArrayBuffer.new(1048576) js_int_buffer = js.Int32Array.new(js_shared_buffer) js_byte_buffer = js.Uint8Array.new(js_shared_buffer, 8) js.Atomics.store(js_int_buffer, 0, ERROR_TIMEOUT) js.Atomics.notify(js_int_buffer, 0) js_absolute_url = js.URL.new(request.url, js.location).href self.js_worker.postMessage( _obj_from_dict( { "buffer": js_shared_buffer, "url": js_absolute_url, "fetchParams": fetch_data, } ) ) # wait for the worker to send something js.Atomics.wait(js_int_buffer, 0, ERROR_TIMEOUT, timeout) if js_int_buffer[0] == ERROR_TIMEOUT: raise _TimeoutError( "Timeout connecting to streaming request", request=request, response=None, ) elif js_int_buffer[0] == SUCCESS_HEADER: # got response # header length is in second int of intBuffer string_len = js_int_buffer[1] # decode the rest to a JSON string js_decoder = js.TextDecoder.new() # this does a copy (the slice) because decode can't work on shared array # for some silly reason json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) # get it as an object response_obj = json.loads(json_str) return EmscriptenResponse( request=request, status_code=response_obj["status"], headers=response_obj["headers"], body=_ReadStream( js_int_buffer, js_byte_buffer, request.timeout, self.js_worker, response_obj["connectionID"], request, ), ) elif js_int_buffer[0] == ERROR_EXCEPTION: string_len = js_int_buffer[1] # decode the error string js_decoder = js.TextDecoder.new() json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) raise _StreamingError( f"Exception thrown in fetch: {json_str}", request=request, response=None ) else: raise _StreamingError( f"Unknown status from worker in fetch: {js_int_buffer[0]}", request=request, response=None, ) class _JSPIReadStream(io.RawIOBase): """ A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch response. This requires support for WebAssembly JavaScript Promise Integration in the containing browser, and for pyodide to be launched via runPythonAsync. :param js_read_stream: The JavaScript stream reader :param timeout: Timeout in seconds :param request: The request we're handling :param response: The response this stream relates to :param js_abort_controller: A JavaScript AbortController object, used for timeouts """ def __init__( self, js_read_stream: Any, timeout: float, request: EmscriptenRequest, response: EmscriptenResponse, js_abort_controller: Any, # JavaScript AbortController for timeouts ): self.js_read_stream = js_read_stream self.timeout = timeout self._is_closed = False self._is_done = False self.request: EmscriptenRequest | None = request self.response: EmscriptenResponse | None = response self.current_buffer = None self.current_buffer_pos = 0 self.js_abort_controller = js_abort_controller def __del__(self) -> None: self.close() # this is compatible with _base_connection def is_closed(self) -> bool: return self._is_closed # for compatibility with RawIOBase @property def closed(self) -> bool: return self.is_closed() def close(self) -> None: if self.is_closed(): return self.read_len = 0 self.read_pos = 0 self.js_read_stream.cancel() self.js_read_stream = None self._is_closed = True self._is_done = True self.request = None self.response = None super().close() def readable(self) -> bool: return True def writable(self) -> bool: return False def seekable(self) -> bool: return False def _get_next_buffer(self) -> bool: result_js = _run_sync_with_timeout( self.js_read_stream.read(), self.timeout, self.js_abort_controller, request=self.request, response=self.response, ) if result_js.done: self._is_done = True return False else: self.current_buffer = result_js.value.to_py() self.current_buffer_pos = 0 return True def readinto(self, byte_obj: Buffer) -> int: if self.current_buffer is None: if not self._get_next_buffer() or self.current_buffer is None: self.close() return 0 ret_length = min( len(byte_obj), len(self.current_buffer) - self.current_buffer_pos ) byte_obj[0:ret_length] = self.current_buffer[ self.current_buffer_pos : self.current_buffer_pos + ret_length ] self.current_buffer_pos += ret_length if self.current_buffer_pos == len(self.current_buffer): self.current_buffer = None return ret_length # check if we are in a worker or not def is_in_browser_main_thread() -> bool: return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window def is_cross_origin_isolated() -> bool: return hasattr(js, "crossOriginIsolated") and js.crossOriginIsolated def is_in_node() -> bool: return ( hasattr(js, "process") and hasattr(js.process, "release") and hasattr(js.process.release, "name") and js.process.release.name == "node" ) def is_worker_available() -> bool: return hasattr(js, "Worker") and hasattr(js, "Blob") _fetcher: _StreamingFetcher | None = None if is_worker_available() and ( (is_cross_origin_isolated() and not is_in_browser_main_thread()) and (not is_in_node()) ): _fetcher = _StreamingFetcher() else: _fetcher = None NODE_JSPI_ERROR = ( "urllib3 only works in Node.js with pyodide.runPythonAsync" " and requires the flag --experimental-wasm-stack-switching in " " versions of node <24." ) def send_streaming_request(request: EmscriptenRequest) -> EmscriptenResponse | None: if has_jspi(): return send_jspi_request(request, True) elif is_in_node(): raise _RequestError( message=NODE_JSPI_ERROR, request=request, response=None, ) if _fetcher and streaming_ready(): return _fetcher.send(request) else: _show_streaming_warning() return None _SHOWN_TIMEOUT_WARNING = False def _show_timeout_warning() -> None: global _SHOWN_TIMEOUT_WARNING if not _SHOWN_TIMEOUT_WARNING: _SHOWN_TIMEOUT_WARNING = True message = "Warning: Timeout is not available on main browser thread" js.console.warn(message) _SHOWN_STREAMING_WARNING = False def _show_streaming_warning() -> None: global _SHOWN_STREAMING_WARNING if not _SHOWN_STREAMING_WARNING: _SHOWN_STREAMING_WARNING = True message = "Can't stream HTTP requests because: \n" if not is_cross_origin_isolated(): message += " Page is not cross-origin isolated\n" if is_in_browser_main_thread(): message += " Python is running in main browser thread\n" if not is_worker_available(): message += " Worker or Blob classes are not available in this environment." # Defensive: this is always False in browsers that we test in if streaming_ready() is False: message += """ Streaming fetch worker isn't ready. If you want to be sure that streaming fetch is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`""" from js import console console.warn(message) def send_request(request: EmscriptenRequest) -> EmscriptenResponse: if has_jspi(): return send_jspi_request(request, False) elif is_in_node(): raise _RequestError( message=NODE_JSPI_ERROR, request=request, response=None, ) try: js_xhr = js.XMLHttpRequest.new() if not is_in_browser_main_thread(): js_xhr.responseType = "arraybuffer" if request.timeout: js_xhr.timeout = int(request.timeout * 1000) else: js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15") if request.timeout: # timeout isn't available on the main thread - show a warning in console # if it is set _show_timeout_warning() js_xhr.open(request.method, request.url, False) for name, value in request.headers.items(): if name.lower() not in HEADERS_TO_IGNORE: js_xhr.setRequestHeader(name, value) js_xhr.send(to_js(request.body)) headers = dict(Parser().parsestr(js_xhr.getAllResponseHeaders())) if not is_in_browser_main_thread(): body = js_xhr.response.to_py().tobytes() else: body = js_xhr.response.encode("ISO-8859-15") return EmscriptenResponse( status_code=js_xhr.status, headers=headers, body=body, request=request ) except JsException as err: if err.name == "TimeoutError": raise _TimeoutError(err.message, request=request) elif err.name == "NetworkError": raise _RequestError(err.message, request=request) else: # general http error raise _RequestError(err.message, request=request) def send_jspi_request( request: EmscriptenRequest, streaming: bool ) -> EmscriptenResponse: """ Send a request using WebAssembly JavaScript Promise Integration to wrap the asynchronous JavaScript fetch api (experimental). :param request: Request to send :param streaming: Whether to stream the response :return: The response object :rtype: EmscriptenResponse """ timeout = request.timeout js_abort_controller = js.AbortController.new() headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE} req_body = request.body fetch_data = { "headers": headers, "body": to_js(req_body), "method": request.method, "signal": js_abort_controller.signal, } # Call JavaScript fetch (async api, returns a promise) fetcher_promise_js = js.fetch(request.url, _obj_from_dict(fetch_data)) # Now suspend WebAssembly until we resolve that promise # or time out. response_js = _run_sync_with_timeout( fetcher_promise_js, timeout, js_abort_controller, request=request, response=None, ) headers = {} header_iter = response_js.headers.entries() while True: iter_value_js = header_iter.next() if getattr(iter_value_js, "done", False): break else: headers[str(iter_value_js.value[0])] = str(iter_value_js.value[1]) status_code = response_js.status body: bytes | io.RawIOBase = b"" response = EmscriptenResponse( status_code=status_code, headers=headers, body=b"", request=request ) if streaming: # get via inputstream if response_js.body is not None: # get a reader from the fetch response body_stream_js = response_js.body.getReader() body = _JSPIReadStream( body_stream_js, timeout, request, response, js_abort_controller ) else: # get directly via arraybuffer # n.b. this is another async JavaScript call. body = _run_sync_with_timeout( response_js.arrayBuffer(), timeout, js_abort_controller, request=request, response=response, ).to_py() response.body = body return response def _run_sync_with_timeout( promise: Any, timeout: float, js_abort_controller: Any, request: EmscriptenRequest | None, response: EmscriptenResponse | None, ) -> Any: """ Await a JavaScript promise synchronously with a timeout which is implemented via the AbortController :param promise: Javascript promise to await :param timeout: Timeout in seconds :param js_abort_controller: A JavaScript AbortController object, used on timeout :param request: The request being handled :param response: The response being handled (if it exists yet) :raises _TimeoutError: If the request times out :raises _RequestError: If the request raises a JavaScript exception :return: The result of awaiting the promise. """ timer_id = None if timeout > 0: timer_id = js.setTimeout( js_abort_controller.abort.bind(js_abort_controller), int(timeout * 1000) ) try: from pyodide.ffi import run_sync # run_sync here uses WebAssembly JavaScript Promise Integration to # suspend python until the JavaScript promise resolves. return run_sync(promise) except JsException as err: if err.name == "AbortError": raise _TimeoutError( message="Request timed out", request=request, response=response ) else: raise _RequestError(message=err.message, request=request, response=response) finally: if timer_id is not None: js.clearTimeout(timer_id) def has_jspi() -> bool: """ Return true if jspi can be used. This requires both browser support and also WebAssembly to be in the correct state - i.e. that the javascript call into python was async not sync. :return: True if jspi can be used. :rtype: bool """ try: from pyodide.ffi import can_run_sync, run_sync # noqa: F401 return bool(can_run_sync()) except ImportError: return False def streaming_ready() -> bool | None: if _fetcher: return _fetcher.streaming_ready else: return None # no fetcher, return None to signify that async def wait_for_streaming_ready() -> bool: if _fetcher: await _fetcher.js_worker_ready_promise return True else: return False PK!`Demscripten/__init__.pynu[from __future__ import annotations import urllib3.connection from ...connectionpool import HTTPConnectionPool, HTTPSConnectionPool from .connection import EmscriptenHTTPConnection, EmscriptenHTTPSConnection def inject_into_urllib3() -> None: # override connection classes to use emscripten specific classes # n.b. mypy complains about the overriding of classes below # if it isn't ignored HTTPConnectionPool.ConnectionCls = EmscriptenHTTPConnection HTTPSConnectionPool.ConnectionCls = EmscriptenHTTPSConnection urllib3.connection.HTTPConnection = EmscriptenHTTPConnection # type: ignore[misc,assignment] urllib3.connection.HTTPSConnection = EmscriptenHTTPSConnection # type: ignore[misc,assignment] PK!Ko_securetransport/__init__.pyonu[ abc@sdS(N((((sY/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/__init__.pyttPK!N$$_securetransport/low_level.pyonu[ abc@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z m Z ej dej ZdZdZdZdd Zd Zd Zd Zd ZdZdZdS(s Low-level helpers for the SecureTransport bindings. These are Python functions that are not directly related to the high-level APIs but are necessary to get them to work. They include a whole bunch of low-level CoreFoundation messing about and memory management. The concerns in this module are almost entirely about trying to avoid memory leaks and providing appropriate and useful assistance to the higher-level code. iNi(tSecuritytCoreFoundationtCFConsts;-----BEGIN CERTIFICATE----- (.*?) -----END CERTIFICATE-----cCstjtj|t|S(sv Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. (Rt CFDataCreatetkCFAllocatorDefaulttlen(t bytestring((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_cf_data_from_bytesscCswt|}d|D}d|D}tj||}tj||}tjtj|||tjtjS(sK Given a list of Python tuples, create an associated CFDictionary. css|]}|dVqdS(iN((t.0tt((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pys ,scss|]}|dVqdS(iN((RR ((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pys -s(RRt CFTypeReftCFDictionaryCreateRtkCFTypeDictionaryKeyCallBackstkCFTypeDictionaryValueCallBacks(ttuplestdictionary_sizetkeystvaluestcf_keyst cf_values((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_cf_dictionary_from_tuples%s cCstj|tjtj}tj|tj}|dkrtj d}tj ||dtj}|s~t dn|j }n|dk r|j d}n|S(s Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. is'Error copying C string from CFStringRefsutf-8N(tctypestcasttPOINTERtc_void_pRtCFStringGetCStringPtrRtkCFStringEncodingUTF8tNonetcreate_string_buffertCFStringGetCStringtOSErrortvaluetdecode(Rtvalue_as_void_ptstringtbuffertresult((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_cf_string_to_unicode;s"     cCs|dkrdStj|d}t|}tj||dksS|dkr`d|}n|dkrxtj}n||dS(s[ Checks the return code and throws an exception if there is an error to report iNuu OSStatus %s(RtSecCopyErrorMessageStringRR%Rt CFReleasetssltSSLError(terrortexception_classtcf_error_stringtoutput((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_assert_no_errorXs      cCs=gtj|D]}tj|jd^q}|sLtjdntjtj dt j tj }|stjdnyx|D]}t |}|stjdntjtj |}tj||stjdntj||tj|qWWntk r8tj|nX|S(s Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. isNo root certificates specifiedisUnable to allocate memory!sUnable to build cert object!(t _PEM_CERTS_REtfinditertbase64t b64decodetgroupR(R)RtCFArrayCreateMutableRRtbyreftkCFTypeArrayCallBacksRRtSecCertificateCreateWithDataR'tCFArrayAppendValuet Exception(t pem_bundletmatcht der_certst cert_arrayt der_bytestcertdatatcert((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_cert_array_from_pemms21    cCstj}tj||kS(s= Returns True if a given CFTypeRef is a certificate. (RtSecCertificateGetTypeIDRt CFGetTypeID(titemtexpected((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_is_certs cCstj}tj||kS(s; Returns True if a given CFTypeRef is an identity. (RtSecIdentityGetTypeIDRRC(RDRE((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt _is_identitys cCstjd}tj|d jd}tj|d}tj}tjj||j d}t j }t j |t ||tdtj|}t|||fS(s This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. i(isutf-8N(tosturandomR1t b64encodeR ttempfiletmkdtemptpathtjointencodeRtSecKeychainReftSecKeychainCreateRtFalseRRR5R.(t random_bytestfilenametpasswordt tempdirectoryt keychain_pathtkeychaintstatus((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_temporary_keychains    c Cskg}g}d}t|d}|j}WdQXztjtj|t|}tj}tj |ddddd|t j |}t |tj |} xt| D]} tj|| } t j| tj} t| r tj| |j| qt| rtj| |j| qqWWd|rStj|ntj|X||fS(s Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. trbNi(RtopentreadRRRRt CFArrayRefRt SecItemImportRR5R.tCFArrayGetCounttrangetCFArrayGetValueAtIndexRR RFtCFRetaintappendRHR'( RYRNt certificatest identitiest result_arraytft raw_filedatatfiledataR$t result_counttindexRD((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_load_items_from_filesH       c GsKg}g}d|D}zx=|D]5}t||\}}|j||j|q&W|stj}tj||dtj|}t||j|t j |j dnt j t j dtjt j} x*tj||D]} t j| | qW| SWdx'tj||D]} t j | q/WXdS(s Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. css|]}|r|VqdS(N((RRN((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pys /siN(RntextendRtSecIdentityReft SecIdentityCreateWithCertificateRR5R.ReRR'tpopR4RR6t itertoolstchainR8( RYtpathsRfRgt file_pathtnew_identitiest new_certst new_identityRZt trust_chainRDtobj((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_load_client_cert_chain s6      (t__doc__R1RRstreRIR(RLtbindingsRRRtcompiletDOTALLR/RRR%RR.RARFRHR[RnR|(((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt s(           +   ( ;PK!y//_securetransport/bindings.pyonu[ abc @@sE dZddlmZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZddlmZmZmZedZesedned Zesed nejdZeeeejd Zedkr+edededfneedeZeedeZ eZ!eZ"e Z#eZ$eZ%eZ&eZ'eZ(eZ)eZ*e Z+ee*Z,eZ-eZ.ee$Z/ee%Z0ee&Z1ee'Z2ee(Z3eZ4eZ5eZ6eeZ7e Z8e Z9eeZ:e Z;eZ<eeZ=e Z>e Z?eeZ@eeZAe ZBe ZCe ZDe ZEe ZFe ZGyze/e0ee8ee9e;ee<e=ee1gejH_Ie.ejH_JgejK_Ie+ejK_JgejL_Ie+ejL_JgejM_Ie+ejM_Je-e/gejN_Ie7ejN_Je7gejO_Ie/ejO_Je.egejP_Ie0ejP_Je,e7ee:gejQ_Ie.ejQ_Je e ee!eee=gejR_Ie.ejR_Je=gejS_Ie.ejS_Je/e3ee1gejT_Ie.ejT_Jee.eBeee ZUee.eBee ee ZVe@eUeVgejW_Ie.ejW_Je@e e gejX_Ie.ejX_Je@e1gejY_Ie.ejY_Je@e,e!gejZ_Ie.ejZ_Je@eBgej[_Ie.ej[_Je@e e gej\_Ie.ej\_Je@gej]_Ie.ej]_Je@e e ee gej^_Ie.ej^_Je@e e ee gej__Ie.ej__Je@gej`_Ie.ej`_Je@ee geja_Ie.eja_Je@ee?ee gejb_Ie.ejb_Je@ee?e gejc_Ie.ejc_Je@ee gejd_ee.ejd_Je@ee?ee gejf_Ie.ejf_Je@ee?gejg_Ie.ejg_Je@ee>gejh_Ie.ejh_Je@eeAgeji_Ie.eji_JeAe1gejj_Ie.ejj_JeAe!gejk_le.ejk_JeAeeCgejm_Ie.ejm_JeAgejn_Ie"ejn_JeAe"gejo_Ie7ejo_Je-eEeFgejp_Ie@ejp_Je@eGe!gejq_Ie.ejq_Je@e>gejr_Ie.ejr_Je@e>gejs_Ie.ejs_Je.egejP_Ie0ejP_JeUe_UeVe_Ve@e_@e>e_>e?e_?e:e_:e=e_=eAe_AeCe_Ce8e_8e.e_.e0jtede_ue0jtede_ve,ge jw_Ie,e jw_Je,ge jx_Ide jx_Je,ge jz_Ie+e jz_Je-e e#ge j{_Ie0e j{_Je0e#ge j|_Ie e j|_Je0e e"e#ge j}_Iee j}_Je-e e"ge j~_Ie/e j~_Je/ge j_Ie"e j_Je/ge j_Iee j_Je-ee,ee,e"e5e6ge j_Ie3e j_Je3e,ge j_Ie,e j_Je-ee,e"e4ge j_Ie1e j_Je-e"e4ge j_Ie2e j_Je2ege j_Ide j_Je1ge j_Ie"e j_Je1e"ge j_Iee j_Je-jte de _ejte de _ejte de _ejte de _e,e _,e1e _1e0e _0e3e _3Wnek r ednXdefdYZdefdYZdS(sy This module uses ctypes to bind a whole bunch of functions and constants from SecureTransport. The goal here is to provide the low-level API to SecureTransport. These are essentially the C-level functions and constants, and they're pretty gross to work with. This code is a bastardised version of the code found in Will Bond's oscrypto library. An enormous debt is owed to him for blazing this trail for us. For that reason, this code should be considered to be covered both by urllib3's license and by oscrypto's: Copyright (c) 2015-2016 Will Bond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. i(tabsolute_importN(t find_library( tc_void_ptc_int32tc_char_ptc_size_ttc_bytetc_uint32tc_ulongtc_longtc_bool(tCDLLtPOINTERt CFUNCTYPEtSecuritys'The library Security could not be foundtCoreFoundations-The library CoreFoundation could not be foundt.i is1Only OS X 10.8 and newer are supported, not %s.%sit use_errnotkSecImportExportPassphrasetkSecImportItemIdentitytkCFAllocatorDefaulttkCFTypeArrayCallBackstkCFTypeDictionaryKeyCallBackstkCFTypeDictionaryValueCallBackssError initializing ctypestCFConstcB@seZdZedZRS(s_ A class object that acts as essentially a namespace for CoreFoundation constants. i(t__name__t __module__t__doc__tCFStringEncodingtkCFStringEncodingUTF8(((sY/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.pyRst SecurityConstcB@seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZd Zd ZdZd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'd Z(d!Z)d"Z*d#Z+d$Z,d%Z-d&Z.d'Z/d(Z0d)Z1d*Z2d+Z3d,Z4d-Z5d.Z6d/Z7d0Z8d1Z9d2Z:d3Z;d4Z<d5Z=d6Z>d7Z?d8Z@d9ZAd:ZBd;ZCd<ZDd=ZEd>ZFd?ZGd@ZHdAZIRS(BsU A class object that acts as essentially a namespace for Security constants. iiiiiii iiiiiiiiiiiiiiiiiiiiii iQi,iRi,i0i+i/iiiii$i(i iikiji9i8i#i'i iigi@i3i2iii=i<i5i/iii(JRRRt"kSSLSessionOptionBreakOnServerAutht kSSLProtocol2t kSSLProtocol3t kTLSProtocol1tkTLSProtocol11tkTLSProtocol12tkSSLClientSidetkSSLStreamTypetkSecFormatPEMSequencetkSecTrustResultInvalidtkSecTrustResultProceedtkSecTrustResultDenytkSecTrustResultUnspecifiedt&kSecTrustResultRecoverableTrustFailuret kSecTrustResultFatalTrustFailuretkSecTrustResultOtherErrorterrSSLProtocolterrSSLWouldBlockterrSSLClosedGracefulterrSSLClosedNoNotifyterrSSLClosedAbortterrSSLXCertChainInvalidt errSSLCryptoterrSSLInternalterrSSLCertExpiredterrSSLCertNotYetValidterrSSLUnknownRootCertterrSSLNoRootCertterrSSLHostNameMismatchterrSSLPeerHandshakeFailterrSSLPeerUserCancelledterrSSLWeakPeerEphemeralDHKeyterrSSLServerAuthCompletedterrSSLRecordOverflowterrSecVerifyFailedterrSecNoTrustSettingsterrSecItemNotFoundterrSecInvalidTrustSettingst'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384t%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384t'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256t%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256t#TLS_DHE_DSS_WITH_AES_256_GCM_SHA384t#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384t#TLS_DHE_DSS_WITH_AES_128_GCM_SHA256t#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256t'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384t%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384t$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAt"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAt#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256t#TLS_DHE_DSS_WITH_AES_256_CBC_SHA256t TLS_DHE_RSA_WITH_AES_256_CBC_SHAt TLS_DHE_DSS_WITH_AES_256_CBC_SHAt'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256t%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256t$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAt"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAt#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256t#TLS_DHE_DSS_WITH_AES_128_CBC_SHA256t TLS_DHE_RSA_WITH_AES_128_CBC_SHAt TLS_DHE_DSS_WITH_AES_128_CBC_SHAtTLS_RSA_WITH_AES_256_GCM_SHA384tTLS_RSA_WITH_AES_128_GCM_SHA256tTLS_RSA_WITH_AES_256_CBC_SHA256tTLS_RSA_WITH_AES_128_CBC_SHA256tTLS_RSA_WITH_AES_256_CBC_SHAtTLS_RSA_WITH_AES_128_CBC_SHAtTLS_AES_128_GCM_SHA256tTLS_AES_256_GCM_SHA384tTLS_CHACHA20_POLY1305_SHA256(((sY/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.pyRs(i i(Rt __future__Rtplatformt ctypes.utilRtctypesRRRRRRRR R R R R t security_patht ImportErrortcore_foundation_pathtmac_vertversionttupletmaptinttsplitt version_infotOSErrortTrueRRtBooleantCFIndexRtCFDatatCFStringtCFArraytCFMutableArrayt CFDictionarytCFErrortCFTypetCFTypeIDt CFTypeReftCFAllocatorReftOSStatust CFDataReft CFStringReft CFArrayReftCFMutableArrayReftCFDictionaryReftCFArrayCallBackstCFDictionaryKeyCallBackstCFDictionaryValueCallBackstSecCertificateReftSecExternalFormattSecExternalItemTypetSecIdentityReftSecItemImportExportFlagst SecItemImportExportKeyParameterstSecKeychainReft SSLProtocoltSSLCipherSuitet SSLContextReft SecTrustReftSSLConnectionReftSecTrustResultTypetSecTrustOptionFlagstSSLProtocolSidetSSLConnectionTypetSSLSessionOptiont SecItemImporttargtypestrestypetSecCertificateGetTypeIDtSecIdentityGetTypeIDtSecKeyGetTypeIDtSecCertificateCreateWithDatatSecCertificateCopyDatatSecCopyErrorMessageStringt SecIdentityCreateWithCertificatetSecKeychainCreatetSecKeychainDeletetSecPKCS12Importt SSLReadFunct SSLWriteFunct SSLSetIOFuncst SSLSetPeerIDtSSLSetCertificatetSSLSetCertificateAuthoritiestSSLSetConnectiontSSLSetPeerDomainNamet SSLHandshaketSSLReadtSSLWritetSSLClosetSSLGetNumberSupportedCipherstSSLGetSupportedCipherstSSLSetEnabledCipherstSSLGetNumberEnabledCipherstargtypetSSLGetEnabledCipherstSSLGetNegotiatedCiphertSSLGetNegotiatedProtocolVersiontSSLCopyPeerTrusttSecTrustSetAnchorCertificatest!SecTrustSetAnchorCertificatesOnlyt argstypestSecTrustEvaluatetSecTrustGetCertificateCounttSecTrustGetCertificateAtIndextSSLCreateContexttSSLSetSessionOptiontSSLSetProtocolVersionMintSSLSetProtocolVersionMaxtin_dllRRtCFRetaint CFReleasetNonet CFGetTypeIDtCFStringCreateWithCStringtCFStringGetCStringPtrtCFStringGetCStringt CFDataCreatetCFDataGetLengthtCFDataGetBytePtrtCFDictionaryCreatetCFDictionaryGetValuet CFArrayCreatetCFArrayCreateMutabletCFArrayAppendValuetCFArrayGetCounttCFArrayGetValueAtIndexRRRRtAttributeErrortobjectRR(((sY/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.pyts, @                               !                                                                  PK!N$$_securetransport/low_level.pycnu[ abc@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z m Z ej dej ZdZdZdZdd Zd Zd Zd Zd ZdZdZdS(s Low-level helpers for the SecureTransport bindings. These are Python functions that are not directly related to the high-level APIs but are necessary to get them to work. They include a whole bunch of low-level CoreFoundation messing about and memory management. The concerns in this module are almost entirely about trying to avoid memory leaks and providing appropriate and useful assistance to the higher-level code. iNi(tSecuritytCoreFoundationtCFConsts;-----BEGIN CERTIFICATE----- (.*?) -----END CERTIFICATE-----cCstjtj|t|S(sv Given a bytestring, create a CFData object from it. This CFData object must be CFReleased by the caller. (Rt CFDataCreatetkCFAllocatorDefaulttlen(t bytestring((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_cf_data_from_bytesscCswt|}d|D}d|D}tj||}tj||}tjtj|||tjtjS(sK Given a list of Python tuples, create an associated CFDictionary. css|]}|dVqdS(iN((t.0tt((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pys ,scss|]}|dVqdS(iN((RR ((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pys -s(RRt CFTypeReftCFDictionaryCreateRtkCFTypeDictionaryKeyCallBackstkCFTypeDictionaryValueCallBacks(ttuplestdictionary_sizetkeystvaluestcf_keyst cf_values((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_cf_dictionary_from_tuples%s cCstj|tjtj}tj|tj}|dkrtj d}tj ||dtj}|s~t dn|j }n|dk r|j d}n|S(s Creates a Unicode string from a CFString object. Used entirely for error reporting. Yes, it annoys me quite a lot that this function is this complex. is'Error copying C string from CFStringRefsutf-8N(tctypestcasttPOINTERtc_void_pRtCFStringGetCStringPtrRtkCFStringEncodingUTF8tNonetcreate_string_buffertCFStringGetCStringtOSErrortvaluetdecode(Rtvalue_as_void_ptstringtbuffertresult((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_cf_string_to_unicode;s"     cCs|dkrdStj|d}t|}tj||dksS|dkr`d|}n|dkrxtj}n||dS(s[ Checks the return code and throws an exception if there is an error to report iNuu OSStatus %s(RtSecCopyErrorMessageStringRR%Rt CFReleasetssltSSLError(terrortexception_classtcf_error_stringtoutput((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_assert_no_errorXs      cCs=gtj|D]}tj|jd^q}|sLtjdntjtj dt j tj }|stjdnyx|D]}t |}|stjdntjtj |}tj||stjdntj||tj|qWWntk r8tj|nX|S(s Given a bundle of certs in PEM format, turns them into a CFArray of certs that can be used to validate a cert chain. isNo root certificates specifiedisUnable to allocate memory!sUnable to build cert object!(t _PEM_CERTS_REtfinditertbase64t b64decodetgroupR(R)RtCFArrayCreateMutableRRtbyreftkCFTypeArrayCallBacksRRtSecCertificateCreateWithDataR'tCFArrayAppendValuet Exception(t pem_bundletmatcht der_certst cert_arrayt der_bytestcertdatatcert((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_cert_array_from_pemms21    cCstj}tj||kS(s= Returns True if a given CFTypeRef is a certificate. (RtSecCertificateGetTypeIDRt CFGetTypeID(titemtexpected((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_is_certs cCstj}tj||kS(s; Returns True if a given CFTypeRef is an identity. (RtSecIdentityGetTypeIDRRC(RDRE((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt _is_identitys cCstjd}tj|d jd}tj|d}tj}tjj||j d}t j }t j |t ||tdtj|}t|||fS(s This function creates a temporary Mac keychain that we can use to work with credentials. This keychain uses a one-time password and a temporary file to store the data. We expect to have one keychain per socket. The returned SecKeychainRef must be freed by the caller, including calling SecKeychainDelete. Returns a tuple of the SecKeychainRef and the path to the temporary directory that contains it. i(isutf-8N(tosturandomR1t b64encodeR ttempfiletmkdtemptpathtjointencodeRtSecKeychainReftSecKeychainCreateRtFalseRRR5R.(t random_bytestfilenametpasswordt tempdirectoryt keychain_pathtkeychaintstatus((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_temporary_keychains    c Cskg}g}d}t|d}|j}WdQXztjtj|t|}tj}tj |ddddd|t j |}t |tj |} xt| D]} tj|| } t j| tj} t| r tj| |j| qt| rtj| |j| qqWWd|rStj|ntj|X||fS(s Given a single file, loads all the trust objects from it into arrays and the keychain. Returns a tuple of lists: the first list is a list of identities, the second a list of certs. trbNi(RtopentreadRRRRt CFArrayRefRt SecItemImportRR5R.tCFArrayGetCounttrangetCFArrayGetValueAtIndexRR RFtCFRetaintappendRHR'( RYRNt certificatest identitiest result_arraytft raw_filedatatfiledataR$t result_counttindexRD((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_load_items_from_filesH       c GsKg}g}d|D}zx=|D]5}t||\}}|j||j|q&W|stj}tj||dtj|}t||j|t j |j dnt j t j dtjt j} x*tj||D]} t j| | qW| SWdx'tj||D]} t j | q/WXdS(s Load certificates and maybe keys from a number of files. Has the end goal of returning a CFArray containing one SecIdentityRef, and then zero or more SecCertificateRef objects, suitable for use as a client certificate trust chain. css|]}|r|VqdS(N((RRN((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pys /siN(RntextendRtSecIdentityReft SecIdentityCreateWithCertificateRR5R.ReRR'tpopR4RR6t itertoolstchainR8( RYtpathsRfRgt file_pathtnew_identitiest new_certst new_identityRZt trust_chainRDtobj((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt_load_client_cert_chain s6      (t__doc__R1RRstreRIR(RLtbindingsRRRtcompiletDOTALLR/RRR%RR.RARFRHR[RnR|(((sZ/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.pyt s(           +   ( ;PK!y//_securetransport/bindings.pycnu[ abc @@sE dZddlmZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZddlmZmZmZedZesedned Zesed nejdZeeeejd Zedkr+edededfneedeZeedeZ eZ!eZ"e Z#eZ$eZ%eZ&eZ'eZ(eZ)eZ*e Z+ee*Z,eZ-eZ.ee$Z/ee%Z0ee&Z1ee'Z2ee(Z3eZ4eZ5eZ6eeZ7e Z8e Z9eeZ:e Z;eZ<eeZ=e Z>e Z?eeZ@eeZAe ZBe ZCe ZDe ZEe ZFe ZGyze/e0ee8ee9e;ee<e=ee1gejH_Ie.ejH_JgejK_Ie+ejK_JgejL_Ie+ejL_JgejM_Ie+ejM_Je-e/gejN_Ie7ejN_Je7gejO_Ie/ejO_Je.egejP_Ie0ejP_Je,e7ee:gejQ_Ie.ejQ_Je e ee!eee=gejR_Ie.ejR_Je=gejS_Ie.ejS_Je/e3ee1gejT_Ie.ejT_Jee.eBeee ZUee.eBee ee ZVe@eUeVgejW_Ie.ejW_Je@e e gejX_Ie.ejX_Je@e1gejY_Ie.ejY_Je@e,e!gejZ_Ie.ejZ_Je@eBgej[_Ie.ej[_Je@e e gej\_Ie.ej\_Je@gej]_Ie.ej]_Je@e e ee gej^_Ie.ej^_Je@e e ee gej__Ie.ej__Je@gej`_Ie.ej`_Je@ee geja_Ie.eja_Je@ee?ee gejb_Ie.ejb_Je@ee?e gejc_Ie.ejc_Je@ee gejd_ee.ejd_Je@ee?ee gejf_Ie.ejf_Je@ee?gejg_Ie.ejg_Je@ee>gejh_Ie.ejh_Je@eeAgeji_Ie.eji_JeAe1gejj_Ie.ejj_JeAe!gejk_le.ejk_JeAeeCgejm_Ie.ejm_JeAgejn_Ie"ejn_JeAe"gejo_Ie7ejo_Je-eEeFgejp_Ie@ejp_Je@eGe!gejq_Ie.ejq_Je@e>gejr_Ie.ejr_Je@e>gejs_Ie.ejs_Je.egejP_Ie0ejP_JeUe_UeVe_Ve@e_@e>e_>e?e_?e:e_:e=e_=eAe_AeCe_Ce8e_8e.e_.e0jtede_ue0jtede_ve,ge jw_Ie,e jw_Je,ge jx_Ide jx_Je,ge jz_Ie+e jz_Je-e e#ge j{_Ie0e j{_Je0e#ge j|_Ie e j|_Je0e e"e#ge j}_Iee j}_Je-e e"ge j~_Ie/e j~_Je/ge j_Ie"e j_Je/ge j_Iee j_Je-ee,ee,e"e5e6ge j_Ie3e j_Je3e,ge j_Ie,e j_Je-ee,e"e4ge j_Ie1e j_Je-e"e4ge j_Ie2e j_Je2ege j_Ide j_Je1ge j_Ie"e j_Je1e"ge j_Iee j_Je-jte de _ejte de _ejte de _ejte de _e,e _,e1e _1e0e _0e3e _3Wnek r ednXdefdYZdefdYZdS(sy This module uses ctypes to bind a whole bunch of functions and constants from SecureTransport. The goal here is to provide the low-level API to SecureTransport. These are essentially the C-level functions and constants, and they're pretty gross to work with. This code is a bastardised version of the code found in Will Bond's oscrypto library. An enormous debt is owed to him for blazing this trail for us. For that reason, this code should be considered to be covered both by urllib3's license and by oscrypto's: Copyright (c) 2015-2016 Will Bond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. i(tabsolute_importN(t find_library( tc_void_ptc_int32tc_char_ptc_size_ttc_bytetc_uint32tc_ulongtc_longtc_bool(tCDLLtPOINTERt CFUNCTYPEtSecuritys'The library Security could not be foundtCoreFoundations-The library CoreFoundation could not be foundt.i is1Only OS X 10.8 and newer are supported, not %s.%sit use_errnotkSecImportExportPassphrasetkSecImportItemIdentitytkCFAllocatorDefaulttkCFTypeArrayCallBackstkCFTypeDictionaryKeyCallBackstkCFTypeDictionaryValueCallBackssError initializing ctypestCFConstcB@seZdZedZRS(s_ A class object that acts as essentially a namespace for CoreFoundation constants. i(t__name__t __module__t__doc__tCFStringEncodingtkCFStringEncodingUTF8(((sY/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.pyRst SecurityConstcB@seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZd Zd ZdZd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'd Z(d!Z)d"Z*d#Z+d$Z,d%Z-d&Z.d'Z/d(Z0d)Z1d*Z2d+Z3d,Z4d-Z5d.Z6d/Z7d0Z8d1Z9d2Z:d3Z;d4Z<d5Z=d6Z>d7Z?d8Z@d9ZAd:ZBd;ZCd<ZDd=ZEd>ZFd?ZGd@ZHdAZIRS(BsU A class object that acts as essentially a namespace for Security constants. iiiiiii iiiiiiiiiiiiiiiiiiiiii iQi,iRi,i0i+i/iiiii$i(i iikiji9i8i#i'i iigi@i3i2iii=i<i5i/iii(JRRRt"kSSLSessionOptionBreakOnServerAutht kSSLProtocol2t kSSLProtocol3t kTLSProtocol1tkTLSProtocol11tkTLSProtocol12tkSSLClientSidetkSSLStreamTypetkSecFormatPEMSequencetkSecTrustResultInvalidtkSecTrustResultProceedtkSecTrustResultDenytkSecTrustResultUnspecifiedt&kSecTrustResultRecoverableTrustFailuret kSecTrustResultFatalTrustFailuretkSecTrustResultOtherErrorterrSSLProtocolterrSSLWouldBlockterrSSLClosedGracefulterrSSLClosedNoNotifyterrSSLClosedAbortterrSSLXCertChainInvalidt errSSLCryptoterrSSLInternalterrSSLCertExpiredterrSSLCertNotYetValidterrSSLUnknownRootCertterrSSLNoRootCertterrSSLHostNameMismatchterrSSLPeerHandshakeFailterrSSLPeerUserCancelledterrSSLWeakPeerEphemeralDHKeyterrSSLServerAuthCompletedterrSSLRecordOverflowterrSecVerifyFailedterrSecNoTrustSettingsterrSecItemNotFoundterrSecInvalidTrustSettingst'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384t%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384t'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256t%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256t#TLS_DHE_DSS_WITH_AES_256_GCM_SHA384t#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384t#TLS_DHE_DSS_WITH_AES_128_GCM_SHA256t#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256t'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384t%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384t$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAt"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAt#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256t#TLS_DHE_DSS_WITH_AES_256_CBC_SHA256t TLS_DHE_RSA_WITH_AES_256_CBC_SHAt TLS_DHE_DSS_WITH_AES_256_CBC_SHAt'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256t%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256t$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAt"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAt#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256t#TLS_DHE_DSS_WITH_AES_128_CBC_SHA256t TLS_DHE_RSA_WITH_AES_128_CBC_SHAt TLS_DHE_DSS_WITH_AES_128_CBC_SHAtTLS_RSA_WITH_AES_256_GCM_SHA384tTLS_RSA_WITH_AES_128_GCM_SHA256tTLS_RSA_WITH_AES_256_CBC_SHA256tTLS_RSA_WITH_AES_128_CBC_SHA256tTLS_RSA_WITH_AES_256_CBC_SHAtTLS_RSA_WITH_AES_128_CBC_SHAtTLS_AES_128_GCM_SHA256tTLS_AES_256_GCM_SHA384tTLS_CHACHA20_POLY1305_SHA256(((sY/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.pyRs(i i(Rt __future__Rtplatformt ctypes.utilRtctypesRRRRRRRR R R R R t security_patht ImportErrortcore_foundation_pathtmac_vertversionttupletmaptinttsplitt version_infotOSErrortTrueRRtBooleantCFIndexRtCFDatatCFStringtCFArraytCFMutableArrayt CFDictionarytCFErrortCFTypetCFTypeIDt CFTypeReftCFAllocatorReftOSStatust CFDataReft CFStringReft CFArrayReftCFMutableArrayReftCFDictionaryReftCFArrayCallBackstCFDictionaryKeyCallBackstCFDictionaryValueCallBackstSecCertificateReftSecExternalFormattSecExternalItemTypetSecIdentityReftSecItemImportExportFlagst SecItemImportExportKeyParameterstSecKeychainReft SSLProtocoltSSLCipherSuitet SSLContextReft SecTrustReftSSLConnectionReftSecTrustResultTypetSecTrustOptionFlagstSSLProtocolSidetSSLConnectionTypetSSLSessionOptiont SecItemImporttargtypestrestypetSecCertificateGetTypeIDtSecIdentityGetTypeIDtSecKeyGetTypeIDtSecCertificateCreateWithDatatSecCertificateCopyDatatSecCopyErrorMessageStringt SecIdentityCreateWithCertificatetSecKeychainCreatetSecKeychainDeletetSecPKCS12Importt SSLReadFunct SSLWriteFunct SSLSetIOFuncst SSLSetPeerIDtSSLSetCertificatetSSLSetCertificateAuthoritiestSSLSetConnectiontSSLSetPeerDomainNamet SSLHandshaketSSLReadtSSLWritetSSLClosetSSLGetNumberSupportedCipherstSSLGetSupportedCipherstSSLSetEnabledCipherstSSLGetNumberEnabledCipherstargtypetSSLGetEnabledCipherstSSLGetNegotiatedCiphertSSLGetNegotiatedProtocolVersiontSSLCopyPeerTrusttSecTrustSetAnchorCertificatest!SecTrustSetAnchorCertificatesOnlyt argstypestSecTrustEvaluatetSecTrustGetCertificateCounttSecTrustGetCertificateAtIndextSSLCreateContexttSSLSetSessionOptiontSSLSetProtocolVersionMintSSLSetProtocolVersionMaxtin_dllRRtCFRetaint CFReleasetNonet CFGetTypeIDtCFStringCreateWithCStringtCFStringGetCStringPtrtCFStringGetCStringt CFDataCreatetCFDataGetLengthtCFDataGetBytePtrtCFDictionaryCreatetCFDictionaryGetValuet CFArrayCreatetCFArrayCreateMutabletCFArrayAppendValuetCFArrayGetCounttCFArrayGetValueAtIndexRRRRtAttributeErrortobjectRR(((sY/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.pyts, @                               !                                                                  PK!Ko_securetransport/__init__.pycnu[ abc@sdS(N((((sY/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/__init__.pyttPK!oe __init__.pyonu[ abc@sdS(N((((sH/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/__init__.pyttPK!GۇDD pyopenssl.pyonu[ abc@@sdZddlmZddlZddlmZddlmZ ddl m Z ddl m Z mZddlmZydd l mZWn'ek rdZd d lmZnXddlZddlZd d lmZddlZd d lmZddgZeZ iej!j"ej#6ej!j$ej%6Z&e'edrie'ej!driej!j(e&ej)ej?e@ZAdZBdZCdZDdZEdZFdeGfdYZHerddZIneZIeIeH_IdeGfd YZJd!ZKdS("sb SSL with SNI_-support for Python 2. Follow these instructions if you would like to verify SSL certificates in Python 2. Note, the default libraries do *not* do certificate checking; you need to do additional work to validate certificates yourself. This needs the following packages installed: * pyOpenSSL (tested with 16.0.0) * cryptography (minimum 1.3.4, from pyopenssl) * idna (minimum 2.0, from cryptography) However, pyopenssl depends on cryptography, which depends on idna, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. Activating this module also has the positive side effect of disabling SSL/TLS compression in Python 2 (see `CRIME attack`_). If you want to configure the default list of supported cipher suites, you can set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit) i(tabsolute_importN(tx509(tbackend(t _Certificate(ttimeoutterror(tBytesIO(t _fileobjecti(tbackport_makefile(tsix(tutiltinject_into_urllib3textract_from_urllib3tPROTOCOL_TLSv1_1tTLSv1_1_METHODtPROTOCOL_TLSv1_2tTLSv1_2_METHODcc@s!|]\}}||fVqdS(N((t.0tktv((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pys `si@cC@sAtttj_tt_ttj_tt_ttj_dS(s7Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.N(t_validate_dependencies_mettPyOpenSSLContextR tssl_t SSLContexttHAS_SNItTruet IS_PYOPENSSL(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyR ms     cC@s:ttj_tt_ttj_tt_ttj_dS(s4Undo monkey-patching by :func:`inject_into_urllib3`.N(torig_util_SSLContextR RRtorig_util_HAS_SNIRtFalseR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyR ys     cC@s{ddlm}t|dddkr7tdnddlm}|}t|dddkrwtdndS( s{ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. i(t Extensionstget_extension_for_classsX'cryptography' module missing required functionality. Try upgrading to v1.3.4 or newer.(tX509t_x509sS'pyOpenSSL' module missing required functionality. Try upgrading to v0.14 or newer.N(tcryptography.x509.extensionsRtgetattrtNonet ImportErrortOpenSSL.cryptoR (RR R((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs cC@s:d}||}tjdkr6|jd}n|S(s Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). cS@siddl}xMddgD]?}|j|r|t|}|jd|j|SqW|j|S(s Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. iNu*.u.tascii(tidnat startswithtlentencode(tnameR(tprefix((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt idna_encodes  iisutf-8(ii(tsyst version_infotdecode(R,R.((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_dnsname_to_stdlibs  cC@st|dr|j}ntt|j}y|jjtjj }WnMtj k rcgStj tj tj tfk r}tjd|gSXg|jtjD]}dt|f^q}|jd|jtjD|S(sU Given an PyOpenSSL certificate, provides all the subject alternative names. tto_cryptographysA problem was encountered with the certificate that prevented urllib3 from finding the SubjectAlternativeName field. This can affect certificate validation. The error was %stDNScs@s!|]}dt|fVqdS(s IP AddressN(tstr(RR,((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pys s(thasattrR3Rtopenssl_backendR!t extensionsRRtSubjectAlternativeNametvaluetExtensionNotFoundtDuplicateExtensiontUnsupportedExtensiontUnsupportedGeneralNameTypet UnicodeErrortlogtwarningtget_values_for_typetDNSNameR2textendt IPAddress(t peer_certtcerttextteR,tnames((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytget_subj_alt_names(   .t WrappedSocketcB@seZdZedZdZdZdZdZdZ dZ dZ d Z d Z ed Zd Zd ZRS(sAPI-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. cC@s1||_||_||_d|_t|_dS(Ni(t connectiontsockettsuppress_ragged_eofst_makefile_refsRt_closed(tselfRMRNRO((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt__init__s     cC@s |jjS(N(RNtfileno(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRTscC@s;|jdkr!|jd8_n|jr7|jndS(Nii(RPRQtclose(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_decref_socketioss cO@sy|jj||}Wntjjk rb}|jrM|jdkrMdStt|ntjj k r}|jj tjj krdSn^tjj k rt j|j|jj}|stdq|j||SnX|SdS(NisUnexpected EOFtsThe read operation timed out(isUnexpected EOF(RMtrecvtOpenSSLtSSLt SysCallErrorROtargst SocketErrorR5tZeroReturnErrort get_shutdowntRECEIVED_SHUTDOWNt WantReadErrorR t wait_for_readRNt gettimeoutR(RRR\tkwargstdataRItrd((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRXs cO@sy|jj||SWntjjk r`}|jrK|jdkrKdStt|ntjj k r}|jj tjj krdSnZtjj k rt j|j|jj}|stdq|j||SnXdS(NisUnexpected EOFisThe read operation timed out(isUnexpected EOF(RMt recv_intoRYRZR[ROR\R]R5R^R_R`RaR RbRNRcR(RRR\RdRIRf((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRgscC@s|jj|S(N(RNt settimeout(RRR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRh*scC@sxtry|jj|SWqtjjk ritj|j|jj }|st qqqtjj k r}t t |qXqWdS(N(RRMtsendRYRZtWantWriteErrorR twait_for_writeRNRcRR[R]R5(RRRetwrRI((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_send_until_done-s  cC@sGd}x:|t|krB|j|||t!}||7}q WdS(Ni(R*RmtSSL_WRITE_BLOCKSIZE(RRRet total_senttsent((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytsendall9scC@s|jjdS(N(RMtshutdown(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRr?scC@sZ|jdkrGyt|_|jjSWqVtjjk rCdSXn|jd8_dS(Ni(RPRRQRMRURYRZtError(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRUCs cC@se|jj}|s|S|r8tjjtjj|Sid|jjfffd6t|d6S(Nt commonNametsubjecttsubjectAltName( RMtget_peer_certificateRYtcryptotdump_certificatet FILETYPE_ASN1t get_subjecttCNRK(RRt binary_formR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt getpeercertMs  cC@s|jd7_dS(Ni(RP(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_reuse_scC@s/|jdkr|jn|jd8_dS(Ni(RPRU(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_dropbs (t__name__t __module__t__doc__RRSRTRVRXRgRhRmRqRrRURR~RR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRLs          icC@s%|jd7_t|||dtS(NiRU(RPRR(RRtmodetbufsize((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytmakefilejsRcB@seZdZdZedZejdZedZejdZdZdZ d d d dZ d d d Z e eed d ZRS( s I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. cC@s;t||_tjj|j|_d|_t|_dS(Ni( t_openssl_versionstprotocolRYRZtContextt_ctxt_optionsRtcheck_hostname(RRR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRSys  cC@s|jS(N(R(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytoptionsscC@s||_|jj|dS(N(RRt set_options(RRR:((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs cC@st|jjS(N(t_openssl_to_stdlib_verifyRtget_verify_mode(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt verify_modescC@s|jjt|tdS(N(Rt set_verifyt_stdlib_to_openssl_verifyt_verify_callback(RRR:((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs cC@s|jjdS(N(Rtset_default_verify_paths(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRscC@s8t|tjr$|jd}n|jj|dS(Nsutf-8(t isinstanceR t text_typeR+Rtset_cipher_list(RRtciphers((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt set_ciphersscC@sx|dk r|jd}n|dk r<|jd}n|jj|||dk rt|jjt|ndS(Nsutf-8(R$R+Rtload_verify_locationsR(RRtcafiletcapathtcadata((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs   c@sR|jj|dk r8|jjfdn|jj|pJ|dS(Nc@sS(N((t max_lengtht prompt_twicetuserdata(tpassword(sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytRW(Rtuse_certificate_fileR$t set_passwd_cbtuse_privatekey_file(RRtcertfiletkeyfileR((RsI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytload_cert_chains c C@stjj|j|}t|tjr<|jd}n|dk rX|j |n|j xt ry|j Wnrtjj k rtj||j}|setdqeqen,tjjk r}tjd|nXPqeWt||S(Nsutf-8sselect timed outsbad handshake: %r(RYRZt ConnectionRRR RR+R$tset_tlsext_host_nametset_connect_stateRt do_handshakeRaR RbRcRRstssltSSLErrorRL( RRtsockt server_sidetdo_handshake_on_connectROtserver_hostnametcnxRfRI((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt wrap_sockets$   N(RRRRStpropertyRtsetterRRRR$RRRRR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRss    cC@s |dkS(Ni((RRterr_not err_deptht return_code((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs(LRt __future__Rt OpenSSL.SSLRYt cryptographyRt$cryptography.hazmat.backends.opensslRR7t)cryptography.hazmat.backends.openssl.x509RRNRRR]tioRRR%R$tpackages.backports.makefileRtloggingRtpackagesR R/RWR t__all__RRRZt SSLv23_METHODtPROTOCOL_SSLv23t TLSv1_METHODtPROTOCOL_TLSv1RR6RR RRtupdatet SSLv3_METHODtPROTOCOL_SSLv3tAttributeErrort VERIFY_NONEt CERT_NONEt VERIFY_PEERt CERT_OPTIONALtVERIFY_FAIL_IF_NO_PEER_CERTt CERT_REQUIREDRtdicttitemsRRnRRRRt getLoggerRR@R R RR2RKtobjectRLRRR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt+sh      !!!      3 SPK!8bXXsecuretransport.pyonu[ abc!@@sdZddlmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlmZmZmZddlmZmZmZmZydd l mZWn'ek r eZdd lmZnXyed Wnek r;ed nXd dgZe Z!ej!Z"ej#j$Z%e j&Z'e j(Z)dZ*ej+ej,ej-ej.ej/ej0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:ej;ej<ej=ej>ej?ej@ejAejBejCejDejEejFejGejHejIejJejKg!ZLiejMejNfe jO6ZPeQe drejRejRfePe jS Undo monkey-patching by :func:`inject_into_urllib3`. N(torig_util_SSLContextRRRtorig_util_HAS_SNIRtFalseR(((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyR s     cC@sd}ytj|}|dkr+tjS|j}|d}|j}d}d}tj|j |} t | } yx||kr|dks|dkrt j |g|} | stj tjdqn|j| ||!} || 7}| s~|s tjSPq~q~WWnVtj k rl} | j}|dk rm|tjkrm|tjkrctjSqmnX||d<||krtjSdSWn/tk r} |dk r| |_ntjSXdS(ss SecureTransport read callback. This is called by ST to request that data be returned from the socket. is timed outN(tNonet_connection_refstgetRterrSSLInternaltsockett gettimeouttctypestc_chart from_addresst memoryviewRt wait_for_readterrorterrnotEAGAINt recv_intoterrSSLClosedGracefult ECONNRESETterrSSLClosedAbortterrSSLWouldBlockt Exceptiont _exception(t connection_idt data_buffertdata_length_pointertwrapped_sockett base_sockettrequested_lengthttimeoutR(t read_counttbuffert buffer_viewt readablest chunk_sizete((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt_read_callbacksN             c C@sd}yetj|}|dkr+tjS|j}|d}tj||}|j}d}d} yx| |kr|dks|dkrt j |g|} | stj t j dqn|j|} | | 7} || }qnWWnVtj k rH} | j }|dk rI|t j krI|t jkr?tjSqInX| |d<| |krftjSdSWn/tk r} |dk r| |_ntjSXdS(sx SecureTransport write callback. This is called by ST to request that data actually be sent on the network. is timed outN(RRRRR R!R#t string_atR"Rtwait_for_writeR(R)R*tsendR-R.R/R0R1( R2R3R4R5R6tbytes_to_writetdataR8R(tsentt writablest chunk_sentR>((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt_write_callbacksD           t WrappedSocketcB@seZdZdZejdZdZdZdZ dZ dZ dZ dd Zd Zd Zd Zd ZdZdZedZdZdZRS(s API-compatibility wrapper for Python's OpenSSL wrapped socket object. Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage collector of PyPy. cC@sn||_d|_d|_t|_d|_d|_d|_d|_ |jj |_ |jj ddS(Ni( R!Rtcontextt_makefile_refsRt_closedR1t _keychaint _keychain_dirt_client_cert_chainR"t_timeoutt settimeout(tselfR!((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt__init__.s        cc@sGd|_dV|jdk rC|jd}|_|j|ndS(s] A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. N(RR1tclose(RRt exception((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt_raise_on_error@s  cC@sEtjttt}tj|j|tt}t|dS(s4 Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. N(RtSSLCipherSuitetlent CIPHER_SUITEStSSLSetEnabledCiphersRJR(RRtcipherstresult((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt _set_ciphersUsc C@s|s dStjj|rCt|d}|j}WdQXnd}tj}zt|}tj |j t j |}t ||stjdntj||}t |tj|t}t |tj}tj|t j |}t |Wd|r'tj|n|dkrCtj|nXtjtjf}|j|kr~tjd|jndS(s Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. NtrbsFailed to copy trust references)certificate verify failed, error code: %d(tostpathtisfiletopentreadRRt SecTrustRefRtSSLCopyPeerTrustRJR#tbyrefRtssltSSLErrortSecTrustSetAnchorCertificatest!SecTrustSetAnchorCertificatesOnlyRtSecTrustResultTypetSecTrustEvaluateRt CFReleaseRtkSecTrustResultUnspecifiedtkSecTrustResultProceedtvalue( RRtverifyt trust_bundletft cert_arrayttrustR\t trust_resultt successes((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt_custom_validatebs@        c C@s[tjdtjtj|_tj|jtt } t | t @t |d} x| t krw| dd} qZW|t | Z    (       > icC@s%|jd7_t|||dtS(NiRT(RKR R(RRtmodetbufsize((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytmakefilestrcO@sd}t|||||S(Ni(R (RRRt bufferingtargstkwargs((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRsRcB@seZdZdZedZejdZedZejdZedZejdZdZ d Z d Z dddd Z ddd Zeeedd ZRS(s I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. cC@sPt|\|_|_d|_t|_d|_d|_d|_ d|_ dS(Ni( t_protocol_to_min_maxt _min_versiont _max_versiont_optionsRt_verifyRt _trust_bundlet _client_certt _client_keyt_client_key_passphrase(RRtprotocol((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRSs     cC@stS(s SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. (R(RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytcheck_hostnamescC@sdS(s SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. N((RRRp((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRscC@s|jS(N(R(RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytoptionsscC@s ||_dS(N(R(RRRp((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRscC@s|jrtjStjS(N(RRgt CERT_REQUIREDt CERT_NONE(RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt verify_modescC@s"|tjkrtnt|_dS(N(RgRRRR(RRRp((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRscC@sdS(N((RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytset_default_verify_pathss cC@s |jS(N(R(RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytload_default_certsscC@s%|tjjkr!tdndS(Ns5SecureTransport doesn't support custom cipher strings(RRtDEFAULT_CIPHERSR(RRR[((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt set_ciphersscC@s.|dk rtdn|p$||_dS(Ns1SecureTransport does not support cert directories(RRR(RRtcafiletcapathtcadata((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytload_verify_locationss  cC@s||_||_||_dS(N(RRt_client_cert_passphrase(RRtcertfiletkeyfiletpassword((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytload_cert_chains  c C@sGt|}|j||j|j|j|j|j|j|j|S(N( RIRRRRRRRR(RRtsockt server_sidetdo_handshake_on_connecttsuppress_ragged_eofsRR5((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt wrap_sockets N(RRRRStpropertyRtsetterRRRRRRRRRRR(((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRs      (gRt __future__RRR#R)tos.pathR_RR!Rgt threadingtweakrefR Rt_securetransport.bindingsRRRt_securetransport.low_levelRRRRR t ImportErrorRtpackages.backports.makefileR R&t NameErrort__all__RRRRRRtWeakValueDictionaryRtLockRRtTLS_AES_256_GCM_SHA384tTLS_CHACHA20_POLY1305_SHA256tTLS_AES_128_GCM_SHA256t'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384t%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384t'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256t%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256t#TLS_DHE_DSS_WITH_AES_256_GCM_SHA384t#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384t#TLS_DHE_DSS_WITH_AES_128_GCM_SHA256t#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256t'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384t%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384t$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAt"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAt#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256t#TLS_DHE_DSS_WITH_AES_256_CBC_SHA256t TLS_DHE_RSA_WITH_AES_256_CBC_SHAt TLS_DHE_DSS_WITH_AES_256_CBC_SHAt'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256t%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256t$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAt"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAt#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256t#TLS_DHE_DSS_WITH_AES_128_CBC_SHA256t TLS_DHE_RSA_WITH_AES_128_CBC_SHAt TLS_DHE_DSS_WITH_AES_128_CBC_SHAtTLS_RSA_WITH_AES_256_GCM_SHA384tTLS_RSA_WITH_AES_128_GCM_SHA256tTLS_RSA_WITH_AES_256_CBC_SHA256tTLS_RSA_WITH_AES_128_CBC_SHA256tTLS_RSA_WITH_AES_256_CBC_SHAtTLS_RSA_WITH_AES_128_CBC_SHARYt kTLSProtocol1tkTLSProtocol12tPROTOCOL_SSLv23Rthasattrt kSSLProtocol2Rt kSSLProtocol3RRtkTLSProtocol11RRRR R R?RHt SSLReadFuncR}t SSLWriteFuncR~tobjectRIRR(((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyts         "         9 5 PK!GۇDD pyopenssl.pycnu[ abc@@sdZddlmZddlZddlmZddlmZ ddl m Z ddl m Z mZddlmZydd l mZWn'ek rdZd d lmZnXddlZddlZd d lmZddlZd d lmZddgZeZ iej!j"ej#6ej!j$ej%6Z&e'edrie'ej!driej!j(e&ej)ej?e@ZAdZBdZCdZDdZEdZFdeGfdYZHerddZIneZIeIeH_IdeGfd YZJd!ZKdS("sb SSL with SNI_-support for Python 2. Follow these instructions if you would like to verify SSL certificates in Python 2. Note, the default libraries do *not* do certificate checking; you need to do additional work to validate certificates yourself. This needs the following packages installed: * pyOpenSSL (tested with 16.0.0) * cryptography (minimum 1.3.4, from pyopenssl) * idna (minimum 2.0, from cryptography) However, pyopenssl depends on cryptography, which depends on idna, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. Activating this module also has the positive side effect of disabling SSL/TLS compression in Python 2 (see `CRIME attack`_). If you want to configure the default list of supported cipher suites, you can set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit) i(tabsolute_importN(tx509(tbackend(t _Certificate(ttimeoutterror(tBytesIO(t _fileobjecti(tbackport_makefile(tsix(tutiltinject_into_urllib3textract_from_urllib3tPROTOCOL_TLSv1_1tTLSv1_1_METHODtPROTOCOL_TLSv1_2tTLSv1_2_METHODcc@s!|]\}}||fVqdS(N((t.0tktv((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pys `si@cC@sAtttj_tt_ttj_tt_ttj_dS(s7Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.N(t_validate_dependencies_mettPyOpenSSLContextR tssl_t SSLContexttHAS_SNItTruet IS_PYOPENSSL(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyR ms     cC@s:ttj_tt_ttj_tt_ttj_dS(s4Undo monkey-patching by :func:`inject_into_urllib3`.N(torig_util_SSLContextR RRtorig_util_HAS_SNIRtFalseR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyR ys     cC@s{ddlm}t|dddkr7tdnddlm}|}t|dddkrwtdndS( s{ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. i(t Extensionstget_extension_for_classsX'cryptography' module missing required functionality. Try upgrading to v1.3.4 or newer.(tX509t_x509sS'pyOpenSSL' module missing required functionality. Try upgrading to v0.14 or newer.N(tcryptography.x509.extensionsRtgetattrtNonet ImportErrortOpenSSL.cryptoR (RR R((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs cC@s:d}||}tjdkr6|jd}n|S(s Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). cS@siddl}xMddgD]?}|j|r|t|}|jd|j|SqW|j|S(s Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. iNu*.u.tascii(tidnat startswithtlentencode(tnameR(tprefix((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt idna_encodes  iisutf-8(ii(tsyst version_infotdecode(R,R.((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_dnsname_to_stdlibs  cC@st|dr|j}ntt|j}y|jjtjj }WnMtj k rcgStj tj tj tfk r}tjd|gSXg|jtjD]}dt|f^q}|jd|jtjD|S(sU Given an PyOpenSSL certificate, provides all the subject alternative names. tto_cryptographysA problem was encountered with the certificate that prevented urllib3 from finding the SubjectAlternativeName field. This can affect certificate validation. The error was %stDNScs@s!|]}dt|fVqdS(s IP AddressN(tstr(RR,((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pys s(thasattrR3Rtopenssl_backendR!t extensionsRRtSubjectAlternativeNametvaluetExtensionNotFoundtDuplicateExtensiontUnsupportedExtensiontUnsupportedGeneralNameTypet UnicodeErrortlogtwarningtget_values_for_typetDNSNameR2textendt IPAddress(t peer_certtcerttextteR,tnames((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytget_subj_alt_names(   .t WrappedSocketcB@seZdZedZdZdZdZdZdZ dZ dZ d Z d Z ed Zd Zd ZRS(sAPI-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. cC@s1||_||_||_d|_t|_dS(Ni(t connectiontsockettsuppress_ragged_eofst_makefile_refsRt_closed(tselfRMRNRO((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt__init__s     cC@s |jjS(N(RNtfileno(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRTscC@s;|jdkr!|jd8_n|jr7|jndS(Nii(RPRQtclose(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_decref_socketioss cO@sy|jj||}Wntjjk rb}|jrM|jdkrMdStt|ntjj k r}|jj tjj krdSn^tjj k rt j|j|jj}|stdq|j||SnX|SdS(NisUnexpected EOFtsThe read operation timed out(isUnexpected EOF(RMtrecvtOpenSSLtSSLt SysCallErrorROtargst SocketErrorR5tZeroReturnErrort get_shutdowntRECEIVED_SHUTDOWNt WantReadErrorR t wait_for_readRNt gettimeoutR(RRR\tkwargstdataRItrd((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRXs cO@sy|jj||SWntjjk r`}|jrK|jdkrKdStt|ntjj k r}|jj tjj krdSnZtjj k rt j|j|jj}|stdq|j||SnXdS(NisUnexpected EOFisThe read operation timed out(isUnexpected EOF(RMt recv_intoRYRZR[ROR\R]R5R^R_R`RaR RbRNRcR(RRR\RdRIRf((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRgscC@s|jj|S(N(RNt settimeout(RRR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRh*scC@sxtry|jj|SWqtjjk ritj|j|jj }|st qqqtjj k r}t t |qXqWdS(N(RRMtsendRYRZtWantWriteErrorR twait_for_writeRNRcRR[R]R5(RRRetwrRI((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_send_until_done-s  cC@sGd}x:|t|krB|j|||t!}||7}q WdS(Ni(R*RmtSSL_WRITE_BLOCKSIZE(RRRet total_senttsent((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytsendall9scC@s|jjdS(N(RMtshutdown(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRr?scC@sZ|jdkrGyt|_|jjSWqVtjjk rCdSXn|jd8_dS(Ni(RPRRQRMRURYRZtError(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRUCs cC@se|jj}|s|S|r8tjjtjj|Sid|jjfffd6t|d6S(Nt commonNametsubjecttsubjectAltName( RMtget_peer_certificateRYtcryptotdump_certificatet FILETYPE_ASN1t get_subjecttCNRK(RRt binary_formR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt getpeercertMs  cC@s|jd7_dS(Ni(RP(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_reuse_scC@s/|jdkr|jn|jd8_dS(Ni(RPRU(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt_dropbs (t__name__t __module__t__doc__RRSRTRVRXRgRhRmRqRrRURR~RR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRLs          icC@s%|jd7_t|||dtS(NiRU(RPRR(RRtmodetbufsize((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytmakefilejsRcB@seZdZdZedZejdZedZejdZdZdZ d d d dZ d d d Z e eed d ZRS( s I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. cC@s;t||_tjj|j|_d|_t|_dS(Ni( t_openssl_versionstprotocolRYRZtContextt_ctxt_optionsRtcheck_hostname(RRR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRSys  cC@s|jS(N(R(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytoptionsscC@s||_|jj|dS(N(RRt set_options(RRR:((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs cC@st|jjS(N(t_openssl_to_stdlib_verifyRtget_verify_mode(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt verify_modescC@s|jjt|tdS(N(Rt set_verifyt_stdlib_to_openssl_verifyt_verify_callback(RRR:((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs cC@s|jjdS(N(Rtset_default_verify_paths(RR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRscC@s8t|tjr$|jd}n|jj|dS(Nsutf-8(t isinstanceR t text_typeR+Rtset_cipher_list(RRtciphers((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt set_ciphersscC@sx|dk r|jd}n|dk r<|jd}n|jj|||dk rt|jjt|ndS(Nsutf-8(R$R+Rtload_verify_locationsR(RRtcafiletcapathtcadata((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs   c@sR|jj|dk r8|jjfdn|jj|pJ|dS(Nc@sS(N((t max_lengtht prompt_twicetuserdata(tpassword(sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytRW(Rtuse_certificate_fileR$t set_passwd_cbtuse_privatekey_file(RRtcertfiletkeyfileR((RsI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pytload_cert_chains c C@stjj|j|}t|tjr<|jd}n|dk rX|j |n|j xt ry|j Wnrtjj k rtj||j}|setdqeqen,tjjk r}tjd|nXPqeWt||S(Nsutf-8sselect timed outsbad handshake: %r(RYRZt ConnectionRRR RR+R$tset_tlsext_host_nametset_connect_stateRt do_handshakeRaR RbRcRRstssltSSLErrorRL( RRtsockt server_sidetdo_handshake_on_connectROtserver_hostnametcnxRfRI((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt wrap_sockets$   N(RRRRStpropertyRtsetterRRRR$RRRRR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRss    cC@s |dkS(Ni((RRterr_not err_deptht return_code((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyRs(LRt __future__Rt OpenSSL.SSLRYt cryptographyRt$cryptography.hazmat.backends.opensslRR7t)cryptography.hazmat.backends.openssl.x509RRNRRR]tioRRR%R$tpackages.backports.makefileRtloggingRtpackagesR R/RWR t__all__RRRZt SSLv23_METHODtPROTOCOL_SSLv23t TLSv1_METHODtPROTOCOL_TLSv1RR6RR RRtupdatet SSLv3_METHODtPROTOCOL_SSLv3tAttributeErrort VERIFY_NONEt CERT_NONEt VERIFY_PEERt CERT_OPTIONALtVERIFY_FAIL_IF_NO_PEER_CERTt CERT_REQUIREDRtdicttitemsRRnRRRRt getLoggerRR@R R RR2RKtobjectRLRRR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.pyt+sh      !!!      3 SPK!^^ socks.pyonu[ abc@@sdZddlmZyddlZWn@ek rhddlZddlmZejdenXddl m Z m Z ddlmZmZdd lmZmZdd lmZmZdd lmZdd lmZyddlZWnek r dZnXd efdYZdeefdYZdefdYZdefdYZdefdYZ dS(s This module contains provisional support for SOCKS proxies from within urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and SOCKS5. To enable its functionality, either install PySocks or install this module with the ``socks`` extra. The SOCKS implementation supports the full range of urllib3 features. It also supports the following SOCKS features: - SOCKS4 - SOCKS4a - SOCKS5 - Usernames and passwords for the SOCKS proxy Known Limitations: - Currently PySocks does not support contacting remote websites via literal IPv6 addresses. Any such connection attempt will fail. You must use a domain name. - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any such connection attempt will fail. i(tabsolute_importNi(tDependencyWarningsSOCKS support in urllib3 requires the installation of optional dependencies: specifically, PySocks. For more information, see https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies(terrorttimeout(tHTTPConnectiontHTTPSConnection(tHTTPConnectionPooltHTTPSConnectionPool(tConnectTimeoutErrortNewConnectionError(t PoolManager(t parse_urltSOCKSConnectioncB@s eZdZdZdZRS(sG A plain-text HTTP connection that connects via a SOCKS proxy. cO@s/|jd|_tt|j||dS(Nt_socks_options(tpopR tsuperR t__init__(tselftargstkwargs((sE/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/socks.pyR?scC@si}|jr|j|ds2    FPK!q(( appengine.pyonu[ abc@@sxdZddlmZddlZddlZddlZddlmZddlm Z m Z m Z m Z m Z mZddlmZddlmZdd lmZdd lmZdd lmZydd lmZWnek rdZnXejeZd e fdYZ de fdYZ!defdYZ"dZ#dZ$dZ%dZ&dZ'dS(sC This module provides a pool manager that uses Google App Engine's `URLFetch Service `_. Example usage:: from urllib3 import PoolManager from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox if is_appengine_sandbox(): # AppEngineManager uses AppEngine's URLFetch API behind the scenes http = AppEngineManager() else: # PoolManager uses a socket-level API behind the scenes http = PoolManager() r = http.request('GET', 'https://google.com/') There are `limitations `_ to the URLFetch service and it may not be the best choice for your application. There are three options for using urllib3 on Google App Engine: 1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is cost-effective in many circumstances as long as your usage is within the limitations. 2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets. Sockets also have `limitations and restrictions `_ and have a lower free quota than URLFetch. To use sockets, be sure to specify the following in your ``app.yaml``:: env_variables: GAE_USE_SOCKETS_HTTPLIB : 'true' 3. If you are using `App Engine Flexible `_, you can use the standard :class:`PoolManager` without any configuration or special environment variables. i(tabsolute_importNi(turljoin(t HTTPErrort HTTPWarningt MaxRetryErrort ProtocolErrort TimeoutErrortSSLError(tBytesIO(tRequestMethods(t HTTPResponse(tTimeout(tRetry(turlfetchtAppEnginePlatformWarningcB@seZRS((t__name__t __module__(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyRGstAppEnginePlatformErrorcB@seZRS((RR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyRKstAppEngineManagercB@skeZdZddeedZdZdZdddeej dZ dZ dZ dZ RS( s  Connection manager for Google App Engine sandbox applications. This manager uses the URLFetch service directly instead of using the emulated httplib, and is subject to URLFetch limitations as described in the App Engine documentation `here `_. Notably it will raise an :class:`AppEnginePlatformError` if: * URLFetch is not available. * If you attempt to use this on App Engine Flexible, as full socket support is available. * If a request size is more than 10 megabytes. * If a response size is more than 32 megabtyes. * If you use an unsupported request method such as OPTIONS. Beyond those cases, it will raise normal urllib3 errors. cC@sutstdntr-tdntjdttj||||_||_ |pkt j |_ dS(Ns.URLFetch is not available in this environment.sUse normal urllib3.PoolManager instead of AppEngineManageron Managed VMs, as using URLFetch is not necessary in this environment.surllib3 is using URLFetch on Google App Engine sandbox instead of sockets. To use sockets directly instead of URLFetch see https://urllib3.readthedocs.io/en/latest/reference/urllib3.contrib.html.( R Rtis_prod_appengine_mvmstwarningstwarnRR t__init__tvalidate_certificateturlfetch_retriesR tDEFAULTtretries(tselftheadersRRR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyRcs     cC@s|S(N((R((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyt __enter__{scC@stS(N(tFalse(Rtexc_typetexc_valtexc_tb((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyt__exit__~scK@sk|j||}yv|o0|jdko0|j} tj|d|d|d|pTidtd|joi| d|j|d|j} Wn"tj k r} t || ntj k r} d t | krt d | nt| ntjk r?} d t | kr0t||d | nt| nntjk rc} t d | nJtjk r} t| n)tjk r} t d|| nX|j| d||} |o| j} | r|jr|jrt||dq| jdkrd}ny"|j||d| d|}Wn0tk rp|jrlt||dn| SX|j| tjd|| t|| }|j||||d|d|d||Snt| j d}|j!|| j|rg|j||d| d|}tjd||j"| |j||d|d|d|d|d||S| S(NitpayloadtmethodRtallow_truncatedtfollow_redirectstdeadlineRs too largesOURLFetch request too large, URLFetch only supports requests up to 10mb in size.sToo many redirectstreasonsPURLFetch response too large, URLFetch only supportsresponses up to 32mb in size.s$URLFetch does not support method: %sRstoo many redirectsi/tGETtresponset_poolsRedirecting %s -> %stredirectttimeouts Retry-Afters Retry: %stbody(#t _get_retriesR,ttotalR tfetchRRt_get_absolute_timeoutRtDeadlineExceededErrorRtInvalidURLErrortstrRRt DownloadErrorRtResponseTooLargeErrortSSLCertificateErrorRtInvalidMethodErrort#_urlfetch_response_to_http_responsetget_redirect_locationtraise_on_redirecttstatust incrementtsleep_for_retrytlogtdebugRturlopentboolt getheadertis_retrytsleep(RR$turlR.RRR,R-t response_kwR&R*tet http_responsetredirect_locationt redirect_urlthas_retry_after((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyRBs     "          cK@str7|jjd}|dkr7|jd=q7n|jjd}|dkr|jd}|jddj||jd's0   .       PK!q(( appengine.pycnu[ abc@@sxdZddlmZddlZddlZddlZddlmZddlm Z m Z m Z m Z m Z mZddlmZddlmZdd lmZdd lmZdd lmZydd lmZWnek rdZnXejeZd e fdYZ de fdYZ!defdYZ"dZ#dZ$dZ%dZ&dZ'dS(sC This module provides a pool manager that uses Google App Engine's `URLFetch Service `_. Example usage:: from urllib3 import PoolManager from urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox if is_appengine_sandbox(): # AppEngineManager uses AppEngine's URLFetch API behind the scenes http = AppEngineManager() else: # PoolManager uses a socket-level API behind the scenes http = PoolManager() r = http.request('GET', 'https://google.com/') There are `limitations `_ to the URLFetch service and it may not be the best choice for your application. There are three options for using urllib3 on Google App Engine: 1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is cost-effective in many circumstances as long as your usage is within the limitations. 2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets. Sockets also have `limitations and restrictions `_ and have a lower free quota than URLFetch. To use sockets, be sure to specify the following in your ``app.yaml``:: env_variables: GAE_USE_SOCKETS_HTTPLIB : 'true' 3. If you are using `App Engine Flexible `_, you can use the standard :class:`PoolManager` without any configuration or special environment variables. i(tabsolute_importNi(turljoin(t HTTPErrort HTTPWarningt MaxRetryErrort ProtocolErrort TimeoutErrortSSLError(tBytesIO(tRequestMethods(t HTTPResponse(tTimeout(tRetry(turlfetchtAppEnginePlatformWarningcB@seZRS((t__name__t __module__(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyRGstAppEnginePlatformErrorcB@seZRS((RR(((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyRKstAppEngineManagercB@skeZdZddeedZdZdZdddeej dZ dZ dZ dZ RS( s  Connection manager for Google App Engine sandbox applications. This manager uses the URLFetch service directly instead of using the emulated httplib, and is subject to URLFetch limitations as described in the App Engine documentation `here `_. Notably it will raise an :class:`AppEnginePlatformError` if: * URLFetch is not available. * If you attempt to use this on App Engine Flexible, as full socket support is available. * If a request size is more than 10 megabytes. * If a response size is more than 32 megabtyes. * If you use an unsupported request method such as OPTIONS. Beyond those cases, it will raise normal urllib3 errors. cC@sutstdntr-tdntjdttj||||_||_ |pkt j |_ dS(Ns.URLFetch is not available in this environment.sUse normal urllib3.PoolManager instead of AppEngineManageron Managed VMs, as using URLFetch is not necessary in this environment.surllib3 is using URLFetch on Google App Engine sandbox instead of sockets. To use sockets directly instead of URLFetch see https://urllib3.readthedocs.io/en/latest/reference/urllib3.contrib.html.( R Rtis_prod_appengine_mvmstwarningstwarnRR t__init__tvalidate_certificateturlfetch_retriesR tDEFAULTtretries(tselftheadersRRR((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyRcs     cC@s|S(N((R((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyt __enter__{scC@stS(N(tFalse(Rtexc_typetexc_valtexc_tb((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyt__exit__~scK@sk|j||}yv|o0|jdko0|j} tj|d|d|d|pTidtd|joi| d|j|d|j} Wn"tj k r} t || ntj k r} d t | krt d | nt| ntjk r?} d t | kr0t||d | nt| nntjk rc} t d | nJtjk r} t| n)tjk r} t d|| nX|j| d||} |o| j} | r|jr|jrt||dq| jdkrd}ny"|j||d| d|}Wn0tk rp|jrlt||dn| SX|j| tjd|| t|| }|j||||d|d|d||Snt| j d}|j!|| j|rg|j||d| d|}tjd||j"| |j||d|d|d|d|d||S| S(NitpayloadtmethodRtallow_truncatedtfollow_redirectstdeadlineRs too largesOURLFetch request too large, URLFetch only supports requests up to 10mb in size.sToo many redirectstreasonsPURLFetch response too large, URLFetch only supportsresponses up to 32mb in size.s$URLFetch does not support method: %sRstoo many redirectsi/tGETtresponset_poolsRedirecting %s -> %stredirectttimeouts Retry-Afters Retry: %stbody(#t _get_retriesR,ttotalR tfetchRRt_get_absolute_timeoutRtDeadlineExceededErrorRtInvalidURLErrortstrRRt DownloadErrorRtResponseTooLargeErrortSSLCertificateErrorRtInvalidMethodErrort#_urlfetch_response_to_http_responsetget_redirect_locationtraise_on_redirecttstatust incrementtsleep_for_retrytlogtdebugRturlopentboolt getheadertis_retrytsleep(RR$turlR.RRR,R-t response_kwR&R*tet http_responsetredirect_locationt redirect_urlthas_retry_after((sI/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/appengine.pyRBs     "          cK@str7|jjd}|dkr7|jd=q7n|jjd}|dkr|jd}|jddj||jd's0   .       PK!CFXXsecuretransport.pycnu[ abc!@@sdZddlmZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlmZmZmZddlmZmZmZmZydd l mZWn'ek r eZdd lmZnXyed Wnek r;ed nXd dgZe Z!ej!Z"ej#j$Z%e j&Z'e j(Z)dZ*ej+ej,ej-ej.ej/ej0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:ej;ej<ej=ej>ej?ej@ejAejBejCejDejEejFejGejHejIejJejKg!ZLiejMejNfe jO6ZPeQe drejRejRfePe jS Undo monkey-patching by :func:`inject_into_urllib3`. N(torig_util_SSLContextRRRtorig_util_HAS_SNIRtFalseR(((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyR s     cC@sd}ytj|}|dkr+tjS|j}|d}|j}d}d}tj|j |} t | } yx||kr|dks|dkrt j |g|} | stj tjdqn|j| ||!} || 7}| s~|s tjSPq~q~WWnVtj k rl} | j}|dk rm|tjkrm|tjkrctjSqmnX||d<||krtjSdSWn/tk r} |dk r| |_ntjSXdS(ss SecureTransport read callback. This is called by ST to request that data be returned from the socket. is timed outN(tNonet_connection_refstgetRterrSSLInternaltsockett gettimeouttctypestc_chart from_addresst memoryviewRt wait_for_readterrorterrnotEAGAINt recv_intoterrSSLClosedGracefult ECONNRESETterrSSLClosedAbortterrSSLWouldBlockt Exceptiont _exception(t connection_idt data_buffertdata_length_pointertwrapped_sockett base_sockettrequested_lengthttimeoutR(t read_counttbuffert buffer_viewt readablest chunk_sizete((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt_read_callbacksN             c C@sd}yetj|}|dkr+tjS|j}|d}tj||}|j}d}d} yx| |kr|dks|dkrt j |g|} | stj t j dqn|j|} | | 7} || }qnWWnVtj k rH} | j }|dk rI|t j krI|t jkr?tjSqInX| |d<| |krftjSdSWn/tk r} |dk r| |_ntjSXdS(sx SecureTransport write callback. This is called by ST to request that data actually be sent on the network. is timed outN(RRRRR R!R#t string_atR"Rtwait_for_writeR(R)R*tsendR-R.R/R0R1( R2R3R4R5R6tbytes_to_writetdataR8R(tsentt writablest chunk_sentR>((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt_write_callbacksD           t WrappedSocketcB@seZdZdZejdZdZdZdZ dZ dZ dZ dd Zd Zd Zd Zd ZdZdZedZdZdZRS(s API-compatibility wrapper for Python's OpenSSL wrapped socket object. Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage collector of PyPy. cC@sn||_d|_d|_t|_d|_d|_d|_d|_ |jj |_ |jj ddS(Ni( R!Rtcontextt_makefile_refsRt_closedR1t _keychaint _keychain_dirt_client_cert_chainR"t_timeoutt settimeout(tselfR!((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt__init__.s        cc@sGd|_dV|jdk rC|jd}|_|j|ndS(s] A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed. N(RR1tclose(RRt exception((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt_raise_on_error@s  cC@sEtjttt}tj|j|tt}t|dS(s4 Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn't allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare. N(RtSSLCipherSuitetlent CIPHER_SUITEStSSLSetEnabledCiphersRJR(RRtcipherstresult((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt _set_ciphersUsc C@s|s dStjj|rCt|d}|j}WdQXnd}tj}zt|}tj |j t j |}t ||stjdntj||}t |tj|t}t |tj}tj|t j |}t |Wd|r'tj|n|dkrCtj|nXtjtjf}|j|kr~tjd|jndS(s Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB. NtrbsFailed to copy trust references)certificate verify failed, error code: %d(tostpathtisfiletopentreadRRt SecTrustRefRtSSLCopyPeerTrustRJR#tbyrefRtssltSSLErrortSecTrustSetAnchorCertificatest!SecTrustSetAnchorCertificatesOnlyRtSecTrustResultTypetSecTrustEvaluateRt CFReleaseRtkSecTrustResultUnspecifiedtkSecTrustResultProceedtvalue( RRtverifyt trust_bundletft cert_arrayttrustR\t trust_resultt successes((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt_custom_validatebs@        c C@s[tjdtjtj|_tj|jtt } t | t @t |d} x| t krw| dd} qZW|t | Z    (       > icC@s%|jd7_t|||dtS(NiRT(RKR R(RRtmodetbufsize((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytmakefilestrcO@sd}t|||||S(Ni(R (RRRt bufferingtargstkwargs((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRsRcB@seZdZdZedZejdZedZejdZedZejdZdZ d Z d Z dddd Z ddd Zeeedd ZRS(s I am a wrapper class for the SecureTransport library, to translate the interface of the standard library ``SSLContext`` object to calls into SecureTransport. cC@sPt|\|_|_d|_t|_d|_d|_d|_ d|_ dS(Ni( t_protocol_to_min_maxt _min_versiont _max_versiont_optionsRt_verifyRt _trust_bundlet _client_certt _client_keyt_client_key_passphrase(RRtprotocol((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRSs     cC@stS(s SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. (R(RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytcheck_hostnamescC@sdS(s SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file. N((RRRp((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRscC@s|jS(N(R(RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytoptionsscC@s ||_dS(N(R(RRRp((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRscC@s|jrtjStjS(N(RRgt CERT_REQUIREDt CERT_NONE(RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt verify_modescC@s"|tjkrtnt|_dS(N(RgRRRR(RRRp((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRscC@sdS(N((RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytset_default_verify_pathss cC@s |jS(N(R(RR((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytload_default_certsscC@s%|tjjkr!tdndS(Ns5SecureTransport doesn't support custom cipher strings(RRtDEFAULT_CIPHERSR(RRR[((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt set_ciphersscC@s.|dk rtdn|p$||_dS(Ns1SecureTransport does not support cert directories(RRR(RRtcafiletcapathtcadata((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytload_verify_locationss  cC@s||_||_||_dS(N(RRt_client_cert_passphrase(RRtcertfiletkeyfiletpassword((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pytload_cert_chains  c C@sl| s t|st|s%tt|}|j||j|j|j|j|j|j|j |S(N( RRIRRRRRRRR(RRtsockt server_sidetdo_handshake_on_connecttsuppress_ragged_eofsRR5((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyt wrap_sockets    N(RRRRStpropertyRtsetterRRRRRRRRRRR(((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyRs      (gRt __future__RRR#R)tos.pathR_RR!Rgt threadingtweakrefR Rt_securetransport.bindingsRRRt_securetransport.low_levelRRRRR t ImportErrorRtpackages.backports.makefileR R&t NameErrort__all__RRRRRRtWeakValueDictionaryRtLockRRtTLS_AES_256_GCM_SHA384tTLS_CHACHA20_POLY1305_SHA256tTLS_AES_128_GCM_SHA256t'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384t%TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384t'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256t%TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256t#TLS_DHE_DSS_WITH_AES_256_GCM_SHA384t#TLS_DHE_RSA_WITH_AES_256_GCM_SHA384t#TLS_DHE_DSS_WITH_AES_128_GCM_SHA256t#TLS_DHE_RSA_WITH_AES_128_GCM_SHA256t'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384t%TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384t$TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHAt"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHAt#TLS_DHE_RSA_WITH_AES_256_CBC_SHA256t#TLS_DHE_DSS_WITH_AES_256_CBC_SHA256t TLS_DHE_RSA_WITH_AES_256_CBC_SHAt TLS_DHE_DSS_WITH_AES_256_CBC_SHAt'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256t%TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256t$TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHAt"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHAt#TLS_DHE_RSA_WITH_AES_128_CBC_SHA256t#TLS_DHE_DSS_WITH_AES_128_CBC_SHA256t TLS_DHE_RSA_WITH_AES_128_CBC_SHAt TLS_DHE_DSS_WITH_AES_128_CBC_SHAtTLS_RSA_WITH_AES_256_GCM_SHA384tTLS_RSA_WITH_AES_128_GCM_SHA256tTLS_RSA_WITH_AES_256_CBC_SHA256tTLS_RSA_WITH_AES_128_CBC_SHA256tTLS_RSA_WITH_AES_256_CBC_SHAtTLS_RSA_WITH_AES_128_CBC_SHARYt kTLSProtocol1tkTLSProtocol12tPROTOCOL_SSLv23Rthasattrt kSSLProtocol2Rt kSSLProtocol3RRtkTLSProtocol11RRRR R R?RHt SSLReadFuncR}t SSLWriteFuncR~tobjectRIRR(((sO/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.pyts         "         9 5 PK!^^ socks.pycnu[ abc@@sdZddlmZyddlZWn@ek rhddlZddlmZejdenXddl m Z m Z ddlmZmZdd lmZmZdd lmZmZdd lmZdd lmZyddlZWnek r dZnXd efdYZdeefdYZdefdYZdefdYZdefdYZ dS(s This module contains provisional support for SOCKS proxies from within urllib3. This module supports SOCKS4 (specifically the SOCKS4A variant) and SOCKS5. To enable its functionality, either install PySocks or install this module with the ``socks`` extra. The SOCKS implementation supports the full range of urllib3 features. It also supports the following SOCKS features: - SOCKS4 - SOCKS4a - SOCKS5 - Usernames and passwords for the SOCKS proxy Known Limitations: - Currently PySocks does not support contacting remote websites via literal IPv6 addresses. Any such connection attempt will fail. You must use a domain name. - Currently PySocks does not support IPv6 connections to the SOCKS proxy. Any such connection attempt will fail. i(tabsolute_importNi(tDependencyWarningsSOCKS support in urllib3 requires the installation of optional dependencies: specifically, PySocks. For more information, see https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies(terrorttimeout(tHTTPConnectiontHTTPSConnection(tHTTPConnectionPooltHTTPSConnectionPool(tConnectTimeoutErrortNewConnectionError(t PoolManager(t parse_urltSOCKSConnectioncB@s eZdZdZdZRS(sG A plain-text HTTP connection that connects via a SOCKS proxy. cO@s/|jd|_tt|j||dS(Nt_socks_options(tpopR tsuperR t__init__(tselftargstkwargs((sE/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/socks.pyR?scC@si}|jr|j|ds2    FPK!RF9gg ntlmpool.pycnu[ abc@@s|dZddlmZddlmZddlmZddlmZddlm Z ee Z defd YZ d S( s NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 i(tabsolute_import(t getLogger(tntlmi(tHTTPSConnectionPool(tHTTPSConnectiontNTLMConnectionPoolcB@s>eZdZdZdZdZdddeedZRS(sQ Implements an NTLM authentication version of an urllib3 connection pool thttpscO@sjtt|j||||_||_|jdd}|dj|_|d|_||_ dS(s authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\username format. pw is the password for the user. s\iiN( tsuperRt__init__tauthurltrawusertsplittuppertdomaintusertpw(tselfRRR targstkwargst user_parts((sH/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/ntlmpool.pyRs   c C@s|jd7_tjd|j|j|ji}d|ds PK!oe __init__.pycnu[ abc@sdS(N((((sH/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/__init__.pyttPK!RF9gg ntlmpool.pyonu[ abc@@s|dZddlmZddlmZddlmZddlmZddlm Z ee Z defd YZ d S( s NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 i(tabsolute_import(t getLogger(tntlmi(tHTTPSConnectionPool(tHTTPSConnectiontNTLMConnectionPoolcB@s>eZdZdZdZdZdddeedZRS(sQ Implements an NTLM authentication version of an urllib3 connection pool thttpscO@sjtt|j||||_||_|jdd}|dj|_|d|_||_ dS(s authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\username format. pw is the password for the user. s\iiN( tsuperRt__init__tauthurltrawusertsplittuppertdomaintusertpw(tselfRRR targstkwargst user_parts((sH/usr/lib/python2.7/site-packages/pip/_vendor/urllib3/contrib/ntlmpool.pyRs   c C@s|jd7_tjd|j|j|ji}d|ds PK!j..rubyforgepublisher.rbnu[PK!Jn $$ spublisher.rbnu[PK!4sys.rbnu[PK!ȉ`t__compositepublisher.rbnu[PK!Vlhsshpublisher.rbnu[PK!¬P q#ftptools.rbnu[PK!W2socks.pynu[PK! K__init__.pynu[PK!K_securetransport/__init__.pynu[PK!Y}DD L_securetransport/bindings.pynu[PK!"-X(X(:_securetransport/__pycache__/bindings.cpython-36.opt-1.pycnu[PK!cl;_securetransport/__pycache__/low_level.cpython-36.opt-1.pycnu[PK!cl5_securetransport/__pycache__/low_level.cpython-36.pycnu[PK!"-X(X(4=_securetransport/__pycache__/bindings.cpython-36.pycnu[PK!5@qq4_securetransport/__pycache__/__init__.cpython-36.pycnu[PK!5@qq:_securetransport/__pycache__/__init__.cpython-36.opt-1.pycnu[PK!sK//_securetransport/low_level.pynu[PK!/xN_appengine_environ.pynu[PK! evevQsecuretransport.pynu[PK!s{GEGE01__pycache__/securetransport.cpython-36.opt-1.pycnu[PK!