| 1 |
<?php |
| 2 |
|
| 3 |
namespace React\Http\Io; |
| 4 |
|
| 5 |
use Evenement\EventEmitter; |
| 6 |
use Psr\Http\Message\ResponseInterface; |
| 7 |
use Psr\Http\Message\ServerRequestInterface; |
| 8 |
use React\EventLoop\LoopInterface; |
| 9 |
use React\Http\Message\Response; |
| 10 |
use React\Http\Message\ServerRequest; |
| 11 |
use React\Promise; |
| 12 |
use React\Promise\CancellablePromiseInterface; |
| 13 |
use React\Promise\PromiseInterface; |
| 14 |
use React\Socket\ConnectionInterface; |
| 15 |
use React\Socket\ServerInterface; |
| 16 |
use React\Stream\ReadableStreamInterface; |
| 17 |
use React\Stream\WritableStreamInterface; |
| 18 |
|
| 19 |
/** |
| 20 |
* The internal `StreamingServer` class is responsible for handling incoming connections and then |
| 21 |
* processing each incoming HTTP request. |
| 22 |
* |
| 23 |
* Unlike the [`Server`](#server) class, it does not buffer and parse the incoming |
| 24 |
* HTTP request body by default. This means that the request handler will be |
| 25 |
* invoked with a streaming request body. Once the request headers have been |
| 26 |
* received, it will invoke the request handler function. This request handler |
| 27 |
* function needs to be passed to the constructor and will be invoked with the |
| 28 |
* respective [request](#request) object and expects a [response](#response) |
| 29 |
* object in return: |
| 30 |
* |
| 31 |
* ```php |
| 32 |
* $server = new StreamingServer($loop, function (ServerRequestInterface $request) { |
| 33 |
* return new Response( |
| 34 |
* 200, |
| 35 |
* array( |
| 36 |
* 'Content-Type' => 'text/plain' |
| 37 |
* ), |
| 38 |
* "Hello World!\n" |
| 39 |
* ); |
| 40 |
* }); |
| 41 |
* ``` |
| 42 |
* |
| 43 |
* Each incoming HTTP request message is always represented by the |
| 44 |
* [PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface), |
| 45 |
* see also following [request](#request) chapter for more details. |
| 46 |
* Each outgoing HTTP response message is always represented by the |
| 47 |
* [PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface), |
| 48 |
* see also following [response](#response) chapter for more details. |
| 49 |
* |
| 50 |
* In order to process any connections, the server needs to be attached to an |
| 51 |
* instance of `React\Socket\ServerInterface` through the [`listen()`](#listen) method |
| 52 |
* as described in the following chapter. In its most simple form, you can attach |
| 53 |
* this to a [`React\Socket\Server`](https://github.com/reactphp/socket#server) |
| 54 |
* in order to start a plaintext HTTP server like this: |
| 55 |
* |
| 56 |
* ```php |
| 57 |
* $server = new StreamingServer($loop, $handler); |
| 58 |
* |
| 59 |
* $socket = new React\Socket\Server('0.0.0.0:8080', $loop); |
| 60 |
* $server->listen($socket); |
| 61 |
* ``` |
| 62 |
* |
| 63 |
* See also the [`listen()`](#listen) method and the [first example](examples) for more details. |
| 64 |
* |
| 65 |
* The `StreamingServer` class is considered advanced usage and unless you know |
| 66 |
* what you're doing, you're recommended to use the [`Server`](#server) class |
| 67 |
* instead. The `StreamingServer` class is specifically designed to help with |
| 68 |
* more advanced use cases where you want to have full control over consuming |
| 69 |
* the incoming HTTP request body and concurrency settings. |
| 70 |
* |
| 71 |
* In particular, this class does not buffer and parse the incoming HTTP request |
| 72 |
* in memory. It will invoke the request handler function once the HTTP request |
| 73 |
* headers have been received, i.e. before receiving the potentially much larger |
| 74 |
* HTTP request body. This means the [request](#request) passed to your request |
| 75 |
* handler function may not be fully compatible with PSR-7. See also |
| 76 |
* [streaming request](#streaming-request) below for more details. |
| 77 |
* |
| 78 |
* @see \React\Http\Server |
| 79 |
* @see \React\Http\Message\Response |
| 80 |
* @see self::listen() |
| 81 |
* @internal |
| 82 |
*/ |
| 83 |
final class StreamingServer extends EventEmitter |
| 84 |
{ |
| 85 |
private $callback; |
| 86 |
private $parser; |
| 87 |
private $loop; |
| 88 |
|
| 89 |
/** |
| 90 |
* Creates an HTTP server that invokes the given callback for each incoming HTTP request |
| 91 |
* |
| 92 |
* In order to process any connections, the server needs to be attached to an |
| 93 |
* instance of `React\Socket\ServerInterface` which emits underlying streaming |
| 94 |
* connections in order to then parse incoming data as HTTP. |
| 95 |
* See also [listen()](#listen) for more details. |
| 96 |
* |
| 97 |
* @param LoopInterface $loop |
| 98 |
* @param callable $requestHandler |
| 99 |
* @see self::listen() |
| 100 |
*/ |
| 101 |
public function __construct(LoopInterface $loop, $requestHandler) |
| 102 |
{ |
| 103 |
if (!\is_callable($requestHandler)) { |
| 104 |
throw new \InvalidArgumentException('Invalid request handler given'); |
| 105 |
} |
| 106 |
|
| 107 |
$this->loop = $loop; |
| 108 |
|
| 109 |
$this->callback = $requestHandler; |
| 110 |
$this->parser = new RequestHeaderParser(); |
| 111 |
|
| 112 |
$that = $this; |
| 113 |
$this->parser->on('headers', function (ServerRequestInterface $request, ConnectionInterface $conn) use ($that) { |
| 114 |
$that->handleRequest($conn, $request); |
| 115 |
}); |
| 116 |
|
| 117 |
$this->parser->on('error', function(\Exception $e, ConnectionInterface $conn) use ($that) { |
| 118 |
$that->emit('error', array($e)); |
| 119 |
|
| 120 |
// parsing failed => assume dummy request and send appropriate error |
| 121 |
$that->writeError( |
| 122 |
$conn, |
| 123 |
$e->getCode() !== 0 ? $e->getCode() : 400, |
| 124 |
new ServerRequest('GET', '/') |
| 125 |
); |
| 126 |
}); |
| 127 |
} |
| 128 |
|
| 129 |
/** |
| 130 |
* Starts listening for HTTP requests on the given socket server instance |
| 131 |
* |
| 132 |
* @param ServerInterface $socket |
| 133 |
* @see \React\Http\Server::listen() |
| 134 |
*/ |
| 135 |
public function listen(ServerInterface $socket) |
| 136 |
{ |
| 137 |
$socket->on('connection', array($this->parser, 'handle')); |
| 138 |
} |
| 139 |
|
| 140 |
/** @internal */ |
| 141 |
public function handleRequest(ConnectionInterface $conn, ServerRequestInterface $request) |
| 142 |
{ |
| 143 |
if ($request->getProtocolVersion() !== '1.0' && '100-continue' === \strtolower($request->getHeaderLine('Expect'))) { |
| 144 |
$conn->write("HTTP/1.1 100 Continue\r\n\r\n"); |
| 145 |
} |
| 146 |
|
| 147 |
// execute request handler callback |
| 148 |
$callback = $this->callback; |
| 149 |
try { |
| 150 |
$response = $callback($request); |
| 151 |
} catch (\Exception $error) { |
| 152 |
// request handler callback throws an Exception |
| 153 |
$response = Promise\reject($error); |
| 154 |
} catch (\Throwable $error) { // @codeCoverageIgnoreStart |
| 155 |
// request handler callback throws a PHP7+ Error |
| 156 |
$response = Promise\reject($error); // @codeCoverageIgnoreEnd |
| 157 |
} |
| 158 |
|
| 159 |
// cancel pending promise once connection closes |
| 160 |
if ($response instanceof CancellablePromiseInterface) { |
| 161 |
$conn->on('close', function () use ($response) { |
| 162 |
$response->cancel(); |
| 163 |
}); |
| 164 |
} |
| 165 |
|
| 166 |
// happy path: response returned, handle and return immediately |
| 167 |
if ($response instanceof ResponseInterface) { |
| 168 |
return $this->handleResponse($conn, $request, $response); |
| 169 |
} |
| 170 |
|
| 171 |
// did not return a promise? this is an error, convert into one for rejection below. |
| 172 |
if (!$response instanceof PromiseInterface) { |
| 173 |
$response = Promise\resolve($response); |
| 174 |
} |
| 175 |
|
| 176 |
$that = $this; |
| 177 |
$response->then( |
| 178 |
function ($response) use ($that, $conn, $request) { |
| 179 |
if (!$response instanceof ResponseInterface) { |
| 180 |
$message = 'The response callback is expected to resolve with an object implementing Psr\Http\Message\ResponseInterface, but resolved with "%s" instead.'; |
| 181 |
$message = \sprintf($message, \is_object($response) ? \get_class($response) : \gettype($response)); |
| 182 |
$exception = new \RuntimeException($message); |
| 183 |
|
| 184 |
$that->emit('error', array($exception)); |
| 185 |
return $that->writeError($conn, 500, $request); |
| 186 |
} |
| 187 |
$that->handleResponse($conn, $request, $response); |
| 188 |
}, |
| 189 |
function ($error) use ($that, $conn, $request) { |
| 190 |
$message = 'The response callback is expected to resolve with an object implementing Psr\Http\Message\ResponseInterface, but rejected with "%s" instead.'; |
| 191 |
$message = \sprintf($message, \is_object($error) ? \get_class($error) : \gettype($error)); |
| 192 |
|
| 193 |
$previous = null; |
| 194 |
|
| 195 |
if ($error instanceof \Throwable || $error instanceof \Exception) { |
| 196 |
$previous = $error; |
| 197 |
} |
| 198 |
|
| 199 |
$exception = new \RuntimeException($message, null, $previous); |
| 200 |
|
| 201 |
$that->emit('error', array($exception)); |
| 202 |
return $that->writeError($conn, 500, $request); |
| 203 |
} |
| 204 |
); |
| 205 |
} |
| 206 |
|
| 207 |
/** @internal */ |
| 208 |
public function writeError(ConnectionInterface $conn, $code, ServerRequestInterface $request) |
| 209 |
{ |
| 210 |
$response = new Response( |
| 211 |
$code, |
| 212 |
array( |
| 213 |
'Content-Type' => 'text/plain' |
| 214 |
), |
| 215 |
'Error ' . $code |
| 216 |
); |
| 217 |
|
| 218 |
// append reason phrase to response body if known |
| 219 |
$reason = $response->getReasonPhrase(); |
| 220 |
if ($reason !== '') { |
| 221 |
$body = $response->getBody(); |
| 222 |
$body->seek(0, SEEK_END); |
| 223 |
$body->write(': ' . $reason); |
| 224 |
} |
| 225 |
|
| 226 |
$this->handleResponse($conn, $request, $response); |
| 227 |
} |
| 228 |
|
| 229 |
|
| 230 |
/** @internal */ |
| 231 |
public function handleResponse(ConnectionInterface $connection, ServerRequestInterface $request, ResponseInterface $response) |
| 232 |
{ |
| 233 |
// return early and close response body if connection is already closed |
| 234 |
$body = $response->getBody(); |
| 235 |
if (!$connection->isWritable()) { |
| 236 |
$body->close(); |
| 237 |
return; |
| 238 |
} |
| 239 |
|
| 240 |
$code = $response->getStatusCode(); |
| 241 |
$method = $request->getMethod(); |
| 242 |
|
| 243 |
// assign HTTP protocol version from request automatically |
| 244 |
$version = $request->getProtocolVersion(); |
| 245 |
$response = $response->withProtocolVersion($version); |
| 246 |
|
| 247 |
// assign default "Server" header automatically |
| 248 |
if (!$response->hasHeader('Server')) { |
| 249 |
$response = $response->withHeader('Server', 'ReactPHP/1'); |
| 250 |
} elseif ($response->getHeaderLine('Server') === ''){ |
| 251 |
$response = $response->withoutHeader('Server'); |
| 252 |
} |
| 253 |
|
| 254 |
// assign default "Date" header from current time automatically |
| 255 |
if (!$response->hasHeader('Date')) { |
| 256 |
// IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT |
| 257 |
$response = $response->withHeader('Date', gmdate('D, d M Y H:i:s') . ' GMT'); |
| 258 |
} elseif ($response->getHeaderLine('Date') === ''){ |
| 259 |
$response = $response->withoutHeader('Date'); |
| 260 |
} |
| 261 |
|
| 262 |
// assign "Content-Length" and "Transfer-Encoding" headers automatically |
| 263 |
$chunked = false; |
| 264 |
if (($method === 'CONNECT' && $code >= 200 && $code < 300) || ($code >= 100 && $code < 200) || $code === 204) { |
| 265 |
// 2xx response to CONNECT and 1xx and 204 MUST NOT include Content-Length or Transfer-Encoding header |
| 266 |
$response = $response->withoutHeader('Content-Length')->withoutHeader('Transfer-Encoding'); |
| 267 |
} elseif ($body->getSize() !== null) { |
| 268 |
// assign Content-Length header when using a "normal" buffered body string |
| 269 |
$response = $response->withHeader('Content-Length', (string)$body->getSize())->withoutHeader('Transfer-Encoding'); |
| 270 |
} elseif (!$response->hasHeader('Content-Length') && $version === '1.1') { |
| 271 |
// assign chunked transfer-encoding if no 'content-length' is given for HTTP/1.1 responses |
| 272 |
$response = $response->withHeader('Transfer-Encoding', 'chunked'); |
| 273 |
$chunked = true; |
| 274 |
} else { |
| 275 |
// remove any Transfer-Encoding headers unless automatically enabled above |
| 276 |
$response = $response->withoutHeader('Transfer-Encoding'); |
| 277 |
} |
| 278 |
|
| 279 |
// assign "Connection" header automatically |
| 280 |
if ($code === 101) { |
| 281 |
// 101 (Switching Protocols) response uses Connection: upgrade header |
| 282 |
$response = $response->withHeader('Connection', 'upgrade'); |
| 283 |
} elseif ($version === '1.1') { |
| 284 |
// HTTP/1.1 assumes persistent connection support by default |
| 285 |
// we do not support persistent connections, so let the client know |
| 286 |
$response = $response->withHeader('Connection', 'close'); |
| 287 |
} else { |
| 288 |
// remove any Connection headers unless automatically enabled above |
| 289 |
$response = $response->withoutHeader('Connection'); |
| 290 |
} |
| 291 |
|
| 292 |
// 101 (Switching Protocols) response (for Upgrade request) forwards upgraded data through duplex stream |
| 293 |
// 2xx (Successful) response to CONNECT forwards tunneled application data through duplex stream |
| 294 |
if (($code === 101 || ($method === 'CONNECT' && $code >= 200 && $code < 300)) && $body instanceof HttpBodyStream && $body->input instanceof WritableStreamInterface) { |
| 295 |
if ($request->getBody()->isReadable()) { |
| 296 |
// request is still streaming => wait for request close before forwarding following data from connection |
| 297 |
$request->getBody()->on('close', function () use ($connection, $body) { |
| 298 |
if ($body->input->isWritable()) { |
| 299 |
$connection->pipe($body->input); |
| 300 |
$connection->resume(); |
| 301 |
} |
| 302 |
}); |
| 303 |
} elseif ($body->input->isWritable()) { |
| 304 |
// request already closed => forward following data from connection |
| 305 |
$connection->pipe($body->input); |
| 306 |
$connection->resume(); |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
// build HTTP response header by appending status line and header fields |
| 311 |
$headers = "HTTP/" . $version . " " . $code . " " . $response->getReasonPhrase() . "\r\n"; |
| 312 |
foreach ($response->getHeaders() as $name => $values) { |
| 313 |
foreach ($values as $value) { |
| 314 |
$headers .= $name . ": " . $value . "\r\n"; |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
// response to HEAD and 1xx, 204 and 304 responses MUST NOT include a body |
| 319 |
// exclude status 101 (Switching Protocols) here for Upgrade request handling above |
| 320 |
if ($method === 'HEAD' || $code === 100 || ($code > 101 && $code < 200) || $code === 204 || $code === 304) { |
| 321 |
$body = ''; |
| 322 |
} |
| 323 |
|
| 324 |
// this is a non-streaming response body or the body stream already closed? |
| 325 |
if (!$body instanceof ReadableStreamInterface || !$body->isReadable()) { |
| 326 |
// add final chunk if a streaming body is already closed and uses `Transfer-Encoding: chunked` |
| 327 |
if ($body instanceof ReadableStreamInterface && $chunked) { |
| 328 |
$body = "0\r\n\r\n"; |
| 329 |
} |
| 330 |
|
| 331 |
// end connection after writing response headers and body |
| 332 |
$connection->write($headers . "\r\n" . $body); |
| 333 |
$connection->end(); |
| 334 |
return; |
| 335 |
} |
| 336 |
|
| 337 |
$connection->write($headers . "\r\n"); |
| 338 |
|
| 339 |
if ($chunked) { |
| 340 |
$body = new ChunkedEncoder($body); |
| 341 |
} |
| 342 |
|
| 343 |
// Close response stream once connection closes. |
| 344 |
// Note that this TCP/IP close detection may take some time, |
| 345 |
// in particular this may only fire on a later read/write attempt. |
| 346 |
$connection->on('close', array($body, 'close')); |
| 347 |
|
| 348 |
$body->pipe($connection); |
| 349 |
} |
| 350 |
} |