Handle initial connection and authentication, bind user data
to client, including filesystem, and switch the client to normal
run mode.
339553
function initClient(client) {
  var ws = client.ws;

  client.state = States.CONNECTING;

  // Wait until we get the user's token so we can finish authorizing
  ws.onmessage = function(msg) {
    var data;
    var info;

    try {
      // Keep track of how much data we receive
      info = client.info();
      if(info) {
        info.bytesReceived += Buffer.byteLength(msg.data, 'utf8');
      }

      data = JSON.parse(msg.data);
    } catch(err) {
      log.error({client: client, err: err}, 'Error parsing client token. Data was `%s`', msg.data);
      ClientInfo.remove(token);
      client.close({
        code: 1011,
        message: 'Error: token could not be parsed.'
      });
      return;
    }

    // Authorize user
    var token = data.token;
    var username = WebsocketAuth.getAuthorizedUsername(token);
    if (!username) {
      log.warn({client: client}, 'Client sent an invalid or expired token (could not get username): token=%s', token);
      ClientInfo.remove(token);
      client.close({
        code: 1008,
        message: 'Error: invalid token.'
      });
      return;
    }

    // Update client details now that he/she is authenticated
    client.id = token;
    client.username = username;
    client.fs = filesystem.create(username);
    ClientInfo.update(client);

    log.info({client: client}, 'Client connected');

    runClient(client);
  };
}
153870
def on_connect(self, client, userdata, flags, result_code):
        
        self.log_info("Connected with result code {}".format(result_code))
        self.state_handler.set_state(State.welcome)
746618
public void bind()
    throws Exception
  {
    if (_isBind.getAndSet(true)) {
      return;
    }

    if (_protocol == null) {
      throw new IllegalStateException(L.l("'{0}' must have a configured protocol before starting.", this));
    }

    // server 1e07
    if (_port < 0 && _unixPath == null) {
      return;
    }

    SocketSystem system = SocketSystem.current();

    if (_throttle == null) {
      _throttle = new ThrottleSocket();
    }
    
    //String protocolName = _protocol.name();
    
    String ssl = _sslFactory != null ? "s" : "";

    if (_serverSocket != null) {
      InetAddress address = _serverSocket.getLocalAddress();
      
      if (address != null)
        log.info("listening to " + address.getHostName() + ":" + _serverSocket.getLocalPort());
      else
        log.info("listening to *:" + _serverSocket.getLocalPort());
    }
    /*
    else if (_sslFactory != null && _socketAddress != null) {
      _serverSocket = _sslFactory.create(_socketAddress, _port);

      log.info(protocolName + "s listening to " + _socketAddress.getHostName() + ":" + _port);
    }
    else if (_sslFactory != null) {
      if (_address == null) {
        _serverSocket = _sslFactory.create(null, _port);
        log.info(protocolName + "s listening to *:" + _port);
      }
      else {
        InetAddress addr = InetAddress.getByName(_address);

        _serverSocket = _sslFactory.create(addr, _port);

        log.info(protocolName + "s listening to " + _address + ":" + _port);
      }
    }
    */
    else if (_socketAddress != null) {
      _serverSocket = system.openServerSocket(_socketAddress, _port,
                                              _acceptListenBacklog,
                                              _isEnableJni);
      
      log.info(_protocol.name() + ssl + " listening to " + _socketAddress.getHostName() + ":" + _serverSocket.getLocalPort());
    }
    else {
      _serverSocket = system.openServerSocket(null, _port, _acceptListenBacklog,
                                              _isEnableJni);
      
      log.info(_protocol.name() + ssl + " listening to *:"
               + _serverSocket.getLocalPort());
    }

    assert(_serverSocket != null);

    postBind();
  }
817310
def session_login(self, user=None, passwd=None):
        
        self.change_credentials(user=user, auth_token=passwd)
1074162
void load() throws StartException {
        FileInputStream fis = null;
        try {
            KeyStore loadedKeystore = KeyStore.getInstance(provider);

            if (new File(path).exists()) {
                fis = new FileInputStream(path);
                loadedKeystore.load(fis, keystorePassword);
            } else if (isKeyStore) {
                throw DomainManagementLogger.ROOT_LOGGER.keyStoreNotFound(path);
            } else {
                loadedKeystore.load(null);
            }

            if (isKeyStore) {
                assertContainsKey(loadedKeystore);
            }

            if (alias == null) {
                this.setKeyStore(loadedKeystore);
            } else {
                KeyStore newKeystore = KeyStore.getInstance(provider);
                newKeystore.load(null);

                KeyStore.ProtectionParameter passParam = new KeyStore.PasswordProtection(keyPassword == null ? keystorePassword
                        : keyPassword);

                if (loadedKeystore.containsAlias(alias)) {
                    if (loadedKeystore.isKeyEntry(alias)) {
                        KeyStore.Entry entry = loadedKeystore.getEntry(this.alias, passParam);
                        newKeystore.setEntry(alias, entry, passParam);
                    } else {
                        throw DomainManagementLogger.ROOT_LOGGER.aliasNotKey(alias, validAliasList(loadedKeystore));
                    }
                } else {
                    throw DomainManagementLogger.ROOT_LOGGER.aliasNotFound(alias, validAliasList(loadedKeystore));
                }

                this.setKeyStore(newKeystore);
            }
            this.lastModificationTime = new File(path).lastModified();
        } catch (KeyStoreException e) {
            throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e);
        } catch (NoSuchAlgorithmException e) {
            throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e);
        } catch (CertificateException e) {
            throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e);
        } catch (IOException e) {
            throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e);
        } catch (UnrecoverableEntryException e) {
            throw DomainManagementLogger.ROOT_LOGGER.unableToStart(e);
        } finally {
            safeClose(fis);
        }
    }
405915
def connect(self):
        

        # Make sure we're in client mode
        if self.mode and self.mode != 'client':
            raise ValueError("%s is not in client mode" %
                             self.__class__.__name__)
        self.mode = 'client'

        # If we're connected, nothing to do
        if self.conn:
            return

        # OK, attempt the connection
        fd = socket.create_connection((self.host, self.port))

        # Initialize the connection object
        self.conn = self.connection_class(fd)

        # Authenticate
        try:
            self.conn.send('AUTH', self.authkey)
            cmd, payload = self.conn.recv()
            if cmd != 'OK':
                LOG.error("Failed to authenticate to %s port %s: %s" %
                          (self.host, self.port, payload[0]))
                self.close()
        except Exception:
            exc_type, exc_value, exc_tb = sys.exc_info()

            # Log the error
            if exc_type == ValueError:
                LOG.error("Received bogus response from server: %s" %
                          str(exc_value))
            elif exc_type == ConnectionClosed:
                LOG.error("%s while authenticating to server" %
                          str(exc_value))
            else:
                LOG.exception("Failed to authenticate to server")

            # Close the connection
            self.close()

            # Re-raise the exception
            raise exc_type, exc_value, exc_tb
92515
public void start()
        throws Exception
    {
        if (getHttpContext().getAuthenticator()==null)
        {
            // Find out the Authenticator.
            if (SecurityConstraint.__BASIC_AUTH.equalsIgnoreCase(_authMethod))
                getHttpContext().setAuthenticator(new BasicAuthenticator());
            else if (SecurityConstraint.__CERT_AUTH.equalsIgnoreCase(_authMethod))
                getHttpContext().setAuthenticator(new ClientCertAuthenticator());
            else
                log.warn("Unknown Authentication method:"+_authMethod);
        }
        
        super.start();
    }
431859
private void startSession() {
        AssumeRoleWithWebIdentityResult sessionTokenResult = securityTokenService
                .assumeRoleWithWebIdentity(new AssumeRoleWithWebIdentityRequest().withWebIdentityToken(wifToken)
                        .withProviderId(wifProvider)
                        .withRoleArn(roleArn)
                        .withRoleSessionName("ProviderSession")
                        .withDurationSeconds(this.sessionDuration));
        Credentials stsCredentials = sessionTokenResult.getCredentials();

        subjectFromWIF = sessionTokenResult.getSubjectFromWebIdentityToken();

        sessionCredentials = new BasicSessionCredentials(
                stsCredentials.getAccessKeyId(),
                stsCredentials.getSecretAccessKey(),
                stsCredentials.getSessionToken());
        sessionCredentialsExpiration = stsCredentials.getExpiration();
    }
651031
function main(onStart) {
    const conf = config.read();

    initLogging(conf);
    initFsStorage(conf);

    logger.debug('Default configuration file: %s', conf.path);
    logger.debug('Configuration parameters: %s', JSON.stringify(conf));

    runWebServer(conf, onStart);
}
1040271
@Override
    protected void doStart() throws Exception
    {
        log.info("starting...");
        super.doStart();
        _client = newClient(_serverString);
        if (_client == null)
        {
            throw new IllegalStateException("newClient(" + _serverString + ") returns null.");
        }
        log.info("use " + _client.getClass().getSimpleName() + " as client factory.");
        _client.establish();
        log.info("started.");
    }
305597
def server_bind(self):
        
        if self.allow_reuse_address:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.setblocking(True)

        if not self.listen_fd:
            self.socket.bind(self.server_address)

        self.server_address = self.socket.getsockname()

        if self.server_address[0] == 0:
            self.server_address = '@' + self.server_address[1:].decode('utf-8')
            if self.mode:
                os.fchmod(self.socket.fileno(), mode=int(self.mode, 8))
        elif self.mode:
            os.chmod(self.server_address, mode=int(self.mode, 8))
53469
def _bind(self):
        

        credentials = pika.PlainCredentials(self.user, self.password)
        params = pika.ConnectionParameters(credentials=credentials,
                                           host=self.server,
                                           virtual_host=self.vhost,
                                           port=self.port)

        self.connection = pika.BlockingConnection(params)
        self.channel = self.connection.channel()

        # NOTE : PIKA version uses 'exchange_type' instead of 'type'

        self.channel.exchange_declare(exchange=self.topic_exchange,
                                      exchange_type="topic")
20381
def reset
      self.user_agent         = DEFAULT_USER_AGENT
      self.environment        = DEFAULT_ENVIRONMENT
      self.api_version        = DEFAULT_API_VERSION
      self.server_url         = DEFAULT_SERVER_URL
      self.client_name        = DEFAULT_CLIENT_NAME
      self.client_key         = DEFAULT_CLIENT_KEY
      self.connection_options = DEFAULT_CONNECTION_OPTIONS
      self.middleware         = DEFAULT_MIDDLEWARE
      self.accept             = DEFAULT_ACCEPT
      self
    end
475327
def handle_connection_exec(client):
    
    class ExitExecLoop(Exception):
        pass

    def exit():
        raise ExitExecLoop()

    client.settimeout(None)
    fh = os.fdopen(client.detach() if hasattr(client, 'detach') else client.fileno())

    with closing(client):
        with closing(fh):
            try:
                payload = fh.readline()
                while payload:
                    _LOG("Running: %r." % payload)
                    eval(compile(payload, '<manhole>', 'exec'), {'exit': exit}, _MANHOLE.locals)
                    payload = fh.readline()
            except ExitExecLoop:
                _LOG("Exiting exec loop.")
882220
def start(self):
        """"""
        self.log.info("Starting Insecure Session for Monitor %s" % self.monitor_id)
        if self.socket is not None:
            raise Exception("Socket already established for %s." % self)

        try:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.connect((self.client.hostname, PUSH_OPEN_PORT))
            self.socket.setblocking(0)
        except socket.error as exception:
            self.socket.close()
            self.socket = None
            raise

        self.send_connection_request()
395676
function handleConnection(client) {
        // set ghostmode callbacks
        if (bs.options.get("ghostMode")) {
            addGhostMode(client);
        }

        client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients

        emitter.emit("client:connected", {
            ua: client.handshake.headers["user-agent"]
        });
    }
977642
public function execute()
    {
        // loop through the open client connections
        foreach ($this->client as $key => $client) {
            // if the client connection doesn exist in the current read iteration
            if (!in_array($client['sock'], $this->read)) {
                // Close the socket
                $this->close($client['sock']);
                // flag for garbage collection
                unset($this->client[$key]);
            }

            // get the input from the client
            $input = socket_read($client['sock'], 1024);


            // Zero length string meaning disconnected
            if ($input == null) {
                unset($this->client[$key]);
            }
            $n = trim($input);

            switch (true) {
                // kill switch for telnet
                case $n === 'exit':
                    $this->close($client['sock']);
                    break;

                default:
                    // here is where it get interesting we will need a Handler who responds
                    socket_write($client['sock'], $this->getResponse($input));
                    break;
            }
        }
    }