]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/HTTP/Request2/Adapter/Socket.php
Rebuilt HTTPClient class as an extension of PEAR HTTP_Request2 package, adding redire...
[quix0rs-gnu-social.git] / extlib / HTTP / Request2 / Adapter / Socket.php
1 <?php\r
2 /**\r
3  * Socket-based adapter for HTTP_Request2\r
4  *\r
5  * PHP version 5\r
6  *\r
7  * LICENSE:\r
8  *\r
9  * Copyright (c) 2008, 2009, Alexey Borzov <avb@php.net>\r
10  * All rights reserved.\r
11  *\r
12  * Redistribution and use in source and binary forms, with or without\r
13  * modification, are permitted provided that the following conditions\r
14  * are met:\r
15  *\r
16  *    * Redistributions of source code must retain the above copyright\r
17  *      notice, this list of conditions and the following disclaimer.\r
18  *    * Redistributions in binary form must reproduce the above copyright\r
19  *      notice, this list of conditions and the following disclaimer in the\r
20  *      documentation and/or other materials provided with the distribution.\r
21  *    * The names of the authors may not be used to endorse or promote products\r
22  *      derived from this software without specific prior written permission.\r
23  *\r
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\r
25  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\r
26  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r
27  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\r
28  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\r
29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r
30  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\r
31  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\r
32  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r
33  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r
34  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
35  *\r
36  * @category   HTTP\r
37  * @package    HTTP_Request2\r
38  * @author     Alexey Borzov <avb@php.net>\r
39  * @license    http://opensource.org/licenses/bsd-license.php New BSD License\r
40  * @version    CVS: $Id: Socket.php 279760 2009-05-03 10:46:42Z avb $\r
41  * @link       http://pear.php.net/package/HTTP_Request2\r
42  */\r
43 \r
44 /**\r
45  * Base class for HTTP_Request2 adapters\r
46  */\r
47 require_once 'HTTP/Request2/Adapter.php';\r
48 \r
49 /**\r
50  * Socket-based adapter for HTTP_Request2\r
51  *\r
52  * This adapter uses only PHP sockets and will work on almost any PHP\r
53  * environment. Code is based on original HTTP_Request PEAR package.\r
54  *\r
55  * @category    HTTP\r
56  * @package     HTTP_Request2\r
57  * @author      Alexey Borzov <avb@php.net>\r
58  * @version     Release: 0.4.1\r
59  */\r
60 class HTTP_Request2_Adapter_Socket extends HTTP_Request2_Adapter\r
61 {\r
62    /**\r
63     * Regular expression for 'token' rule from RFC 2616\r
64     */ \r
65     const REGEXP_TOKEN = '[^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+';\r
66 \r
67    /**\r
68     * Regular expression for 'quoted-string' rule from RFC 2616\r
69     */\r
70     const REGEXP_QUOTED_STRING = '"(?:\\\\.|[^\\\\"])*"';\r
71 \r
72    /**\r
73     * Connected sockets, needed for Keep-Alive support\r
74     * @var  array\r
75     * @see  connect()\r
76     */\r
77     protected static $sockets = array();\r
78 \r
79    /**\r
80     * Data for digest authentication scheme\r
81     *\r
82     * The keys for the array are URL prefixes. \r
83     *\r
84     * The values are associative arrays with data (realm, nonce, nonce-count, \r
85     * opaque...) needed for digest authentication. Stored here to prevent making \r
86     * duplicate requests to digest-protected resources after we have already \r
87     * received the challenge.\r
88     *\r
89     * @var  array\r
90     */\r
91     protected static $challenges = array();\r
92 \r
93    /**\r
94     * Connected socket\r
95     * @var  resource\r
96     * @see  connect()\r
97     */\r
98     protected $socket;\r
99 \r
100    /**\r
101     * Challenge used for server digest authentication\r
102     * @var  array\r
103     */\r
104     protected $serverChallenge;\r
105 \r
106    /**\r
107     * Challenge used for proxy digest authentication\r
108     * @var  array\r
109     */\r
110     protected $proxyChallenge;\r
111 \r
112    /**\r
113     * Global timeout, exception will be raised if request continues past this time\r
114     * @var  integer\r
115     */\r
116     protected $timeout = null;\r
117 \r
118    /**\r
119     * Remaining length of the current chunk, when reading chunked response\r
120     * @var  integer\r
121     * @see  readChunked()\r
122     */ \r
123     protected $chunkLength = 0;\r
124 \r
125    /**\r
126     * Sends request to the remote server and returns its response\r
127     *\r
128     * @param    HTTP_Request2\r
129     * @return   HTTP_Request2_Response\r
130     * @throws   HTTP_Request2_Exception\r
131     */\r
132     public function sendRequest(HTTP_Request2 $request)\r
133     {\r
134         $this->request = $request;\r
135         $keepAlive     = $this->connect();\r
136         $headers       = $this->prepareHeaders();\r
137 \r
138         // Use global request timeout if given, see feature requests #5735, #8964 \r
139         if ($timeout = $request->getConfig('timeout')) {\r
140             $this->timeout = time() + $timeout;\r
141         } else {\r
142             $this->timeout = null;\r
143         }\r
144 \r
145         try {\r
146             if (false === @fwrite($this->socket, $headers, strlen($headers))) {\r
147                 throw new HTTP_Request2_Exception('Error writing request');\r
148             }\r
149             // provide request headers to the observer, see request #7633\r
150             $this->request->setLastEvent('sentHeaders', $headers);\r
151             $this->writeBody();\r
152 \r
153             if ($this->timeout && time() > $this->timeout) {\r
154                 throw new HTTP_Request2_Exception(\r
155                     'Request timed out after ' . \r
156                     $request->getConfig('timeout') . ' second(s)'\r
157                 );\r
158             }\r
159 \r
160             $response = $this->readResponse();\r
161 \r
162             if (!$this->canKeepAlive($keepAlive, $response)) {\r
163                 $this->disconnect();\r
164             }\r
165 \r
166             if ($this->shouldUseProxyDigestAuth($response)) {\r
167                 return $this->sendRequest($request);\r
168             }\r
169             if ($this->shouldUseServerDigestAuth($response)) {\r
170                 return $this->sendRequest($request);\r
171             }\r
172             if ($authInfo = $response->getHeader('authentication-info')) {\r
173                 $this->updateChallenge($this->serverChallenge, $authInfo);\r
174             }\r
175             if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {\r
176                 $this->updateChallenge($this->proxyChallenge, $proxyInfo);\r
177             }\r
178 \r
179         } catch (Exception $e) {\r
180             $this->disconnect();\r
181             throw $e;\r
182         }\r
183 \r
184         return $response;\r
185     }\r
186 \r
187    /**\r
188     * Connects to the remote server\r
189     *\r
190     * @return   bool    whether the connection can be persistent\r
191     * @throws   HTTP_Request2_Exception\r
192     */\r
193     protected function connect()\r
194     {\r
195         $secure  = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');\r
196         $tunnel  = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();\r
197         $headers = $this->request->getHeaders();\r
198         $reqHost = $this->request->getUrl()->getHost();\r
199         if (!($reqPort = $this->request->getUrl()->getPort())) {\r
200             $reqPort = $secure? 443: 80;\r
201         }\r
202 \r
203         if ($host = $this->request->getConfig('proxy_host')) {\r
204             if (!($port = $this->request->getConfig('proxy_port'))) {\r
205                 throw new HTTP_Request2_Exception('Proxy port not provided');\r
206             }\r
207             $proxy = true;\r
208         } else {\r
209             $host  = $reqHost;\r
210             $port  = $reqPort;\r
211             $proxy = false;\r
212         }\r
213 \r
214         if ($tunnel && !$proxy) {\r
215             throw new HTTP_Request2_Exception(\r
216                 "Trying to perform CONNECT request without proxy"\r
217             );\r
218         }\r
219         if ($secure && !in_array('ssl', stream_get_transports())) {\r
220             throw new HTTP_Request2_Exception(\r
221                 'Need OpenSSL support for https:// requests'\r
222             );\r
223         }\r
224 \r
225         // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive\r
226         // connection token to a proxy server...\r
227         if ($proxy && !$secure && \r
228             !empty($headers['connection']) && 'Keep-Alive' == $headers['connection']\r
229         ) {\r
230             $this->request->setHeader('connection');\r
231         }\r
232 \r
233         $keepAlive = ('1.1' == $this->request->getConfig('protocol_version') && \r
234                       empty($headers['connection'])) ||\r
235                      (!empty($headers['connection']) &&\r
236                       'Keep-Alive' == $headers['connection']);\r
237         $host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;\r
238 \r
239         $options = array();\r
240         if ($secure || $tunnel) {\r
241             foreach ($this->request->getConfig() as $name => $value) {\r
242                 if ('ssl_' == substr($name, 0, 4) && null !== $value) {\r
243                     if ('ssl_verify_host' == $name) {\r
244                         if ($value) {\r
245                             $options['CN_match'] = $reqHost;\r
246                         }\r
247                     } else {\r
248                         $options[substr($name, 4)] = $value;\r
249                     }\r
250                 }\r
251             }\r
252             ksort($options);\r
253         }\r
254 \r
255         // Changing SSL context options after connection is established does *not*\r
256         // work, we need a new connection if options change\r
257         $remote    = $host . ':' . $port;\r
258         $socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .\r
259                      (empty($options)? '': ':' . serialize($options));\r
260         unset($this->socket);\r
261 \r
262         // We use persistent connections and have a connected socket?\r
263         // Ensure that the socket is still connected, see bug #16149\r
264         if ($keepAlive && !empty(self::$sockets[$socketKey]) &&\r
265             !feof(self::$sockets[$socketKey])\r
266         ) {\r
267             $this->socket =& self::$sockets[$socketKey];\r
268 \r
269         } elseif ($secure && $proxy && !$tunnel) {\r
270             $this->establishTunnel();\r
271             $this->request->setLastEvent(\r
272                 'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"\r
273             );\r
274             self::$sockets[$socketKey] =& $this->socket;\r
275 \r
276         } else {\r
277             // Set SSL context options if doing HTTPS request or creating a tunnel\r
278             $context = stream_context_create();\r
279             foreach ($options as $name => $value) {\r
280                 if (!stream_context_set_option($context, 'ssl', $name, $value)) {\r
281                     throw new HTTP_Request2_Exception(\r
282                         "Error setting SSL context option '{$name}'"\r
283                     );\r
284                 }\r
285             }\r
286             $this->socket = @stream_socket_client(\r
287                 $remote, $errno, $errstr,\r
288                 $this->request->getConfig('connect_timeout'),\r
289                 STREAM_CLIENT_CONNECT, $context\r
290             );\r
291             if (!$this->socket) {\r
292                 throw new HTTP_Request2_Exception(\r
293                     "Unable to connect to {$remote}. Error #{$errno}: {$errstr}"\r
294                 );\r
295             }\r
296             $this->request->setLastEvent('connect', $remote);\r
297             self::$sockets[$socketKey] =& $this->socket;\r
298         }\r
299         return $keepAlive;\r
300     }\r
301 \r
302    /**\r
303     * Establishes a tunnel to a secure remote server via HTTP CONNECT request\r
304     *\r
305     * This method will fail if 'ssl_verify_peer' is enabled. Probably because PHP\r
306     * sees that we are connected to a proxy server (duh!) rather than the server\r
307     * that presents its certificate.\r
308     *\r
309     * @link     http://tools.ietf.org/html/rfc2817#section-5.2\r
310     * @throws   HTTP_Request2_Exception\r
311     */\r
312     protected function establishTunnel()\r
313     {\r
314         $donor   = new self;\r
315         $connect = new HTTP_Request2(\r
316             $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,\r
317             array_merge($this->request->getConfig(),\r
318                         array('adapter' => $donor))\r
319         );\r
320         $response = $connect->send();\r
321         // Need any successful (2XX) response\r
322         if (200 > $response->getStatus() || 300 <= $response->getStatus()) {\r
323             throw new HTTP_Request2_Exception(\r
324                 'Failed to connect via HTTPS proxy. Proxy response: ' .\r
325                 $response->getStatus() . ' ' . $response->getReasonPhrase()\r
326             );\r
327         }\r
328         $this->socket = $donor->socket;\r
329 \r
330         $modes = array(\r
331             STREAM_CRYPTO_METHOD_TLS_CLIENT, \r
332             STREAM_CRYPTO_METHOD_SSLv3_CLIENT,\r
333             STREAM_CRYPTO_METHOD_SSLv23_CLIENT,\r
334             STREAM_CRYPTO_METHOD_SSLv2_CLIENT \r
335         );\r
336 \r
337         foreach ($modes as $mode) {\r
338             if (stream_socket_enable_crypto($this->socket, true, $mode)) {\r
339                 return;\r
340             }\r
341         }\r
342         throw new HTTP_Request2_Exception(\r
343             'Failed to enable secure connection when connecting through proxy'\r
344         );\r
345     }\r
346 \r
347    /**\r
348     * Checks whether current connection may be reused or should be closed\r
349     *\r
350     * @param    boolean                 whether connection could be persistent \r
351     *                                   in the first place\r
352     * @param    HTTP_Request2_Response  response object to check\r
353     * @return   boolean\r
354     */\r
355     protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)\r
356     {\r
357         // Do not close socket on successful CONNECT request\r
358         if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&\r
359             200 <= $response->getStatus() && 300 > $response->getStatus()\r
360         ) {\r
361             return true;\r
362         }\r
363 \r
364         $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding')) ||\r
365                        null !== $response->getHeader('content-length');\r
366         $persistent  = 'keep-alive' == strtolower($response->getHeader('connection')) ||\r
367                        (null === $response->getHeader('connection') &&\r
368                         '1.1' == $response->getVersion());\r
369         return $requestKeepAlive && $lengthKnown && $persistent;\r
370     }\r
371 \r
372    /**\r
373     * Disconnects from the remote server\r
374     */\r
375     protected function disconnect()\r
376     {\r
377         if (is_resource($this->socket)) {\r
378             fclose($this->socket);\r
379             $this->socket = null;\r
380             $this->request->setLastEvent('disconnect');\r
381         }\r
382     }\r
383 \r
384    /**\r
385     * Checks whether another request should be performed with server digest auth\r
386     *\r
387     * Several conditions should be satisfied for it to return true:\r
388     *   - response status should be 401\r
389     *   - auth credentials should be set in the request object\r
390     *   - response should contain WWW-Authenticate header with digest challenge\r
391     *   - there is either no challenge stored for this URL or new challenge\r
392     *     contains stale=true parameter (in other case we probably just failed \r
393     *     due to invalid username / password)\r
394     *\r
395     * The method stores challenge values in $challenges static property\r
396     *\r
397     * @param    HTTP_Request2_Response  response to check\r
398     * @return   boolean whether another request should be performed\r
399     * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters\r
400     */\r
401     protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)\r
402     {\r
403         // no sense repeating a request if we don't have credentials\r
404         if (401 != $response->getStatus() || !$this->request->getAuth()) {\r
405             return false;\r
406         }\r
407         if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {\r
408             return false;\r
409         }\r
410 \r
411         $url    = $this->request->getUrl();\r
412         $scheme = $url->getScheme();\r
413         $host   = $scheme . '://' . $url->getHost();\r
414         if ($port = $url->getPort()) {\r
415             if ((0 == strcasecmp($scheme, 'http') && 80 != $port) ||\r
416                 (0 == strcasecmp($scheme, 'https') && 443 != $port)\r
417             ) {\r
418                 $host .= ':' . $port;\r
419             }\r
420         }\r
421 \r
422         if (!empty($challenge['domain'])) {\r
423             $prefixes = array();\r
424             foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {\r
425                 // don't bother with different servers\r
426                 if ('/' == substr($prefix, 0, 1)) {\r
427                     $prefixes[] = $host . $prefix;\r
428                 }\r
429             }\r
430         }\r
431         if (empty($prefixes)) {\r
432             $prefixes = array($host . '/');\r
433         }\r
434 \r
435         $ret = true;\r
436         foreach ($prefixes as $prefix) {\r
437             if (!empty(self::$challenges[$prefix]) &&\r
438                 (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))\r
439             ) {\r
440                 // probably credentials are invalid\r
441                 $ret = false;\r
442             }\r
443             self::$challenges[$prefix] =& $challenge;\r
444         }\r
445         return $ret;\r
446     }\r
447 \r
448    /**\r
449     * Checks whether another request should be performed with proxy digest auth\r
450     *\r
451     * Several conditions should be satisfied for it to return true:\r
452     *   - response status should be 407\r
453     *   - proxy auth credentials should be set in the request object\r
454     *   - response should contain Proxy-Authenticate header with digest challenge\r
455     *   - there is either no challenge stored for this proxy or new challenge\r
456     *     contains stale=true parameter (in other case we probably just failed \r
457     *     due to invalid username / password)\r
458     *\r
459     * The method stores challenge values in $challenges static property\r
460     *\r
461     * @param    HTTP_Request2_Response  response to check\r
462     * @return   boolean whether another request should be performed\r
463     * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters\r
464     */\r
465     protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)\r
466     {\r
467         if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {\r
468             return false;\r
469         }\r
470         if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {\r
471             return false;\r
472         }\r
473 \r
474         $key = 'proxy://' . $this->request->getConfig('proxy_host') .\r
475                ':' . $this->request->getConfig('proxy_port');\r
476 \r
477         if (!empty(self::$challenges[$key]) &&\r
478             (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))\r
479         ) {\r
480             $ret = false;\r
481         } else {\r
482             $ret = true;\r
483         }\r
484         self::$challenges[$key] = $challenge;\r
485         return $ret;\r
486     }\r
487 \r
488    /**\r
489     * Extracts digest method challenge from (WWW|Proxy)-Authenticate header value\r
490     *\r
491     * There is a problem with implementation of RFC 2617: several of the parameters\r
492     * here are defined as quoted-string and thus may contain backslash escaped\r
493     * double quotes (RFC 2616, section 2.2). However, RFC 2617 defines unq(X) as\r
494     * just value of quoted-string X without surrounding quotes, it doesn't speak\r
495     * about removing backslash escaping.\r
496     *\r
497     * Now realm parameter is user-defined and human-readable, strange things\r
498     * happen when it contains quotes:\r
499     *   - Apache allows quotes in realm, but apparently uses realm value without\r
500     *     backslashes for digest computation\r
501     *   - Squid allows (manually escaped) quotes there, but it is impossible to\r
502     *     authorize with either escaped or unescaped quotes used in digest,\r
503     *     probably it can't parse the response (?)\r
504     *   - Both IE and Firefox display realm value with backslashes in \r
505     *     the password popup and apparently use the same value for digest\r
506     *\r
507     * HTTP_Request2 follows IE and Firefox (and hopefully RFC 2617) in\r
508     * quoted-string handling, unfortunately that means failure to authorize \r
509     * sometimes\r
510     *\r
511     * @param    string  value of WWW-Authenticate or Proxy-Authenticate header\r
512     * @return   mixed   associative array with challenge parameters, false if\r
513     *                   no challenge is present in header value\r
514     * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters\r
515     */\r
516     protected function parseDigestChallenge($headerValue)\r
517     {\r
518         $authParam   = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .\r
519                        self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';\r
520         $challenge   = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";\r
521         if (!preg_match($challenge, $headerValue, $matches)) {\r
522             return false;\r
523         }\r
524 \r
525         preg_match_all('!' . $authParam . '!', $matches[0], $params);\r
526         $paramsAry   = array();\r
527         $knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',\r
528                              'algorithm', 'qop');\r
529         for ($i = 0; $i < count($params[0]); $i++) {\r
530             // section 3.2.1: Any unrecognized directive MUST be ignored.\r
531             if (in_array($params[1][$i], $knownParams)) {\r
532                 if ('"' == substr($params[2][$i], 0, 1)) {\r
533                     $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);\r
534                 } else {\r
535                     $paramsAry[$params[1][$i]] = $params[2][$i];\r
536                 }\r
537             }\r
538         }\r
539         // we only support qop=auth\r
540         if (!empty($paramsAry['qop']) && \r
541             !in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))\r
542         ) {\r
543             throw new HTTP_Request2_Exception(\r
544                 "Only 'auth' qop is currently supported in digest authentication, " .\r
545                 "server requested '{$paramsAry['qop']}'"\r
546             );\r
547         }\r
548         // we only support algorithm=MD5\r
549         if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {\r
550             throw new HTTP_Request2_Exception(\r
551                 "Only 'MD5' algorithm is currently supported in digest authentication, " .\r
552                 "server requested '{$paramsAry['algorithm']}'"\r
553             );\r
554         }\r
555 \r
556         return $paramsAry; \r
557     }\r
558 \r
559    /**\r
560     * Parses [Proxy-]Authentication-Info header value and updates challenge\r
561     *\r
562     * @param    array   challenge to update\r
563     * @param    string  value of [Proxy-]Authentication-Info header\r
564     * @todo     validate server rspauth response\r
565     */ \r
566     protected function updateChallenge(&$challenge, $headerValue)\r
567     {\r
568         $authParam   = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .\r
569                        self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';\r
570         $paramsAry   = array();\r
571 \r
572         preg_match_all($authParam, $headerValue, $params);\r
573         for ($i = 0; $i < count($params[0]); $i++) {\r
574             if ('"' == substr($params[2][$i], 0, 1)) {\r
575                 $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);\r
576             } else {\r
577                 $paramsAry[$params[1][$i]] = $params[2][$i];\r
578             }\r
579         }\r
580         // for now, just update the nonce value\r
581         if (!empty($paramsAry['nextnonce'])) {\r
582             $challenge['nonce'] = $paramsAry['nextnonce'];\r
583             $challenge['nc']    = 1;\r
584         }\r
585     }\r
586 \r
587    /**\r
588     * Creates a value for [Proxy-]Authorization header when using digest authentication\r
589     *\r
590     * @param    string  user name\r
591     * @param    string  password\r
592     * @param    string  request URL\r
593     * @param    array   digest challenge parameters\r
594     * @return   string  value of [Proxy-]Authorization request header\r
595     * @link     http://tools.ietf.org/html/rfc2617#section-3.2.2\r
596     */ \r
597     protected function createDigestResponse($user, $password, $url, &$challenge)\r
598     {\r
599         if (false !== ($q = strpos($url, '?')) && \r
600             $this->request->getConfig('digest_compat_ie')\r
601         ) {\r
602             $url = substr($url, 0, $q);\r
603         }\r
604 \r
605         $a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);\r
606         $a2 = md5($this->request->getMethod() . ':' . $url);\r
607 \r
608         if (empty($challenge['qop'])) {\r
609             $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);\r
610         } else {\r
611             $challenge['cnonce'] = 'Req2.' . rand();\r
612             if (empty($challenge['nc'])) {\r
613                 $challenge['nc'] = 1;\r
614             }\r
615             $nc     = sprintf('%08x', $challenge['nc']++);\r
616             $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .\r
617                           $challenge['cnonce'] . ':auth:' . $a2);\r
618         }\r
619         return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .\r
620                'realm="' . $challenge['realm'] . '", ' .\r
621                'nonce="' . $challenge['nonce'] . '", ' .\r
622                'uri="' . $url . '", ' .\r
623                'response="' . $digest . '"' .\r
624                (!empty($challenge['opaque'])? \r
625                 ', opaque="' . $challenge['opaque'] . '"':\r
626                 '') .\r
627                (!empty($challenge['qop'])?\r
628                 ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':\r
629                 '');\r
630     }\r
631 \r
632    /**\r
633     * Adds 'Authorization' header (if needed) to request headers array\r
634     *\r
635     * @param    array   request headers\r
636     * @param    string  request host (needed for digest authentication)\r
637     * @param    string  request URL (needed for digest authentication)\r
638     * @throws   HTTP_Request2_Exception\r
639     */\r
640     protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)\r
641     {\r
642         if (!($auth = $this->request->getAuth())) {\r
643             return;\r
644         }\r
645         switch ($auth['scheme']) {\r
646             case HTTP_Request2::AUTH_BASIC:\r
647                 $headers['authorization'] = \r
648                     'Basic ' . base64_encode($auth['user'] . ':' . $auth['password']);\r
649                 break;\r
650 \r
651             case HTTP_Request2::AUTH_DIGEST:\r
652                 unset($this->serverChallenge);\r
653                 $fullUrl = ('/' == $requestUrl[0])?\r
654                            $this->request->getUrl()->getScheme() . '://' .\r
655                             $requestHost . $requestUrl:\r
656                            $requestUrl;\r
657                 foreach (array_keys(self::$challenges) as $key) {\r
658                     if ($key == substr($fullUrl, 0, strlen($key))) {\r
659                         $headers['authorization'] = $this->createDigestResponse(\r
660                             $auth['user'], $auth['password'], \r
661                             $requestUrl, self::$challenges[$key]\r
662                         );\r
663                         $this->serverChallenge =& self::$challenges[$key];\r
664                         break;\r
665                     }\r
666                 }\r
667                 break;\r
668 \r
669             default:\r
670                 throw new HTTP_Request2_Exception(\r
671                     "Unknown HTTP authentication scheme '{$auth['scheme']}'"\r
672                 );\r
673         }\r
674     }\r
675 \r
676    /**\r
677     * Adds 'Proxy-Authorization' header (if needed) to request headers array\r
678     *\r
679     * @param    array   request headers\r
680     * @param    string  request URL (needed for digest authentication)\r
681     * @throws   HTTP_Request2_Exception\r
682     */\r
683     protected function addProxyAuthorizationHeader(&$headers, $requestUrl)\r
684     {\r
685         if (!$this->request->getConfig('proxy_host') ||\r
686             !($user = $this->request->getConfig('proxy_user')) ||\r
687             (0 == strcasecmp('https', $this->request->getUrl()->getScheme()) &&\r
688              HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())\r
689         ) {\r
690             return;\r
691         }\r
692 \r
693         $password = $this->request->getConfig('proxy_password');\r
694         switch ($this->request->getConfig('proxy_auth_scheme')) {\r
695             case HTTP_Request2::AUTH_BASIC:\r
696                 $headers['proxy-authorization'] =\r
697                     'Basic ' . base64_encode($user . ':' . $password);\r
698                 break;\r
699 \r
700             case HTTP_Request2::AUTH_DIGEST:\r
701                 unset($this->proxyChallenge);\r
702                 $proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .\r
703                             ':' . $this->request->getConfig('proxy_port');\r
704                 if (!empty(self::$challenges[$proxyUrl])) {\r
705                     $headers['proxy-authorization'] = $this->createDigestResponse(\r
706                         $user, $password,\r
707                         $requestUrl, self::$challenges[$proxyUrl]\r
708                     );\r
709                     $this->proxyChallenge =& self::$challenges[$proxyUrl];\r
710                 }\r
711                 break;\r
712 \r
713             default:\r
714                 throw new HTTP_Request2_Exception(\r
715                     "Unknown HTTP authentication scheme '" .\r
716                     $this->request->getConfig('proxy_auth_scheme') . "'"\r
717                 );\r
718         }\r
719     }\r
720 \r
721 \r
722    /**\r
723     * Creates the string with the Request-Line and request headers\r
724     *\r
725     * @return   string\r
726     * @throws   HTTP_Request2_Exception\r
727     */\r
728     protected function prepareHeaders()\r
729     {\r
730         $headers = $this->request->getHeaders();\r
731         $url     = $this->request->getUrl();\r
732         $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();\r
733         $host    = $url->getHost();\r
734 \r
735         $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;\r
736         if (($port = $url->getPort()) && $port != $defaultPort || $connect) {\r
737             $host .= ':' . (empty($port)? $defaultPort: $port);\r
738         }\r
739         // Do not overwrite explicitly set 'Host' header, see bug #16146\r
740         if (!isset($headers['host'])) {\r
741             $headers['host'] = $host;\r
742         }\r
743 \r
744         if ($connect) {\r
745             $requestUrl = $host;\r
746 \r
747         } else {\r
748             if (!$this->request->getConfig('proxy_host') ||\r
749                 0 == strcasecmp($url->getScheme(), 'https')\r
750             ) {\r
751                 $requestUrl = '';\r
752             } else {\r
753                 $requestUrl = $url->getScheme() . '://' . $host;\r
754             }\r
755             $path        = $url->getPath();\r
756             $query       = $url->getQuery();\r
757             $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);\r
758         }\r
759 \r
760         if ('1.1' == $this->request->getConfig('protocol_version') &&\r
761             extension_loaded('zlib') && !isset($headers['accept-encoding'])\r
762         ) {\r
763             $headers['accept-encoding'] = 'gzip, deflate';\r
764         }\r
765 \r
766         $this->addAuthorizationHeader($headers, $host, $requestUrl);\r
767         $this->addProxyAuthorizationHeader($headers, $requestUrl);\r
768         $this->calculateRequestLength($headers);\r
769 \r
770         $headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .\r
771                       $this->request->getConfig('protocol_version') . "\r\n";\r
772         foreach ($headers as $name => $value) {\r
773             $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));\r
774             $headersStr   .= $canonicalName . ': ' . $value . "\r\n";\r
775         }\r
776         return $headersStr . "\r\n";\r
777     }\r
778 \r
779    /**\r
780     * Sends the request body\r
781     *\r
782     * @throws   HTTP_Request2_Exception\r
783     */\r
784     protected function writeBody()\r
785     {\r
786         if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||\r
787             0 == $this->contentLength\r
788         ) {\r
789             return;\r
790         }\r
791 \r
792         $position   = 0;\r
793         $bufferSize = $this->request->getConfig('buffer_size');\r
794         while ($position < $this->contentLength) {\r
795             if (is_string($this->requestBody)) {\r
796                 $str = substr($this->requestBody, $position, $bufferSize);\r
797             } elseif (is_resource($this->requestBody)) {\r
798                 $str = fread($this->requestBody, $bufferSize);\r
799             } else {\r
800                 $str = $this->requestBody->read($bufferSize);\r
801             }\r
802             if (false === @fwrite($this->socket, $str, strlen($str))) {\r
803                 throw new HTTP_Request2_Exception('Error writing request');\r
804             }\r
805             // Provide the length of written string to the observer, request #7630\r
806             $this->request->setLastEvent('sentBodyPart', strlen($str));\r
807             $position += strlen($str); \r
808         }\r
809     }\r
810 \r
811    /**\r
812     * Reads the remote server's response\r
813     *\r
814     * @return   HTTP_Request2_Response\r
815     * @throws   HTTP_Request2_Exception\r
816     */\r
817     protected function readResponse()\r
818     {\r
819         $bufferSize = $this->request->getConfig('buffer_size');\r
820 \r
821         do {\r
822             $response = new HTTP_Request2_Response($this->readLine($bufferSize), true);\r
823             do {\r
824                 $headerLine = $this->readLine($bufferSize);\r
825                 $response->parseHeaderLine($headerLine);\r
826             } while ('' != $headerLine);\r
827         } while (in_array($response->getStatus(), array(100, 101)));\r
828 \r
829         $this->request->setLastEvent('receivedHeaders', $response);\r
830 \r
831         // No body possible in such responses\r
832         if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() ||\r
833             (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&\r
834              200 <= $response->getStatus() && 300 > $response->getStatus()) ||\r
835             in_array($response->getStatus(), array(204, 304))\r
836         ) {\r
837             return $response;\r
838         }\r
839 \r
840         $chunked = 'chunked' == $response->getHeader('transfer-encoding');\r
841         $length  = $response->getHeader('content-length');\r
842         $hasBody = false;\r
843         if ($chunked || null === $length || 0 < intval($length)) {\r
844             // RFC 2616, section 4.4:\r
845             // 3. ... If a message is received with both a\r
846             // Transfer-Encoding header field and a Content-Length header field,\r
847             // the latter MUST be ignored.\r
848             $toRead = ($chunked || null === $length)? null: $length;\r
849             $this->chunkLength = 0;\r
850 \r
851             while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {\r
852                 if ($chunked) {\r
853                     $data = $this->readChunked($bufferSize);\r
854                 } elseif (is_null($toRead)) {\r
855                     $data = $this->fread($bufferSize);\r
856                 } else {\r
857                     $data    = $this->fread(min($toRead, $bufferSize));\r
858                     $toRead -= strlen($data);\r
859                 }\r
860                 if ('' == $data && (!$this->chunkLength || feof($this->socket))) {\r
861                     break;\r
862                 }\r
863 \r
864                 $hasBody = true;\r
865                 if ($this->request->getConfig('store_body')) {\r
866                     $response->appendBody($data);\r
867                 }\r
868                 if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {\r
869                     $this->request->setLastEvent('receivedEncodedBodyPart', $data);\r
870                 } else {\r
871                     $this->request->setLastEvent('receivedBodyPart', $data);\r
872                 }\r
873             }\r
874         }\r
875 \r
876         if ($hasBody) {\r
877             $this->request->setLastEvent('receivedBody', $response);\r
878         }\r
879         return $response;\r
880     }\r
881 \r
882    /**\r
883     * Reads until either the end of the socket or a newline, whichever comes first \r
884     *\r
885     * Strips the trailing newline from the returned data, handles global \r
886     * request timeout. Method idea borrowed from Net_Socket PEAR package. \r
887     *\r
888     * @param    int     buffer size to use for reading\r
889     * @return   Available data up to the newline (not including newline)\r
890     * @throws   HTTP_Request2_Exception     In case of timeout\r
891     */\r
892     protected function readLine($bufferSize)\r
893     {\r
894         $line = '';\r
895         while (!feof($this->socket)) {\r
896             if ($this->timeout) {\r
897                 stream_set_timeout($this->socket, max($this->timeout - time(), 1));\r
898             }\r
899             $line .= @fgets($this->socket, $bufferSize);\r
900             $info  = stream_get_meta_data($this->socket);\r
901             if ($info['timed_out'] || $this->timeout && time() > $this->timeout) {\r
902                 throw new HTTP_Request2_Exception(\r
903                     'Request timed out after ' . \r
904                     $this->request->getConfig('timeout') . ' second(s)'\r
905                 );\r
906             }\r
907             if (substr($line, -1) == "\n") {\r
908                 return rtrim($line, "\r\n");\r
909             }\r
910         }\r
911         return $line;\r
912     }\r
913 \r
914    /**\r
915     * Wrapper around fread(), handles global request timeout\r
916     *\r
917     * @param    int     Reads up to this number of bytes\r
918     * @return   Data read from socket\r
919     * @throws   HTTP_Request2_Exception     In case of timeout\r
920     */\r
921     protected function fread($length)\r
922     {\r
923         if ($this->timeout) {\r
924             stream_set_timeout($this->socket, max($this->timeout - time(), 1));\r
925         }\r
926         $data = fread($this->socket, $length);\r
927         $info = stream_get_meta_data($this->socket);\r
928         if ($info['timed_out'] || $this->timeout && time() > $this->timeout) {\r
929             throw new HTTP_Request2_Exception(\r
930                 'Request timed out after ' . \r
931                 $this->request->getConfig('timeout') . ' second(s)'\r
932             );\r
933         }\r
934         return $data;\r
935     }\r
936 \r
937    /**\r
938     * Reads a part of response body encoded with chunked Transfer-Encoding\r
939     *\r
940     * @param    int     buffer size to use for reading\r
941     * @return   string\r
942     * @throws   HTTP_Request2_Exception\r
943     */\r
944     protected function readChunked($bufferSize)\r
945     {\r
946         // at start of the next chunk?\r
947         if (0 == $this->chunkLength) {\r
948             $line = $this->readLine($bufferSize);\r
949             if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {\r
950                 throw new HTTP_Request2_Exception(\r
951                     "Cannot decode chunked response, invalid chunk length '{$line}'"\r
952                 );\r
953             } else {\r
954                 $this->chunkLength = hexdec($matches[1]);\r
955                 // Chunk with zero length indicates the end\r
956                 if (0 == $this->chunkLength) {\r
957                     $this->readLine($bufferSize);\r
958                     return '';\r
959                 }\r
960             }\r
961         }\r
962         $data = $this->fread(min($this->chunkLength, $bufferSize));\r
963         $this->chunkLength -= strlen($data);\r
964         if (0 == $this->chunkLength) {\r
965             $this->readLine($bufferSize); // Trailing CRLF\r
966         }\r
967         return $data;\r
968     }\r
969 }\r
970 \r
971 ?>