Passed
Push — master ( 8cdf44...424db6 )
by Gaetano
08:49
created

Http::getLogger()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
ccs 0
cts 1
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpXmlRpc\Helper;
4
5
use PhpXmlRpc\Exception\HttpException;
6
use PhpXmlRpc\PhpXmlRpc;
7
8
/**
9
 *
10
 * @todo allow usage of a custom Logger via the DIC(ish) pattern we use in other classes
11
 */
12
class Http
13
{
14
    protected static $logger;
15
16
    public function getLogger()
17
    {
18
        if (self::$logger === null) {
19
            self::$logger = Logger::instance();
20
        }
21
        return self::$logger;
22
    }
23
24
    /**
25
     * @param $logger
26
     * @return void
27
     */
28
    public static function setLogger($logger)
29
    {
30
        self::$logger = $logger;
31
    }
32
33
    /**
34
     * Decode a string that is encoded with "chunked" transfer encoding as defined in rfc2068 par. 19.4.6.
35
     * Code shamelessly stolen from nusoap library by Dietrich Ayala.
36
     * @internal this function will become protected in the future
37
     *
38
     * @param string $buffer the string to be decoded
39
     * @return string
40
     */
41
    public static function decodeChunked($buffer)
42
    {
43
        // length := 0
44
        $length = 0;
45
        $new = '';
46
47
        // read chunk-size, chunk-extension (if any) and crlf
48
        // get the position of the linebreak
49
        $chunkEnd = strpos($buffer, "\r\n") + 2;
50
        $temp = substr($buffer, 0, $chunkEnd);
51
        $chunkSize = hexdec(trim($temp));
52
        $chunkStart = $chunkEnd;
53
        while ($chunkSize > 0) {
54
            $chunkEnd = strpos($buffer, "\r\n", $chunkStart + $chunkSize);
0 ignored issues
show
Bug introduced by
$chunkStart + $chunkSize of type double is incompatible with the type integer expected by parameter $offset of strpos(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

54
            $chunkEnd = strpos($buffer, "\r\n", /** @scrutinizer ignore-type */ $chunkStart + $chunkSize);
Loading history...
55
56
            // just in case we got a broken connection
57
            if ($chunkEnd == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $chunkEnd of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
58
                $chunk = substr($buffer, $chunkStart);
59
                // append chunk-data to entity-body
60
                $new .= $chunk;
61
                $length += strlen($chunk);
62
                break;
63
            }
64
65
            // read chunk-data and crlf
66
            $chunk = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
67
            // append chunk-data to entity-body
68
            $new .= $chunk;
69
            // length := length + chunk-size
70
            $length += strlen($chunk);
71
            // read chunk-size and crlf
72
            $chunkStart = $chunkEnd + 2;
73 699
74
            $chunkEnd = strpos($buffer, "\r\n", $chunkStart) + 2;
75 699
            if ($chunkEnd == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $chunkEnd of type integer to the boolean false. If you are specifically checking for 0, consider using something more explicit like === 0 instead.
Loading history...
76
                break; // just in case we got a broken connection
77
            }
78 699
            $temp = substr($buffer, $chunkStart, $chunkEnd - $chunkStart);
79
            $chunkSize = hexdec(trim($temp));
80
            $chunkStart = $chunkEnd;
81 32
        }
82 32
83 32
        return $new;
84
    }
85
86
    /**
87
     * Parses HTTP an http response's headers and separates them from the body.
88
     *
89
     * @param string $data the http response, headers and body. It will be stripped of headers
90
     * @param bool $headersProcessed when true, we assume that response inflating and dechunking has been already carried out
91
     * @param int $debug when != 0, logs to screen messages detailing info about the parsed data
92
     * @return array with keys 'headers', 'cookies', 'raw_data' and 'status_code'
93 32
     * @throws HttpException
94
     *
95
     * @todo if $debug is 0, we could avoid populating 'raw_data' and 'headers' in the returned value - even better, have
96 32
     *       2 debug levels
97
     */
98
    public function parseResponseHeaders(&$data, $headersProcessed = false, $debug = 0)
99
    {
100
        $httpResponse = array('raw_data' => $data, 'headers'=> array(), 'cookies' => array(), 'status_code' => null);
101
102
        // Support "web-proxy-tunnelling" connections for https through proxies
103
        if (preg_match('/^HTTP\/1\.[0-1] 200 Connection established/', $data)) {
104 699
            // Look for CR/LF or simple LF as line separator (even though it is not valid http)
105 1
            $pos = strpos($data, "\r\n\r\n");
106
            if ($pos || is_int($pos)) {
0 ignored issues
show
introduced by
The condition is_int($pos) is always true.
Loading history...
107
                $bd = $pos + 4;
108 1
            } else {
109
                $pos = strpos($data, "\n\n");
110
                if ($pos || is_int($pos)) {
111
                    $bd = $pos + 2;
112
                } else {
113 1
                    // No separation between response headers and body: fault?
114
                    $bd = 0;
115
                }
116
            }
117
            if ($bd) {
118 699
                // this filters out all http headers from proxy. maybe we could take them into account, too?
119 32
                $data = substr($data, $bd);
120 32
            } else {
121
                $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': HTTPS via proxy error, tunnel connection possibly failed');
122
                throw new HttpException(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (HTTPS via proxy error, tunnel connection possibly failed)', PhpXmlRpc::$xmlrpcerr['http_error']);
123
            }
124 699
        }
125 699
126 699
        // Strip HTTP 1.1 100 Continue header if present
127
        while (preg_match('/^HTTP\/1\.1 1[0-9]{2} /', $data)) {
128
            $pos = strpos($data, 'HTTP', 12);
129 699
            // server sent a Continue header without any (valid) content following...
130 3
            // give the client a chance to know it
131 3
            if (!$pos && !is_int($pos)) {
132 3
                /// @todo this construct works fine in php 3, 4 and 5 - 8; would it not be enough to have !== false now ?
133
134
                break;
135
            }
136
            $data = substr($data, $pos);
137 696
        }
138 696
139 695
        // When using Curl to query servers using Digest Auth, we get back a double set of http headers.
140
        // Same when following redirects
141 1
        // We strip out the 1st...
142 1
        /// @todo we should let the caller know that there was a redirect involved
143 1
        if ($headersProcessed && preg_match('/^HTTP\/[0-9](?:\.[0-9])? (?:401|30[1278]) /', $data)) {
144
            if (preg_match('/(\r?\n){2}HTTP\/[0-9](?:\.[0-9])? 200 /', $data)) {
145
                $data = preg_replace('/^HTTP\/[0-9](?:\.[0-9])? (?:401|30[1278]) .+?(?:\r?\n){2}(HTTP\/[0-9.]+ 200 )/s', '$1', $data, 1);
146
            }
147
        }
148
149
        if (preg_match('/^HTTP\/([0-9](?:\.[0-9])?) ([0-9]{3}) /', $data, $matches)) {
150
            $httpResponse['protocol_version'] = $matches[1];
151
            $httpResponse['status_code'] = $matches[2];
152 696
        }
153
154 696
        if ($httpResponse['status_code'] !== '200') {
155
            $errstr = substr($data, 0, strpos($data, "\n") - 1);
156 696
            $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': HTTP error, got response: ' . $errstr);
157 696
            throw new HttpException(PhpXmlRpc::$xmlrpcstr['http_error'] . ' (' . $errstr . ')', PhpXmlRpc::$xmlrpcerr['http_error'], null, $httpResponse['status_code']);
158 696
        }
159
160
        // be tolerant to usage of \n instead of \r\n to separate headers and data (even though it is not valid http)
161
        $pos = strpos($data, "\r\n\r\n");
162
        if ($pos || is_int($pos)) {
0 ignored issues
show
introduced by
The condition is_int($pos) is always true.
Loading history...
163
            $bd = $pos + 4;
164 696
        } else {
165 22
            $pos = strpos($data, "\n\n");
166
            if ($pos || is_int($pos)) {
167
                $bd = $pos + 2;
168
            } else {
169
                // No separation between response headers and body: fault?
170 22
                // we could take some action here instead of going on...
171
                $bd = 0;
172 22
            }
173
        }
174
175 22
        // be tolerant to line endings, and extra empty lines
176 22
        $ar = preg_split("/\r?\n/", trim(substr($data, 0, $pos)));
177
178 22
        foreach ($ar as $line) {
179
            // take care of multi-line headers and cookies
180
            $arr = explode(':', $line, 2);
181
            if (count($arr) > 1) {
182
                $headerName = strtolower(trim($arr[0]));
183 22
                /// @todo some other headers (the ones that allow a CSV list of values) do allow many values to be
184 22
                ///       passed using multiple header lines.
185 22
                ///       We should add content to $xmlrpc->_xh['headers'][$headerName] instead of replacing it for those...
186 22
                /// @todo should we drop support for rfc2965 (set-cookie2) cookies? It has been obsoleted since 2011
187 22
                if ($headerName == 'set-cookie' || $headerName == 'set-cookie2') {
188
                    if ($headerName == 'set-cookie2') {
189 22
                        // version 2 cookies:
190 22
                        // there could be many cookies on one line, comma separated
191 22
                        $cookies = explode(',', $arr[1]);
192 22
                    } else {
193
                        $cookies = array($arr[1]);
194 22
                    }
195 22
                    foreach ($cookies as $cookie) {
196
                        // glue together all received cookies, using a comma to separate them (same as php does with getallheaders())
197
                        if (isset($httpResponse['headers'][$headerName])) {
198
                            $httpResponse['headers'][$headerName] .= ', ' . trim($cookie);
199
                        } else {
200
                            $httpResponse['headers'][$headerName] = trim($cookie);
201 696
                        }
202
                        // parse cookie attributes, in case user wants to correctly honour them
203
                        // feature creep: only allow rfc-compliant cookie attributes?
204
                        // @todo support for server sending multiple time cookie with same name, but using different PATHs
205 1
                        $cookie = explode(';', $cookie);
206
                        foreach ($cookie as $pos => $val) {
207
                            $val = explode('=', $val, 2);
208
                            $tag = trim($val[0]);
209 696
                            $val = isset($val[1]) ? trim($val[1]) : '';
210
                            /// @todo with version 1 cookies, we should strip leading and trailing " chars
211 696
                            if ($pos == 0) {
212 3
                                $cookiename = $tag;
213 3
                                $httpResponse['cookies'][$tag] = array();
214 3
                                $httpResponse['cookies'][$cookiename]['value'] = urldecode($val);
215
                            } else {
216 3
                                if ($tag != 'value') {
217
                                    $httpResponse['cookies'][$cookiename][$tag] = $val;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $cookiename does not seem to be defined for all execution paths leading up to this point.
Loading history...
218
                                }
219 3
                            }
220
                        }
221
                    }
222
                } else {
223
                    $httpResponse['headers'][$headerName] = trim($arr[1]);
224 696
                }
225
            } elseif (isset($headerName)) {
226
                /// @todo version1 cookies might span multiple lines, thus breaking the parsing above
227 374
                $httpResponse['headers'][$headerName] .= ' ' . trim($line);
228
            }
229
        }
230
231
        $data = substr($data, $bd);
232
233
        if ($debug && count($httpResponse['headers'])) {
234
            $msg = '';
235
            foreach ($httpResponse['headers'] as $header => $value) {
236 374
                $msg .= "HEADER: $header: $value\n";
237 71
            }
238 71
            foreach ($httpResponse['cookies'] as $header => $value) {
239
                $msg .= "COOKIE: $header={$value['value']}\n";
240 71
            }
241 71
            $this->getLogger()->debugMessage($msg);
242 32
        }
243 32
244 32
        // if CURL was used for the call, http headers have been processed, and dechunking + reinflating have been carried out
245
        if (!$headersProcessed) {
246 39
247 39
            // Decode chunked encoding sent by http 1.1 servers
248 39
            if (isset($httpResponse['headers']['transfer-encoding']) && $httpResponse['headers']['transfer-encoding'] == 'chunked') {
249 35
                if (!$data = static::decodeChunked($data)) {
250
                    $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to rebuild the chunked data received from server');
251
                    throw new HttpException(PhpXmlRpc::$xmlrpcstr['dechunk_fail'], PhpXmlRpc::$xmlrpcerr['dechunk_fail'], null, $httpResponse['status_code']);
252
                }
253 64
            }
254
255
            // Decode gzip-compressed stuff
256
            // code shamelessly inspired from nusoap library by Dietrich Ayala
257
            if (isset($httpResponse['headers']['content-encoding'])) {
258
                $httpResponse['headers']['content-encoding'] = str_replace('x-', '', $httpResponse['headers']['content-encoding']);
259
                if ($httpResponse['headers']['content-encoding'] == 'deflate' || $httpResponse['headers']['content-encoding'] == 'gzip') {
260
                    // if decoding works, use it. else assume data wasn't gzencoded
261
                    if (function_exists('gzinflate')) {
262
                        if ($httpResponse['headers']['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) {
263 696
                            $data = $degzdata;
264
                            if ($debug) {
265
                                $this->getLogger()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
266
                            }
267
                        } elseif ($httpResponse['headers']['content-encoding'] == 'gzip' && $degzdata = @gzinflate(substr($data, 10))) {
268
                            $data = $degzdata;
269
                            if ($debug) {
270
                                $this->getLogger()->debugMessage("---INFLATED RESPONSE---[" . strlen($data) . " chars]---\n$data\n---END---");
271
                            }
272
                        } else {
273
                            $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': errors occurred when trying to decode the deflated data received from server');
274
                            throw new HttpException(PhpXmlRpc::$xmlrpcstr['decompress_fail'], PhpXmlRpc::$xmlrpcerr['decompress_fail'], null, $httpResponse['status_code']);
275
                        }
276
                    } else {
277
                        $this->getLogger()->errorLog('XML-RPC: ' . __METHOD__ . ': the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
278
                        throw new HttpException(PhpXmlRpc::$xmlrpcstr['cannot_decompress'], PhpXmlRpc::$xmlrpcerr['cannot_decompress'], null, $httpResponse['status_code']);
279
                    }
280
                }
281
            }
282
        } // end of 'if needed, de-chunk, re-inflate response'
283
284
        return $httpResponse;
285
    }
286
}
287