Make server sockets

@throws SocketException|\Exception
@return void
11503
protected function makeSocket(): void
    {
        if ($this->useSSL) {
            if (!file_exists($this->cert)) {
                throw new \Exception('Cert file not found');
            }

            $context = stream_context_create([
                'ssl' => [
                    'local_cert'        => $this->cert,
                    'passphrase'        => $this->passPhrase,
                    'verify_peer'       => false,
                    'verify_peer_name'  => false,
                    'allow_self_signed' => true,
                    'verify_depth'      => 0
                ]
            ]);

            $protocol = 'ssl';
        } else {
            $context = stream_context_create();
            $protocol = 'tcp';
        }

        $this->socket = stream_socket_server("$protocol://{$this->host}:{$this->port}", $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);

        if ($this->useConnector) {
            if (file_exists(static::$connector)) {
                unlink(static::$connector);
            }

            $this->unixConnector = stream_socket_server('unix://' . static::$connector, $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
            chmod(static::$connector, 0777);
        }

        if (!$this->socket) {
            throw new SocketException($errorString, $errorNumber);
        }
    }
672083
private function createServerInstance()
    {
        if (! $this->serverInstance instanceof $this->class) {
            $class = $this->class;
            $this->serverInstance = $this->ratchetServer = new $class($this);
        }
    }
22405
public function connect()
    {
        if ($this->connection) {
            $this->disconnect();
        }

        $hasProtocol = strpos($this->_config['host'], '://') !== false;
        if ($hasProtocol) {
            list($this->_config['protocol'], $this->_config['host']) = explode('://', $this->_config['host']);
        }
        $scheme = null;
        if (!empty($this->_config['protocol'])) {
            $scheme = $this->_config['protocol'] . '://';
        }

        $this->_setSslContext($this->_config['host']);
        if (!empty($this->_config['context'])) {
            $context = stream_context_create($this->_config['context']);
        } else {
            $context = stream_context_create();
        }

        $connectAs = STREAM_CLIENT_CONNECT;
        if ($this->_config['persistent']) {
            $connectAs |= STREAM_CLIENT_PERSISTENT;
        }

        set_error_handler([$this, '_connectionErrorHandler']);
        $this->connection = stream_socket_client(
            $scheme . $this->_config['host'] . ':' . $this->_config['port'],
            $errNum,
            $errStr,
            $this->_config['timeout'],
            $connectAs,
            $context
        );
        restore_error_handler();

        if (!empty($errNum) || !empty($errStr)) {
            $this->setLastError($errNum, $errStr);
            throw new SocketException($errStr, $errNum);
        }

        if (!$this->connection && $this->_connectionErrors) {
            $message = implode("\n", $this->_connectionErrors);
            throw new SocketException($message, E_WARNING);
        }

        $this->connected = is_resource($this->connection);
        if ($this->connected) {
            stream_set_timeout($this->connection, $this->_config['timeout']);
        }

        return $this->connected;
    }
1031899
public function initWebSocketServer()
    {
        $webSocketServer = $this->getWebSocketServer();

        $webSocketServer->setLogger(
            $this->getLogger()
        );

        if ($this->getNodeClass() !== null) {
            $webSocketServer->getConnection()->setNodeName(
                $this->getNodeClass()
            );
        }

        $socket = $webSocketServer->getConnection()->getSocket();

        $this->getLogger()->log('<fg=yellow>Starting server...</fg=yellow>');
        $this->getLogger()->log('Environment: <fg=green>%s</fg=green>', $this->kernelEnvironment);
        $this->getLogger()->log('Class used:');
        $this->getLogger()->log('  Logger           : %s', get_class($this->getLogger()));
        $this->getLogger()->log('  Runner           : %s', get_class($this));
        $this->getLogger()->log('  WebSocket Server : %s', get_class($webSocketServer));
        $this->getLogger()->log('  Socket Server    : %s', get_class($socket));
        $this->getLogger()->log('  Node             : %s', ltrim($webSocketServer->getConnection()->getNodeName(), '\\'));

        $this->getLogger()->log(
            '<fg=yellow>Listening on %s:%d</fg=yellow>',
            $socket->getAddress(),
            $socket->getPort()
        );

        $webSocketServer->on('open', xcallable($this, 'onOpen'));
        $webSocketServer->on('message', xcallable($this, 'onMessage'));
        $webSocketServer->on('binary-message', xcallable($this, 'onBinaryMessage'));
        $webSocketServer->on('ping', xcallable($this, 'onPing'));
        $webSocketServer->on('error', xcallable($this, 'onError'));
        $webSocketServer->on('close', xcallable($this, 'onClose'));

        $this->loadEvents();

        return $webSocketServer;
    }
1092629
public function open()
    {
        // Connect the socket.
        if (@!socket_connect($this->socket, $this->host, $this->port)) {
         Logger::get()->error(socket_strerror(socket_last_error()));
            throw new Exception('Socket connection error: ' . socket_strerror(socket_last_error()));
        }
    }
447442
protected function _connect()
    {
        $this->_generateSocket();
        if (!$this->_socket->connect()) {
            throw new SocketException('Unable to connect to SMTP server.');
        }
        $this->_smtpSend(null, '220');

        $config = $this->_config;

        if (isset($config['client'])) {
            $host = $config['client'];
        } elseif ($httpHost = env('HTTP_HOST')) {
            list($host) = explode(':', $httpHost);
        } else {
            $host = 'localhost';
        }

        try {
            $this->_smtpSend("EHLO {$host}", '250');
            if ($config['tls']) {
                $this->_smtpSend('STARTTLS', '220');
                $this->_socket->enableCrypto('tls');
                $this->_smtpSend("EHLO {$host}", '250');
            }
        } catch (SocketException $e) {
            if ($config['tls']) {
                throw new SocketException('SMTP server did not accept the connection or trying to connect to non TLS SMTP server using TLS.', null, $e);
            }
            try {
                $this->_smtpSend("HELO {$host}", '250');
            } catch (SocketException $e2) {
                throw new SocketException('SMTP server did not accept the connection.', null, $e2);
            }
        }
    }
431175
private function acceptConnection(): void
    {
        $clientSocket = @stream_socket_accept($this->serverSocket);

        if (false !== $clientSocket) {
            stream_set_blocking($clientSocket, false);

            $connection = new StreamSocketConnection($clientSocket);

            $id = spl_object_hash($connection);

            $this->clientSockets[$id] = $clientSocket;
            $this->connections[$id]   = $connection;
        }
    }
890812
public function connect(): void
    {
        // no need to get excited
        if ($this->isConnected()) {
            return;
        }

        // export credentials & others
        [$host, $name, $username, $password] = [
            $this->config['host'], $this->config['name'],
            $this->config['username'], $this->config['password'],
        ];
        $port = (int) $this->config['port'];
        $socket = (string) $this->config['socket'];

        // call big boss
        $resource = mysqli_init();

        // supported constants: http://php.net/mysqli.options
        if (isset($this->config['options'])) {
            foreach ($this->config['options'] as $option => $value) {
                if (!$resource->options($option, $value)) {
                    throw new ConnectionException("Setting '{$option}' option failed!");
                }
            }
        }

        // start connection profile
        $this->profiler && $this->profiler->start('connection');

        $resourceStatus =@ $resource->real_connect($host, $username, $password, $name, $port, $socket);
        if (!$resourceStatus) {
            $error = $this->parseConnectionError();
            throw new ConnectionException($error['message'], $error['code'], $error['sql_state']);
        }

        // finish connection profile
        $this->profiler && $this->profiler->end('connection');

        // log with info level
        $this->logger && $this->logger->log(Logger::INFO, sprintf('New connection via %s addr.', Util::getIp()));

        // set charset for connection
        if (isset($this->config['charset'])) {
            $run = $resource->set_charset($this->config['charset']);
            if (!$run) {
                throw new ConnectionException(sprintf('Unable to connect to MySQL server at "%s", '.
                    'invalid or not-supported character set "%s" given!', $this->config['host'], $this->config['charset']),
                        $resource->errno, SqlState::OPPA_CHARSET_ERROR);
            }
        }

        // set timezone for connection
        if (isset($this->config['timezone'])) {
            $run = $resource->query('SET time_zone = \''. $resource->real_escape_string($this->config['timezone']) .'\'');
            if (!$run) {
                throw new ConnectionException(sprintf('Unable to connect to MySQL server at "%s", '.
                    'invalid or not-supported timezone "%s" given.', $this->config['host'], $this->config['timezone']),
                        $resource->errno, SqlState::OPPA_TIMEZONE_ERROR);
            }
        }

        // assign resource
        $this->resource = new Resource($resource);

        // fill mapper map for once
        if ($this->mapper) {
            $map = $cache = null;
            if ($this->config['map_result_cache']) {
                $cache = new Cache();
                $cache->read('mapper.map', $map, true, $this->config['map_result_cache_ttl']);
            }

            if ($map == null) {
                try {
                    $result = $this->query("SELECT table_name, column_name, data_type, is_nullable, numeric_precision, character_maximum_length FROM information_schema.columns WHERE table_schema = '{$name}'", null, -1, 2);
                    if ($result->count()) {
                        $map = [];
                        foreach ($result->items() as $item) {
                            $item = (object) array_change_key_case($item); // normalize key cases

                            $length = null;
                            if ($item->data_type == 'bit') { // for only bools
                                $length = (int) $item->numeric_precision;
                            } elseif (substr($item->data_type, -4) == 'char') { // for extra (char) crop
                                $length = (int) $item->character_maximum_length;
                            }

                            $map[$item->table_name][$item->column_name] = [
                                /* type */ Mapper::normalizeType($item->data_type, $length),
                                /* length */ $length,
                                /* nullable */ ($item->is_nullable == 'YES'),
                            ];
                        }

                        $cache && $cache->write('mapper.map', $map);
                    }
                    $result->reset();
                } catch (QueryException $e) {
                    throw new QueryException('Could not retrieve schema info for mapper!', null,
                        SqlState::OPPA_CONNECTION_ERROR, $e);
                }
            }

            // set map
            $this->mapper->setMap($map);
        }
    }
1239469
protected function connect(): void
    {
        $this->connection = @\stream_socket_client( // @ is escalated to exception
            ($this->secure === 'ssl' ? 'ssl://' : '') . $this->host . ':' . $this->port,
            $errno, $error, $this->timeout, STREAM_CLIENT_CONNECT, $this->context
        );
        if (!$this->connection) {
            throw new SmtpException($error ?: error_get_last()['message'], $errno);
        }
        \stream_set_timeout($this->connection, $this->timeout, 0);
        $this->read(); // greeting

        $this->write("EHLO {$this->clientHost}");
        $ehloResponse = $this->read();
        if ((int) $ehloResponse !== 250) {
            $this->write("HELO {$this->clientHost}", 250);
        }

        if ($this->secure === 'tls') {
            $this->write('STARTTLS', 220);
            if (!\stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
                throw new SmtpException('Unable to connect via TLS.');
            }
            $this->write("EHLO {$this->clientHost}", 250);
        }

        $password = $this->getPassword();
        if ($this->username !== '' && $password !== '') {
            $authMechanisms = [];
            if (\preg_match('~^250[ -]AUTH (.*)$~im', $ehloResponse, $matches)) {
                $authMechanisms = \explode(' ', \trim($matches[1]));
            }

            if (\in_array('PLAIN', $authMechanisms, true)) {
                $credentials = $this->username . "\0" . $this->username . "\0" . $password;
                $this->write('AUTH PLAIN ' . \base64_encode($credentials), 235, 'PLAIN credentials');
            } else {
                $this->write('AUTH LOGIN', 334);
                $this->write(\base64_encode($this->username), 334, 'username');
                $this->write(\base64_encode($password), 235, 'password');
            }
        }
    }
1191400
def __make_server(self):
        ""
        notice('Making server, getting listening socket', self.color)
        self.mode = 's'
        sock = utils.get_server_sock()
        self.__s = sock
        with self.__client_list_lock:
            self.clients = deque()
        self.threads = deque()
        notice('Making beacon', self.color)
        b = Thread(target=self.__beacon_thread, name='beacon')
        b.start()
        self.threads.append(b)
        l = Thread(target=self.__listen_thread, name='listen')
        notice('Starting listen thread', self.color)
        l.start()
        self.threads.append(l)
27599
protected function createSwooleServer()
    {
        $server = $this->isWebsocket ? WebsocketServer::class : HttpServer::class;
        $config = $this->app->make('config');
        $host = $config->get('swoole_http.server.host');
        $port = $config->get('swoole_http.server.port');
        $socketType = $config->get('swoole_http.server.socket_type', SWOOLE_SOCK_TCP);
        $processType = $config->get('swoole.http.server.process_type', SWOOLE_PROCESS);

        static::$server = new $server($host, $port, $processType, $socketType);
    }
985478
private function startWampServer()
    {
        if (! $this->serverInstance instanceof RatchetWampServer) {
            throw new \Exception("{$this->class} must be an instance of ".RatchetWampServer::class." to create a Wamp server");
        }

        // Decorate the server instance with a WampServer
        $this->serverInstance = new WampServer($this->serverInstance);

        return $this->bootWebSocketServer(true);
    }
1060928
public function start()
    {
        // Create server instance
        $this->serverInstance = $this->createSwooleServerInstance();

        // Bind server events
        $this->bindSwooleServerEvents($this->serverInstance);

        // Start
        $this->serverInstance->start();
    }
945072
protected function configureServerSockets($server, array $serverSockets)
    {
        foreach ($serverSockets as $config) {
            $serverSocket = $this->createServerSocket($config);

            if ($handler = $this->parseEventHandler($config)) {
                $serverSocket->setEventHandler($handler);
            }

            $server->listen($serverSocket);
        }
    }
1181056
protected function processMasterSocket(): void
    {
        $new = null;

        try {
            $new = $this->socket->accept();
        } catch (Exception $e) {
            $this->logger->error('Socket error: {exception}', [
                'exception' => $e,
            ]);
            return;
        }

        $connection = $this->createConnection($new);
        $this->server->notify(Server::EVENT_SOCKET_CONNECT, [$new, $connection]);
    }
1065714
public function listen()
    {

        if (!$this->_socketName || $this->_mainSocket) {
            return;
        }

        // Autoload.
        Autoloader::setRootPath($this->_autoloadRootPath);

        // Get the application layer communication protocol and listening address.
        list($scheme, $address) = explode(':', $this->_socketName, 2);
        // Check application layer protocol class.
        if (!isset(self::$_builtinTransports[$scheme])) {
            if(class_exists($scheme)){
                $this->protocol = $scheme;
            } else {
                $scheme         = ucfirst($scheme);
                $this->protocol = '\\Protocols\\' . $scheme;
                if (!class_exists($this->protocol)) {
                    $this->protocol = "\\Workerman\\Protocols\\$scheme";
                    if (!class_exists($this->protocol)) {
                        throw new Exception("class \\Protocols\\$scheme not exist");
                    }
                }
            }
            if (!isset(self::$_builtinTransports[$this->transport])) {
                throw new \Exception('Bad worker->transport ' . var_export($this->transport, true));
            }
        } else {
            $this->transport = $scheme;
        }

        $local_socket = self::$_builtinTransports[$this->transport] . ":" . $address;

        // Flag.
        $flags  = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
        $errno  = 0;
        $errmsg = '';
        // SO_REUSEPORT.
        if ($this->reusePort) {
            stream_context_set_option($this->_context, 'socket', 'so_reuseport', 1);
        }

        // Create an Internet or Unix domain server socket.
        $this->_mainSocket = stream_socket_server($local_socket, $errno, $errmsg, $flags, $this->_context);
        if (!$this->_mainSocket) {
            throw new Exception($errmsg);
        }

        if ($this->transport === 'ssl') {
            stream_socket_enable_crypto($this->_mainSocket, false);
        }

        // Try to open keepalive for tcp and disable Nagle algorithm.
        if (function_exists('socket_import_stream') && self::$_builtinTransports[$this->transport] === 'tcp') {
            $socket = socket_import_stream($this->_mainSocket);
            @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
            @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
        }

        // Non blocking.
        stream_set_blocking($this->_mainSocket, 0);

        // Register a listener to be notified when server socket is ready to read.
        if (self::$globalEvent) {
            if ($this->transport !== 'udp') {
                self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ, array($this, 'acceptConnection'));
            } else {
                self::$globalEvent->add($this->_mainSocket, EventInterface::EV_READ,
                    array($this, 'acceptUdpConnection'));
            }
        }
    }
1095617
protected function connect()
    {
        if (!empty($this->conn)) {
            return;
        }

        if (!extension_loaded('ssh2')) {
            throw new ServerException(
                "Unable to initialize sftp storage server, extension 'ssh2' not found"
            );
        }

        $session = ssh2_connect(
            $this->options['host'],
            $this->options['port'],
            $this->options['methods']
        );

        if (empty($session)) {
            throw new ServerException(
                "Unable to connect to remote SSH server '{$this->options['host']}'"
            );
        }

        //Authorization
        switch ($this->options['authMethod']) {
            case self::NONE:
                ssh2_auth_none($session, $this->options['username']);
                break;

            case self::PASSWORD:
                ssh2_auth_password(
                    $session,
                    $this->options['username'],
                    $this->options['password']
                );
                break;

            case self::PUB_KEY:
                ssh2_auth_pubkey_file(
                    $session,
                    $this->options['username'],
                    $this->options['publicKey'],
                    $this->options['privateKey'],
                    $this->options['secret']
                );
                break;
        }

        $this->conn = ssh2_sftp($session);
    }