├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── example ├── chat_ws_server.php └── test.html ├── src ├── WebSocketConnection.php ├── WebSocketMiddleware.php └── WebSocketOptions.php └── tests └── ab ├── fuzzingclient.json └── testServer.php /.gitignore: -------------------------------------------------------------------------------- 1 | /composer.lock 2 | /vendor 3 | /tests/ab/reports -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Voryx 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebSocketMiddleware 2 | WebSocket Middleware for react/http 3 | # Try it out 4 | Run `chat_ws_server.php` from the examples directory and navigate a few browser windows to http://127.0.0.1:4321/ (only tested briefly in Chrome) 5 | # Simple Usage 6 | A simple echo server: 7 | ```php 8 | use Ratchet\RFC6455\Messaging\Message; 9 | use React\EventLoop\Factory; 10 | use React\Http\Server; 11 | use Voryx\WebSocketMiddleware\WebSocketConnection; 12 | use Voryx\WebSocketMiddleware\WebSocketMiddleware; 13 | 14 | require __DIR__ . '/../../vendor/autoload.php'; 15 | 16 | $loop = Factory::create(); 17 | 18 | $ws = new WebSocketMiddleware([], function (WebSocketConnection $conn) { 19 | $conn->on('message', function (Message $message) use ($conn) { 20 | $conn->send($message); 21 | }); 22 | }); 23 | 24 | $server = new Server($loop, $ws); 25 | 26 | $server->listen(new \React\Socket\Server('127.0.0.1:4321', $loop)); 27 | 28 | $loop->run(); 29 | ``` 30 | # Options 31 | By default `WebSocketMiddleware` uses the `ratchet/rfc6455` default max sizes for messages and frames and also disables compression. 32 | These settings can be overridden with the `WebSocketOptions` object. 33 | ```php 34 | $ws = new WebSocketMiddleware( 35 | [], 36 | $connectionHandler, 37 | [], 38 | WebSocketOptions::getDefault() 39 | ->withMaxFramePayloadSize(2048) 40 | ->withMaxMessagePayloadSize(4096) 41 | ->withPermessageDeflate()); 42 | ``` 43 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "voryx/websocketmiddleware", 3 | "type": "library", 4 | "description": "WebSocket Middleware for React", 5 | "keywords": [ 6 | "websocket", 7 | "ws", 8 | "server", 9 | "websocket server" 10 | ], 11 | "license": "MIT", 12 | "authors": [ 13 | { 14 | "name": "David Dan", 15 | "email": "davidwdan@gmail.com", 16 | "role": "Developer" 17 | }, 18 | { 19 | "name": "Matt Bonneau", 20 | "email": "matt@bonneau.net", 21 | "role": "Developer" 22 | } 23 | ], 24 | "require": { 25 | "ratchet/rfc6455": "^0.3", 26 | "react/http": "^1.0" 27 | }, 28 | "require-dev":{ 29 | "react/child-process": "^0.5.0" 30 | }, 31 | "autoload": { 32 | "psr-4": { 33 | "Voryx\\WebSocketMiddleware\\": "src/" 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /example/chat_ws_server.php: -------------------------------------------------------------------------------- 1 | addTimer(0, function () use ($conn, $user, $broadcast) { 28 | $broadcast->write('user ' . $user . ' connected'); 29 | $conn->send('Welcome. You are user ' . $user); 30 | }); 31 | 32 | $broadcastHandler = function ($data) use ($conn) { 33 | $conn->send($data); 34 | }; 35 | 36 | $broadcast->on('data', $broadcastHandler); 37 | 38 | $conn->on('message', function (Message $message) use ($broadcast, $conn, $user) { 39 | $broadcast->write('user ' . $user . ': ' . $message->getPayload()); 40 | }); 41 | 42 | $conn->on('error', function (Throwable $e) use ($broadcast, $user, $broadcastHandler) { 43 | $broadcast->removeListener('data', $broadcastHandler); 44 | $broadcast->write('user ' . $user . ' left because of error: ' . $e->getMessage()); 45 | }); 46 | 47 | $conn->on('close', function () use ($broadcast, $user, $broadcastHandler) { 48 | $broadcast->removeListener('data', $broadcastHandler); 49 | $broadcast->write('user ' . $user . ' closed their connection'); 50 | }); 51 | 52 | $user++; 53 | }); 54 | 55 | $server = new Server( 56 | $loop, 57 | function (ServerRequestInterface $request, callable $next) use ($broadcast) { 58 | // lets let the people chatting see what requests are happening too. 59 | $broadcast->write('Request: ' . $request->getUri()->getPath() . ''); 60 | return $next($request); 61 | }, 62 | $ws, 63 | function (ServerRequestInterface $request, callable $next) { 64 | $request = $request->withHeader('Request-Time', time()); 65 | return $next($request); 66 | }, 67 | function (ServerRequestInterface $request) use ($frontend) { 68 | return new Response(200, [], $frontend); 69 | }, 70 | ); 71 | 72 | $server->listen(new \React\Socket\Server('127.0.0.1:4321', $loop)); 73 | $server->on('error', static function (Throwable $e) { 74 | echo $e; 75 | }); 76 | 77 | openWebPage($loop, 'http://' . $uri); 78 | 79 | $loop->run(); 80 | 81 | function openWebPage($loop, $url) 82 | { 83 | $os = strtolower(php_uname(PHP_OS)); 84 | 85 | if (strpos($os, 'darwin') !== false) { 86 | $open = 'open'; 87 | } elseif (strpos($os, 'linux') !== false) { 88 | $open = 'xdg-open'; 89 | } else { 90 | echo "Can't open your browser, you'll have to manually navigate to {$url}", PHP_EOL; 91 | return; 92 | } 93 | 94 | $process = new React\ChildProcess\Process("{$open} {$url}"); 95 | 96 | try { 97 | $process->start($loop); 98 | } catch (Exception $e) { 99 | echo $e->getMessage(), PHP_EOL; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /example/test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Test WebSocket 6 | 7 | 8 | 9 |
10 | 11 |
12 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/WebSocketConnection.php: -------------------------------------------------------------------------------- 1 | stream = $stream; 32 | $this->webSocketOptions = $webSocketOptions; 33 | $this->permessageDeflateOptions = $permessageDeflateOptions; 34 | 35 | $mb = new MessageBuffer( 36 | new CloseFrameChecker(), 37 | function (Message $message) { 38 | $this->emit('message', [$message, $this]); 39 | }, 40 | function (Frame $frame) { 41 | switch ($frame->getOpcode()) { 42 | case Frame::OP_PING: 43 | $this->stream->write((new Frame($frame->getPayload(), true, Frame::OP_PONG))->getContents()); 44 | return; 45 | case Frame::OP_CLOSE: 46 | $closeCode = unpack('n*', substr($frame->getPayload(), 0, 2)); 47 | $closeCode = reset($closeCode) ?: 1000; 48 | $reason = ''; 49 | 50 | if ($frame->getPayloadLength() > 2) { 51 | $reason = substr($frame->getPayload(), 2); 52 | } 53 | 54 | $this->stream->end($frame->getContents()); 55 | 56 | $this->emit('close', [$closeCode, $this, $reason]); 57 | return; 58 | } 59 | }, 60 | true, 61 | null, 62 | $this->webSocketOptions->getMaxMessagePayloadSize(), 63 | $this->webSocketOptions->getMaxFramePayloadSize(), 64 | [$this->stream, 'write'], 65 | $this->permessageDeflateOptions 66 | ); 67 | 68 | $this->messageBuffer = $mb; 69 | 70 | $stream->on('data', [$mb, 'onData']); 71 | $stream->on('close', function () { 72 | $this->emit('close', [1006, $this, '']); 73 | }); 74 | } 75 | 76 | public function send($data) 77 | { 78 | if ($data instanceof Frame) { 79 | $this->messageBuffer->sendFrame($data); 80 | return; 81 | } 82 | 83 | if ($data instanceof MessageInterface) { 84 | $this->messageBuffer->sendMessage($data->getPayload(), true, $data->isBinary()); 85 | return; 86 | } 87 | 88 | $this->messageBuffer->sendMessage($data); 89 | } 90 | 91 | public function close($code = 1000, $reason = '') 92 | { 93 | $this->stream->end((new Frame(pack('n', $code) . $reason, true, Frame::OP_CLOSE))->getContents()); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/WebSocketMiddleware.php: -------------------------------------------------------------------------------- 1 | paths = $paths; 23 | $this->connectionHandler = $connectionHandler ?: function () {}; 24 | $this->subProtocols = $subProtocols; 25 | $this->webSocketOptions = $webSocketOptions ?? WebSocketOptions::getDefault(); 26 | } 27 | 28 | public function __invoke(ServerRequestInterface $request, callable $next = null) 29 | { 30 | // check path at some point - for now we just go go ws 31 | if (count($this->paths) > 0) { 32 | if (!in_array($request->getUri()->getPath(), $this->paths)) { 33 | if ($next === null) { 34 | return new Response(404); 35 | } 36 | 37 | return $next($request); 38 | } 39 | } 40 | 41 | $negotiator = new ServerNegotiator(new RequestVerifier(), $this->webSocketOptions->isPermessageDeflateEnabled()); 42 | $negotiator->setSupportedSubProtocols($this->subProtocols); 43 | $negotiator->setStrictSubProtocolCheck(true); 44 | 45 | $response = $negotiator->handshake($request); 46 | 47 | if ($response->getStatusCode() != '101') { 48 | if ($next === null) { 49 | return new Response(404); 50 | } 51 | 52 | // TODO: this should return an error or something not continue the chain 53 | return $next($request); 54 | } 55 | 56 | try { 57 | $permessageDeflateOptions = PermessageDeflateOptions::fromRequestOrResponse($request); 58 | } catch (\Exception $e) { 59 | // 500 - Internal server error 60 | return new Response(500, [], 'Error negotiating websocket permessage-deflate: ' . $e->getMessage()); 61 | } 62 | 63 | if (!$this->webSocketOptions->isPermessageDeflateEnabled()) { 64 | $permessageDeflateOptions = [ 65 | PermessageDeflateOptions::createDisabled() 66 | ]; 67 | } 68 | 69 | $inStream = new ThroughStream(); 70 | $outStream = new ThroughStream(); 71 | 72 | $response = new Response( 73 | $response->getStatusCode(), 74 | $response->getHeaders(), 75 | new CompositeStream( 76 | $outStream, 77 | $inStream 78 | ) 79 | ); 80 | 81 | $conn = new WebSocketConnection( 82 | new CompositeStream($inStream, $outStream), 83 | $this->webSocketOptions, 84 | $permessageDeflateOptions[0] 85 | ); 86 | 87 | call_user_func($this->connectionHandler, $conn, $request, $response); 88 | 89 | return $response; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/WebSocketOptions.php: -------------------------------------------------------------------------------- 1 | permessageDeflateEnabled = true; 27 | 28 | return $c; 29 | } 30 | 31 | public function withoutPermessageDeflate() 32 | { 33 | $c = clone $this; 34 | $c->permessageDeflateEnabled = false; 35 | 36 | return $c; 37 | } 38 | 39 | public function withMaxMessagePayloadSize($maxSize) 40 | { 41 | $c = clone $this; 42 | $c->maxMessagePayloadSize = $maxSize; 43 | 44 | return $c; 45 | } 46 | 47 | public function withMaxFramePayloadSize($maxSize) 48 | { 49 | $c = clone $this; 50 | $c->maxFramePayloadSize = $maxSize; 51 | 52 | return $c; 53 | } 54 | 55 | public function isPermessageDeflateEnabled() 56 | { 57 | return $this->permessageDeflateEnabled; 58 | } 59 | 60 | public function getMaxMessagePayloadSize() 61 | { 62 | return $this->maxMessagePayloadSize; 63 | } 64 | 65 | public function getMaxFramePayloadSize() 66 | { 67 | return $this->maxFramePayloadSize; 68 | } 69 | } -------------------------------------------------------------------------------- /tests/ab/fuzzingclient.json: -------------------------------------------------------------------------------- 1 | { 2 | "options": {"failByDrop": false} 3 | , "outdir": "reports" 4 | 5 | , "servers": [ 6 | {"agent": "WebSocketMiddleware", "url": "ws://localhost:4321", "options": {"version": 18}} 7 | ] 8 | 9 | , "cases": ["*"] 10 | , "exclude-cases": [] 11 | , "exclude-agent-cases": {} 12 | } 13 | -------------------------------------------------------------------------------- /tests/ab/testServer.php: -------------------------------------------------------------------------------- 1 | on('message', function (Message $message) use ($conn) { 15 | $conn->send($message); 16 | }); 17 | }, [], \Voryx\WebSocketMiddleware\WebSocketOptions::getDefault()->withPermessageDeflate()); 18 | 19 | $server = new Server($loop, $ws); 20 | 21 | $server->listen(new \React\Socket\Server('0.0.0.0:4321', $loop)); 22 | 23 | $loop->run(); 24 | 25 | --------------------------------------------------------------------------------