Processes an RPC handshake.
@param AvroIOBinaryDecoder $decoder Where to read from
@param AvroIOBinaryEncoder $encoder  Where to write to.
@param Transceiver $transceiver the transceiver used for the response
@return AvroProtocol The requested Protocol.
978737
public function process_handshake(AvroIOBinaryDecoder $decoder, AvroIOBinaryEncoder $encoder, Transceiver $transceiver)
  {
    if ($transceiver->is_connected()) 
      return $transceiver->get_remote();
    
    $handshake_request = $this->handshake_responder_reader->read($decoder);
    $client_hash = $handshake_request["clientHash"];
    $client_protocol = $handshake_request["clientProtocol"];
    $remote_protocol =  $this->get_protocol_cache($client_hash);
    
    if (is_null($remote_protocol) && !is_null($client_protocol)) {
      $remote_protocol = AvroProtocol::parse($client_protocol);
      $this->set_protocol_cache($client_hash, $remote_protocol);
    }
    
    $server_hash = $handshake_request["serverHash"];
    $handshake_response = array();
    
    if ($this->local_hash == $server_hash)
      $handshake_response['match'] = (is_null($remote_protocol)) ? 'NONE' : 'BOTH';
    else
      $handshake_response['match'] = (is_null($remote_protocol)) ? 'NONE' : 'CLIENT';

    $handshake_response["meta"] = null;
    if ($handshake_response['match'] != 'BOTH') {
      $handshake_response["serverProtocol"] = $this->local_protocol->__toString();
      $handshake_response["serverHash"] = $this->local_hash;
    } else {
      $handshake_response["serverProtocol"] = null;
      $handshake_response["serverHash"] = null;
    }
    
    $this->handshake_responder_writer->write($handshake_response, $encoder);
    
    if ($handshake_response['match'] != 'NONE')
      $transceiver->set_remote($remote_protocol);

    return $remote_protocol;
  }
1015450
public function setEncoder(Swift_Mime_ContentEncoder $encoder)
    {
        if ($encoder !== $this->encoder) {
            $this->clearCache();
        }

        $this->encoder = $encoder;
        $this->setEncoding($encoder->getName());
        $this->notifyEncoderChanged($encoder);

        return $this;
    }
239095
function Remote(server, socket, version, maxFrameSize, encoder, decoder, delay) {

    // Events
    Emitter.call(this);

    // Internals
    this._server = server;
    this._socket = socket;
    this._isPending = true;

    // Public properties
    this.id = socket.remoteAddress + ':' + socket.remotePort;
    this.address = socket.remoteAddress;
    this.port = socket.remotePort;
    this.bytesSend = 0;
    this.bytesReceived = 0;
    this.version = version;
    this.delay = delay || 0;

    // Protocol
    this._encoder = encoder;
    this._decoder = decoder;
    this._protocol = Protocol(this, socket, version, maxFrameSize);
    Protocol.bind(this._protocol, this, socket, this.delay);
    this._protocol.init();

}
156674
private function findDecoderByKey(string $encoderKey): MessageDecoder
    {
        /** @var string $encoderContainerId */
        $encoderContainerId = true === !empty($this->decodersConfiguration[$encoderKey])
            ? $this->decodersConfiguration[$encoderKey]
            : self::DEFAULT_DECODER;

        return $this->obtainDecoder($encoderContainerId);
    }
1274559
public function decrypt($encrypted)
    {
        if (!$encrypted || !is_string($encrypted)) {
            throw new CryptoException(sprintf(self::ERR_CANNOT_DECRYPT, gettype($encrypted)));
        }

        // Sanity check size of payload is larger than MAC + NONCE
        if (ByteString::strlen($encrypted) < self::NONCE_SIZE_BYTES + $this->sodiumCryptoBytes()) {
            throw new CryptoException(self::ERR_SIZE);
        }

        // Split into nonce, mac, and encrypted payload
        $nonce = ByteString::substr($encrypted, 0, self::NONCE_SIZE_BYTES);
        $mac = ByteString::substr($encrypted, self::NONCE_SIZE_BYTES, $this->sodiumCryptoBytes());
        $encrypted = ByteString::substr($encrypted, self::NONCE_SIZE_BYTES + $this->sodiumCryptoBytes());

        // Verify MAC
        try {
            $isVerified = $this->sodiumCryptoAuthVerify($mac, $nonce . $encrypted, $this->authSecret->getValue());
        } catch (Exception $ex) {
            throw new CryptoException(sprintf(self::ERR_DECODE_UNEXPECTED, $ex->getMessage()), $ex->getCode(), $ex);
        }

        if (!$isVerified) {
            throw new CryptoException(self::ERR_DECODE);
        }

        // Decrypt authenticated payload
        try {
            $unencrypted = $this->sodiumSecretBoxOpen($encrypted, $nonce, $this->cryptoSecret->getValue());
        } catch (Exception $ex) {
            throw new CryptoException(sprintf(self::ERR_DECRYPT, $ex->getMessage()), $ex->getCode(), $ex);
        }

        return $unencrypted;
    }
542583
public function encodeControlAttribution(Attribution $attribution, Encoder $encoder)
    {
        $result = $this->doControlEncode('attribution', $attribution, $encoder);

        foreach ($attribution->getAttributions() as $value) {
            $result .= sprintf(
                '%s.addAttribution(\'%s\');' . "\n",
                $encoder->encodeReference($attribution),
                $value
            );
        }

        return $result;
    }
522321
public function sendTo(int $receiver, string $data, int $sender = -1): int
    {
        $finish = true;
        $opcode = 1;
        $fromUser = $sender < 0 ? 'SYSTEM' : $sender;

        $this->log("(private)The #{$fromUser} send message to the user #{$receiver}. Data: {$data}");

        return $this->server->push($receiver, $data, $opcode, $finish) ? 1 : 0;
    }
1155337
public function handle(
        $msgType,
        \fpoirotte\Pssht\Wire\Decoder $decoder,
        \fpoirotte\Pssht\Transport $transport,
        array &$context
    ) {
        $encoder    = new \fpoirotte\Pssht\Wire\Encoder();
        $channel    = $decoder->decodeUint32();
        $type       = $decoder->decodeString();
        $wantsReply = $decoder->decodeBoolean();

        $encoder->encodeUint32($channel);
        $encoder->encodeString($type);
        $encoder->encodeBoolean($wantsReply);
        $decoder->getBuffer()->unget($encoder->getBuffer()->get(0));
        $remoteChannel = $this->connection->getChannel($channel);

        switch ($type) {
            case 'exec':
            case 'shell':
            case 'pty-req':
                // Normalize the name.
                // Eg. "pty-req" becomes "PtyReq".
                $cls = str_replace(' ', '', ucwords(str_replace('-', ' ', $type)));
                $cls = '\\fpoirotte\\Pssht\\Messages\\CHANNEL\\REQUEST\\' . $cls;
                $message = $cls::unserialize($decoder);
                break;

            default:
                if ($wantsReply) {
                    $response = new \fpoirotte\Pssht\Messages\CHANNEL\FAILURE($remoteChannel);
                    $transport->writeMessage($response);
                }
                return true;
        }

        if (!$wantsReply) {
            return true;
        }

        if (in_array($type, array('shell', 'exec'), true)) {
            $response = new \fpoirotte\Pssht\Messages\CHANNEL\SUCCESS($remoteChannel);
        } else {
            $response = new \fpoirotte\Pssht\Messages\CHANNEL\FAILURE($remoteChannel);
        }
        $transport->writeMessage($response);

        if (in_array($type, array('shell', 'exec'), true)) {
            $callable = $transport->getApplicationFactory();
            if ($callable !== null) {
                call_user_func($callable, $transport, $this->connection, $message);
            }
        }

        return true;
    }
1132080
public function receiveRequest() {

		$request = $this->server->decodeRequest();

		if (!in_array($request->mode, array('checkid_immediate', 'checkid_setup'), TRUE)) {
			$this->sendResponse($this->server->handleRequest($request));
		}

		$state = array(
			'request' => $request,
		);

		$this->processRequest($state);
	}
753165
public function propagateEncoding(Encode $encode)
    {
        $this->encode = $encode;
        $this->tag->setEncoding($encode);
    }
261266
public function handle(
        $msgType,
        \fpoirotte\Pssht\Wire\Decoder $decoder,
        \fpoirotte\Pssht\Transport $transport,
        array &$context
    ) {
        if ($this->connection !== null) {
            // Silently ignore subsequent authentication requests
            // after a successful authentication took place.
            return true;
        }

        $encoder    = new \fpoirotte\Pssht\Wire\Encoder();
        $user       = $decoder->decodeString();
        $service    = $decoder->decodeString();
        $method     = $decoder->decodeString();

        $encoder->encodeString($user);
        $encoder->encodeString($service);
        $encoder->encodeString($method);
        $decoder->getBuffer()->unget($encoder->getBuffer()->get(0));

        if (!isset($context['authMethods'])) {
            $context['authMethods']     = $this->methods;
        }

        if (!isset($context['banner'])) {
            $context['banner'] = (string) $transport->getBanner();
            if ($context['banner'] !== '') {
                $response = new \fpoirotte\Pssht\Messages\USERAUTH\BANNER($context['banner']);
                $transport->writeMessage($response);
            }
        }

        if (!isset($context['authMethods'][$method])) {
            return $this->failure($transport, $context);
        }

        $messagesCls = array(
            'none' =>
                '\\fpoirotte\\Pssht\\Messages\\USERAUTH\\REQUEST\\None',
            'hostbased' =>
                '\\fpoirotte\\Pssht\\Messages\\USERAUTH\\REQUEST\\HostBased',
            'password' =>
                '\\fpoirotte\\Pssht\\Messages\\USERAUTH\\REQUEST\\Password',
            'publickey' =>
                '\\fpoirotte\\Pssht\\Messages\\USERAUTH\\REQUEST\\PublicKey',
        );
        $methodObj  = $context['authMethods'][$method];
        $message    = $messagesCls[$method]::unserialize($decoder);

        switch ($methodObj->check($message, $transport, $context)) {
            case AuthenticationInterface::CHECK_IGNORE:
                return true;

            case AuthenticationInterface::CHECK_REJECT:
                return $this->failure($transport, $context);

            case AuthenticationInterface::CHECK_OK:
                break;

            default:
                throw new \RuntimeException();
        }

        switch ($methodObj->authenticate($message, $transport, $context)) {
            case AuthenticationInterface::AUTH_REMOVE:
                unset($context['authMethods'][$method]);
                // Do not break.

            case AuthenticationInterface::AUTH_REJECT:
                return $this->failure($transport, $context);

            case AuthenticationInterface::AUTH_ACCEPT:
                break;

            default:
                throw new \RuntimeException();
        }

        unset($context['authMethods'][$method]);
        $response = new \fpoirotte\Pssht\Messages\USERAUTH\SUCCESS();
        $this->connection = new \fpoirotte\Pssht\Connection($transport);
        $transport->writeMessage($response);

        $compressor = $transport->getCompressor();
        if ($compressor instanceof \fpoirotte\Pssht\DelayedCompressionInterface) {
            $compressor->setAuthenticated();
        }
        $uncompressor = $transport->getUncompressor();
        if ($uncompressor instanceof \fpoirotte\Pssht\DelayedCompressionInterface) {
            $uncompressor->setAuthenticated();
        }

        return true;
    }
1185855
public function receiveMessage(ProtoStream $stream, $messageCode)
    {
        $response = $this->connection->receive($stream);
        $class    = $this->classForCode($messageCode);
        $respCode = $response[0];
        $respBody = $response[1];

        if ($respCode != $messageCode) {
            throw $this->createResponseException($respCode, $respBody);
        }

        if ($class == null) {
            return;
        }

        return Protobuf::decode($class, (string) $respBody);
    }
339615
public function handle($sender, ProtocolInterface $protocol, $flags, callable $success = null, callable $failure = null, callable $cancel = null, $timeout = 0.0)
    {
        $callback = $this->handler;
        $callback($sender, $protocol, $flags, $success, $failure, $cancel, $timeout);

        if ($this->limit > 0)
        {
            $this->limit--;
            if ($this->limit === 0)
            {
                $this->cancel();
            }
        }

        return $this->propagate;
    }
878755
public function handlePayload(Payload $payload): void
    {
        $app = $this->getClientApplication();

        $this->logger->debug('Handling payload: ' . $payload->getPayload());

        switch ($type = $payload->getType()) {
            case Protocol::TYPE_TEXT:
                if (method_exists($app, 'onData')) {
                    $app->onData((string)$payload, $this);
                }
                return;

            case Protocol::TYPE_BINARY:
                if (method_exists($app, 'onBinaryData')) {
                    $app->onBinaryData((string)$payload, $this);
                } else {
                    $this->close(1003);
                }
                break;

            case Protocol::TYPE_PING:
                $this->logger->info('Ping received', 'notice');
                $this->send($payload->getPayload(), Protocol::TYPE_PONG);
                $this->logger->info('Pong!', 'debug');
                break;

            /**
             * A Pong frame MAY be sent unsolicited.  This serves as a
             * unidirectional heartbeat.  A response to an unsolicited Pong
             * frame is not expected.
             */
            case Protocol::TYPE_PONG:
                $this->logger->info('Received unsolicited pong');
                break;

            case Protocol::TYPE_CLOSE:
                $this->logger->notice('Close frame received');
                $this->close();
                $this->logger->info('Disconnected');
                break;

            default:
                throw new ConnectionException('Unhandled payload type');
        }
    }
1290327
public function recreateForNewResponseTransformer(ResponseTransformerInterface $responseTransformer): self
    {
        return new self($this->client, $responseTransformer, $this->apiExceptionTransformer, $this->accessToken);
    }
750289
@Override
    protected final void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
        out.add(new JNRPERequest(JNRPEProtocolPacketFactory.produce(in)));
    }
260727
@SuppressWarnings("unchecked")
	protected void _handshake() throws IOException {
		// do connection handshake

		PyroSerializer ser = PyroSerializer.getFor(Config.SERIALIZER);
		Map<String, Object> handshakedata = new HashMap<String, Object>();
		handshakedata.put("handshake", pyroHandshake);
		if(Config.METADATA)
			handshakedata.put("object", objectid);
		byte[] data = ser.serializeData(handshakedata);
		int flags = Config.METADATA? Message.FLAGS_META_ON_CONNECT : 0;
		Message msg = new Message(Message.MSG_CONNECT, data, ser.getSerializerId(), flags, sequenceNr, annotations(), pyroHmacKey);
		IOUtil.send(sock_out, msg.to_bytes());
		if(Config.MSG_TRACE_DIR!=null) {
			Message.TraceMessageSend(sequenceNr, msg.get_header_bytes(), msg.get_annotations_bytes(), msg.data);
		}

		// process handshake response
		msg = Message.recv(sock_in, new int[]{Message.MSG_CONNECTOK, Message.MSG_CONNECTFAIL}, pyroHmacKey);
		responseAnnotations(msg.annotations, msg.type);
		Object handshake_response = "?";
		if(msg.data!=null) {
			if((msg.flags & Message.FLAGS_COMPRESSED) != 0) {
				_decompressMessageData(msg);
			}
			try {
				ser = PyroSerializer.getFor(msg.serializer_id);
				handshake_response = ser.deserializeData(msg.data);
			} catch (Exception x) {
				msg.type=Message.MSG_CONNECTFAIL;
				handshake_response = "<not available because unsupported serialization format>";
			}
		}
		if(msg.type==Message.MSG_CONNECTOK) {
			if((msg.flags & Message.FLAGS_META_ON_CONNECT) != 0) {
				HashMap<String, Object> response_dict = (HashMap<String, Object>)handshake_response;
				HashMap<String, Object> metadata = (HashMap<String, Object>) response_dict.get("meta");
				_processMetadata(metadata);
				handshake_response = response_dict.get("handshake");
				try {
					validateHandshake(handshake_response);
				} catch (IOException x) {
					close();
					throw x;
				}
			}
		} else if (msg.type==Message.MSG_CONNECTFAIL) {
			close();
			throw new PyroException("connection rejected, reason: "+handshake_response);
		} else {
			close();
			throw new PyroException("connect: invalid msg type "+msg.type+" received");
		}
	}