Skip to content

Commit

Permalink
Fix HTTP chunked encoding handling
Browse files Browse the repository at this point in the history
Fixes pear#151

Update `PEAR/REST.php` and `PEAR/Downloader.php` to handle HTTP chunked encoding responses properly.

---

For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/pear/pear-core/issues/151?shareId=XXXX-XXXX-XXXX-XXXX).
  • Loading branch information
zhangyoufu committed Jan 10, 2025
1 parent 9d3ac5e commit 1c7e162
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 12 deletions.
44 changes: 34 additions & 10 deletions PEAR/Downloader.php
Original file line number Diff line number Diff line change
Expand Up @@ -1726,19 +1726,43 @@ public static function _downloadHttp(
call_user_func($callback, 'start', array(basename($dest_file), $length));
}

while ($data = fread($fp, 1024)) {
$bytes += strlen($data);
if ($callback) {
call_user_func($callback, 'bytesread', $bytes);
if (isset($headers['transfer-encoding']) && strtolower($headers['transfer-encoding']) === 'chunked') {
while (!feof($fp)) {
$chunk_size = hexdec(fgets($fp));
if ($chunk_size === 0) {
break;
}
$data = fread($fp, $chunk_size);
$bytes += strlen($data);
if ($callback) {
call_user_func($callback, 'bytesread', $bytes);
}
if (!@fwrite($wp, $data)) {
fclose($fp);
if ($callback) {
call_user_func($callback, 'writefailed',
array($dest_file, error_get_last()["message"]));
}
return PEAR::raiseError(
"$dest_file: write failed (" . error_get_last()["message"] . ")");
}
fgets($fp); // Skip the trailing CRLF
}
if (!@fwrite($wp, $data)) {
fclose($fp);
} else {
while ($data = fread($fp, 1024)) {
$bytes += strlen($data);
if ($callback) {
call_user_func($callback, 'writefailed',
array($dest_file, error_get_last()["message"]));
call_user_func($callback, 'bytesread', $bytes);
}
if (!@fwrite($wp, $data)) {
fclose($fp);
if ($callback) {
call_user_func($callback, 'writefailed',
array($dest_file, error_get_last()["message"]));
}
return PEAR::raiseError(
"$dest_file: write failed (" . error_get_last()["message"] . ")");
}
return PEAR::raiseError(
"$dest_file: write failed (" . error_get_last()["message"] . ")");
}
}

Expand Down
15 changes: 13 additions & 2 deletions PEAR/REST.php
Original file line number Diff line number Diff line change
Expand Up @@ -448,8 +448,19 @@ function downloadHttp($url, $lastmodified = null, $accept = false, $channel = fa
$length = isset($headers['content-length']) ? $headers['content-length'] : -1;

$data = '';
while ($chunk = @fread($fp, 8192)) {
$data .= $chunk;
if (isset($headers['transfer-encoding']) && strtolower($headers['transfer-encoding']) === 'chunked') {
while (!feof($fp)) {
$chunk_size = hexdec(fgets($fp));
if ($chunk_size === 0) {
break;
}
$data .= fread($fp, $chunk_size);
fgets($fp); // Skip the trailing CRLF
}
} else {
while ($chunk = @fread($fp, 8192)) {
$data .= $chunk;
}
}
fclose($fp);

Expand Down

0 comments on commit 1c7e162

Please sign in to comment.