Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.
178775
def inject_into_urllib3():
    ''

    _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
1112333
def wrap_requests(requests_func):
    """"""
    def call(url, *args, **kwargs):
        blacklist_hostnames = execution_context.get_opencensus_attr(
            'blacklist_hostnames')
        parsed_url = urlparse(url)
        if parsed_url.port is None:
            dest_url = parsed_url.hostname
        else:
            dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
        if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
            return requests_func(url, *args, **kwargs)

        _tracer = execution_context.get_opencensus_tracer()
        _span = _tracer.start_span()
        _span.name = '[requests]{}'.format(requests_func.__name__)
        _span.span_kind = span_module.SpanKind.CLIENT

        # Add the requests url to attributes
        _tracer.add_attribute_to_current_span(HTTP_URL, url)

        result = requests_func(url, *args, **kwargs)

        # Add the status code to attributes
        _tracer.add_attribute_to_current_span(
            HTTP_STATUS_CODE, str(result.status_code))

        _tracer.end_span()
        return result

    return call
1022289
def open_url(self, url):
        
        try:
            c = pycurl.Curl()
            c.setopt(pycurl.FAILONERROR, True)
            c.setopt(pycurl.URL, "%s/api/v0/%s" % (self.url, url))
            c.setopt(pycurl.HTTPHEADER, ["User-Agent: %s" % self.userAgent,
                                         "apiToken: %s" % self.apiToken])
            b = StringIO.StringIO()
            c.setopt(pycurl.WRITEFUNCTION, b.write)
            c.setopt(pycurl.FOLLOWLOCATION, 1)
            c.setopt(pycurl.MAXREDIRS, 5)
            # Persoonlijkrooster only supports SSLv3, not the default SSLv23.
            c.setopt(pycurl.SSLVERSION, pycurl.SSLVERSION_SSLv3) 
            # Verify authenticity of peer's certificate. (0 will not check it)
            c.setopt(pycurl.SSL_VERIFYPEER, 1)
            # Verify that domain in URL matches to the Common Name Field or
            # a Subject Alternate Name field in the certificate.
            # (0 will not check it; 1 is an invalid value)
            c.setopt(pycurl.SSL_VERIFYHOST, 2) 
            c.perform()
            return b.getvalue()
        except pycurl.error, e:
            raise MyTimetableError(e)
71622
def _get_ssl_sock(self):
        """"""
        assert self.scheme == u"https", self
        raw_connection = self.url_connection.raw._connection
        if raw_connection.sock is None:
            # sometimes the socket is not yet connected
            # see https://github.com/kennethreitz/requests/issues/1966
            raw_connection.connect()
        return raw_connection.sock
1276417
def chunk(url):
    
    chunks = lambda l, n: [l[x: x+n] for x in xrange(0, len(l), n)]
    url_64 = base64.urlsafe_b64encode(url)
    return chunks(url_64, 255)
371614
def chomp_protocol(url):
        
        if '+' in url:
            url = url.split('+', 1)[1]
        scheme, netloc, path, query, frag = urlparse.urlsplit(url)
        rev = None
        if '@' in path:
            path, rev = path.rsplit('@', 1)
        url = urlparse.urlunsplit((scheme, netloc, path, query, ''))
        if url.startswith('ssh://git@github.com/'):
            url = url.replace('ssh://', 'git+ssh://')
        elif '://' not in url:
            assert 'file:' not in url
            url = url.replace('git+', 'git+ssh://')
            url = url.replace('ssh://', '')
        return url
221287
function peerResolved (ip, addressType) {
    // Possible cancelation during DNS lookup.
    if (!socket._connecting) return;

    socket._peer = { address: ip || '127.0.0.1', port: options.port };

    // Generate random bytes used to set randomized socket properties.
    // `crypto.randomBytes` calls OpenSSL `RAND_bytes` to generate the bytes.
    //
    //  * [RAND_bytes](http://www.openssl.org/docs/crypto/RAND_bytes.html).
    //  * [node_crypto.cc](https://github.com/joyent/node/blob/v0.8/src/node_crypto.cc#L4517)
    crypto.randomBytes(4, valid(randomzied));
  }
459600
def connect_ssl(cls, user, password, endpoints,
                    ca_certs=None, validate=None):
        
        if isinstance(endpoints, basestring):
            endpoints = [endpoints]
        transport = SingleEndpointTransport(
            SocketTransport.connect_ssl, endpoints, ca_certs=ca_certs,
            validate=validate)
        return cls(transport, user, password)
735397
function HttpsProxyingAgent(options) {
  options.tunnel = true;
  ProxyingAgent.call(this, options, https.Agent);
}
679074
def wrap(self, sock):
        """"""
        try:
            s = ssl.wrap_socket(sock, do_handshake_on_connect=True,
                    server_side=True, certfile=self.certificate,
                    keyfile=self.private_key, ssl_version=ssl.PROTOCOL_SSLv23)
        except ssl.SSLError, e:
            if e.errno == ssl.SSL_ERROR_EOF:
                # This is almost certainly due to the cherrypy engine
                # 'pinging' the socket to assert it's connectable;
                # the 'ping' isn't SSL.
                return None, {}
            elif e.errno == ssl.SSL_ERROR_SSL:
                if e.args[1].endswith('http request'):
                    # The client is speaking HTTP to an HTTPS server.
                    raise wsgiserver.NoSSLError
            raise
        return s, self.get_environ(s)
217340
def srp(x, promisc=None, iface=None, iface_hint=None, filter=None,
        nofilter=0, type=ETH_P_ALL, *args, **kargs):
    """"""
    if iface is None and iface_hint is not None:
        iface = conf.route.route(iface_hint)[0]
    s = conf.L2socket(promisc=promisc, iface=iface,
                      filter=filter, nofilter=nofilter, type=type)
    result = sndrcv(s, x, *args, **kargs)
    s.close()
    return result
306632
def _ssl_wrap_socket(self, sock):
        
        context = self._parameters['ssl_options'].get('context')
        if context is not None:
            hostname = self._parameters['ssl_options'].get('server_hostname')
            return context.wrap_socket(
                sock, do_handshake_on_connect=True,
                server_hostname=hostname
            )
        if 'ssl_version' not in self._parameters['ssl_options']:
            self._parameters['ssl_options']['ssl_version'] = (
                compatibility.DEFAULT_SSL_VERSION
            )
        return ssl.wrap_socket(
            sock, do_handshake_on_connect=True,
            **self._parameters['ssl_options']
        )
250119
def monkey_patch_issue_25593():
    
    save = asyncio.selector_events.BaseSelectorEventLoop._sock_connect_cb

    @functools.wraps(save)
    def patched(instance, fut, sock, address):
        if not fut.done():
            save(instance, fut, sock, address)
    asyncio.selector_events.BaseSelectorEventLoop._sock_connect_cb = patched
504396
def _python_psk_client_callback(ssl_id, hint):
    
    if ssl_id not in _callbacks:
        return ("", "")
    else:
        res = _callbacks[ssl_id](hint)
        return res if isinstance(res, tuple) else (res, "")
552834
def _build_ssl_context(cls, session: AppSession) -> ssl.SSLContext:
        '''
        '''
        args = session.args

        # Logic is based on tornado.netutil.ssl_options_to_context
        ssl_context = ssl.SSLContext(args.secure_protocol)

        if args.check_certificate:
            ssl_context.verify_mode = ssl.CERT_REQUIRED
            cls._load_ca_certs(session)
            ssl_context.load_verify_locations(session.ca_certs_filename)
        else:
            ssl_context.verify_mode = ssl.CERT_NONE

        if args.strong_crypto:
            ssl_context.options |= ssl.OP_NO_SSLv2
            ssl_context.options |= ssl.OP_NO_SSLv3  # POODLE

            if hasattr(ssl, 'OP_NO_COMPRESSION'):
                ssl_context.options |= ssl.OP_NO_COMPRESSION  # CRIME
            else:
                _logger.warning(_('Unable to disable TLS compression.'))

        if args.certificate:
            ssl_context.load_cert_chain(args.certificate, args.private_key)

        if args.edg_file:
            ssl.RAND_egd(args.edg_file)

        if args.random_file:
            with open(args.random_file, 'rb') as in_file:
                # Use 16KB because Wget
                ssl.RAND_add(in_file.read(15360), 0.0)

        return ssl_context
71896
def url_fix(s, charset=None):
    
    if charset:
        warnings.warn("{}.url_fix() charset argument is deprecated".format(__name__), DeprecationWarning)

    scheme, netloc, path, querystring, fragment = urlsplit(s)
    path = quote(path, b'/%')
    querystring = quote_plus(querystring, b':&=')
    return urlunsplit((scheme, netloc, path, querystring, fragment))
656149
def monkey_patch_bson(bson=None):
  ''''''
  if not bson:
    import bson

  if not hasattr(bson, 'loads'):
    bson.loads = lambda bsondoc: bson.BSON(bsondoc).decode()

  if not hasattr(bson, 'dumps'):
    bson.dumps = lambda document: bson.BSON.encode(document)