Debian Codegraph @

vendor/guzzlehttp/psr7/src/Rfc7230.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace GuzzleHttp\Psr7;
6
7 /**
8 * @internal
9 */
10 final class Rfc7230
11 {
12 /**
13 * Header related regular expressions (based on amphp/http package)
14 *
15 * Note: header delimiter (\r\n) is modified to \r?\n to accept line feed only delimiters for BC reasons.
16 *
17 * @see https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
18 *
19 * @license https://github.com/amphp/http/blob/v1.0.1/LICENSE
20 */
21 public const HEADER_REGEX = "(^([^()<>@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m";
22 public const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)";
23
24 /**
25 * @return array{0: string, 1: int|null}|null
26 */
27 public static function parseHostHeader(string $authority): ?array
28 {
29 if ($authority === '') {
30 return null;
31 }
32
33 $host = $authority;
34 $port = null;
35
36 if ($authority[0] === '[') {
37 $closingBracket = strpos($authority, ']');
38 if ($closingBracket === false) {
39 return null;
40 }
41
42 $host = substr($authority, 0, $closingBracket + 1);
43 $remainder = substr($authority, $closingBracket + 1);
44 if ($remainder !== '') {
45 if ($remainder[0] !== ':') {
46 return null;
47 }
48
49 $port = self::parseAuthorityPort(substr($remainder, 1));
50 if ($port === null) {
51 return null;
52 }
53 }
54 } elseif (false !== ($colon = strpos($authority, ':'))) {
55 $host = substr($authority, 0, $colon);
56 $port = self::parseAuthorityPort(substr($authority, $colon + 1));
57 if ($port === null) {
58 return null;
59 }
60 }
61
62 if ($host === '' || !self::isValidHostHeaderHost($host)) {
63 return null;
64 }
65
66 return [$host, $port];
67 }
68
69 private static function isValidHostHeaderHost(string $host): bool
70 {
71 $invalidHost = preg_match('/[\x00-\x20\x7F\/\?#@\\\\]/', $host);
72
73 if ($invalidHost === false) {
74 return false;
75 }
76
77 if ($invalidHost === 1) {
78 return false;
79 }
80
81 if (strpos($host, '[') !== false || strpos($host, ']') !== false) {
82 if ($host[0] !== '[' || substr($host, -1) !== ']') {
83 return false;
84 }
85
86 $address = substr($host, 1, -1);
87
88 return filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6) !== false
89 || preg_match('/^v[0-9a-f]+\.['.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.':]+$/iD', $address) === 1;
90 }
91
92 return strpos($host, ':') === false;
93 }
94
95 private static function parseAuthorityPort(string $port): ?int
96 {
97 if ($port === '' || !ctype_digit($port)) {
98 return null;
99 }
100
101 $normalized = ltrim($port, '0');
102 if ($normalized === '') {
103 return 0;
104 }
105
106 if (strlen($normalized) > 5 || (int) $normalized > 0xFFFF) {
107 return null;
108 }
109
110 return (int) $normalized;
111 }
112 }