MessageParser.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\RequestInterface;
  5. use Psr\Http\Message\ResponseInterface;
  6. /**
  7. * @internal
  8. */
  9. final class MessageParser
  10. {
  11. private function __construct()
  12. {
  13. }
  14. public static function parseMessage(string $message): array
  15. {
  16. if (!$message) {
  17. throw new \InvalidArgumentException('Invalid message');
  18. }
  19. $message = ltrim($message, "\r\n");
  20. $messageParts = preg_split("/\r?\n\r?\n/", $message, 2);
  21. if ($messageParts === false) {
  22. throw new \RuntimeException('Unable to split HTTP message: '.preg_last_error_msg());
  23. }
  24. if (count($messageParts) !== 2) {
  25. throw new \InvalidArgumentException('Invalid message: Missing header delimiter');
  26. }
  27. [$rawHeaders, $body] = $messageParts;
  28. $rawHeaders .= "\r\n"; // Put back the delimiter we split previously
  29. $headerParts = preg_split("/\r?\n/", $rawHeaders, 2);
  30. if ($headerParts === false) {
  31. throw new \RuntimeException('Unable to split HTTP message headers: '.preg_last_error_msg());
  32. }
  33. if (count($headerParts) !== 2) {
  34. throw new \InvalidArgumentException('Invalid message: Missing status line');
  35. }
  36. [$startLine, $rawHeaders] = $headerParts;
  37. $versionMatch = preg_match(
  38. '/(?:^HTTP\/|^'.Rfc9110::TOKEN_PATTERN.' '.Rfc9112::REQUEST_TARGET_PATTERN.' HTTP\/)('.Rfc9112::PROTOCOL_VERSION_PATTERN.')/i',
  39. $startLine,
  40. $matches
  41. );
  42. if ($versionMatch === false) {
  43. throw new \RuntimeException('Unable to parse HTTP start line: '.preg_last_error_msg());
  44. }
  45. if ($versionMatch === 1 && $matches[1] === '1.0') {
  46. // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0
  47. $rawHeaders = preg_replace(Rfc9112::HEADER_FOLD_REGEX, ' ', $rawHeaders);
  48. if ($rawHeaders === null) {
  49. throw new \RuntimeException('Unable to unfold HTTP headers: '.preg_last_error_msg());
  50. }
  51. }
  52. $count = preg_match_all(Rfc9112::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER);
  53. /** @var list<array<int, string>> $headerLines */
  54. if ($count === false) {
  55. throw new \RuntimeException('Unable to parse HTTP headers: '.preg_last_error_msg());
  56. }
  57. // If these aren't the same, then one line didn't match and there's an invalid header.
  58. if ($count !== substr_count($rawHeaders, "\n")) {
  59. // Folding is deprecated, see https://datatracker.ietf.org/doc/html/rfc9112#section-5.2
  60. $hasFoldedHeader = preg_match(Rfc9112::HEADER_FOLD_REGEX, $rawHeaders);
  61. if ($hasFoldedHeader === false) {
  62. throw new \RuntimeException('Unable to inspect HTTP header folding: '.preg_last_error_msg());
  63. }
  64. if ($hasFoldedHeader === 1) {
  65. throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
  66. }
  67. throw new \InvalidArgumentException('Invalid header syntax');
  68. }
  69. $headers = [];
  70. foreach ($headerLines as $headerLine) {
  71. $headers[$headerLine[1]][] = $headerLine[2];
  72. }
  73. return [
  74. 'start-line' => $startLine,
  75. 'headers' => $headers,
  76. 'body' => $body,
  77. ];
  78. }
  79. public static function parseRequestUri(string $path, array $headers): string
  80. {
  81. $host = self::getHostFromHeaders($headers);
  82. // If no host is found, then a full URI cannot be constructed.
  83. // Collapse leading slashes so an origin-form target cannot be
  84. // parsed as a network-path reference with its own authority.
  85. if ($host === null) {
  86. return self::normalizePathForOriginForm($path);
  87. }
  88. [$authorityHost, $port] = self::parseHostHeaderAuthority($host);
  89. $scheme = $port === 443 ? 'https' : 'http';
  90. return $scheme.'://'.self::composeAuthority($authorityHost, $port).'/'.ltrim($path, '/');
  91. }
  92. private static function normalizePathForOriginForm(string $path): string
  93. {
  94. if (str_starts_with($path, '//')) {
  95. return '/'.ltrim($path, '/');
  96. }
  97. return $path;
  98. }
  99. /**
  100. * @return array{0: string, 1: int|null}
  101. */
  102. private static function parseHostHeaderAuthority(string $authority): array
  103. {
  104. $parsed = Rfc9112::parseHostHeader($authority);
  105. if ($parsed === null) {
  106. throw new \InvalidArgumentException('Invalid request string');
  107. }
  108. return $parsed;
  109. }
  110. private static function composeAuthority(string $host, ?int $port): string
  111. {
  112. return $host.($port !== null ? ':'.$port : '');
  113. }
  114. /**
  115. * @param array $headers Array of headers (each value an array).
  116. */
  117. private static function getHostFromHeaders(array $headers): ?string
  118. {
  119. $host = self::getSingleHostHeader($headers);
  120. if ($host === null) {
  121. return null;
  122. }
  123. self::parseHostHeaderAuthority($host);
  124. return $host;
  125. }
  126. /**
  127. * @param array $headers Array of headers (each value an array).
  128. */
  129. private static function getSingleHostHeader(array $headers): ?string
  130. {
  131. $host = null;
  132. $found = false;
  133. foreach ($headers as $name => $values) {
  134. if (Utils::asciiToLower((string) $name) !== 'host') {
  135. continue;
  136. }
  137. if ($found || !is_array($values) || count($values) !== 1) {
  138. throw new \InvalidArgumentException('Invalid request string');
  139. }
  140. $found = true;
  141. $host = reset($values);
  142. }
  143. if (!$found) {
  144. return null;
  145. }
  146. if (!is_string($host)) {
  147. throw new \InvalidArgumentException('Invalid request string');
  148. }
  149. return $host;
  150. }
  151. /**
  152. * @param array $headers Array of headers (each value an array).
  153. */
  154. private static function parseRequestAuthorityUri(array $headers): string
  155. {
  156. $host = self::getHostFromHeaders($headers);
  157. if ($host === null) {
  158. return '';
  159. }
  160. [$authorityHost, $port] = self::parseHostHeaderAuthority($host);
  161. $scheme = $port === 443 ? 'https' : 'http';
  162. return $scheme.'://'.self::composeAuthority($authorityHost, $port);
  163. }
  164. public static function parseRequest(string $message): RequestInterface
  165. {
  166. $data = self::parseMessage($message);
  167. $matches = [];
  168. $matched = preg_match(
  169. '/^(?P<method>'.Rfc9110::TOKEN_PATTERN.') (?P<target>'.Rfc9112::REQUEST_TARGET_PATTERN.') HTTP\/(?P<version>'.Rfc9112::PROTOCOL_VERSION_PATTERN.')$/D',
  170. $data['start-line'],
  171. $matches
  172. );
  173. if ($matched === false) {
  174. throw new \RuntimeException('Unable to parse request start line: '.preg_last_error_msg());
  175. }
  176. if ($matched === 0) {
  177. throw new \InvalidArgumentException('Invalid request string');
  178. }
  179. self::getHostFromHeaders($data['headers']);
  180. if (str_starts_with($matches['target'], '/')) {
  181. return new Request(
  182. $matches['method'],
  183. self::parseRequestUri($matches['target'], $data['headers']),
  184. $data['headers'],
  185. $data['body'],
  186. $matches['version']
  187. );
  188. }
  189. $absoluteFormUri = self::parseAbsoluteFormRequestTarget($matches['target']);
  190. if ($absoluteFormUri !== null) {
  191. return (new Request(
  192. $matches['method'],
  193. $absoluteFormUri,
  194. $data['headers'],
  195. $data['body'],
  196. $matches['version']
  197. ))->withRequestTarget($matches['target']);
  198. }
  199. if (Rfc9112::isAsteriskFormRequestTarget($matches['method'], $matches['target'])) {
  200. return (new Request(
  201. $matches['method'],
  202. self::parseRequestAuthorityUri($data['headers']),
  203. $data['headers'],
  204. $data['body'],
  205. $matches['version']
  206. ))->withRequestTarget($matches['target']);
  207. }
  208. $connectUri = self::parseConnectAuthorityFormRequestTarget($matches['method'], $matches['target']);
  209. if ($connectUri !== null) {
  210. return (new Request(
  211. $matches['method'],
  212. $connectUri,
  213. $data['headers'],
  214. $data['body'],
  215. $matches['version']
  216. ))->withRequestTarget($matches['target']);
  217. }
  218. throw new \InvalidArgumentException('Invalid request string');
  219. }
  220. private static function parseAbsoluteFormRequestTarget(string $target): ?Uri
  221. {
  222. if (!Rfc9112::isAbsoluteFormRequestTarget($target)) {
  223. return null;
  224. }
  225. $authority = substr($target, strpos($target, '//') + 2);
  226. $authority = substr($authority, 0, strcspn($authority, '/?#'));
  227. // RFC 9110 deprecates userinfo in message target URIs and directs
  228. // recipients to treat its presence as an error, since it can obscure
  229. // the authority. Host headers and CONNECT targets already reject it.
  230. if (str_contains($authority, '@')) {
  231. return null;
  232. }
  233. try {
  234. $uri = new Uri($target);
  235. } catch (\InvalidArgumentException $e) {
  236. return null;
  237. }
  238. if ($uri->getHost() === '') {
  239. return null;
  240. }
  241. try {
  242. self::parseHostHeaderAuthority(self::composeAuthority($uri->getHost(), $uri->getPort()));
  243. } catch (\InvalidArgumentException $e) {
  244. return null;
  245. }
  246. return $uri;
  247. }
  248. private static function parseConnectAuthorityFormRequestTarget(string $method, string $target): ?Uri
  249. {
  250. if (!Rfc9112::isConnectAuthorityFormRequestTarget($method, $target)) {
  251. return null;
  252. }
  253. $parsed = Rfc9112::parseHostHeader($target);
  254. if ($parsed === null) {
  255. return null;
  256. }
  257. [$host, $port] = $parsed;
  258. if ($port === null) {
  259. return null;
  260. }
  261. try {
  262. return new Uri('//'.self::composeAuthority($host, $port));
  263. } catch (\InvalidArgumentException $e) {
  264. return null;
  265. }
  266. }
  267. public static function parseResponse(string $message): ResponseInterface
  268. {
  269. $data = self::parseMessage($message);
  270. // According to https://datatracker.ietf.org/doc/html/rfc9112#section-4
  271. // the space between status-code and reason-phrase is required. But
  272. // browsers accept responses without space and reason as well.
  273. $matched = preg_match(
  274. '/^HTTP\/(?P<version>'.Rfc9112::PROTOCOL_VERSION_PATTERN.') (?P<status>[1-5][0-9]{2})(?: (?P<reason>'.Rfc9110::FIELD_VALUE_PATTERN.'))?$/D',
  275. $data['start-line'],
  276. $matches
  277. );
  278. if ($matched === false) {
  279. throw new \RuntimeException('Unable to parse response start line: '.preg_last_error_msg());
  280. }
  281. if ($matched === 0) {
  282. throw new \InvalidArgumentException(\sprintf('Invalid response string: %s', DiagnosticValue::escape($data['start-line'])));
  283. }
  284. return new Response(
  285. (int) $matches['status'],
  286. $data['headers'],
  287. $data['body'],
  288. $matches['version'],
  289. $matches['reason'] ?? null
  290. );
  291. }
  292. }