vendor/guzzlehttp/psr7/src/Message.php

382 lines · 12481 bytes

  1<?php
  2
  3declare(strict_types=1);
  4
  5namespace GuzzleHttp\Psr7;
  6
  7use Psr\Http\Message\MessageInterface;
  8use Psr\Http\Message\RequestInterface;
  9use Psr\Http\Message\ResponseInterface;
 10
 11final 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(), " \n\r\t\0\x0B")
 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) && Utils::asciiToLower($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        // Collapse leading slashes so an origin-form target cannot be
269        // parsed as a network-path reference with its own authority.
270        if ($host === null) {
271            return self::normalizePathForOriginForm($path);
272        }
273
274        $scheme = substr($host, -4) === ':443' ? 'https' : 'http';
275
276        return $scheme.'://'.$host.'/'.ltrim($path, '/');
277    }
278
279    private static function normalizePathForOriginForm(string $path): string
280    {
281        if (0 === strpos($path, '//')) {
282            return '/'.ltrim($path, '/');
283        }
284
285        return $path;
286    }
287
288    /**
289     * @param array $headers Array of headers (each value an array).
290     */
291    private static function getHostFromHeaders(array $headers): ?string
292    {
293        $hostKey = array_filter(array_keys($headers), function ($k) {
294            // Numeric array keys are converted to int by PHP.
295            $k = (string) $k;
296
297            return Utils::asciiToLower($k) === 'host';
298        });
299
300        if (!$hostKey) {
301            return null;
302        }
303
304        $host = $headers[reset($hostKey)][0];
305        if (!is_string($host) || Rfc7230::parseHostHeader($host) === null) {
306            throw new \InvalidArgumentException('Invalid request string');
307        }
308
309        return $host;
310    }
311
312    /**
313     * Parses a request message string into a request object.
314     *
315     * @param string $message Request message string.
316     */
317    public static function parseRequest(string $message): RequestInterface
318    {
319        $data = self::parseMessage($message);
320        if (strpbrk($data['start-line'], "\r\n") !== false) {
321            throw new \InvalidArgumentException('Invalid request string');
322        }
323
324        $matches = [];
325        $requestStartLineMatch = preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches);
326
327        if ($requestStartLineMatch === false) {
328            throw new \RuntimeException('Unable to parse request start line: '.preg_last_error_msg());
329        }
330
331        if ($requestStartLineMatch === 0) {
332            throw new \InvalidArgumentException('Invalid request string');
333        }
334        $parts = explode(' ', $data['start-line'], 3);
335        $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
336
337        $request = new Request(
338            $parts[0],
339            $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1],
340            $data['headers'],
341            $data['body'],
342            $version
343        );
344
345        return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
346    }
347
348    /**
349     * Parses a response message string into a response object.
350     *
351     * @param string $message Response message string.
352     */
353    public static function parseResponse(string $message): ResponseInterface
354    {
355        $data = self::parseMessage($message);
356        if (strpbrk($data['start-line'], "\r\n") !== false) {
357            throw new \InvalidArgumentException('Invalid response string');
358        }
359
360        // According to https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2
361        // the space between status-code and reason-phrase is required. But
362        // browsers accept responses without space and reason as well.
363        $responseStartLineMatch = preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/D', $data['start-line']);
364
365        if ($responseStartLineMatch === false) {
366            throw new \RuntimeException('Unable to parse response start line: '.preg_last_error_msg());
367        }
368
369        if ($responseStartLineMatch === 0) {
370            throw new \InvalidArgumentException('Invalid response string: '.$data['start-line']);
371        }
372        $parts = explode(' ', $data['start-line'], 3);
373
374        return new Response(
375            (int) $parts[1],
376            $data['headers'],
377            $data['body'],
378            explode('/', $parts[0])[1],
379            $parts[2] ?? null
380        );
381    }
382}