Debian Codegraph @

vendor/guzzlehttp/psr7/src/Message.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace GuzzleHttp\Psr7;
6
7 use Psr\Http\Message\MessageInterface;
8 use Psr\Http\Message\RequestInterface;
9 use Psr\Http\Message\ResponseInterface;
10
11 final class Message
12 {
13 /**
14 * Returns the string representation of an HTTP message.
15 *
16 * @param MessageInterface $message Message to convert to a string.
17 */
18 public static function toString(MessageInterface $message): string
19 {
20 if ($message instanceof RequestInterface) {
21 $msg = trim($message->getMethod().' '
22 .$message->getRequestTarget())
23 .' HTTP/'.$message->getProtocolVersion();
24 if (!$message->hasHeader('host')) {
25 $msg .= "\r\nHost: ".$message->getUri()->getHost();
26 }
27 } elseif ($message instanceof ResponseInterface) {
28 $msg = 'HTTP/'.$message->getProtocolVersion().' '
29 .$message->getStatusCode().' '
30 .$message->getReasonPhrase();
31 } else {
32 throw new \InvalidArgumentException('Unknown message type');
33 }
34
35 foreach ($message->getHeaders() as $name => $values) {
36 if (is_string($name) && strtolower($name) === 'set-cookie') {
37 foreach ($values as $value) {
38 $msg .= "\r\n{$name}: ".$value;
39 }
40 } else {
41 $msg .= "\r\n{$name}: ".implode(', ', $values);
42 }
43 }
44
45 return "{$msg}\r\n\r\n".$message->getBody();
46 }
47
48 /**
49 * Get a short summary of the message body.
50 *
51 * Will return `null` if the response is not printable.
52 *
53 * @param MessageInterface $message The message to get the body summary
54 * @param int $truncateAt The maximum allowed size of the summary
55 */
56 public static function bodySummary(MessageInterface $message, int $truncateAt = 120): ?string
57 {
58 $body = $message->getBody();
59
60 if (!$body->isSeekable() || !$body->isReadable()) {
61 return null;
62 }
63
64 $size = $body->getSize();
65
66 if ($size === 0) {
67 return null;
68 }
69
70 $body->rewind();
71 $summary = $body->read($truncateAt);
72
73 if ($size > $truncateAt) {
74 if (preg_match('//u', $summary) !== 1) {
75 $summary = self::trimTrailingIncompleteUtf8Character($summary, $body->read(3));
76 }
77
78 $summary .= ' (truncated...)';
79 }
80
81 $body->rewind();
82
83 // Matches any printable character, including unicode characters:
84 // letters, marks, numbers, punctuation, spacing, and separators.
85 if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary) !== 0) {
86 return null;
87 }
88
89 return $summary;
90 }
91
92 /**
93 * Trims a partial UTF-8 character from the end of a truncated string.
94 */
95 private static function trimTrailingIncompleteUtf8Character(string $summary, string $lookahead): string
96 {
97 $length = strlen($summary);
98
99 if ($length === 0) {
100 return $summary;
101 }
102
103 $start = $length - 1;
104
105 while ($start >= 0) {
106 $byte = ord($summary[$start]);
107
108 if ($byte < 0x80 || $byte > 0xBF) {
109 break;
110 }
111
112 --$start;
113 }
114
115 if ($start < 0) {
116 return $summary;
117 }
118
119 $lead = ord($summary[$start]);
120
121 if ($lead >= 0xC2 && $lead <= 0xDF) {
122 $expectedLength = 2;
123 } elseif ($lead >= 0xE0 && $lead <= 0xEF) {
124 $expectedLength = 3;
125 } elseif ($lead >= 0xF0 && $lead <= 0xF4) {
126 $expectedLength = 4;
127 } else {
128 return $summary;
129 }
130
131 $availableLength = $length - $start;
132
133 if ($availableLength >= $expectedLength) {
134 return $summary;
135 }
136
137 $sequence = substr($summary, $start).substr($lookahead, 0, $expectedLength - $availableLength);
138
139 if (strlen($sequence) !== $expectedLength || preg_match('//u', $sequence) !== 1) {
140 return $summary;
141 }
142
143 return substr($summary, 0, $start);
144 }
145
146 /**
147 * Attempts to rewind a message body and throws an exception on failure.
148 *
149 * The body of the message will only be rewound if a call to `tell()`
150 * returns a value other than `0`.
151 *
152 * @param MessageInterface $message Message to rewind
153 *
154 * @throws \RuntimeException
155 */
156 public static function rewindBody(MessageInterface $message): void
157 {
158 $body = $message->getBody();
159
160 if ($body->tell()) {
161 $body->rewind();
162 }
163 }
164
165 /**
166 * Parses an HTTP message into an associative array.
167 *
168 * The array contains the "start-line" key containing the start line of
169 * the message, "headers" key containing an associative array of header
170 * array values, and a "body" key containing the body of the message.
171 *
172 * @param string $message HTTP request or response to parse.
173 */
174 public static function parseMessage(string $message): array
175 {
176 if (!$message) {
177 throw new \InvalidArgumentException('Invalid message');
178 }
179
180 $message = ltrim($message, "\r\n");
181
182 $messageParts = preg_split("/\r?\n\r?\n/", $message, 2);
183
184 if ($messageParts === false) {
185 throw new \RuntimeException('Unable to split HTTP message: '.preg_last_error_msg());
186 }
187
188 if (count($messageParts) !== 2) {
189 throw new \InvalidArgumentException('Invalid message: Missing header delimiter');
190 }
191
192 [$rawHeaders, $body] = $messageParts;
193 $rawHeaders .= "\r\n"; // Put back the delimiter we split previously
194 $headerParts = preg_split("/\r?\n/", $rawHeaders, 2);
195
196 if ($headerParts === false) {
197 throw new \RuntimeException('Unable to split HTTP message headers: '.preg_last_error_msg());
198 }
199
200 if (count($headerParts) !== 2) {
201 throw new \InvalidArgumentException('Invalid message: Missing status line');
202 }
203
204 [$startLine, $rawHeaders] = $headerParts;
205
206 $versionMatch = preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches);
207
208 if ($versionMatch === false) {
209 throw new \RuntimeException('Unable to parse HTTP start line: '.preg_last_error_msg());
210 }
211
212 if ($versionMatch === 1 && $matches[1] === '1.0') {
213 // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0
214 $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders);
215
216 if ($rawHeaders === null) {
217 throw new \RuntimeException('Unable to unfold HTTP headers: '.preg_last_error_msg());
218 }
219 }
220
221 /** @var array[] $headerLines */
222 $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER);
223
224 if ($count === false) {
225 throw new \RuntimeException('Unable to parse HTTP headers: '.preg_last_error_msg());
226 }
227
228 // If these aren't the same, then one line didn't match and there's an invalid header.
229 if ($count !== substr_count($rawHeaders, "\n")) {
230 // Folding is deprecated, see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4
231 $hasFoldedHeader = preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders);
232
233 if ($hasFoldedHeader === false) {
234 throw new \RuntimeException('Unable to inspect HTTP header folding: '.preg_last_error_msg());
235 }
236
237 if ($hasFoldedHeader === 1) {
238 throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
239 }
240
241 throw new \InvalidArgumentException('Invalid header syntax');
242 }
243
244 $headers = [];
245
246 foreach ($headerLines as $headerLine) {
247 $headers[$headerLine[1]][] = $headerLine[2];
248 }
249
250 return [
251 'start-line' => $startLine,
252 'headers' => $headers,
253 'body' => $body,
254 ];
255 }
256
257 /**
258 * Constructs a URI for an HTTP request message.
259 *
260 * @param string $path Path from the start-line
261 * @param array $headers Array of headers (each value an array).
262 */
263 public static function parseRequestUri(string $path, array $headers): string
264 {
265 $host = self::getHostFromHeaders($headers);
266
267 // If no host is found, then a full URI cannot be constructed.
268 if ($host === null) {
269 return $path;
270 }
271
272 $scheme = substr($host, -4) === ':443' ? 'https' : 'http';
273
274 return $scheme.'://'.$host.'/'.ltrim($path, '/');
275 }
276
277 /**
278 * @param array $headers Array of headers (each value an array).
279 */
280 private static function getHostFromHeaders(array $headers): ?string
281 {
282 $hostKey = array_filter(array_keys($headers), function ($k) {
283 // Numeric array keys are converted to int by PHP.
284 $k = (string) $k;
285
286 return strtolower($k) === 'host';
287 });
288
289 if (!$hostKey) {
290 return null;
291 }
292
293 $host = $headers[reset($hostKey)][0];
294 if (!is_string($host) || Rfc7230::parseHostHeader($host) === null) {
295 throw new \InvalidArgumentException('Invalid request string');
296 }
297
298 return $host;
299 }
300
301 /**
302 * Parses a request message string into a request object.
303 *
304 * @param string $message Request message string.
305 */
306 public static function parseRequest(string $message): RequestInterface
307 {
308 $data = self::parseMessage($message);
309 if (strpbrk($data['start-line'], "\r\n") !== false) {
310 throw new \InvalidArgumentException('Invalid request string');
311 }
312
313 $matches = [];
314 $requestStartLineMatch = preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches);
315
316 if ($requestStartLineMatch === false) {
317 throw new \RuntimeException('Unable to parse request start line: '.preg_last_error_msg());
318 }
319
320 if ($requestStartLineMatch === 0) {
321 throw new \InvalidArgumentException('Invalid request string');
322 }
323 $parts = explode(' ', $data['start-line'], 3);
324 $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
325
326 $request = new Request(
327 $parts[0],
328 $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1],
329 $data['headers'],
330 $data['body'],
331 $version
332 );
333
334 return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
335 }
336
337 /**
338 * Parses a response message string into a response object.
339 *
340 * @param string $message Response message string.
341 */
342 public static function parseResponse(string $message): ResponseInterface
343 {
344 $data = self::parseMessage($message);
345 if (strpbrk($data['start-line'], "\r\n") !== false) {
346 throw new \InvalidArgumentException('Invalid response string');
347 }
348
349 // According to https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2
350 // the space between status-code and reason-phrase is required. But
351 // browsers accept responses without space and reason as well.
352 $responseStartLineMatch = preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line']);
353
354 if ($responseStartLineMatch === false) {
355 throw new \RuntimeException('Unable to parse response start line: '.preg_last_error_msg());
356 }
357
358 if ($responseStartLineMatch === 0) {
359 throw new \InvalidArgumentException('Invalid response string: '.$data['start-line']);
360 }
361 $parts = explode(' ', $data['start-line'], 3);
362
363 return new Response(
364 (int) $parts[1],
365 $data['headers'],
366 $data['body'],
367 explode('/', $parts[0])[1],
368 $parts[2] ?? null
369 );
370 }
371 }