comments and formatting
[plcapi.git] / src / Helper / Http.php
1 <?php
2
3 namespace PhpXmlRpc\Helper;
4
5 use PhpXmlRpc\PhpXmlRpc;
6
7 class Http
8 {
9     /**
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.
12      *
13      * @param string $buffer the string to be decoded
14      *
15      * @return string
16      * @internal this function will become protected in the future
17      */
18     public static function decodeChunked($buffer)
19     {
20         // length := 0
21         $length = 0;
22         $new = '';
23
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);
32
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
37                 $new .= $chunk;
38                 $length += strlen($chunk);
39                 break;
40             }
41
42             // read chunk-data and crlf
43             $chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
44             // append chunk-data to entity-body
45             $new .= $chunk;
46             // length := length + chunk-size
47             $length += strlen($chunk);
48             // read chunk-size and crlf
49             $chunkStart = $chunkEnd + 2;
50
51             $chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
52             if ($chunkEnd == false) {
53                 break; //just in case we got a broken connection
54             }
55             $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
56             $chunkSize = hexdec(trim($temp));
57             $chunkStart = $chunkEnd;
58         }
59
60         return $new;
61     }
62
63     /**
64      * Parses HTTP an http response headers and separates them from the body.
65      *
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
68      *
69      * @return array with keys 'headers' and 'cookies'
70      * @throws \Exception
71      */
72     public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0)
73     {
74         $httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array());
75
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)) {
82                 $bd = $pos + 4;
83             } else {
84                 $pos = strpos($data, "\n\n");
85                 if ($pos || is_int($pos)) {
86                     $bd = $pos + 2;
87                 } else {
88                     // No separation between response headers and body: fault?
89                     $bd = 0;
90                 }
91             }
92             if ($bd) {
93                 // this filters out all http headers from proxy.
94                 // maybe we could take them into account, too?
95                 $data = substr($data, $bd);
96             } else {
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']);
99             }
100         }
101
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 ?
109
110                 break;
111             }
112             $data = substr($data, $pos);
113         }
114
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);
120             }
121         }
122
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']);
127         }
128
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)) {
133             $bd = $pos + 4;
134         } else {
135             $pos = strpos($data, "\n\n");
136             if ($pos || is_int($pos)) {
137                 $bd = $pos + 2;
138             } else {
139                 // No separation between response headers and body: fault?
140                 // we could take some action here instead of going on...
141                 $bd = 0;
142             }
143         }
144
145         // be tolerant to line endings, and extra empty lines
146         $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
147
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]);
162                     } else {
163                         $cookies = array($arr[1]);
164                     }
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);
170                         } else {
171                             $httpResponse['headers'][$headerName] = trim($cookie);
172                         }
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
182                             if ($pos == 0) {
183                                 $cookiename = $tag;
184                                 $httpResponse['cookies'][$tag] = array();
185                                 $httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
186                             } else {
187                                 if ($tag != 'value') {
188                                     $httpResponse['cookies'][$cookiename][$tag] = $val;
189                                 }
190                             }
191                         }
192                     }
193                 } else {
194                     $httpResponse['headers'][$headerName] = trim($arr[1]);
195                 }
196             } elseif (isset($headerName)) {
197                 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
198                 $httpResponse['headers'][$headerName] .= ' ' . trim($line);
199             }
200         }
201
202         $data = substr($data, $bd);
203
204         if ($debug && count($httpResponse['headers'])) {
205             $msg = '';
206             foreach ($httpResponse['headers'] as $header => $value) {
207                 $msg .= "HEADER: $header: $value\n";
208             }
209             foreach ($httpResponse['cookies'] as $header => $value) {
210                 $msg .= "COOKIE: $header={$value['value']}\n";
211             }
212             Logger::instance()->debugMessage($msg);
213         }
214
215         // if CURL was used for the call, http headers have been processed,
216         // and dechunking + reinflating have been carried out
217         if (!$headersProcessed) {
218
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']);
224                 }
225             }
226
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)) {
235                             $data = $degzdata;
236                             if ($debug) {
237                                 Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
238                             }
239                         } elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
240                             $data = $degzdata;
241                             if ($debug) {
242                                 Logger::instance()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
243                             }
244                         } else {
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']);
247                         }
248                     } else {
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']);
251                     }
252                 }
253             }
254         } // end of 'if needed, de-chunk, re-inflate response'
255
256         return $httpResponse;
257     }
258 }