Debian Codegraph @

vendor/react/http/src/Io/RequestHeaderParser.php

raw
1 <?php
2
3 namespace React\Http\Io;
4
5 use Evenement\EventEmitter;
6 use Psr\Http\Message\ServerRequestInterface;
7 use React\Http\Message\ServerRequest;
8 use React\Socket\ConnectionInterface;
9 use Exception;
10
11 /**
12 * [Internal] Parses an incoming request header from an input stream
13 *
14 * This is used internally to parse the request header from the connection and
15 * then process the remaining connection as the request body.
16 *
17 * @event headers
18 * @event error
19 *
20 * @internal
21 */
22 class RequestHeaderParser extends EventEmitter
23 {
24 private $maxSize = 8192;
25
26 public function handle(ConnectionInterface $conn)
27 {
28 $buffer = '';
29 $maxSize = $this->maxSize;
30 $that = $this;
31 $conn->on('data', $fn = function ($data) use (&$buffer, &$fn, $conn, $maxSize, $that) {
32 // append chunk of data to buffer and look for end of request headers
33 $buffer .= $data;
34 $endOfHeader = \strpos($buffer, "\r\n\r\n");
35
36 // reject request if buffer size is exceeded
37 if ($endOfHeader > $maxSize || ($endOfHeader === false && isset($buffer[$maxSize]))) {
38 $conn->removeListener('data', $fn);
39 $fn = null;
40
41 $that->emit('error', array(
42 new \OverflowException("Maximum header size of {$maxSize} exceeded.", 431),
43 $conn
44 ));
45 return;
46 }
47
48 // ignore incomplete requests
49 if ($endOfHeader === false) {
50 return;
51 }
52
53 // request headers received => try to parse request
54 $conn->removeListener('data', $fn);
55 $fn = null;
56
57 try {
58 $request = $that->parseRequest(
59 (string)\substr($buffer, 0, $endOfHeader + 2),
60 $conn->getRemoteAddress(),
61 $conn->getLocalAddress()
62 );
63 } catch (Exception $exception) {
64 $buffer = '';
65 $that->emit('error', array(
66 $exception,
67 $conn
68 ));
69 return;
70 }
71
72 $contentLength = 0;
73 if ($request->hasHeader('Transfer-Encoding')) {
74 $contentLength = null;
75 } elseif ($request->hasHeader('Content-Length')) {
76 $contentLength = (int)$request->getHeaderLine('Content-Length');
77 }
78
79 if ($contentLength === 0) {
80 // happy path: request body is known to be empty
81 $stream = new EmptyBodyStream();
82 $request = $request->withBody($stream);
83 } else {
84 // otherwise body is present => delimit using Content-Length or ChunkedDecoder
85 $stream = new CloseProtectionStream($conn);
86 if ($contentLength !== null) {
87 $stream = new LengthLimitedStream($stream, $contentLength);
88 } else {
89 $stream = new ChunkedDecoder($stream);
90 }
91
92 $request = $request->withBody(new HttpBodyStream($stream, $contentLength));
93 }
94
95 $bodyBuffer = isset($buffer[$endOfHeader + 4]) ? \substr($buffer, $endOfHeader + 4) : '';
96 $buffer = '';
97 $that->emit('headers', array($request, $conn));
98
99 if ($bodyBuffer !== '') {
100 $conn->emit('data', array($bodyBuffer));
101 }
102
103 // happy path: request body is known to be empty => immediately end stream
104 if ($contentLength === 0) {
105 $stream->emit('end');
106 $stream->close();
107 }
108 });
109
110 $conn->on('close', function () use (&$buffer, &$fn) {
111 $fn = $buffer = null;
112 });
113 }
114
115 /**
116 * @param string $headers buffer string containing request headers only
117 * @param ?string $remoteSocketUri
118 * @param ?string $localSocketUri
119 * @return ServerRequestInterface
120 * @throws \InvalidArgumentException
121 * @internal
122 */
123 public function parseRequest($headers, $remoteSocketUri, $localSocketUri)
124 {
125 // additional, stricter safe-guard for request line
126 // because request parser doesn't properly cope with invalid ones
127 $start = array();
128 if (!\preg_match('#^(?<method>[^ ]+) (?<target>[^ ]+) HTTP/(?<version>\d\.\d)#m', $headers, $start)) {
129 throw new \InvalidArgumentException('Unable to parse invalid request-line');
130 }
131
132 // only support HTTP/1.1 and HTTP/1.0 requests
133 if ($start['version'] !== '1.1' && $start['version'] !== '1.0') {
134 throw new \InvalidArgumentException('Received request with invalid protocol version', 505);
135 }
136
137 // match all request header fields into array, thanks to @kelunik for checking the HTTP specs and coming up with this regex
138 $matches = array();
139 $n = \preg_match_all('/^([^()<>@,;:\\\"\/\[\]?={}\x01-\x20\x7F]++):[\x20\x09]*+((?:[\x20\x09]*+[\x21-\x7E\x80-\xFF]++)*+)[\x20\x09]*+[\r]?+\n/m', $headers, $matches, \PREG_SET_ORDER);
140
141 // check number of valid header fields matches number of lines + request line
142 if (\substr_count($headers, "\n") !== $n + 1) {
143 throw new \InvalidArgumentException('Unable to parse invalid request header fields');
144 }
145
146 // format all header fields into associative array
147 $host = null;
148 $fields = array();
149 foreach ($matches as $match) {
150 $fields[$match[1]][] = $match[2];
151
152 // match `Host` request header
153 if ($host === null && \strtolower($match[1]) === 'host') {
154 $host = $match[2];
155 }
156 }
157
158 // create new obj implementing ServerRequestInterface by preserving all
159 // previous properties and restoring original request-target
160 $serverParams = array(
161 'REQUEST_TIME' => \time(),
162 'REQUEST_TIME_FLOAT' => \microtime(true)
163 );
164
165 // scheme is `http` unless TLS is used
166 $localParts = \parse_url($localSocketUri);
167 if (isset($localParts['scheme']) && $localParts['scheme'] === 'tls') {
168 $scheme = 'https://';
169 $serverParams['HTTPS'] = 'on';
170 } else {
171 $scheme = 'http://';
172 }
173
174 // default host if unset comes from local socket address or defaults to localhost
175 if ($host === null) {
176 $host = isset($localParts['host'], $localParts['port']) ? $localParts['host'] . ':' . $localParts['port'] : '127.0.0.1';
177 }
178
179 if ($start['method'] === 'OPTIONS' && $start['target'] === '*') {
180 // support asterisk-form for `OPTIONS *` request line only
181 $uri = $scheme . $host;
182 } elseif ($start['method'] === 'CONNECT') {
183 $parts = \parse_url('tcp://' . $start['target']);
184
185 // check this is a valid authority-form request-target (host:port)
186 if (!isset($parts['scheme'], $parts['host'], $parts['port']) || \count($parts) !== 3) {
187 throw new \InvalidArgumentException('CONNECT method MUST use authority-form request target');
188 }
189 $uri = $scheme . $start['target'];
190 } else {
191 // support absolute-form or origin-form for proxy requests
192 if ($start['target'][0] === '/') {
193 $uri = $scheme . $host . $start['target'];
194 } else {
195 // ensure absolute-form request-target contains a valid URI
196 $parts = \parse_url($start['target']);
197
198 // make sure value contains valid host component (IP or hostname), but no fragment
199 if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'http' || isset($parts['fragment'])) {
200 throw new \InvalidArgumentException('Invalid absolute-form request-target');
201 }
202
203 $uri = $start['target'];
204 }
205 }
206
207 // apply REMOTE_ADDR and REMOTE_PORT if source address is known
208 // address should always be known, unless this is over Unix domain sockets (UDS)
209 if ($remoteSocketUri !== null) {
210 $remoteAddress = \parse_url($remoteSocketUri);
211 $serverParams['REMOTE_ADDR'] = $remoteAddress['host'];
212 $serverParams['REMOTE_PORT'] = $remoteAddress['port'];
213 }
214
215 // apply SERVER_ADDR and SERVER_PORT if server address is known
216 // address should always be known, even for Unix domain sockets (UDS)
217 // but skip UDS as it doesn't have a concept of host/port.
218 if ($localSocketUri !== null && isset($localParts['host'], $localParts['port'])) {
219 $serverParams['SERVER_ADDR'] = $localParts['host'];
220 $serverParams['SERVER_PORT'] = $localParts['port'];
221 }
222
223 $request = new ServerRequest(
224 $start['method'],
225 $uri,
226 $fields,
227 '',
228 $start['version'],
229 $serverParams
230 );
231
232 // only assign request target if it is not in origin-form (happy path for most normal requests)
233 if ($start['target'][0] !== '/') {
234 $request = $request->withRequestTarget($start['target']);
235 }
236
237 // Optional Host header value MUST be valid (host and optional port)
238 if ($request->hasHeader('Host')) {
239 $parts = \parse_url('http://' . $request->getHeaderLine('Host'));
240
241 // make sure value contains valid host component (IP or hostname)
242 if (!$parts || !isset($parts['scheme'], $parts['host'])) {
243 $parts = false;
244 }
245
246 // make sure value does not contain any other URI component
247 unset($parts['scheme'], $parts['host'], $parts['port']);
248 if ($parts === false || $parts) {
249 throw new \InvalidArgumentException('Invalid Host header value');
250 }
251 }
252
253 // ensure message boundaries are valid according to Content-Length and Transfer-Encoding request headers
254 if ($request->hasHeader('Transfer-Encoding')) {
255 if (\strtolower($request->getHeaderLine('Transfer-Encoding')) !== 'chunked') {
256 throw new \InvalidArgumentException('Only chunked-encoding is allowed for Transfer-Encoding', 501);
257 }
258
259 // Transfer-Encoding: chunked and Content-Length header MUST NOT be used at the same time
260 // as per https://tools.ietf.org/html/rfc7230#section-3.3.3
261 if ($request->hasHeader('Content-Length')) {
262 throw new \InvalidArgumentException('Using both `Transfer-Encoding: chunked` and `Content-Length` is not allowed', 400);
263 }
264 } elseif ($request->hasHeader('Content-Length')) {
265 $string = $request->getHeaderLine('Content-Length');
266
267 if ((string)(int)$string !== $string) {
268 // Content-Length value is not an integer or not a single integer
269 throw new \InvalidArgumentException('The value of `Content-Length` is not valid', 400);
270 }
271 }
272
273 // always sanitize Host header because it contains critical routing information
274 $request = $request->withUri($request->getUri()->withUserInfo('u')->withUserInfo(''));
275
276 return $request;
277 }
278 }