xref: /plugin/upgrade/HTTP/HTTPClient.php (revision 4e3e87e45b11e1184e5fb1995e14bdc3ab70ccf5)
1*4e3e87e4SAndreas Gohr<?php
2*4e3e87e4SAndreas Gohr
3*4e3e87e4SAndreas Gohrnamespace dokuwiki\plugin\upgrade\HTTP;
4*4e3e87e4SAndreas Gohr
5*4e3e87e4SAndreas Gohrdefine('HTTP_NL',"\r\n");
6*4e3e87e4SAndreas Gohr
7*4e3e87e4SAndreas Gohr
8*4e3e87e4SAndreas Gohr/**
9*4e3e87e4SAndreas Gohr * This class implements a basic HTTP client
10*4e3e87e4SAndreas Gohr *
11*4e3e87e4SAndreas Gohr * It supports POST and GET, Proxy usage, basic authentication,
12*4e3e87e4SAndreas Gohr * handles cookies and referers. It is based upon the httpclient
13*4e3e87e4SAndreas Gohr * function from the VideoDB project.
14*4e3e87e4SAndreas Gohr *
15*4e3e87e4SAndreas Gohr * @link   http://www.splitbrain.org/go/videodb
16*4e3e87e4SAndreas Gohr * @author Andreas Goetz <cpuidle@gmx.de>
17*4e3e87e4SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
18*4e3e87e4SAndreas Gohr * @author Tobias Sarnowski <sarnowski@new-thoughts.org>
19*4e3e87e4SAndreas Gohr */
20*4e3e87e4SAndreas Gohrclass HTTPClient {
21*4e3e87e4SAndreas Gohr    //set these if you like
22*4e3e87e4SAndreas Gohr    public $agent;         // User agent
23*4e3e87e4SAndreas Gohr    public $http;          // HTTP version defaults to 1.0
24*4e3e87e4SAndreas Gohr    public $timeout;       // read timeout (seconds)
25*4e3e87e4SAndreas Gohr    public $cookies;
26*4e3e87e4SAndreas Gohr    public $referer;
27*4e3e87e4SAndreas Gohr    public $max_redirect;
28*4e3e87e4SAndreas Gohr    public $max_bodysize;
29*4e3e87e4SAndreas Gohr    public $max_bodysize_abort = true;  // if set, abort if the response body is bigger than max_bodysize
30*4e3e87e4SAndreas Gohr    public $header_regexp; // if set this RE must match against the headers, else abort
31*4e3e87e4SAndreas Gohr    public $headers;
32*4e3e87e4SAndreas Gohr    public $debug;
33*4e3e87e4SAndreas Gohr    public $start = 0.0; // for timings
34*4e3e87e4SAndreas Gohr    public $keep_alive = true; // keep alive rocks
35*4e3e87e4SAndreas Gohr
36*4e3e87e4SAndreas Gohr    // don't set these, read on error
37*4e3e87e4SAndreas Gohr    public $error;
38*4e3e87e4SAndreas Gohr    public $redirect_count;
39*4e3e87e4SAndreas Gohr
40*4e3e87e4SAndreas Gohr    // read these after a successful request
41*4e3e87e4SAndreas Gohr    public $status;
42*4e3e87e4SAndreas Gohr    public $resp_body;
43*4e3e87e4SAndreas Gohr    public $resp_headers;
44*4e3e87e4SAndreas Gohr
45*4e3e87e4SAndreas Gohr    // set these to do basic authentication
46*4e3e87e4SAndreas Gohr    public $user;
47*4e3e87e4SAndreas Gohr    public $pass;
48*4e3e87e4SAndreas Gohr
49*4e3e87e4SAndreas Gohr    // set these if you need to use a proxy
50*4e3e87e4SAndreas Gohr    public $proxy_host;
51*4e3e87e4SAndreas Gohr    public $proxy_port;
52*4e3e87e4SAndreas Gohr    public $proxy_user;
53*4e3e87e4SAndreas Gohr    public $proxy_pass;
54*4e3e87e4SAndreas Gohr    public $proxy_ssl; //boolean set to true if your proxy needs SSL
55*4e3e87e4SAndreas Gohr    public $proxy_except; // regexp of URLs to exclude from proxy
56*4e3e87e4SAndreas Gohr
57*4e3e87e4SAndreas Gohr    // list of kept alive connections
58*4e3e87e4SAndreas Gohr    protected static $connections = array();
59*4e3e87e4SAndreas Gohr
60*4e3e87e4SAndreas Gohr    // what we use as boundary on multipart/form-data posts
61*4e3e87e4SAndreas Gohr    protected $boundary = '---DokuWikiHTTPClient--4523452351';
62*4e3e87e4SAndreas Gohr
63*4e3e87e4SAndreas Gohr    /**
64*4e3e87e4SAndreas Gohr     * Constructor.
65*4e3e87e4SAndreas Gohr     *
66*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
67*4e3e87e4SAndreas Gohr     */
68*4e3e87e4SAndreas Gohr    public function __construct(){
69*4e3e87e4SAndreas Gohr        $this->agent        = 'Mozilla/4.0 (compatible; DokuWiki HTTP Client; '.PHP_OS.')';
70*4e3e87e4SAndreas Gohr        $this->timeout      = 15;
71*4e3e87e4SAndreas Gohr        $this->cookies      = array();
72*4e3e87e4SAndreas Gohr        $this->referer      = '';
73*4e3e87e4SAndreas Gohr        $this->max_redirect = 3;
74*4e3e87e4SAndreas Gohr        $this->redirect_count = 0;
75*4e3e87e4SAndreas Gohr        $this->status       = 0;
76*4e3e87e4SAndreas Gohr        $this->headers      = array();
77*4e3e87e4SAndreas Gohr        $this->http         = '1.0';
78*4e3e87e4SAndreas Gohr        $this->debug        = false;
79*4e3e87e4SAndreas Gohr        $this->max_bodysize = 0;
80*4e3e87e4SAndreas Gohr        $this->header_regexp= '';
81*4e3e87e4SAndreas Gohr        if(extension_loaded('zlib')) $this->headers['Accept-encoding'] = 'gzip';
82*4e3e87e4SAndreas Gohr        $this->headers['Accept'] = 'text/xml,application/xml,application/xhtml+xml,'.
83*4e3e87e4SAndreas Gohr            'text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
84*4e3e87e4SAndreas Gohr        $this->headers['Accept-Language'] = 'en-us';
85*4e3e87e4SAndreas Gohr    }
86*4e3e87e4SAndreas Gohr
87*4e3e87e4SAndreas Gohr
88*4e3e87e4SAndreas Gohr    /**
89*4e3e87e4SAndreas Gohr     * Simple function to do a GET request
90*4e3e87e4SAndreas Gohr     *
91*4e3e87e4SAndreas Gohr     * Returns the wanted page or false on an error;
92*4e3e87e4SAndreas Gohr     *
93*4e3e87e4SAndreas Gohr     * @param  string $url       The URL to fetch
94*4e3e87e4SAndreas Gohr     * @param  bool   $sloppy304 Return body on 304 not modified
95*4e3e87e4SAndreas Gohr     * @return false|string  response body, false on error
96*4e3e87e4SAndreas Gohr     *
97*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
98*4e3e87e4SAndreas Gohr     */
99*4e3e87e4SAndreas Gohr    public function get($url,$sloppy304=false){
100*4e3e87e4SAndreas Gohr        if(!$this->sendRequest($url)) return false;
101*4e3e87e4SAndreas Gohr        if($this->status == 304 && $sloppy304) return $this->resp_body;
102*4e3e87e4SAndreas Gohr        if($this->status < 200 || $this->status > 206) return false;
103*4e3e87e4SAndreas Gohr        return $this->resp_body;
104*4e3e87e4SAndreas Gohr    }
105*4e3e87e4SAndreas Gohr
106*4e3e87e4SAndreas Gohr    /**
107*4e3e87e4SAndreas Gohr     * Simple function to do a GET request with given parameters
108*4e3e87e4SAndreas Gohr     *
109*4e3e87e4SAndreas Gohr     * Returns the wanted page or false on an error.
110*4e3e87e4SAndreas Gohr     *
111*4e3e87e4SAndreas Gohr     * This is a convenience wrapper around get(). The given parameters
112*4e3e87e4SAndreas Gohr     * will be correctly encoded and added to the given base URL.
113*4e3e87e4SAndreas Gohr     *
114*4e3e87e4SAndreas Gohr     * @param  string $url       The URL to fetch
115*4e3e87e4SAndreas Gohr     * @param  array  $data      Associative array of parameters
116*4e3e87e4SAndreas Gohr     * @param  bool   $sloppy304 Return body on 304 not modified
117*4e3e87e4SAndreas Gohr     * @return false|string  response body, false on error
118*4e3e87e4SAndreas Gohr     *
119*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
120*4e3e87e4SAndreas Gohr     */
121*4e3e87e4SAndreas Gohr    public function dget($url,$data,$sloppy304=false){
122*4e3e87e4SAndreas Gohr        if(strpos($url,'?')){
123*4e3e87e4SAndreas Gohr            $url .= '&';
124*4e3e87e4SAndreas Gohr        }else{
125*4e3e87e4SAndreas Gohr            $url .= '?';
126*4e3e87e4SAndreas Gohr        }
127*4e3e87e4SAndreas Gohr        $url .= $this->postEncode($data);
128*4e3e87e4SAndreas Gohr        return $this->get($url,$sloppy304);
129*4e3e87e4SAndreas Gohr    }
130*4e3e87e4SAndreas Gohr
131*4e3e87e4SAndreas Gohr    /**
132*4e3e87e4SAndreas Gohr     * Simple function to do a POST request
133*4e3e87e4SAndreas Gohr     *
134*4e3e87e4SAndreas Gohr     * Returns the resulting page or false on an error;
135*4e3e87e4SAndreas Gohr     *
136*4e3e87e4SAndreas Gohr     * @param  string $url       The URL to fetch
137*4e3e87e4SAndreas Gohr     * @param  array  $data      Associative array of parameters
138*4e3e87e4SAndreas Gohr     * @return false|string  response body, false on error
139*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
140*4e3e87e4SAndreas Gohr     */
141*4e3e87e4SAndreas Gohr    public function post($url,$data){
142*4e3e87e4SAndreas Gohr        if(!$this->sendRequest($url,$data,'POST')) return false;
143*4e3e87e4SAndreas Gohr        if($this->status < 200 || $this->status > 206) return false;
144*4e3e87e4SAndreas Gohr        return $this->resp_body;
145*4e3e87e4SAndreas Gohr    }
146*4e3e87e4SAndreas Gohr
147*4e3e87e4SAndreas Gohr    /**
148*4e3e87e4SAndreas Gohr     * Send an HTTP request
149*4e3e87e4SAndreas Gohr     *
150*4e3e87e4SAndreas Gohr     * This method handles the whole HTTP communication. It respects set proxy settings,
151*4e3e87e4SAndreas Gohr     * builds the request headers, follows redirects and parses the response.
152*4e3e87e4SAndreas Gohr     *
153*4e3e87e4SAndreas Gohr     * Post data should be passed as associative array. When passed as string it will be
154*4e3e87e4SAndreas Gohr     * sent as is. You will need to setup your own Content-Type header then.
155*4e3e87e4SAndreas Gohr     *
156*4e3e87e4SAndreas Gohr     * @param  string $url    - the complete URL
157*4e3e87e4SAndreas Gohr     * @param  mixed  $data   - the post data either as array or raw data
158*4e3e87e4SAndreas Gohr     * @param  string $method - HTTP Method usually GET or POST.
159*4e3e87e4SAndreas Gohr     * @return bool - true on success
160*4e3e87e4SAndreas Gohr     *
161*4e3e87e4SAndreas Gohr     * @author Andreas Goetz <cpuidle@gmx.de>
162*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
163*4e3e87e4SAndreas Gohr     */
164*4e3e87e4SAndreas Gohr    public function sendRequest($url,$data='',$method='GET'){
165*4e3e87e4SAndreas Gohr        $this->start  = $this->time();
166*4e3e87e4SAndreas Gohr        $this->error  = '';
167*4e3e87e4SAndreas Gohr        $this->status = 0;
168*4e3e87e4SAndreas Gohr        $this->resp_body = '';
169*4e3e87e4SAndreas Gohr        $this->resp_headers = array();
170*4e3e87e4SAndreas Gohr
171*4e3e87e4SAndreas Gohr        // save unencoded data for recursive call
172*4e3e87e4SAndreas Gohr        $unencodedData = $data;
173*4e3e87e4SAndreas Gohr
174*4e3e87e4SAndreas Gohr        // don't accept gzip if truncated bodies might occur
175*4e3e87e4SAndreas Gohr        if($this->max_bodysize &&
176*4e3e87e4SAndreas Gohr            !$this->max_bodysize_abort &&
177*4e3e87e4SAndreas Gohr            isset($this->headers['Accept-encoding']) &&
178*4e3e87e4SAndreas Gohr            $this->headers['Accept-encoding'] == 'gzip'){
179*4e3e87e4SAndreas Gohr            unset($this->headers['Accept-encoding']);
180*4e3e87e4SAndreas Gohr        }
181*4e3e87e4SAndreas Gohr
182*4e3e87e4SAndreas Gohr        // parse URL into bits
183*4e3e87e4SAndreas Gohr        $uri = parse_url($url);
184*4e3e87e4SAndreas Gohr        $server = $uri['host'];
185*4e3e87e4SAndreas Gohr        $path   = !empty($uri['path']) ? $uri['path'] : '/';
186*4e3e87e4SAndreas Gohr        $uriPort = !empty($uri['port']) ? $uri['port'] : null;
187*4e3e87e4SAndreas Gohr        if(!empty($uri['query'])) $path .= '?'.$uri['query'];
188*4e3e87e4SAndreas Gohr        if(isset($uri['user'])) $this->user = $uri['user'];
189*4e3e87e4SAndreas Gohr        if(isset($uri['pass'])) $this->pass = $uri['pass'];
190*4e3e87e4SAndreas Gohr
191*4e3e87e4SAndreas Gohr        // proxy setup
192*4e3e87e4SAndreas Gohr        if($this->useProxyForUrl($url)){
193*4e3e87e4SAndreas Gohr            $request_url = $url;
194*4e3e87e4SAndreas Gohr            $server      = $this->proxy_host;
195*4e3e87e4SAndreas Gohr            $port        = $this->proxy_port;
196*4e3e87e4SAndreas Gohr            if (empty($port)) $port = 8080;
197*4e3e87e4SAndreas Gohr            $use_tls     = $this->proxy_ssl;
198*4e3e87e4SAndreas Gohr        }else{
199*4e3e87e4SAndreas Gohr            $request_url = $path;
200*4e3e87e4SAndreas Gohr            $port = $uriPort ?: ($uri['scheme'] == 'https' ? 443 : 80);
201*4e3e87e4SAndreas Gohr            $use_tls     = ($uri['scheme'] == 'https');
202*4e3e87e4SAndreas Gohr        }
203*4e3e87e4SAndreas Gohr
204*4e3e87e4SAndreas Gohr        // add SSL stream prefix if needed - needs SSL support in PHP
205*4e3e87e4SAndreas Gohr        if($use_tls) {
206*4e3e87e4SAndreas Gohr            if(!in_array('ssl', stream_get_transports())) {
207*4e3e87e4SAndreas Gohr                $this->status = -200;
208*4e3e87e4SAndreas Gohr                $this->error = 'This PHP version does not support SSL - cannot connect to server';
209*4e3e87e4SAndreas Gohr            }
210*4e3e87e4SAndreas Gohr            $server = 'ssl://'.$server;
211*4e3e87e4SAndreas Gohr        }
212*4e3e87e4SAndreas Gohr
213*4e3e87e4SAndreas Gohr        // prepare headers
214*4e3e87e4SAndreas Gohr        $headers               = $this->headers;
215*4e3e87e4SAndreas Gohr        $headers['Host']       = $uri['host']
216*4e3e87e4SAndreas Gohr            . ($uriPort ? ':' . $uriPort : '');
217*4e3e87e4SAndreas Gohr        $headers['User-Agent'] = $this->agent;
218*4e3e87e4SAndreas Gohr        $headers['Referer']    = $this->referer;
219*4e3e87e4SAndreas Gohr
220*4e3e87e4SAndreas Gohr        if($method == 'POST'){
221*4e3e87e4SAndreas Gohr            if(is_array($data)){
222*4e3e87e4SAndreas Gohr                if (empty($headers['Content-Type'])) {
223*4e3e87e4SAndreas Gohr                    $headers['Content-Type'] = null;
224*4e3e87e4SAndreas Gohr                }
225*4e3e87e4SAndreas Gohr                switch ($headers['Content-Type']) {
226*4e3e87e4SAndreas Gohr                    case 'multipart/form-data':
227*4e3e87e4SAndreas Gohr                        $headers['Content-Type']   = 'multipart/form-data; boundary=' . $this->boundary;
228*4e3e87e4SAndreas Gohr                        $data = $this->postMultipartEncode($data);
229*4e3e87e4SAndreas Gohr                        break;
230*4e3e87e4SAndreas Gohr                    default:
231*4e3e87e4SAndreas Gohr                        $headers['Content-Type']   = 'application/x-www-form-urlencoded';
232*4e3e87e4SAndreas Gohr                        $data = $this->postEncode($data);
233*4e3e87e4SAndreas Gohr                }
234*4e3e87e4SAndreas Gohr            }
235*4e3e87e4SAndreas Gohr        }elseif($method == 'GET'){
236*4e3e87e4SAndreas Gohr            $data = ''; //no data allowed on GET requests
237*4e3e87e4SAndreas Gohr        }
238*4e3e87e4SAndreas Gohr
239*4e3e87e4SAndreas Gohr        $contentlength = strlen($data);
240*4e3e87e4SAndreas Gohr        if($contentlength)  {
241*4e3e87e4SAndreas Gohr            $headers['Content-Length'] = $contentlength;
242*4e3e87e4SAndreas Gohr        }
243*4e3e87e4SAndreas Gohr
244*4e3e87e4SAndreas Gohr        if($this->user) {
245*4e3e87e4SAndreas Gohr            $headers['Authorization'] = 'Basic '.base64_encode($this->user.':'.$this->pass);
246*4e3e87e4SAndreas Gohr        }
247*4e3e87e4SAndreas Gohr        if($this->proxy_user) {
248*4e3e87e4SAndreas Gohr            $headers['Proxy-Authorization'] = 'Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass);
249*4e3e87e4SAndreas Gohr        }
250*4e3e87e4SAndreas Gohr
251*4e3e87e4SAndreas Gohr        // already connected?
252*4e3e87e4SAndreas Gohr        $connectionId = $this->uniqueConnectionId($server,$port);
253*4e3e87e4SAndreas Gohr        $this->debug('connection pool', self::$connections);
254*4e3e87e4SAndreas Gohr        $socket = null;
255*4e3e87e4SAndreas Gohr        if (isset(self::$connections[$connectionId])) {
256*4e3e87e4SAndreas Gohr            $this->debug('reusing connection', $connectionId);
257*4e3e87e4SAndreas Gohr            $socket = self::$connections[$connectionId];
258*4e3e87e4SAndreas Gohr        }
259*4e3e87e4SAndreas Gohr        if (is_null($socket) || feof($socket)) {
260*4e3e87e4SAndreas Gohr            $this->debug('opening connection', $connectionId);
261*4e3e87e4SAndreas Gohr            // open socket
262*4e3e87e4SAndreas Gohr            $socket = @fsockopen($server,$port,$errno, $errstr, $this->timeout);
263*4e3e87e4SAndreas Gohr            if (!$socket){
264*4e3e87e4SAndreas Gohr                $this->status = -100;
265*4e3e87e4SAndreas Gohr                $this->error = "Could not connect to $server:$port\n$errstr ($errno)";
266*4e3e87e4SAndreas Gohr                return false;
267*4e3e87e4SAndreas Gohr            }
268*4e3e87e4SAndreas Gohr
269*4e3e87e4SAndreas Gohr            // try establish a CONNECT tunnel for SSL
270*4e3e87e4SAndreas Gohr            try {
271*4e3e87e4SAndreas Gohr                if($this->ssltunnel($socket, $request_url)){
272*4e3e87e4SAndreas Gohr                    // no keep alive for tunnels
273*4e3e87e4SAndreas Gohr                    $this->keep_alive = false;
274*4e3e87e4SAndreas Gohr                    // tunnel is authed already
275*4e3e87e4SAndreas Gohr                    if(isset($headers['Proxy-Authentication'])) unset($headers['Proxy-Authentication']);
276*4e3e87e4SAndreas Gohr                }
277*4e3e87e4SAndreas Gohr            } catch (HTTPClientException $e) {
278*4e3e87e4SAndreas Gohr                $this->status = $e->getCode();
279*4e3e87e4SAndreas Gohr                $this->error = $e->getMessage();
280*4e3e87e4SAndreas Gohr                fclose($socket);
281*4e3e87e4SAndreas Gohr                return false;
282*4e3e87e4SAndreas Gohr            }
283*4e3e87e4SAndreas Gohr
284*4e3e87e4SAndreas Gohr            // keep alive?
285*4e3e87e4SAndreas Gohr            if ($this->keep_alive) {
286*4e3e87e4SAndreas Gohr                self::$connections[$connectionId] = $socket;
287*4e3e87e4SAndreas Gohr            } else {
288*4e3e87e4SAndreas Gohr                unset(self::$connections[$connectionId]);
289*4e3e87e4SAndreas Gohr            }
290*4e3e87e4SAndreas Gohr        }
291*4e3e87e4SAndreas Gohr
292*4e3e87e4SAndreas Gohr        if ($this->keep_alive && !$this->useProxyForUrl($request_url)) {
293*4e3e87e4SAndreas Gohr            // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive
294*4e3e87e4SAndreas Gohr            // connection token to a proxy server. We still do keep the connection the
295*4e3e87e4SAndreas Gohr            // proxy alive (well except for CONNECT tunnels)
296*4e3e87e4SAndreas Gohr            $headers['Connection'] = 'Keep-Alive';
297*4e3e87e4SAndreas Gohr        } else {
298*4e3e87e4SAndreas Gohr            $headers['Connection'] = 'Close';
299*4e3e87e4SAndreas Gohr        }
300*4e3e87e4SAndreas Gohr
301*4e3e87e4SAndreas Gohr        try {
302*4e3e87e4SAndreas Gohr            //set non-blocking
303*4e3e87e4SAndreas Gohr            stream_set_blocking($socket, 0);
304*4e3e87e4SAndreas Gohr
305*4e3e87e4SAndreas Gohr            // build request
306*4e3e87e4SAndreas Gohr            $request  = "$method $request_url HTTP/".$this->http.HTTP_NL;
307*4e3e87e4SAndreas Gohr            $request .= $this->buildHeaders($headers);
308*4e3e87e4SAndreas Gohr            $request .= $this->getCookies();
309*4e3e87e4SAndreas Gohr            $request .= HTTP_NL;
310*4e3e87e4SAndreas Gohr            $request .= $data;
311*4e3e87e4SAndreas Gohr
312*4e3e87e4SAndreas Gohr            $this->debug('request',$request);
313*4e3e87e4SAndreas Gohr            $this->sendData($socket, $request, 'request');
314*4e3e87e4SAndreas Gohr
315*4e3e87e4SAndreas Gohr            // read headers from socket
316*4e3e87e4SAndreas Gohr            $r_headers = '';
317*4e3e87e4SAndreas Gohr            do{
318*4e3e87e4SAndreas Gohr                $r_line = $this->readLine($socket, 'headers');
319*4e3e87e4SAndreas Gohr                $r_headers .= $r_line;
320*4e3e87e4SAndreas Gohr            }while($r_line != "\r\n" && $r_line != "\n");
321*4e3e87e4SAndreas Gohr
322*4e3e87e4SAndreas Gohr            $this->debug('response headers',$r_headers);
323*4e3e87e4SAndreas Gohr
324*4e3e87e4SAndreas Gohr            // check if expected body size exceeds allowance
325*4e3e87e4SAndreas Gohr            if($this->max_bodysize && preg_match('/\r?\nContent-Length:\s*(\d+)\r?\n/i',$r_headers,$match)){
326*4e3e87e4SAndreas Gohr                if($match[1] > $this->max_bodysize){
327*4e3e87e4SAndreas Gohr                    if ($this->max_bodysize_abort)
328*4e3e87e4SAndreas Gohr                        throw new HTTPClientException('Reported content length exceeds allowed response size');
329*4e3e87e4SAndreas Gohr                    else
330*4e3e87e4SAndreas Gohr                        $this->error = 'Reported content length exceeds allowed response size';
331*4e3e87e4SAndreas Gohr                }
332*4e3e87e4SAndreas Gohr            }
333*4e3e87e4SAndreas Gohr
334*4e3e87e4SAndreas Gohr            // get Status
335*4e3e87e4SAndreas Gohr            if (!preg_match('/^HTTP\/(\d\.\d)\s*(\d+).*?\n/s', $r_headers, $m))
336*4e3e87e4SAndreas Gohr                throw new HTTPClientException('Server returned bad answer '.$r_headers);
337*4e3e87e4SAndreas Gohr
338*4e3e87e4SAndreas Gohr            $this->status = $m[2];
339*4e3e87e4SAndreas Gohr
340*4e3e87e4SAndreas Gohr            // handle headers and cookies
341*4e3e87e4SAndreas Gohr            $this->resp_headers = $this->parseHeaders($r_headers);
342*4e3e87e4SAndreas Gohr            if(isset($this->resp_headers['set-cookie'])){
343*4e3e87e4SAndreas Gohr                foreach ((array) $this->resp_headers['set-cookie'] as $cookie){
344*4e3e87e4SAndreas Gohr                    list($cookie) = sexplode(';', $cookie, 2, '');
345*4e3e87e4SAndreas Gohr                    list($key, $val) = sexplode('=', $cookie, 2, '');
346*4e3e87e4SAndreas Gohr                    $key = trim($key);
347*4e3e87e4SAndreas Gohr                    if($val == 'deleted'){
348*4e3e87e4SAndreas Gohr                        if(isset($this->cookies[$key])){
349*4e3e87e4SAndreas Gohr                            unset($this->cookies[$key]);
350*4e3e87e4SAndreas Gohr                        }
351*4e3e87e4SAndreas Gohr                    }elseif($key){
352*4e3e87e4SAndreas Gohr                        $this->cookies[$key] = $val;
353*4e3e87e4SAndreas Gohr                    }
354*4e3e87e4SAndreas Gohr                }
355*4e3e87e4SAndreas Gohr            }
356*4e3e87e4SAndreas Gohr
357*4e3e87e4SAndreas Gohr            $this->debug('Object headers',$this->resp_headers);
358*4e3e87e4SAndreas Gohr
359*4e3e87e4SAndreas Gohr            // check server status code to follow redirect
360*4e3e87e4SAndreas Gohr            if(in_array($this->status, [301, 302, 303, 307, 308])){
361*4e3e87e4SAndreas Gohr                if (empty($this->resp_headers['location'])){
362*4e3e87e4SAndreas Gohr                    throw new HTTPClientException('Redirect but no Location Header found');
363*4e3e87e4SAndreas Gohr                }elseif($this->redirect_count == $this->max_redirect){
364*4e3e87e4SAndreas Gohr                    throw new HTTPClientException('Maximum number of redirects exceeded');
365*4e3e87e4SAndreas Gohr                }else{
366*4e3e87e4SAndreas Gohr                    // close the connection because we don't handle content retrieval here
367*4e3e87e4SAndreas Gohr                    // that's the easiest way to clean up the connection
368*4e3e87e4SAndreas Gohr                    fclose($socket);
369*4e3e87e4SAndreas Gohr                    unset(self::$connections[$connectionId]);
370*4e3e87e4SAndreas Gohr
371*4e3e87e4SAndreas Gohr                    $this->redirect_count++;
372*4e3e87e4SAndreas Gohr                    $this->referer = $url;
373*4e3e87e4SAndreas Gohr                    // handle non-RFC-compliant relative redirects
374*4e3e87e4SAndreas Gohr                    if (!preg_match('/^http/i', $this->resp_headers['location'])){
375*4e3e87e4SAndreas Gohr                        if($this->resp_headers['location'][0] != '/'){
376*4e3e87e4SAndreas Gohr                            $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uriPort.
377*4e3e87e4SAndreas Gohr                                dirname($path).'/'.$this->resp_headers['location'];
378*4e3e87e4SAndreas Gohr                        }else{
379*4e3e87e4SAndreas Gohr                            $this->resp_headers['location'] = $uri['scheme'].'://'.$uri['host'].':'.$uriPort.
380*4e3e87e4SAndreas Gohr                                $this->resp_headers['location'];
381*4e3e87e4SAndreas Gohr                        }
382*4e3e87e4SAndreas Gohr                    }
383*4e3e87e4SAndreas Gohr                    if($this->status == 307 || $this->status == 308) {
384*4e3e87e4SAndreas Gohr                        // perform redirected request, same method as before (required by RFC)
385*4e3e87e4SAndreas Gohr                        return $this->sendRequest($this->resp_headers['location'],$unencodedData,$method);
386*4e3e87e4SAndreas Gohr                    }else{
387*4e3e87e4SAndreas Gohr                        // perform redirected request, always via GET (required by RFC)
388*4e3e87e4SAndreas Gohr                        return $this->sendRequest($this->resp_headers['location'],array(),'GET');
389*4e3e87e4SAndreas Gohr                    }
390*4e3e87e4SAndreas Gohr                }
391*4e3e87e4SAndreas Gohr            }
392*4e3e87e4SAndreas Gohr
393*4e3e87e4SAndreas Gohr            // check if headers are as expected
394*4e3e87e4SAndreas Gohr            if($this->header_regexp && !preg_match($this->header_regexp,$r_headers))
395*4e3e87e4SAndreas Gohr                throw new HTTPClientException('The received headers did not match the given regexp');
396*4e3e87e4SAndreas Gohr
397*4e3e87e4SAndreas Gohr            //read body (with chunked encoding if needed)
398*4e3e87e4SAndreas Gohr            $r_body    = '';
399*4e3e87e4SAndreas Gohr            if(
400*4e3e87e4SAndreas Gohr                (
401*4e3e87e4SAndreas Gohr                    isset($this->resp_headers['transfer-encoding']) &&
402*4e3e87e4SAndreas Gohr                    $this->resp_headers['transfer-encoding'] == 'chunked'
403*4e3e87e4SAndreas Gohr                ) || (
404*4e3e87e4SAndreas Gohr                    isset($this->resp_headers['transfer-coding']) &&
405*4e3e87e4SAndreas Gohr                    $this->resp_headers['transfer-coding'] == 'chunked'
406*4e3e87e4SAndreas Gohr                )
407*4e3e87e4SAndreas Gohr            ) {
408*4e3e87e4SAndreas Gohr                $abort = false;
409*4e3e87e4SAndreas Gohr                do {
410*4e3e87e4SAndreas Gohr                    $chunk_size = '';
411*4e3e87e4SAndreas Gohr                    while (preg_match('/^[a-zA-Z0-9]?$/',$byte=$this->readData($socket,1,'chunk'))){
412*4e3e87e4SAndreas Gohr                        // read chunksize until \r
413*4e3e87e4SAndreas Gohr                        $chunk_size .= $byte;
414*4e3e87e4SAndreas Gohr                        if (strlen($chunk_size) > 128) // set an abritrary limit on the size of chunks
415*4e3e87e4SAndreas Gohr                            throw new HTTPClientException('Allowed response size exceeded');
416*4e3e87e4SAndreas Gohr                    }
417*4e3e87e4SAndreas Gohr                    $this->readLine($socket, 'chunk');     // readtrailing \n
418*4e3e87e4SAndreas Gohr                    $chunk_size = hexdec($chunk_size);
419*4e3e87e4SAndreas Gohr
420*4e3e87e4SAndreas Gohr                    if($this->max_bodysize && $chunk_size+strlen($r_body) > $this->max_bodysize){
421*4e3e87e4SAndreas Gohr                        if ($this->max_bodysize_abort)
422*4e3e87e4SAndreas Gohr                            throw new HTTPClientException('Allowed response size exceeded');
423*4e3e87e4SAndreas Gohr                        $this->error = 'Allowed response size exceeded';
424*4e3e87e4SAndreas Gohr                        $chunk_size = $this->max_bodysize - strlen($r_body);
425*4e3e87e4SAndreas Gohr                        $abort = true;
426*4e3e87e4SAndreas Gohr                    }
427*4e3e87e4SAndreas Gohr
428*4e3e87e4SAndreas Gohr                    if ($chunk_size > 0) {
429*4e3e87e4SAndreas Gohr                        $r_body .= $this->readData($socket, $chunk_size, 'chunk');
430*4e3e87e4SAndreas Gohr                        $this->readData($socket, 2, 'chunk'); // read trailing \r\n
431*4e3e87e4SAndreas Gohr                    }
432*4e3e87e4SAndreas Gohr                } while ($chunk_size && !$abort);
433*4e3e87e4SAndreas Gohr            }elseif(isset($this->resp_headers['content-length']) && !isset($this->resp_headers['transfer-encoding'])){
434*4e3e87e4SAndreas Gohr                /* RFC 2616
435*4e3e87e4SAndreas Gohr                 * If a message is received with both a Transfer-Encoding header field and a Content-Length
436*4e3e87e4SAndreas Gohr                 * header field, the latter MUST be ignored.
437*4e3e87e4SAndreas Gohr                 */
438*4e3e87e4SAndreas Gohr
439*4e3e87e4SAndreas Gohr                // read up to the content-length or max_bodysize
440*4e3e87e4SAndreas Gohr                // for keep alive we need to read the whole message to clean up the socket for the next read
441*4e3e87e4SAndreas Gohr                if(
442*4e3e87e4SAndreas Gohr                    !$this->keep_alive &&
443*4e3e87e4SAndreas Gohr                    $this->max_bodysize &&
444*4e3e87e4SAndreas Gohr                    $this->max_bodysize < $this->resp_headers['content-length']
445*4e3e87e4SAndreas Gohr                ) {
446*4e3e87e4SAndreas Gohr                    $length = $this->max_bodysize + 1;
447*4e3e87e4SAndreas Gohr                }else{
448*4e3e87e4SAndreas Gohr                    $length = $this->resp_headers['content-length'];
449*4e3e87e4SAndreas Gohr                }
450*4e3e87e4SAndreas Gohr
451*4e3e87e4SAndreas Gohr                $r_body = $this->readData($socket, $length, 'response (content-length limited)', true);
452*4e3e87e4SAndreas Gohr            }elseif( !isset($this->resp_headers['transfer-encoding']) && $this->max_bodysize && !$this->keep_alive){
453*4e3e87e4SAndreas Gohr                $r_body = $this->readData($socket, $this->max_bodysize+1, 'response (content-length limited)', true);
454*4e3e87e4SAndreas Gohr            } elseif ((int)$this->status === 204) {
455*4e3e87e4SAndreas Gohr                // request has no content
456*4e3e87e4SAndreas Gohr            } else{
457*4e3e87e4SAndreas Gohr                // read entire socket
458*4e3e87e4SAndreas Gohr                while (!feof($socket)) {
459*4e3e87e4SAndreas Gohr                    $r_body .= $this->readData($socket, 4096, 'response (unlimited)', true);
460*4e3e87e4SAndreas Gohr                }
461*4e3e87e4SAndreas Gohr            }
462*4e3e87e4SAndreas Gohr
463*4e3e87e4SAndreas Gohr            // recheck body size, we might have read max_bodysize+1 or even the whole body, so we abort late here
464*4e3e87e4SAndreas Gohr            if($this->max_bodysize){
465*4e3e87e4SAndreas Gohr                if(strlen($r_body) > $this->max_bodysize){
466*4e3e87e4SAndreas Gohr                    if ($this->max_bodysize_abort) {
467*4e3e87e4SAndreas Gohr                        throw new HTTPClientException('Allowed response size exceeded');
468*4e3e87e4SAndreas Gohr                    } else {
469*4e3e87e4SAndreas Gohr                        $this->error = 'Allowed response size exceeded';
470*4e3e87e4SAndreas Gohr                    }
471*4e3e87e4SAndreas Gohr                }
472*4e3e87e4SAndreas Gohr            }
473*4e3e87e4SAndreas Gohr
474*4e3e87e4SAndreas Gohr        } catch (HTTPClientException $err) {
475*4e3e87e4SAndreas Gohr            $this->error = $err->getMessage();
476*4e3e87e4SAndreas Gohr            if ($err->getCode())
477*4e3e87e4SAndreas Gohr                $this->status = $err->getCode();
478*4e3e87e4SAndreas Gohr            unset(self::$connections[$connectionId]);
479*4e3e87e4SAndreas Gohr            fclose($socket);
480*4e3e87e4SAndreas Gohr            return false;
481*4e3e87e4SAndreas Gohr        }
482*4e3e87e4SAndreas Gohr
483*4e3e87e4SAndreas Gohr        if (!$this->keep_alive ||
484*4e3e87e4SAndreas Gohr            (isset($this->resp_headers['connection']) && $this->resp_headers['connection'] == 'Close')) {
485*4e3e87e4SAndreas Gohr            // close socket
486*4e3e87e4SAndreas Gohr            fclose($socket);
487*4e3e87e4SAndreas Gohr            unset(self::$connections[$connectionId]);
488*4e3e87e4SAndreas Gohr        }
489*4e3e87e4SAndreas Gohr
490*4e3e87e4SAndreas Gohr        // decode gzip if needed
491*4e3e87e4SAndreas Gohr        if(isset($this->resp_headers['content-encoding']) &&
492*4e3e87e4SAndreas Gohr            $this->resp_headers['content-encoding'] == 'gzip' &&
493*4e3e87e4SAndreas Gohr            strlen($r_body) > 10 && substr($r_body,0,3)=="\x1f\x8b\x08"){
494*4e3e87e4SAndreas Gohr            $this->resp_body = @gzinflate(substr($r_body, 10));
495*4e3e87e4SAndreas Gohr            if($this->resp_body === false){
496*4e3e87e4SAndreas Gohr                $this->error = 'Failed to decompress gzip encoded content';
497*4e3e87e4SAndreas Gohr                $this->resp_body = $r_body;
498*4e3e87e4SAndreas Gohr            }
499*4e3e87e4SAndreas Gohr        }else{
500*4e3e87e4SAndreas Gohr            $this->resp_body = $r_body;
501*4e3e87e4SAndreas Gohr        }
502*4e3e87e4SAndreas Gohr
503*4e3e87e4SAndreas Gohr        $this->debug('response body',$this->resp_body);
504*4e3e87e4SAndreas Gohr        $this->redirect_count = 0;
505*4e3e87e4SAndreas Gohr        return true;
506*4e3e87e4SAndreas Gohr    }
507*4e3e87e4SAndreas Gohr
508*4e3e87e4SAndreas Gohr    /**
509*4e3e87e4SAndreas Gohr     * Tries to establish a CONNECT tunnel via Proxy
510*4e3e87e4SAndreas Gohr     *
511*4e3e87e4SAndreas Gohr     * Protocol, Servername and Port will be stripped from the request URL when a successful CONNECT happened
512*4e3e87e4SAndreas Gohr     *
513*4e3e87e4SAndreas Gohr     * @param resource &$socket
514*4e3e87e4SAndreas Gohr     * @param string   &$requesturl
515*4e3e87e4SAndreas Gohr     * @throws HTTPClientException when a tunnel is needed but could not be established
516*4e3e87e4SAndreas Gohr     * @return bool true if a tunnel was established
517*4e3e87e4SAndreas Gohr     */
518*4e3e87e4SAndreas Gohr    protected function ssltunnel(&$socket, &$requesturl){
519*4e3e87e4SAndreas Gohr        if(!$this->useProxyForUrl($requesturl)) return false;
520*4e3e87e4SAndreas Gohr        $requestinfo = parse_url($requesturl);
521*4e3e87e4SAndreas Gohr        if($requestinfo['scheme'] != 'https') return false;
522*4e3e87e4SAndreas Gohr        if(empty($requestinfo['port'])) $requestinfo['port'] = 443;
523*4e3e87e4SAndreas Gohr
524*4e3e87e4SAndreas Gohr        // build request
525*4e3e87e4SAndreas Gohr        $request  = "CONNECT {$requestinfo['host']}:{$requestinfo['port']} HTTP/1.0".HTTP_NL;
526*4e3e87e4SAndreas Gohr        $request .= "Host: {$requestinfo['host']}".HTTP_NL;
527*4e3e87e4SAndreas Gohr        if($this->proxy_user) {
528*4e3e87e4SAndreas Gohr            $request .= 'Proxy-Authorization: Basic '.base64_encode($this->proxy_user.':'.$this->proxy_pass).HTTP_NL;
529*4e3e87e4SAndreas Gohr        }
530*4e3e87e4SAndreas Gohr        $request .= HTTP_NL;
531*4e3e87e4SAndreas Gohr
532*4e3e87e4SAndreas Gohr        $this->debug('SSL Tunnel CONNECT',$request);
533*4e3e87e4SAndreas Gohr        $this->sendData($socket, $request, 'SSL Tunnel CONNECT');
534*4e3e87e4SAndreas Gohr
535*4e3e87e4SAndreas Gohr        // read headers from socket
536*4e3e87e4SAndreas Gohr        $r_headers = '';
537*4e3e87e4SAndreas Gohr        do{
538*4e3e87e4SAndreas Gohr            $r_line = $this->readLine($socket, 'headers');
539*4e3e87e4SAndreas Gohr            $r_headers .= $r_line;
540*4e3e87e4SAndreas Gohr        }while($r_line != "\r\n" && $r_line != "\n");
541*4e3e87e4SAndreas Gohr
542*4e3e87e4SAndreas Gohr        $this->debug('SSL Tunnel Response',$r_headers);
543*4e3e87e4SAndreas Gohr        if(preg_match('/^HTTP\/1\.[01] 200/i',$r_headers)){
544*4e3e87e4SAndreas Gohr            // set correct peer name for verification (enabled since PHP 5.6)
545*4e3e87e4SAndreas Gohr            stream_context_set_option($socket, 'ssl', 'peer_name', $requestinfo['host']);
546*4e3e87e4SAndreas Gohr
547*4e3e87e4SAndreas Gohr            // SSLv3 is broken, use only TLS connections.
548*4e3e87e4SAndreas Gohr            // @link https://bugs.php.net/69195
549*4e3e87e4SAndreas Gohr            if (PHP_VERSION_ID >= 50600 && PHP_VERSION_ID <= 50606) {
550*4e3e87e4SAndreas Gohr                $cryptoMethod = STREAM_CRYPTO_METHOD_TLS_CLIENT;
551*4e3e87e4SAndreas Gohr            } else {
552*4e3e87e4SAndreas Gohr                // actually means neither SSLv2 nor SSLv3
553*4e3e87e4SAndreas Gohr                $cryptoMethod = STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
554*4e3e87e4SAndreas Gohr            }
555*4e3e87e4SAndreas Gohr
556*4e3e87e4SAndreas Gohr            if (@stream_socket_enable_crypto($socket, true, $cryptoMethod)) {
557*4e3e87e4SAndreas Gohr                $requesturl = $requestinfo['path'].
558*4e3e87e4SAndreas Gohr                    (!empty($requestinfo['query'])?'?'.$requestinfo['query']:'');
559*4e3e87e4SAndreas Gohr                return true;
560*4e3e87e4SAndreas Gohr            }
561*4e3e87e4SAndreas Gohr
562*4e3e87e4SAndreas Gohr            throw new HTTPClientException(
563*4e3e87e4SAndreas Gohr                'Failed to set up crypto for secure connection to '.$requestinfo['host'], -151
564*4e3e87e4SAndreas Gohr            );
565*4e3e87e4SAndreas Gohr        }
566*4e3e87e4SAndreas Gohr
567*4e3e87e4SAndreas Gohr        throw new HTTPClientException('Failed to establish secure proxy connection', -150);
568*4e3e87e4SAndreas Gohr    }
569*4e3e87e4SAndreas Gohr
570*4e3e87e4SAndreas Gohr    /**
571*4e3e87e4SAndreas Gohr     * Safely write data to a socket
572*4e3e87e4SAndreas Gohr     *
573*4e3e87e4SAndreas Gohr     * @param  resource $socket     An open socket handle
574*4e3e87e4SAndreas Gohr     * @param  string   $data       The data to write
575*4e3e87e4SAndreas Gohr     * @param  string   $message    Description of what is being read
576*4e3e87e4SAndreas Gohr     * @throws HTTPClientException
577*4e3e87e4SAndreas Gohr     *
578*4e3e87e4SAndreas Gohr     * @author Tom N Harris <tnharris@whoopdedo.org>
579*4e3e87e4SAndreas Gohr     */
580*4e3e87e4SAndreas Gohr    protected function sendData($socket, $data, $message) {
581*4e3e87e4SAndreas Gohr        // send request
582*4e3e87e4SAndreas Gohr        $towrite = strlen($data);
583*4e3e87e4SAndreas Gohr        $written = 0;
584*4e3e87e4SAndreas Gohr        while($written < $towrite){
585*4e3e87e4SAndreas Gohr            // check timeout
586*4e3e87e4SAndreas Gohr            $time_used = $this->time() - $this->start;
587*4e3e87e4SAndreas Gohr            if($time_used > $this->timeout)
588*4e3e87e4SAndreas Gohr                throw new HTTPClientException(sprintf('Timeout while sending %s (%.3fs)',$message, $time_used), -100);
589*4e3e87e4SAndreas Gohr            if(feof($socket))
590*4e3e87e4SAndreas Gohr                throw new HTTPClientException("Socket disconnected while writing $message");
591*4e3e87e4SAndreas Gohr
592*4e3e87e4SAndreas Gohr            // select parameters
593*4e3e87e4SAndreas Gohr            $sel_r = null;
594*4e3e87e4SAndreas Gohr            $sel_w = array($socket);
595*4e3e87e4SAndreas Gohr            $sel_e = null;
596*4e3e87e4SAndreas Gohr            // wait for stream ready or timeout (1sec)
597*4e3e87e4SAndreas Gohr            if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
598*4e3e87e4SAndreas Gohr                usleep(1000);
599*4e3e87e4SAndreas Gohr                continue;
600*4e3e87e4SAndreas Gohr            }
601*4e3e87e4SAndreas Gohr
602*4e3e87e4SAndreas Gohr            // write to stream
603*4e3e87e4SAndreas Gohr            $nbytes = fwrite($socket, substr($data,$written,4096));
604*4e3e87e4SAndreas Gohr            if($nbytes === false)
605*4e3e87e4SAndreas Gohr                throw new HTTPClientException("Failed writing to socket while sending $message", -100);
606*4e3e87e4SAndreas Gohr            $written += $nbytes;
607*4e3e87e4SAndreas Gohr        }
608*4e3e87e4SAndreas Gohr    }
609*4e3e87e4SAndreas Gohr
610*4e3e87e4SAndreas Gohr    /**
611*4e3e87e4SAndreas Gohr     * Safely read data from a socket
612*4e3e87e4SAndreas Gohr     *
613*4e3e87e4SAndreas Gohr     * Reads up to a given number of bytes or throws an exception if the
614*4e3e87e4SAndreas Gohr     * response times out or ends prematurely.
615*4e3e87e4SAndreas Gohr     *
616*4e3e87e4SAndreas Gohr     * @param  resource $socket     An open socket handle in non-blocking mode
617*4e3e87e4SAndreas Gohr     * @param  int      $nbytes     Number of bytes to read
618*4e3e87e4SAndreas Gohr     * @param  string   $message    Description of what is being read
619*4e3e87e4SAndreas Gohr     * @param  bool     $ignore_eof End-of-file is not an error if this is set
620*4e3e87e4SAndreas Gohr     * @throws HTTPClientException
621*4e3e87e4SAndreas Gohr     * @return string
622*4e3e87e4SAndreas Gohr     *
623*4e3e87e4SAndreas Gohr     * @author Tom N Harris <tnharris@whoopdedo.org>
624*4e3e87e4SAndreas Gohr     */
625*4e3e87e4SAndreas Gohr    protected function readData($socket, $nbytes, $message, $ignore_eof = false) {
626*4e3e87e4SAndreas Gohr        $r_data = '';
627*4e3e87e4SAndreas Gohr        // Does not return immediately so timeout and eof can be checked
628*4e3e87e4SAndreas Gohr        if ($nbytes < 0) $nbytes = 0;
629*4e3e87e4SAndreas Gohr        $to_read = $nbytes;
630*4e3e87e4SAndreas Gohr        do {
631*4e3e87e4SAndreas Gohr            $time_used = $this->time() - $this->start;
632*4e3e87e4SAndreas Gohr            if ($time_used > $this->timeout)
633*4e3e87e4SAndreas Gohr                throw new HTTPClientException(
634*4e3e87e4SAndreas Gohr                    sprintf('Timeout while reading %s after %d bytes (%.3fs)', $message,
635*4e3e87e4SAndreas Gohr                        strlen($r_data), $time_used), -100);
636*4e3e87e4SAndreas Gohr            if(feof($socket)) {
637*4e3e87e4SAndreas Gohr                if(!$ignore_eof)
638*4e3e87e4SAndreas Gohr                    throw new HTTPClientException("Premature End of File (socket) while reading $message");
639*4e3e87e4SAndreas Gohr                break;
640*4e3e87e4SAndreas Gohr            }
641*4e3e87e4SAndreas Gohr
642*4e3e87e4SAndreas Gohr            if ($to_read > 0) {
643*4e3e87e4SAndreas Gohr                // select parameters
644*4e3e87e4SAndreas Gohr                $sel_r = array($socket);
645*4e3e87e4SAndreas Gohr                $sel_w = null;
646*4e3e87e4SAndreas Gohr                $sel_e = null;
647*4e3e87e4SAndreas Gohr                // wait for stream ready or timeout (1sec)
648*4e3e87e4SAndreas Gohr                if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
649*4e3e87e4SAndreas Gohr                    usleep(1000);
650*4e3e87e4SAndreas Gohr                    continue;
651*4e3e87e4SAndreas Gohr                }
652*4e3e87e4SAndreas Gohr
653*4e3e87e4SAndreas Gohr                $bytes = fread($socket, $to_read);
654*4e3e87e4SAndreas Gohr                if($bytes === false)
655*4e3e87e4SAndreas Gohr                    throw new HTTPClientException("Failed reading from socket while reading $message", -100);
656*4e3e87e4SAndreas Gohr                $r_data .= $bytes;
657*4e3e87e4SAndreas Gohr                $to_read -= strlen($bytes);
658*4e3e87e4SAndreas Gohr            }
659*4e3e87e4SAndreas Gohr        } while ($to_read > 0 && strlen($r_data) < $nbytes);
660*4e3e87e4SAndreas Gohr        return $r_data;
661*4e3e87e4SAndreas Gohr    }
662*4e3e87e4SAndreas Gohr
663*4e3e87e4SAndreas Gohr    /**
664*4e3e87e4SAndreas Gohr     * Safely read a \n-terminated line from a socket
665*4e3e87e4SAndreas Gohr     *
666*4e3e87e4SAndreas Gohr     * Always returns a complete line, including the terminating \n.
667*4e3e87e4SAndreas Gohr     *
668*4e3e87e4SAndreas Gohr     * @param  resource $socket     An open socket handle in non-blocking mode
669*4e3e87e4SAndreas Gohr     * @param  string   $message    Description of what is being read
670*4e3e87e4SAndreas Gohr     * @throws HTTPClientException
671*4e3e87e4SAndreas Gohr     * @return string
672*4e3e87e4SAndreas Gohr     *
673*4e3e87e4SAndreas Gohr     * @author Tom N Harris <tnharris@whoopdedo.org>
674*4e3e87e4SAndreas Gohr     */
675*4e3e87e4SAndreas Gohr    protected function readLine($socket, $message) {
676*4e3e87e4SAndreas Gohr        $r_data = '';
677*4e3e87e4SAndreas Gohr        do {
678*4e3e87e4SAndreas Gohr            $time_used = $this->time() - $this->start;
679*4e3e87e4SAndreas Gohr            if ($time_used > $this->timeout)
680*4e3e87e4SAndreas Gohr                throw new HTTPClientException(
681*4e3e87e4SAndreas Gohr                    sprintf('Timeout while reading %s (%.3fs) >%s<', $message, $time_used, $r_data),
682*4e3e87e4SAndreas Gohr                    -100);
683*4e3e87e4SAndreas Gohr            if(feof($socket))
684*4e3e87e4SAndreas Gohr                throw new HTTPClientException("Premature End of File (socket) while reading $message");
685*4e3e87e4SAndreas Gohr
686*4e3e87e4SAndreas Gohr            // select parameters
687*4e3e87e4SAndreas Gohr            $sel_r = array($socket);
688*4e3e87e4SAndreas Gohr            $sel_w = null;
689*4e3e87e4SAndreas Gohr            $sel_e = null;
690*4e3e87e4SAndreas Gohr            // wait for stream ready or timeout (1sec)
691*4e3e87e4SAndreas Gohr            if(@stream_select($sel_r,$sel_w,$sel_e,1) === false){
692*4e3e87e4SAndreas Gohr                usleep(1000);
693*4e3e87e4SAndreas Gohr                continue;
694*4e3e87e4SAndreas Gohr            }
695*4e3e87e4SAndreas Gohr
696*4e3e87e4SAndreas Gohr            $r_data = fgets($socket, 1024);
697*4e3e87e4SAndreas Gohr        } while (!preg_match('/\n$/',$r_data));
698*4e3e87e4SAndreas Gohr        return $r_data;
699*4e3e87e4SAndreas Gohr    }
700*4e3e87e4SAndreas Gohr
701*4e3e87e4SAndreas Gohr    /**
702*4e3e87e4SAndreas Gohr     * print debug info
703*4e3e87e4SAndreas Gohr     *
704*4e3e87e4SAndreas Gohr     * Uses _debug_text or _debug_html depending on the SAPI name
705*4e3e87e4SAndreas Gohr     *
706*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
707*4e3e87e4SAndreas Gohr     *
708*4e3e87e4SAndreas Gohr     * @param string $info
709*4e3e87e4SAndreas Gohr     * @param mixed  $var
710*4e3e87e4SAndreas Gohr     */
711*4e3e87e4SAndreas Gohr    protected function debug($info,$var=null){
712*4e3e87e4SAndreas Gohr        if(!$this->debug) return;
713*4e3e87e4SAndreas Gohr        if(php_sapi_name() == 'cli'){
714*4e3e87e4SAndreas Gohr            $this->debugText($info, $var);
715*4e3e87e4SAndreas Gohr        }else{
716*4e3e87e4SAndreas Gohr            $this->debugHtml($info, $var);
717*4e3e87e4SAndreas Gohr        }
718*4e3e87e4SAndreas Gohr    }
719*4e3e87e4SAndreas Gohr
720*4e3e87e4SAndreas Gohr    /**
721*4e3e87e4SAndreas Gohr     * print debug info as HTML
722*4e3e87e4SAndreas Gohr     *
723*4e3e87e4SAndreas Gohr     * @param string $info
724*4e3e87e4SAndreas Gohr     * @param mixed  $var
725*4e3e87e4SAndreas Gohr     */
726*4e3e87e4SAndreas Gohr    protected function debugHtml($info, $var=null){
727*4e3e87e4SAndreas Gohr        print '<b>'.$info.'</b> '.($this->time() - $this->start).'s<br />';
728*4e3e87e4SAndreas Gohr        if(!is_null($var)){
729*4e3e87e4SAndreas Gohr            ob_start();
730*4e3e87e4SAndreas Gohr            print_r($var);
731*4e3e87e4SAndreas Gohr            $content = htmlspecialchars(ob_get_contents());
732*4e3e87e4SAndreas Gohr            ob_end_clean();
733*4e3e87e4SAndreas Gohr            print '<pre>'.$content.'</pre>';
734*4e3e87e4SAndreas Gohr        }
735*4e3e87e4SAndreas Gohr    }
736*4e3e87e4SAndreas Gohr
737*4e3e87e4SAndreas Gohr    /**
738*4e3e87e4SAndreas Gohr     * prints debug info as plain text
739*4e3e87e4SAndreas Gohr     *
740*4e3e87e4SAndreas Gohr     * @param string $info
741*4e3e87e4SAndreas Gohr     * @param mixed  $var
742*4e3e87e4SAndreas Gohr     */
743*4e3e87e4SAndreas Gohr    protected function debugText($info, $var=null){
744*4e3e87e4SAndreas Gohr        print '*'.$info.'* '.($this->time() - $this->start)."s\n";
745*4e3e87e4SAndreas Gohr        if(!is_null($var)) print_r($var);
746*4e3e87e4SAndreas Gohr        print "\n-----------------------------------------------\n";
747*4e3e87e4SAndreas Gohr    }
748*4e3e87e4SAndreas Gohr
749*4e3e87e4SAndreas Gohr    /**
750*4e3e87e4SAndreas Gohr     * Return current timestamp in microsecond resolution
751*4e3e87e4SAndreas Gohr     *
752*4e3e87e4SAndreas Gohr     * @return float
753*4e3e87e4SAndreas Gohr     */
754*4e3e87e4SAndreas Gohr    protected static function time(){
755*4e3e87e4SAndreas Gohr        list($usec, $sec) = explode(" ", microtime());
756*4e3e87e4SAndreas Gohr        return ((float)$usec + (float)$sec);
757*4e3e87e4SAndreas Gohr    }
758*4e3e87e4SAndreas Gohr
759*4e3e87e4SAndreas Gohr    /**
760*4e3e87e4SAndreas Gohr     * convert given header string to Header array
761*4e3e87e4SAndreas Gohr     *
762*4e3e87e4SAndreas Gohr     * All Keys are lowercased.
763*4e3e87e4SAndreas Gohr     *
764*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
765*4e3e87e4SAndreas Gohr     *
766*4e3e87e4SAndreas Gohr     * @param string $string
767*4e3e87e4SAndreas Gohr     * @return array
768*4e3e87e4SAndreas Gohr     */
769*4e3e87e4SAndreas Gohr    protected function parseHeaders($string){
770*4e3e87e4SAndreas Gohr        $headers = array();
771*4e3e87e4SAndreas Gohr        $lines = explode("\n",$string);
772*4e3e87e4SAndreas Gohr        array_shift($lines); //skip first line (status)
773*4e3e87e4SAndreas Gohr        foreach($lines as $line){
774*4e3e87e4SAndreas Gohr            list($key, $val) = sexplode(':', $line, 2, '');
775*4e3e87e4SAndreas Gohr            $key = trim($key);
776*4e3e87e4SAndreas Gohr            $val = trim($val);
777*4e3e87e4SAndreas Gohr            $key = strtolower($key);
778*4e3e87e4SAndreas Gohr            if(!$key) continue;
779*4e3e87e4SAndreas Gohr            if(isset($headers[$key])){
780*4e3e87e4SAndreas Gohr                if(is_array($headers[$key])){
781*4e3e87e4SAndreas Gohr                    $headers[$key][] = $val;
782*4e3e87e4SAndreas Gohr                }else{
783*4e3e87e4SAndreas Gohr                    $headers[$key] = array($headers[$key],$val);
784*4e3e87e4SAndreas Gohr                }
785*4e3e87e4SAndreas Gohr            }else{
786*4e3e87e4SAndreas Gohr                $headers[$key] = $val;
787*4e3e87e4SAndreas Gohr            }
788*4e3e87e4SAndreas Gohr        }
789*4e3e87e4SAndreas Gohr        return $headers;
790*4e3e87e4SAndreas Gohr    }
791*4e3e87e4SAndreas Gohr
792*4e3e87e4SAndreas Gohr    /**
793*4e3e87e4SAndreas Gohr     * convert given header array to header string
794*4e3e87e4SAndreas Gohr     *
795*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
796*4e3e87e4SAndreas Gohr     *
797*4e3e87e4SAndreas Gohr     * @param array $headers
798*4e3e87e4SAndreas Gohr     * @return string
799*4e3e87e4SAndreas Gohr     */
800*4e3e87e4SAndreas Gohr    protected function buildHeaders($headers){
801*4e3e87e4SAndreas Gohr        $string = '';
802*4e3e87e4SAndreas Gohr        foreach($headers as $key => $value){
803*4e3e87e4SAndreas Gohr            if($value === '') continue;
804*4e3e87e4SAndreas Gohr            $string .= $key.': '.$value.HTTP_NL;
805*4e3e87e4SAndreas Gohr        }
806*4e3e87e4SAndreas Gohr        return $string;
807*4e3e87e4SAndreas Gohr    }
808*4e3e87e4SAndreas Gohr
809*4e3e87e4SAndreas Gohr    /**
810*4e3e87e4SAndreas Gohr     * get cookies as http header string
811*4e3e87e4SAndreas Gohr     *
812*4e3e87e4SAndreas Gohr     * @author Andreas Goetz <cpuidle@gmx.de>
813*4e3e87e4SAndreas Gohr     *
814*4e3e87e4SAndreas Gohr     * @return string
815*4e3e87e4SAndreas Gohr     */
816*4e3e87e4SAndreas Gohr    protected function getCookies(){
817*4e3e87e4SAndreas Gohr        $headers = '';
818*4e3e87e4SAndreas Gohr        foreach ($this->cookies as $key => $val){
819*4e3e87e4SAndreas Gohr            $headers .= "$key=$val; ";
820*4e3e87e4SAndreas Gohr        }
821*4e3e87e4SAndreas Gohr        $headers = substr($headers, 0, -2);
822*4e3e87e4SAndreas Gohr        if ($headers) $headers = "Cookie: $headers".HTTP_NL;
823*4e3e87e4SAndreas Gohr        return $headers;
824*4e3e87e4SAndreas Gohr    }
825*4e3e87e4SAndreas Gohr
826*4e3e87e4SAndreas Gohr    /**
827*4e3e87e4SAndreas Gohr     * Encode data for posting
828*4e3e87e4SAndreas Gohr     *
829*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
830*4e3e87e4SAndreas Gohr     *
831*4e3e87e4SAndreas Gohr     * @param array $data
832*4e3e87e4SAndreas Gohr     * @return string
833*4e3e87e4SAndreas Gohr     */
834*4e3e87e4SAndreas Gohr    protected function postEncode($data){
835*4e3e87e4SAndreas Gohr        return http_build_query($data,'','&');
836*4e3e87e4SAndreas Gohr    }
837*4e3e87e4SAndreas Gohr
838*4e3e87e4SAndreas Gohr    /**
839*4e3e87e4SAndreas Gohr     * Encode data for posting using multipart encoding
840*4e3e87e4SAndreas Gohr     *
841*4e3e87e4SAndreas Gohr     * @fixme use of urlencode might be wrong here
842*4e3e87e4SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
843*4e3e87e4SAndreas Gohr     *
844*4e3e87e4SAndreas Gohr     * @param array $data
845*4e3e87e4SAndreas Gohr     * @return string
846*4e3e87e4SAndreas Gohr     */
847*4e3e87e4SAndreas Gohr    protected function postMultipartEncode($data){
848*4e3e87e4SAndreas Gohr        $boundary = '--'.$this->boundary;
849*4e3e87e4SAndreas Gohr        $out = '';
850*4e3e87e4SAndreas Gohr        foreach($data as $key => $val){
851*4e3e87e4SAndreas Gohr            $out .= $boundary.HTTP_NL;
852*4e3e87e4SAndreas Gohr            if(!is_array($val)){
853*4e3e87e4SAndreas Gohr                $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"'.HTTP_NL;
854*4e3e87e4SAndreas Gohr                $out .= HTTP_NL; // end of headers
855*4e3e87e4SAndreas Gohr                $out .= $val;
856*4e3e87e4SAndreas Gohr                $out .= HTTP_NL;
857*4e3e87e4SAndreas Gohr            }else{
858*4e3e87e4SAndreas Gohr                $out .= 'Content-Disposition: form-data; name="'.urlencode($key).'"';
859*4e3e87e4SAndreas Gohr                if($val['filename']) $out .= '; filename="'.urlencode($val['filename']).'"';
860*4e3e87e4SAndreas Gohr                $out .= HTTP_NL;
861*4e3e87e4SAndreas Gohr                if($val['mimetype']) $out .= 'Content-Type: '.$val['mimetype'].HTTP_NL;
862*4e3e87e4SAndreas Gohr                $out .= HTTP_NL; // end of headers
863*4e3e87e4SAndreas Gohr                $out .= $val['body'];
864*4e3e87e4SAndreas Gohr                $out .= HTTP_NL;
865*4e3e87e4SAndreas Gohr            }
866*4e3e87e4SAndreas Gohr        }
867*4e3e87e4SAndreas Gohr        $out .= "$boundary--".HTTP_NL;
868*4e3e87e4SAndreas Gohr        return $out;
869*4e3e87e4SAndreas Gohr    }
870*4e3e87e4SAndreas Gohr
871*4e3e87e4SAndreas Gohr    /**
872*4e3e87e4SAndreas Gohr     * Generates a unique identifier for a connection.
873*4e3e87e4SAndreas Gohr     *
874*4e3e87e4SAndreas Gohr     * @param  string $server
875*4e3e87e4SAndreas Gohr     * @param  string $port
876*4e3e87e4SAndreas Gohr     * @return string unique identifier
877*4e3e87e4SAndreas Gohr     */
878*4e3e87e4SAndreas Gohr    protected function uniqueConnectionId($server, $port) {
879*4e3e87e4SAndreas Gohr        return "$server:$port";
880*4e3e87e4SAndreas Gohr    }
881*4e3e87e4SAndreas Gohr
882*4e3e87e4SAndreas Gohr    /**
883*4e3e87e4SAndreas Gohr     * Should the Proxy be used for the given URL?
884*4e3e87e4SAndreas Gohr     *
885*4e3e87e4SAndreas Gohr     * Checks the exceptions
886*4e3e87e4SAndreas Gohr     *
887*4e3e87e4SAndreas Gohr     * @param string $url
888*4e3e87e4SAndreas Gohr     * @return bool
889*4e3e87e4SAndreas Gohr     */
890*4e3e87e4SAndreas Gohr    protected function useProxyForUrl($url) {
891*4e3e87e4SAndreas Gohr        return $this->proxy_host && (!$this->proxy_except || !preg_match('/' . $this->proxy_except . '/i', $url));
892*4e3e87e4SAndreas Gohr    }
893*4e3e87e4SAndreas Gohr}
894