3 namespace PhpXmlRpc\Helper;
5 use PhpXmlRpc\PhpXmlRpc;
10 * Decode a string that is encoded with "chunked" transfer encoding as defined in rfc2068 par. 19.4.6
11 * Code shamelessly stolen from nusoap library by Dietrich Ayala.
13 * @param string $buffer the string to be decoded
16 * @internal this function will become protected in the future
18 public static function decodeChunked($buffer)
24 // read chunk-size, chunk-extension (if any) and crlf
25 // get the position of the linebreak
26 $chunkEnd = strpos($buffer, "\r\n") + 2;
27 $temp = substr($buffer, 0, $chunkEnd);
28 $chunkSize = hexdec(trim($temp));
29 $chunkStart = $chunkEnd;
30 while ($chunkSize > 0) {
31 $chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize);
33 // just in case we got a broken connection
34 if ($chunkEnd == false) {
35 $chunk = substr($buffer, $chunkStart);
36 // append chunk-data to entity-body
38 $length += strlen($chunk);
42 // read chunk-data and crlf
43 $chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
44 // append chunk-data to entity-body
46 // length := length + chunk-size
47 $length += strlen($chunk);
48 // read chunk-size and crlf
49 $chunkStart = $chunkEnd + 2;
51 $chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
52 if ($chunkEnd == false) {
53 break; //just in case we got a broken connection
55 $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
56 $chunkSize = hexdec(trim($temp));
57 $chunkStart = $chunkEnd;
64 * Parses HTTP an http response headers and separates them from the body.
66 * @param string $data the http response, headers and body. It will be stripped of headers
67 * @param bool $headersProcessed when true, we assume that response inflating and dechunking has been already carried out
69 * @return array with keys 'headers' and 'cookies'
72 public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0)
74 $httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array());
76 // Support "web-proxy-tunnelling" connections for https through proxies
77 if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
78 // Look for CR/LF or simple LF as line separator,
79 // (even though it is not valid http)
80 $pos = strpos($data, "\r\n\r\n");
81 if ($pos || is_int($pos)) {
84 $pos = strpos($data, "\n\n");
85 if ($pos || is_int($pos)) {
88 // No separation between response headers and body: fault?
93 // this filters out all http headers from proxy.
94 // maybe we could take them into account, too?
95 $data = substr($data, $bd);
97 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
98 throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']);
102 // Strip HTTP 1.1 100 Continue header if present
103 while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
104 $pos = strpos($data, 'HTTP', 12);
105 // server sent a Continue header without any (valid) content following...
106 // give the client a chance to know it
107 if (!$pos && !is_int($pos)) {
108 /// @todo this construct works fine in php 3, 4 and 5 - 8; would it not be enough to have !== false now ?
112 $data = substr($data, $pos);
115 // When using Curl to query servers using Digest Auth, we get back a double set of http headers.
116 // We strip out the 1st...
117 if ($headersProcessed && preg_match('/^HTTP\/[0-9.]+ 401 /', $data)) {
118 if (preg_match('/(\r?\n){2}HTTP\/[0-9.]+ 200 /', $data)) {
119 $data = preg_replace('/^HTTP\/[0-9.]+ 401 .+?(?:\r?\n){2}(HTTP\/[0-9.]+ 200 )/s', '$1', $data, 1);
123 if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) {
124 $errstr = substr($data, 0, strpos($data, "\n") - 1);
125 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
126 throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error']);
129 // be tolerant to usage of \n instead of \r\n to separate headers and data
130 // (even though it is not valid http)
131 $pos = strpos($data, "\r\n\r\n");
132 if ($pos || is_int($pos)) {
135 $pos = strpos($data, "\n\n");
136 if ($pos || is_int($pos)) {
139 // No separation between response headers and body: fault?
140 // we could take some action here instead of going on...
145 // be tolerant to line endings, and extra empty lines
146 $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
148 foreach($ar as $line) {
149 // take care of multi-line headers and cookies
150 $arr = explode(':', $line, 2);
151 if (count($arr) > 1) {
152 $headerName = strtolower(trim($arr[0]));
153 /// @todo some other headers (the ones that allow a CSV list of values)
154 /// do allow many values to be passed using multiple header lines.
155 /// We should add content to $xmlrpc->_xh['headers'][$headerName]
156 /// instead of replacing it for those...
157 if ($headerName == 'set-cookie' || $headerName == 'set-cookie2') {
158 if ($headerName == 'set-cookie2') {
159 // version 2 cookies:
160 // there could be many cookies on one line, comma separated
161 $cookies = explode(',', $arr[1]);
163 $cookies = array($arr[1]);
165 foreach ($cookies as $cookie) {
166 // glue together all received cookies, using a comma to separate them
167 // (same as php does with getallheaders())
168 if (isset($httpResponse['headers'][$headerName])) {
169 $httpResponse['headers'][$headerName] .= ', ' . trim($cookie);
171 $httpResponse['headers'][$headerName] = trim($cookie);
173 // parse cookie attributes, in case user wants to correctly honour them
174 // feature creep: only allow rfc-compliant cookie attributes?
175 // @todo support for server sending multiple time cookie with same name, but using different PATHs
176 $cookie = explode(';', $cookie);
177 foreach ($cookie as $pos => $val) {
178 $val = explode('=', $val, 2);
179 $tag = trim($val[0]);
180 $val = trim(@$val[1]);
181 /// @todo with version 1 cookies, we should strip leading and trailing " chars
184 $httpResponse['cookies'][$tag] = array();
185 $httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
187 if ($tag != 'value') {
188 $httpResponse['cookies'][$cookiename][$tag] = $val;
194 $httpResponse['headers'][$headerName] = trim($arr[1]);
196 } elseif (isset($headerName)) {
197 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
198 $httpResponse['headers'][$headerName] .= ' ' . trim($line);
202 $data = substr($data, $bd);
204 if ($debug && count($httpResponse['headers'])) {
206 foreach ($httpResponse['headers'] as $header => $value) {
207 $msg .= "HEADER: $header: $value\n";
209 foreach ($httpResponse['cookies'] as $header => $value) {
210 $msg .= "COOKIE: $header={$value['value']}\n";
212 Logger::instance()->debugMessage($msg);
215 // if CURL was used for the call, http headers have been processed,
216 // and dechunking + reinflating have been carried out
217 if (!$headersProcessed) {
219 // Decode chunked encoding sent by http 1.1 servers
220 if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') {
221 if (!$data = static::decodeChunked($data)) {
222 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
223 throw new \Exception(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail']);
227 // Decode gzip-compressed stuff
228 // code shamelessly inspired from nusoap library by Dietrich Ayala
229 if (isset($httpResponse['headers']['content-encoding'])) {
230 $httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']);
231 if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') {
232 // if decoding works, use it. else assume data wasn't gzencoded
233 if (function_exists('gzinflate')) {
234 if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
237 Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
239 } elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
242 Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
245 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
246 throw new \Exception(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail']);
249 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
250 throw new \Exception(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress']);
254 } // end of 'if needed, de-chunk, re-inflate response'
256 return $httpResponse;