This commit is contained in:
Marcel Pociot
2020-04-14 21:19:23 +02:00
commit 2b03398f40
48 changed files with 8099 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
<?php
namespace App\Server\Connections;
use Illuminate\Support\Str;
use Ratchet\ConnectionInterface;
class Connection
{
/** @var IoConnection */
public $socket;
public $host;
public $subdomain;
public $client_id;
public $proxies = [];
public function __construct(IoConnection $socket, string $host, string $subdomain, string $clientId)
{
$this->socket = $socket;
$this->host = $host;
$this->subdomain = $subdomain;
$this->client_id = $clientId;
}
public function setProxy(ConnectionInterface $proxy)
{
$this->proxies[] = $proxy;
}
public function getProxy(): ?ConnectionInterface
{
return array_pop($this->proxies);
}
public function rewriteHostInformation($serverHost, $port, string $data)
{
$appName = config('app.name');
$appVersion = config('app.version');
return str_replace(
"Host: {$this->subdomain}.{$serverHost}:{$port}\r\n",
"Host: {$this->host}\r\n" .
"X-Tunnel-By: {$appName} {$appVersion}\r\n" .
"X-Original-Host: {$this->subdomain}.{$serverHost}:{$port}\r\n",
$data
);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Server\Connections;
use Illuminate\Support\Str;
use Ratchet\ConnectionInterface;
class ConnectionManager
{
/** @var array */
protected $connections = [];
protected $host;
protected $port;
public function __construct($host, $port)
{
$this->host = $host;
$this->port = $port;
}
public function storeConnection(string $host, ?string $subdomain, IoConnection $connection)
{
$clientId = (string)uniqid();
$storedConnection = new Connection($connection, $host, $subdomain ?? $this->generateSubdomain(), $clientId);
$this->connections[] = $storedConnection;
return $storedConnection;
}
public function findConnectionForSubdomain($subdomain): ?Connection
{
return collect($this->connections)->last(function ($connection) use ($subdomain) {
return $connection->subdomain == $subdomain;
});
}
public function findConnectionForClientId(string $clientId): ?Connection
{
return collect($this->connections)->last(function ($connection) use ($clientId) {
return $connection->client_id == $clientId;
});
}
protected function generateSubdomain(): string
{
return strtolower(Str::random(10));
}
public function host()
{
return $this->host === '127.0.0.1' ? 'localhost' : $this->host;
}
public function port()
{
return $this->port;
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace App\Server\Connections;
use Ratchet\ConnectionInterface;
use React\Socket\ConnectionInterface as ReactConn;
class IoConnection implements ConnectionInterface {
/**
* @var \React\Socket\ConnectionInterface
*/
protected $conn;
/**
* @param \React\Socket\ConnectionInterface $conn
*/
public function __construct(ReactConn $conn) {
$this->conn = $conn;
}
/**
* @return ReactConn
*/
public function getConnection(): ReactConn
{
return $this->conn;
}
/**
* {@inheritdoc}
*/
public function send($data) {
$this->conn->write($data);
return $this;
}
/**
* {@inheritdoc}
*/
public function close() {
$this->conn->end();
}
}

58
app/Server/Factory.php Normal file
View File

@@ -0,0 +1,58 @@
<?php
namespace App\Server;
use App\Server\Connections\ConnectionManager;
use React\Socket\Server;
use React\EventLoop\LoopInterface;
use React\EventLoop\Factory as LoopFactory;
class Factory
{
/** @var string */
protected $host = '127.0.0.1';
/** @var int */
protected $port = 8080;
/** @var \React\EventLoop\LoopInterface */
protected $loop;
public function __construct()
{
$this->loop = LoopFactory::create();
}
public function setHost(string $host)
{
$this->host = $host;
return $this;
}
public function setPort(int $port)
{
$this->port = $port;
return $this;
}
public function setLoop(LoopInterface $loop)
{
$this->loop = $loop;
return $this;
}
public function createServer()
{
$socket = new Server("{$this->host}:{$this->port}", $this->loop);
$connectionManager = new ConnectionManager($this->host, $this->port);
$app = new Shaft($connectionManager);
return new IoServer($app, $socket, $this->loop);
}
}

32
app/Server/IoServer.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace App\Server;
use App\Server\Connections\IoConnection;
class IoServer extends \Ratchet\Server\IoServer
{
public function handleConnect($conn) {
$conn->decor = new IoConnection($conn);
$conn->decor->resourceId = (int)$conn->stream;
$uri = $conn->getRemoteAddress();
$conn->decor->remoteAddress = trim(
parse_url((strpos($uri, '://') === false ? 'tcp://' : '') . $uri, PHP_URL_HOST),
'[]'
);
$this->app->onOpen($conn->decor);
$conn->on('data', function ($data) use ($conn) {
$this->handleData($data, $conn);
});
$conn->on('close', function () use ($conn) {
$this->handleEnd($conn);
});
$conn->on('error', function (\Exception $e) use ($conn) {
$this->handleError($e, $conn);
});
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Server\Messages;
use App\Server\Connections\ConnectionManager;
use Illuminate\Support\Str;
use Ratchet\ConnectionInterface;
use stdClass;
class ControlMessage implements Message
{
/** \stdClass */
protected $payload;
/** @var \Ratchet\ConnectionInterface */
protected $connection;
/** @var ConnectionManager */
protected $connectionManager;
public function __construct($payload, ConnectionInterface $connection, ConnectionManager $connectionManager)
{
$this->payload = $payload;
$this->connection = $connection;
$this->connectionManager = $connectionManager;
}
public function respond()
{
$eventName = $this->payload->event;
if (method_exists($this, $eventName)) {
call_user_func([$this, $eventName], $this->connection, $this->payload->data ?? new stdClass());
}
}
protected function authenticate(ConnectionInterface $connection, $data)
{
$connectionInfo = $this->connectionManager->storeConnection($data->host, $data->subdomain, $connection);
$connection->send(json_encode([
'event' => 'authenticated',
'subdomain' => $connectionInfo->subdomain,
'client_id' => $connectionInfo->client_id
]));
}
protected function registerProxy(ConnectionInterface $connection, $data)
{
$connectionInfo = $this->connectionManager->findConnectionForClientId($data->client_id);
$connectionInfo->socket->getConnection()->emit('proxy_ready_'.$data->request_id, [
$connection,
]);
$connectionInfo->setProxy($connection);
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace App\Server\Messages;
interface Message
{
public function respond();
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Server\Messages;
use App\Server\Connections\ConnectionManager;
use Ratchet\ConnectionInterface;
class MessageFactory
{
public static function createForMessage(string $message, ConnectionInterface $connection, ConnectionManager $connectionManager)
{
$payload = json_decode($message);
return json_last_error() === JSON_ERROR_NONE
? new ControlMessage($payload, $connection, $connectionManager)
: new TunnelMessage($message, $connection, $connectionManager);
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace App\Server\Messages;
use App\Server\Connections\Connection;
use App\Server\Connections\ConnectionManager;
use App\Server\Connections\IoConnection;
use BFunky\HttpParser\HttpRequestParser;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Ratchet\ConnectionInterface;
use React\Stream\Util;
use function GuzzleHttp\Psr7\parse_request;
class TunnelMessage implements Message
{
/** string */
protected $payload;
/** @var \Ratchet\ConnectionInterface */
protected $connection;
/** @var ConnectionManager */
private $connectionManager;
public function __construct($payload, ConnectionInterface $connection, ConnectionManager $connectionManager)
{
$this->payload = $payload;
$this->connection = $connection;
$this->connectionManager = $connectionManager;
}
public function respond()
{
$clientConnection = $this->connectionManager->findConnectionForSubdomain($this->detectSubdomain());
if (is_null($clientConnection)) {
return;
}
if ($this->hasBufferedAllData()) {
$this->copyDataToClient($clientConnection);
}
}
protected function getContentLength(): ?int
{
$request = parse_request($this->connection->buffer);
return Arr::first($request->getHeader('Content-Length'));
}
protected function detectSubdomain(): ?string
{
$subdomain = '';
$headers = collect(explode("\r\n", $this->connection->buffer))->map(function ($header) use (&$subdomain) {
$headerData = explode(':', $header);
if ($headerData[0] === 'Host') {
$domainParts = explode('.', $headerData[1]);
$subdomain = trim($domainParts[0]);
}
});
return $subdomain;
}
private function copyDataToClient(Connection $clientConnection)
{
$data = $clientConnection->rewriteHostInformation($this->connectionManager->host(), $this->connectionManager->port(), $this->connection->buffer);
$requestId = uniqid();
// Ask client to create a new proxy
$clientConnection->socket->send(json_encode([
'event' => 'createProxy',
'request_id' => $requestId,
'client_id' => $clientConnection->client_id,
]) . "||");
$clientConnection->socket->getConnection()->once('proxy_ready_' . $requestId, function (IoConnection $proxy) use ($data, $requestId) {
Util::pipe($proxy->getConnection(), $this->connection->getConnection());
$proxy->send($data);
});
unset($this->connection->buffer);
}
protected function hasBufferedAllData()
{
return is_null($this->getContentLength()) || strlen(Str::after($this->connection->buffer, "\r\n\r\n")) === $this->getContentLength();
}
}

54
app/Server/Shaft.php Normal file
View File

@@ -0,0 +1,54 @@
<?php
namespace App\Server;
use App\Server\Connections\ConnectionManager;
use App\Server\Messages\ControlMessage;
use App\Server\Messages\MessageFactory;
use App\Server\Messages\TunnelMessage;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
use function GuzzleHttp\Psr7\parse_request;
class Shaft implements MessageComponentInterface
{
protected $connectionManager;
public function __construct(ConnectionManager $connectionManager)
{
$this->connectionManager = $connectionManager;
}
public function onOpen(ConnectionInterface $conn)
{
// TODO: Implement onOpen() method.
}
public function onClose(ConnectionInterface $conn)
{
dump("close connection");
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
// TODO: Implement onError() method.
}
public function onMessage(ConnectionInterface $connection, $message)
{
$payload = json_decode($message);
if (json_last_error() === JSON_ERROR_NONE) {
$message = new ControlMessage($payload, $connection, $this->connectionManager);
$message->respond();
} else {
if (! isset($connection->buffer)) {
$connection->buffer = '';
}
$connection->buffer .= $message;
$message = new TunnelMessage($connection->buffer, $connection, $this->connectionManager);
$message->respond();
}
}
}