Skip to content

Commit

Permalink
fix: improve parsing of encapsulated icap headers
Browse files Browse the repository at this point in the history
Signed-off-by: Robin Appelman <[email protected]>
  • Loading branch information
icewind1991 committed May 23, 2024
1 parent 22a14c5 commit 7de05b4
Showing 1 changed file with 12 additions and 33 deletions.
45 changes: 12 additions & 33 deletions lib/ICAP/ResponseParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,58 +66,37 @@ private function readIcapStatusLine($stream): IcapResponseStatus {
}

private function parseResHdr($stream, string $headerValue): array {
$encapsulatedHeaders = [];
$encapsulatedParts = \explode(",", $headerValue);
foreach ($encapsulatedParts as $encapsulatedPart) {
$pieces = \explode("=", \trim($encapsulatedPart));
if ($pieces[1] === "0") {
continue;
if ($pieces[0] === "res-hdr") {
$offset = (int)$pieces[1];
if ($offset > 0) {
fseek($stream, $offset);
}
break;
}
$rawEncapsulatedHeaders = \fread($stream, (int)$pieces[1]);
$encapsulatedHeaders = $this->parseEncapsulatedHeaders($rawEncapsulatedHeaders);
// According to the spec we have a single res-hdr part and are not interested in res-body content
break;
}

$status = trim(\fgets($stream));
$encapsulatedHeaders = $this->readHeaders($stream);
$encapsulatedHeaders['HTTP_STATUS'] = $status;

return $encapsulatedHeaders;
}

private function readHeaders($stream): array {
$headers = [];
$prevString = "";
while (($headerString = \fgets($stream)) !== false) {
$trimmedHeaderString = \trim($headerString);
if ($prevString === "" && $trimmedHeaderString === "") {
if ($trimmedHeaderString === "") {
break;
}
[$headerName, $headerValue] = $this->parseHeader($trimmedHeaderString);
if ($headerName !== '') {
$headers[$headerName] = $headerValue;
if ($headerName == "Encapsulated") {
break;
}
}
$prevString = $trimmedHeaderString;
}
return $headers;
}

private function parseEncapsulatedHeaders(string $headerString): array {
$headers = [];
$split = \preg_split('/\r?\n/', \trim($headerString));
$statusLine = \array_shift($split);
if ($statusLine !== null) {
$headers['HTTP_STATUS'] = $statusLine;
}
foreach (\preg_split('/\r?\n/', $headerString) as $line) {
if ($line === '') {
continue;
}
[$name, $value] = $this->parseHeader($line);
if ($name !== '') {
$headers[$name] = $value;
}
}

return $headers;
}

Expand Down

0 comments on commit 7de05b4

Please sign in to comment.