0fa3f51bcb8f4f86ceba68bad800163e39b11679
[plcapi.git] / src / Helper / Http.php
1 <?php
2
3 namespace PhpXmlRpc\Helper;
4
5 use PhpXmlRpc\PhpXmlRpc;
6 use PhpXmlRpc\Helper\Logger;
7
8 class Http
9 {
10     /**
11      * Decode a string that is encoded w/ "chunked" transfer encoding
12      * as defined in rfc2068 par. 19.4.6
13      * code shamelessly stolen from nusoap library by Dietrich Ayala.
14      *
15      * @param string $buffer the string to be decoded
16      *
17      * @return string
18      */
19     public static function decodeChunked($buffer)
20     {
21         // length := 0
22         $length = 0;
23         $new = '';
24
25         // read chunk-size, chunk-extension (if any) and crlf
26         // get the position of the linebreak
27         $chunkEnd = strpos($buffer, "\r\n") + 2;
28         $temp = substr($buffer, 0, $chunkEnd);
29         $chunkSize = hexdec(trim($temp));
30         $chunkStart = $chunkEnd;
31         while ($chunkSize > 0) {
32             $chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize);
33
34             // just in case we got a broken connection
35             if ($chunkEnd == false) {
36                 $chunk = substr($buffer, $chunkStart);
37                 // append chunk-data to entity-body
38                 $new .= $chunk;
39                 $length += strlen($chunk);
40                 break;
41             }
42
43             // read chunk-data and crlf
44             $chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
45             // append chunk-data to entity-body
46             $new .= $chunk;
47             // length := length + chunk-size
48             $length += strlen($chunk);
49             // read chunk-size and crlf
50             $chunkStart = $chunkEnd + 2;
51
52             $chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
53             if ($chunkEnd == false) {
54                 break; //just in case we got a broken connection
55             }
56             $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
57             $chunkSize = hexdec(trim($temp));
58             $chunkStart = $chunkEnd;
59         }
60
61         return $new;
62     }
63
64     /**
65      * Parses HTTP an http response headers and separates them from the body.
66      *
67      * @param string $data the http response,headers and body. It will be stripped of headers
68      * @param bool $headersProcessed when true, we assume that response inflating and dechunking has been already carried out
69      *
70      * @return array with keys 'headers' and 'cookies'
71      * @throws \Exception
72      */
73     public function parseResponseHeaders(&$data, $headersProcessed = false, $debug=0)
74     {
75         $httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array());
76
77         // Support "web-proxy-tunelling" connections for https through proxies
78         if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
79             // Look for CR/LF or simple LF as line separator,
80             // (even though it is not valid http)
81             $pos = strpos($data, "\r\n\r\n");
82             if ($pos || is_int($pos)) {
83                 $bd = $pos + 4;
84             } else {
85                 $pos = strpos($data, "\n\n");
86                 if ($pos || is_int($pos)) {
87                     $bd = $pos + 2;
88                 } else {
89                     // No separation between response headers and body: fault?
90                     $bd = 0;
91                 }
92             }
93             if ($bd) {
94                 // this filters out all http headers from proxy.
95                 // maybe we could take them into account, too?
96                 $data = substr($data, $bd);
97             } else {
98                 error_log('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
99                 throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']);
100             }
101         }
102
103         // Strip HTTP 1.1 100 Continue header if present
104         while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
105             $pos = strpos($data, 'HTTP', 12);
106             // server sent a Continue header without any (valid) content following...
107             // give the client a chance to know it
108             if (!$pos && !is_int($pos)) {
109                 // works fine in php 3, 4 and 5
110
111                 break;
112             }
113             $data = substr($data, $pos);
114         }
115         if (!preg_match('/^HTTP\/[0-9.]+ 200 /', $data)) {
116             $errstr = substr($data, 0, strpos($data, "\n") - 1);
117             error_log('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
118             throw new \Exception(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error']);
119         }
120
121         // be tolerant to usage of \n instead of \r\n to separate headers and data
122         // (even though it is not valid http)
123         $pos = strpos($data, "\r\n\r\n");
124         if ($pos || is_int($pos)) {
125             $bd = $pos + 4;
126         } else {
127             $pos = strpos($data, "\n\n");
128             if ($pos || is_int($pos)) {
129                 $bd = $pos + 2;
130             } else {
131                 // No separation between response headers and body: fault?
132                 // we could take some action here instead of going on...
133                 $bd = 0;
134             }
135         }
136         // be tolerant to line endings, and extra empty lines
137         $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
138         while (list(, $line) = @each($ar)) {
139             // take care of multi-line headers and cookies
140             $arr = explode(':', $line, 2);
141             if (count($arr) > 1) {
142                 $headerName = strtolower(trim($arr[0]));
143                 /// @todo some other headers (the ones that allow a CSV list of values)
144                 /// do allow many values to be passed using multiple header lines.
145                 /// We should add content to $xmlrpc->_xh['headers'][$headerName]
146                 /// instead of replacing it for those...
147                 if ($headerName == 'set-cookie' || $headerName == 'set-cookie2') {
148                     if ($headerName == 'set-cookie2') {
149                         // version 2 cookies:
150                         // there could be many cookies on one line, comma separated
151                         $cookies = explode(',', $arr[1]);
152                     } else {
153                         $cookies = array($arr[1]);
154                     }
155                     foreach ($cookies as $cookie) {
156                         // glue together all received cookies, using a comma to separate them
157                         // (same as php does with getallheaders())
158                         if (isset($httpResponse['headers'][$headerName])) {
159                             $httpResponse['headers'][$headerName] .= ', ' . trim($cookie);
160                         } else {
161                             $httpResponse['headers'][$headerName] = trim($cookie);
162                         }
163                         // parse cookie attributes, in case user wants to correctly honour them
164                         // feature creep: only allow rfc-compliant cookie attributes?
165                         // @todo support for server sending multiple time cookie with same name, but using different PATHs
166                         $cookie = explode(';', $cookie);
167                         foreach ($cookie as $pos => $val) {
168                             $val = explode('=', $val, 2);
169                             $tag = trim($val[0]);
170                             $val = trim(@$val[1]);
171                             /// @todo with version 1 cookies, we should strip leading and trailing " chars
172                             if ($pos == 0) {
173                                 $cookiename = $tag;
174                                 $httpResponse['cookies'][$tag] = array();
175                                 $httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
176                             } else {
177                                 if ($tag != 'value') {
178                                     $httpResponse['cookies'][$cookiename][$tag] = $val;
179                                 }
180                             }
181                         }
182                     }
183                 } else {
184                     $httpResponse['headers'][$headerName] = trim($arr[1]);
185                 }
186             } elseif (isset($headerName)) {
187                 /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
188                 $httpResponse['headers'][$headerName] .= ' ' . trim($line);
189             }
190         }
191
192         $data = substr($data, $bd);
193
194         if ($debug && count($httpResponse['headers'])) {
195             $msg = '';
196             foreach ($httpResponse['headers'] as $header => $value) {
197                 $msg .= "HEADER: $header: $value\n";
198             }
199             foreach ($httpResponse['cookies'] as $header => $value) {
200                 $msg .= "COOKIE: $header={$value['value']}\n";
201             }
202             Logger::debugMessage($msg);
203         }
204
205         // if CURL was used for the call, http headers have been processed,
206         // and dechunking + reinflating have been carried out
207         if (!$headersProcessed) {
208             // Decode chunked encoding sent by http 1.1 servers
209             if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') {
210                 if (!$data = Http::decodeChunked($data)) {
211                     error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
212                     throw new \Exception(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail']);
213                 }
214             }
215
216             // Decode gzip-compressed stuff
217             // code shamelessly inspired from nusoap library by Dietrich Ayala
218             if (isset($httpResponse['headers']['content-encoding'])) {
219                 $httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']);
220                 if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') {
221                     // if decoding works, use it. else assume data wasn't gzencoded
222                     if (function_exists('gzinflate')) {
223                         if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
224                             $data = $degzdata;
225                             if ($debug) {
226                                 Logger::debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
227                             }
228                         } elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
229                             $data = $degzdata;
230                             if ($debug) {
231                                 Logger::debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
232                             }
233                         } else {
234                             error_log('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
235                             throw new \Exception(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail']);
236                         }
237                     } else {
238                         error_log('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
239                         throw new \Exception(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress']);
240                     }
241                 }
242             }
243         } // end of 'if needed, de-chunk, re-inflate response'
244
245         return $httpResponse;
246     }
247 }