Debian Codegraph @

vendor/react/http/src/Server.php

raw
1 <?php
2
3 namespace React\Http;
4
5 use Evenement\EventEmitter;
6 use React\EventLoop\LoopInterface;
7 use React\Http\Io\IniUtil;
8 use React\Http\Io\MiddlewareRunner;
9 use React\Http\Io\StreamingServer;
10 use React\Http\Middleware\LimitConcurrentRequestsMiddleware;
11 use React\Http\Middleware\StreamingRequestMiddleware;
12 use React\Http\Middleware\RequestBodyBufferMiddleware;
13 use React\Http\Middleware\RequestBodyParserMiddleware;
14 use React\Socket\ServerInterface;
15
16 /**
17 * The `React\Http\Server` class is responsible for handling incoming connections and then
18 * processing each incoming HTTP request.
19 *
20 * When a complete HTTP request has been received, it will invoke the given
21 * request handler function. This request handler function needs to be passed to
22 * the constructor and will be invoked with the respective [request](#server-request)
23 * object and expects a [response](#server-response) object in return:
24 *
25 * ```php
26 * $server = new React\Http\Server($loop, function (Psr\Http\Message\ServerRequestInterface $request) {
27 * return new React\Http\Message\Response(
28 * 200,
29 * array(
30 * 'Content-Type' => 'text/plain'
31 * ),
32 * "Hello World!\n"
33 * );
34 * });
35 * ```
36 *
37 * Each incoming HTTP request message is always represented by the
38 * [PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface),
39 * see also following [request](#server-request) chapter for more details.
40 *
41 * Each outgoing HTTP response message is always represented by the
42 * [PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface),
43 * see also following [response](#server-response) chapter for more details.
44 *
45 * In order to start listening for any incoming connections, the `Server` needs
46 * to be attached to an instance of
47 * [`React\Socket\ServerInterface`](https://github.com/reactphp/socket#serverinterface)
48 * through the [`listen()`](#listen) method as described in the following
49 * chapter. In its most simple form, you can attach this to a
50 * [`React\Socket\Server`](https://github.com/reactphp/socket#server) in order
51 * to start a plaintext HTTP server like this:
52 *
53 * ```php
54 * $server = new React\Http\Server($loop, $handler);
55 *
56 * $socket = new React\Socket\Server('0.0.0.0:8080', $loop);
57 * $server->listen($socket);
58 * ```
59 *
60 * See also the [`listen()`](#listen) method and
61 * [hello world server example](../examples/51-server-hello-world.php)
62 * for more details.
63 *
64 * By default, the `Server` buffers and parses the complete incoming HTTP
65 * request in memory. It will invoke the given request handler function when the
66 * complete request headers and request body has been received. This means the
67 * [request](#server-request) object passed to your request handler function will be
68 * fully compatible with PSR-7 (http-message). This provides sane defaults for
69 * 80% of the use cases and is the recommended way to use this library unless
70 * you're sure you know what you're doing.
71 *
72 * On the other hand, buffering complete HTTP requests in memory until they can
73 * be processed by your request handler function means that this class has to
74 * employ a number of limits to avoid consuming too much memory. In order to
75 * take the more advanced configuration out your hand, it respects setting from
76 * your [`php.ini`](https://www.php.net/manual/en/ini.core.php) to apply its
77 * default settings. This is a list of PHP settings this class respects with
78 * their respective default values:
79 *
80 * ```
81 * memory_limit 128M
82 * post_max_size 8M // capped at 64K
83 *
84 * enable_post_data_reading 1
85 * max_input_nesting_level 64
86 * max_input_vars 1000
87 *
88 * file_uploads 1
89 * upload_max_filesize 2M
90 * max_file_uploads 20
91 * ```
92 *
93 * In particular, the `post_max_size` setting limits how much memory a single
94 * HTTP request is allowed to consume while buffering its request body. This
95 * needs to be limited because the server can process a large number of requests
96 * concurrently, so the server may potentially consume a large amount of memory
97 * otherwise. To support higher concurrency by default, this value is capped
98 * at `64K`. If you assign a higher value, it will only allow `64K` by default.
99 * If a request exceeds this limit, its request body will be ignored and it will
100 * be processed like a request with no request body at all. See below for
101 * explicit configuration to override this setting.
102 *
103 * By default, this class will try to avoid consuming more than half of your
104 * `memory_limit` for buffering multiple concurrent HTTP requests. As such, with
105 * the above default settings of `128M` max, it will try to consume no more than
106 * `64M` for buffering multiple concurrent HTTP requests. As a consequence, it
107 * will limit the concurrency to `1024` HTTP requests with the above defaults.
108 *
109 * It is imperative that you assign reasonable values to your PHP ini settings.
110 * It is usually recommended to not support buffering incoming HTTP requests
111 * with a large HTTP request body (e.g. large file uploads). If you want to
112 * increase this buffer size, you will have to also increase the total memory
113 * limit to allow for more concurrent requests (set `memory_limit 512M` or more)
114 * or explicitly limit concurrency.
115 *
116 * In order to override the above buffering defaults, you can configure the
117 * `Server` explicitly. You can use the
118 * [`LimitConcurrentRequestsMiddleware`](#limitconcurrentrequestsmiddleware) and
119 * [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) (see below)
120 * to explicitly configure the total number of requests that can be handled at
121 * once like this:
122 *
123 * ```php
124 * $server = new React\Http\Server(
125 * $loop,
126 * new React\Http\Middleware\StreamingRequestMiddleware(),
127 * new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers
128 * new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request
129 * new React\Http\Middleware\RequestBodyParserMiddleware(),
130 * $handler
131 * ));
132 * ```
133 *
134 * In this example, we allow processing up to 100 concurrent requests at once
135 * and each request can buffer up to `2M`. This means you may have to keep a
136 * maximum of `200M` of memory for incoming request body buffers. Accordingly,
137 * you need to adjust the `memory_limit` ini setting to allow for these buffers
138 * plus your actual application logic memory requirements (think `512M` or more).
139 *
140 * > Internally, this class automatically assigns these middleware handlers
141 * automatically when no [`StreamingRequestMiddleware`](#streamingrequestmiddleware)
142 * is given. Accordingly, you can use this example to override all default
143 * settings to implement custom limits.
144 *
145 * As an alternative to buffering the complete request body in memory, you can
146 * also use a streaming approach where only small chunks of data have to be kept
147 * in memory:
148 *
149 * ```php
150 * $server = new React\Http\Server(
151 * $loop,
152 * new React\Http\Middleware\StreamingRequestMiddleware(),
153 * $handler
154 * );
155 * ```
156 *
157 * In this case, it will invoke the request handler function once the HTTP
158 * request headers have been received, i.e. before receiving the potentially
159 * much larger HTTP request body. This means the [request](#server-request) passed to
160 * your request handler function may not be fully compatible with PSR-7. This is
161 * specifically designed to help with more advanced use cases where you want to
162 * have full control over consuming the incoming HTTP request body and
163 * concurrency settings. See also [streaming incoming request](#streaming-incoming-request)
164 * below for more details.
165 */
166 final class Server extends EventEmitter
167 {
168 /**
169 * The maximum buffer size used for each request.
170 *
171 * This needs to be limited because the server can process a large number of
172 * requests concurrently, so the server may potentially consume a large
173 * amount of memory otherwise.
174 *
175 * See `RequestBodyBufferMiddleware` to override this setting.
176 *
177 * @internal
178 */
179 const MAXIMUM_BUFFER_SIZE = 65536; // 64 KiB
180
181 /**
182 * @var StreamingServer
183 */
184 private $streamingServer;
185
186 /**
187 * Creates an HTTP server that invokes the given callback for each incoming HTTP request
188 *
189 * In order to process any connections, the server needs to be attached to an
190 * instance of `React\Socket\ServerInterface` which emits underlying streaming
191 * connections in order to then parse incoming data as HTTP.
192 * See also [listen()](#listen) for more details.
193 *
194 * @param LoopInterface $loop
195 * @param callable[] ...$requestHandler
196 * @see self::listen()
197 */
198 public function __construct(LoopInterface $loop)
199 {
200 $requestHandlers = \func_get_args();
201 \array_shift($requestHandlers);
202 $requestHandlersCount = \count($requestHandlers);
203 if ($requestHandlersCount === 0 || \count(\array_filter($requestHandlers, 'is_callable')) < $requestHandlersCount) {
204 throw new \InvalidArgumentException('Invalid request handler given');
205 }
206
207 $streaming = false;
208 foreach ((array) $requestHandlers as $handler) {
209 if ($handler instanceof StreamingRequestMiddleware) {
210 $streaming = true;
211 break;
212 }
213 }
214
215 $middleware = array();
216 if (!$streaming) {
217 $maxSize = $this->getMaxRequestSize();
218 $concurrency = $this->getConcurrentRequestsLimit(\ini_get('memory_limit'), $maxSize);
219 if ($concurrency !== null) {
220 $middleware[] = new LimitConcurrentRequestsMiddleware($concurrency);
221 }
222 $middleware[] = new RequestBodyBufferMiddleware($maxSize);
223 // Checking for an empty string because that is what a boolean
224 // false is returned as by ini_get depending on the PHP version.
225 // @link http://php.net/manual/en/ini.core.php#ini.enable-post-data-reading
226 // @link http://php.net/manual/en/function.ini-get.php#refsect1-function.ini-get-notes
227 // @link https://3v4l.org/qJtsa
228 $enablePostDataReading = \ini_get('enable_post_data_reading');
229 if ($enablePostDataReading !== '') {
230 $middleware[] = new RequestBodyParserMiddleware();
231 }
232 }
233
234 $middleware = \array_merge($middleware, $requestHandlers);
235
236 $this->streamingServer = new StreamingServer($loop, new MiddlewareRunner($middleware));
237
238 $that = $this;
239 $this->streamingServer->on('error', function ($error) use ($that) {
240 $that->emit('error', array($error));
241 });
242 }
243
244 /**
245 * Starts listening for HTTP requests on the given socket server instance
246 *
247 * The given [`React\Socket\ServerInterface`](https://github.com/reactphp/socket#serverinterface)
248 * is responsible for emitting the underlying streaming connections. This
249 * HTTP server needs to be attached to it in order to process any
250 * connections and pase incoming streaming data as incoming HTTP request
251 * messages. In its most common form, you can attach this to a
252 * [`React\Socket\Server`](https://github.com/reactphp/socket#server) in
253 * order to start a plaintext HTTP server like this:
254 *
255 * ```php
256 * $server = new React\Http\Server($loop, $handler);
257 *
258 * $socket = new React\Socket\Server(8080, $loop);
259 * $server->listen($socket);
260 * ```
261 *
262 * See also [hello world server example](../examples/51-server-hello-world.php)
263 * for more details.
264 *
265 * This example will start listening for HTTP requests on the alternative
266 * HTTP port `8080` on all interfaces (publicly). As an alternative, it is
267 * very common to use a reverse proxy and let this HTTP server listen on the
268 * localhost (loopback) interface only by using the listen address
269 * `127.0.0.1:8080` instead. This way, you host your application(s) on the
270 * default HTTP port `80` and only route specific requests to this HTTP
271 * server.
272 *
273 * Likewise, it's usually recommended to use a reverse proxy setup to accept
274 * secure HTTPS requests on default HTTPS port `443` (TLS termination) and
275 * only route plaintext requests to this HTTP server. As an alternative, you
276 * can also accept secure HTTPS requests with this HTTP server by attaching
277 * this to a [`React\Socket\Server`](https://github.com/reactphp/socket#server)
278 * using a secure TLS listen address, a certificate file and optional
279 * `passphrase` like this:
280 *
281 * ```php
282 * $server = new React\Http\Server($loop, $handler);
283 *
284 * $socket = new React\Socket\Server('tls://0.0.0.0:8443', $loop, array(
285 * 'local_cert' => __DIR__ . '/localhost.pem'
286 * ));
287 * $server->listen($socket);
288 * ```
289 *
290 * See also [hello world HTTPS example](../examples/61-server-hello-world-https.php)
291 * for more details.
292 *
293 * @param ServerInterface $socket
294 */
295 public function listen(ServerInterface $socket)
296 {
297 $this->streamingServer->listen($socket);
298 }
299
300 /**
301 * @param string $memory_limit
302 * @param string $post_max_size
303 * @return ?int
304 */
305 private function getConcurrentRequestsLimit($memory_limit, $post_max_size)
306 {
307 if ($memory_limit == -1) {
308 return null;
309 }
310
311 $availableMemory = IniUtil::iniSizeToBytes($memory_limit) / 2;
312 $concurrentRequests = (int) \ceil($availableMemory / IniUtil::iniSizeToBytes($post_max_size));
313
314 return $concurrentRequests;
315 }
316
317 /**
318 * @param ?string $post_max_size
319 * @return int
320 */
321 private function getMaxRequestSize($post_max_size = null)
322 {
323 $maxSize = IniUtil::iniSizeToBytes($post_max_size === null ? \ini_get('post_max_size') : $post_max_size);
324
325 return ($maxSize === 0 || $maxSize >= self::MAXIMUM_BUFFER_SIZE) ? self::MAXIMUM_BUFFER_SIZE : $maxSize;
326 }
327 }