Override SocketHandler.makeSocket, to allow creating wrapped
        TLS sockets
162864
def makeSocket(self, timeout=1):
        """"""
        plain_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        if hasattr(plain_socket, 'settimeout'):
            plain_socket.settimeout(timeout)

        wrapped_socket = ssl.wrap_socket(
            plain_socket,
            ca_certs=self.ca_certs,
            cert_reqs=self.reqs,
            keyfile=self.keyfile,
            certfile=self.certfile
        )
        wrapped_socket.connect((self.host, self.port))

        return wrapped_socket
984946
def start_tls(self, ssl_context: Union[bool, dict, ssl.SSLContext]=True) \
            -> 'SSLConnection':
        '''
        '''
        sock = self.writer.get_extra_info('socket')
        ssl_conn = SSLConnection(
            self._address,
            ssl_context=ssl_context,
            hostname=self._hostname, timeout=self._timeout,
            connect_timeout=self._connect_timeout, bind_host=self._bind_host,
            bandwidth_limiter=self._bandwidth_limiter, sock=sock
        )

        yield from ssl_conn.connect()

        return ssl_conn
1059878
def create_tcp_socket (self, host):
        """"""
        port = int(self['TCPSocket'])
        sockinfo = get_sockinfo(host, port=port)
        sock = create_socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.connect(sockinfo[0][4])
        except socket.error:
            sock.close()
            raise
        return sock
936311
function Socket(/* [options] */) {
    events.EventEmitter.call(this);
    var self = this;

    // Socket
    if (arguments[0] instanceof net.Socket) {
        this._socket = arguments[0];
    } else {
        var options = arguments[0] || {};
        this._socket = new net.Socket(options);
    }
    
    // Configuration
    this.signature = 174021652;

    // Read data
    this._buffers = [];
    this._offset = 0;            // Current offset in the first buffer    
    this._length = 0;            // Sum of all buffers minus offset
    this._messageLength = null;

    // Write data
    this._header = new Buffer(8);
    this._header.writeUInt32BE(this.signature, 0);

    // Event handlers
    this._socket.on('data', this.onData.bind(this));

    // Relay some of the socket events that don't need to be handled
    [   'connect',
        'end',
        'close',
        'timeout',
        'drain',
        'error'
    ].forEach(function (event) {
        self._socket.on(event, function (data) {
            self.emit(event, data);
        });
    });

    // Relay some of the socket properties that don't need to be handled
    [   'remoteAddress',
        'remotePort',
        'bytesRead',
        'bytesWritten',
        'bufferSize'
    ].forEach(function (propertyName) {
        Object.defineProperty(self, propertyName, {
            get: function () {
                return self._socket[propertyName];
            },
            enumerable: true
        });
    });

    // Relay some of the socket functions that don't need to be handled
    [   'connect',
        'destroy',
        'pause',
        'resume',
        'setTimeout',
        'setNoDelay',
        'setKeepAlive',
        'address'
    ].forEach(function (functionName) {
        self[functionName] = function () {
            return self._socket[functionName].apply(self._socket, arguments);
        };
    });
}
608672
public static ProtocolNegotiator serverTls(final SslContext sslContext) {
    Preconditions.checkNotNull(sslContext, "sslContext");
    return new ProtocolNegotiator() {
      @Override
      public ChannelHandler newHandler(GrpcHttp2ConnectionHandler handler) {
        return new ServerTlsHandler(sslContext, handler);
      }

      @Override
      public void close() {}


      @Override
      public AsciiString scheme() {
        return Utils.HTTPS;
      }
    };
  }
270704
public SSLSocketFactory createSslSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{this}, null);
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new AssertionError(e);
        }
    }
606286
public static SocketFactory createSSLClientSocketFactory(Configuration config) throws Exception {
		SSLContext sslContext = createInternalSSLContext(config);
		if (sslContext == null) {
			throw new IllegalConfigurationException("SSL is not enabled");
		}

		return sslContext.getSocketFactory();
	}
781945
def _createSocket(self, port):
        '''
        
        '''
        self._logger.info(
            'Setting up UDP socket to listen to port {:}'.format(port))
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        sock.settimeout(self._timeout)
        self._logger.info(
            'Successfully set socket timeout to {_timeout}'
            .format(**self.__dict__))

        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._logger.info('Successfully set socket option to SO_REUSEADDR')

        sock.bind(('', port))
        self._logger.info(
            'Successfully bound socket to ("", {port})'
            .format(port=port, **self.__dict__))

        return sock
497454
private SSLEngineResult doHandshake(boolean async) throws IOException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "doHandshake");
        }

        SSLEngineResult sslResult;
        // Line up all the buffers needed for the SSL handshake. Temporary so
        // use indirect allocation for speed.
        int appSize = getConnLink().getAppBufferSize();
        int packetSize = getConnLink().getPacketBufferSize();
        WsByteBuffer localNetBuffer = SSLUtils.allocateByteBuffer(packetSize, true);
        WsByteBuffer decryptedNetBuffer = SSLUtils.allocateByteBuffer(appSize, false);
        WsByteBuffer encryptedAppBuffer = SSLUtils.allocateByteBuffer(packetSize, true);
        // Callback to be used if the request is async.
        MyHandshakeCompletedCallback handshakeCallback = null;
        if (async) {
            handshakeCallback = new MyHandshakeCompletedCallback(this, callback, localNetBuffer, decryptedNetBuffer, encryptedAppBuffer);
        }

        try {
            // Do the SSL handshake. Note, if synchronous the handshakeCallback is null.
            sslResult = SSLUtils.handleHandshake(
                                                 getConnLink(),
                                                 localNetBuffer,
                                                 decryptedNetBuffer,
                                                 encryptedAppBuffer,
                                                 null,
                                                 handshakeCallback,
                                                 false);
        } catch (IOException e) {
            // Release buffers used in the handshake.
            localNetBuffer.release();
            localNetBuffer = null;
            decryptedNetBuffer.release();
            decryptedNetBuffer = null;
            encryptedAppBuffer.release();
            encryptedAppBuffer = null;
            throw e;
        }
        if (sslResult != null) {
            // Handshake was done synchronously.
            // Release buffers used in the handshake.
            localNetBuffer.release();
            localNetBuffer = null;
            decryptedNetBuffer.release();
            decryptedNetBuffer = null;
            encryptedAppBuffer.release();
            encryptedAppBuffer = null;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "doHandshake");
        }
        return sslResult;
    }
98348
def start_tls(req, options)
      return unless req.uri.https? && !failed_proxy_connect?

      ssl_context = options.ssl_context

      unless ssl_context
        ssl_context = OpenSSL::SSL::SSLContext.new
        ssl_context.set_params(options.ssl || {})
      end

      @socket.start_tls(req.uri.host, options.ssl_socket_class, ssl_context)
    end
326355
private TSocket createTLSSocket(String host) throws TTransportException {
        TSSLTransportParameters sslParams = new TSSLTransportParameters("SSL", m_dbtls_cipher_suites);
        if (!Utils.isEmpty(m_keystore)) {
            sslParams.setKeyStore(m_keystore, m_keystorepassword);
        }
        if (!Utils.isEmpty(m_truststore)) {
            sslParams.setTrustStore(m_truststore, m_truststorepassword);
        }
        return TSSLTransportFactory.getClientSocket(host, m_dbport, m_db_timeout_millis, sslParams);
    }
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)
531978
private static SSLSocketFactory createSocketFactory(Ssl context) {
    try {
      return context.newFactory(new AlwaysTrustManager());
    } catch (Exception e) {
      throw new IllegalStateException("Fail to build SSL factory", e);
    }
  }
1317339
public Socket createSocket(
        final Socket socket,
        final String host,
        final int port,
        final boolean autoClose
    ) throws IOException, UnknownHostException {
        SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket(
              socket,
              host,
              port,
              autoClose
        );
        hostnameVerifier.verify(host, sslSocket);
        // verifyHostName() didn't blowup - good!
        return sslSocket;
    }
1285382
private ServerSocket createServerSocket(int port) throws IOException {
    try {
      ServerSocket sock = new ServerSocket();
      // Prevent 2MSL delay problem on server restarts
      sock.setReuseAddress(true);
      // Bind to listening port
      if (port == 0) {
        sock.bind(null);
        serverPort = sock.getLocalPort();
      } else {
        sock.bind(new InetSocketAddress(port));
      }
      return sock;
    } catch (IOException ioe) {
      throw new IOException("Could not create ServerSocket on port " + port + "." +
                            ioe);
    }
  }
280279
def make_tls_property(default=None):
    """"""
    class TLSProperty(object):
        def __init__(self):
            from threading import local
            self.local = local()

        def __get__(self, instance, cls):
            if not instance:
                return self
            return self.value

        def __set__(self, instance, value):
            self.value = value

        def _get_value(self):
            return getattr(self.local, 'value', default)
        def _set_value(self, value):
            self.local.value = value
        value = property(_get_value, _set_value)

    return TLSProperty()
948011
def prepare_socket(bind_addr, family, type, proto, nodelay, ssl_adapter):
        """"""
        sock = socket.socket(family, type, proto)
        prevent_socket_inheritance(sock)

        host, port = bind_addr[:2]
        IS_EPHEMERAL_PORT = port == 0

        if not (IS_WINDOWS or IS_EPHEMERAL_PORT):
            """Enable SO_REUSEADDR for the current socket.

            Skip for Windows (has different semantics)
            or ephemeral ports (can steal ports from others).

            Refs:
            * https://msdn.microsoft.com/en-us/library/ms740621(v=vs.85).aspx
            * https://github.com/cherrypy/cheroot/issues/114
            * https://gavv.github.io/blog/ephemeral-port-reuse/
            """
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if nodelay and not isinstance(bind_addr, str):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

        if ssl_adapter is not None:
            sock = ssl_adapter.bind(sock)

        # If listening on the IPV6 any address ('::' = IN6ADDR_ANY),
        # activate dual-stack. See
        # https://github.com/cherrypy/cherrypy/issues/871.
        listening_ipv6 = (
            hasattr(socket, 'AF_INET6')
            and family == socket.AF_INET6
            and host in ('::', '::0', '::0.0.0.0')
        )
        if listening_ipv6:
            try:
                sock.setsockopt(
                    socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0,
                )
            except (AttributeError, socket.error):
                # Apparently, the socket option is not available in
                # this machine's TCP stack
                pass

        return sock