forked from phacility/phabricator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAphrontHTTPHeaderParser.php
150 lines (125 loc) · 3.12 KB
/
AphrontHTTPHeaderParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
<?php
final class AphrontHTTPHeaderParser extends Phobject {
private $name;
private $content;
private $pairs;
public function parseRawHeader($raw_header) {
$this->name = null;
$this->content = null;
$parts = explode(':', $raw_header, 2);
$this->name = trim($parts[0]);
if (count($parts) > 1) {
$this->content = trim($parts[1]);
}
$this->pairs = null;
return $this;
}
public function getHeaderName() {
$this->requireParse();
return $this->name;
}
public function getHeaderContent() {
$this->requireParse();
return $this->content;
}
public function getHeaderContentAsPairs() {
$content = $this->getHeaderContent();
$state = 'prekey';
$length = strlen($content);
$pair_name = null;
$pair_value = null;
$pairs = array();
$ii = 0;
while ($ii < $length) {
$c = $content[$ii];
switch ($state) {
case 'prekey';
// We're eating space in front of a key.
if ($c == ' ') {
$ii++;
break;
}
$pair_name = '';
$state = 'key';
break;
case 'key';
// We're parsing a key name until we find "=" or ";".
if ($c == ';') {
$state = 'done';
break;
}
if ($c == '=') {
$ii++;
$state = 'value';
break;
}
$ii++;
$pair_name .= $c;
break;
case 'value':
// We found an "=", so now figure out if the value is quoted
// or not.
if ($c == '"') {
$ii++;
$state = 'quoted';
break;
}
$state = 'unquoted';
break;
case 'quoted':
// We're in a quoted string, parse until we find the closing quote.
if ($c == '"') {
$ii++;
$state = 'done';
break;
}
$ii++;
$pair_value .= $c;
break;
case 'unquoted':
// We're in an unquoted string, parse until we find a space or a
// semicolon.
if ($c == ' ' || $c == ';') {
$state = 'done';
break;
}
$ii++;
$pair_value .= $c;
break;
case 'done':
// We parsed something, so eat any trailing whitespace and semicolons
// and look for a new value.
if ($c == ' ' || $c == ';') {
$ii++;
break;
}
$pairs[] = array(
$pair_name,
$pair_value,
);
$pair_name = null;
$pair_value = null;
$state = 'prekey';
break;
}
}
if ($state == 'quoted') {
throw new Exception(
pht(
'Header has unterminated double quote for key "%s".',
$pair_name));
}
if ($pair_name !== null) {
$pairs[] = array(
$pair_name,
$pair_value,
);
}
return $pairs;
}
private function requireParse() {
if ($this->name === null) {
throw new PhutilInvalidStateException('parseRawHeader');
}
}
}