Debian Codegraph @

lib/3rdParty/composer/guzzlehttp/psr7/src/Rfc7230.php

raw symbols SCIP
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 if (preg_match('/[\x00-\x20\x7F\/\?#@\\\\]/', $host)) {
72 return false;
73 }
74
75 if (strpos($host, '[') !== false || strpos($host, ']') !== false) {
76 if ($host[0] !== '[' || substr($host, -1) !== ']') {
77 return false;
78 }
79
80 $address = substr($host, 1, -1);
81
82 return filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6) !== false
83 || preg_match('/^v[0-9a-f]+\.['.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.':]+$/iD', $address) === 1;
84 }
85
86 return strpos($host, ':') === false;
87 }
88
89 private static function parseAuthorityPort(string $port): ?int
90 {
91 if ($port === '' || !ctype_digit($port)) {
92 return null;
93 }
94
95 $normalized = ltrim($port, '0');
96 if ($normalized === '') {
97 return 0;
98 }
99
100 if (strlen($normalized) > 5 || (int) $normalized > 0xFFFF) {
101 return null;
102 }
103
104 return (int) $normalized;
105 }
106 }