]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/HTTP/Request2/Adapter/Socket.php
05cc4c715bb6b8f83adc502694d49dd3ae5337ef
[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-2011, 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    SVN: $Id: Socket.php 309921 2011-04-03 16:43:02Z 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: 2.0.0RC1\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     * Sum of start time and global timeout, exception will be thrown if request continues past this time\r
114     * @var  integer\r
115     */\r
116     protected $deadline = 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     * Remaining amount of redirections to follow\r
127     *\r
128     * Starts at 'max_redirects' configuration parameter and is reduced on each\r
129     * subsequent redirect. An Exception will be thrown once it reaches zero.\r
130     *\r
131     * @var  integer\r
132     */\r
133     protected $redirectCountdown = null;\r
134 \r
135    /**\r
136     * Sends request to the remote server and returns its response\r
137     *\r
138     * @param    HTTP_Request2\r
139     * @return   HTTP_Request2_Response\r
140     * @throws   HTTP_Request2_Exception\r
141     */\r
142     public function sendRequest(HTTP_Request2 $request)\r
143     {\r
144         $this->request = $request;\r
145 \r
146         // Use global request timeout if given, see feature requests #5735, #8964\r
147         if ($timeout = $request->getConfig('timeout')) {\r
148             $this->deadline = time() + $timeout;\r
149         } else {\r
150             $this->deadline = null;\r
151         }\r
152 \r
153         try {\r
154             $keepAlive = $this->connect();\r
155             $headers   = $this->prepareHeaders();\r
156             if (false === @fwrite($this->socket, $headers, strlen($headers))) {\r
157                 throw new HTTP_Request2_MessageException('Error writing request');\r
158             }\r
159             // provide request headers to the observer, see request #7633\r
160             $this->request->setLastEvent('sentHeaders', $headers);\r
161             $this->writeBody();\r
162 \r
163             if ($this->deadline && time() > $this->deadline) {\r
164                 throw new HTTP_Request2_MessageException(\r
165                     'Request timed out after ' .\r
166                     $request->getConfig('timeout') . ' second(s)',\r
167                     HTTP_Request2_Exception::TIMEOUT\r
168                 );\r
169             }\r
170 \r
171             $response = $this->readResponse();\r
172 \r
173             if ($jar = $request->getCookieJar()) {\r
174                 $jar->addCookiesFromResponse($response, $request->getUrl());\r
175             }\r
176 \r
177             if (!$this->canKeepAlive($keepAlive, $response)) {\r
178                 $this->disconnect();\r
179             }\r
180 \r
181             if ($this->shouldUseProxyDigestAuth($response)) {\r
182                 return $this->sendRequest($request);\r
183             }\r
184             if ($this->shouldUseServerDigestAuth($response)) {\r
185                 return $this->sendRequest($request);\r
186             }\r
187             if ($authInfo = $response->getHeader('authentication-info')) {\r
188                 $this->updateChallenge($this->serverChallenge, $authInfo);\r
189             }\r
190             if ($proxyInfo = $response->getHeader('proxy-authentication-info')) {\r
191                 $this->updateChallenge($this->proxyChallenge, $proxyInfo);\r
192             }\r
193 \r
194         } catch (Exception $e) {\r
195             $this->disconnect();\r
196         }\r
197 \r
198         unset($this->request, $this->requestBody);\r
199 \r
200         if (!empty($e)) {\r
201             $this->redirectCountdown = null;\r
202             throw $e;\r
203         }\r
204 \r
205         if (!$request->getConfig('follow_redirects') || !$response->isRedirect()) {\r
206             $this->redirectCountdown = null;\r
207             return $response;\r
208         } else {\r
209             return $this->handleRedirect($request, $response);\r
210         }\r
211     }\r
212 \r
213    /**\r
214     * Connects to the remote server\r
215     *\r
216     * @return   bool    whether the connection can be persistent\r
217     * @throws   HTTP_Request2_Exception\r
218     */\r
219     protected function connect()\r
220     {\r
221         $secure  = 0 == strcasecmp($this->request->getUrl()->getScheme(), 'https');\r
222         $tunnel  = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();\r
223         $headers = $this->request->getHeaders();\r
224         $reqHost = $this->request->getUrl()->getHost();\r
225         if (!($reqPort = $this->request->getUrl()->getPort())) {\r
226             $reqPort = $secure? 443: 80;\r
227         }\r
228 \r
229         if ($host = $this->request->getConfig('proxy_host')) {\r
230             if (!($port = $this->request->getConfig('proxy_port'))) {\r
231                 throw new HTTP_Request2_LogicException(\r
232                     'Proxy port not provided',\r
233                     HTTP_Request2_Exception::MISSING_VALUE\r
234                 );\r
235             }\r
236             $proxy = true;\r
237         } else {\r
238             $host  = $reqHost;\r
239             $port  = $reqPort;\r
240             $proxy = false;\r
241         }\r
242 \r
243         if ($tunnel && !$proxy) {\r
244             throw new HTTP_Request2_LogicException(\r
245                 "Trying to perform CONNECT request without proxy",\r
246                 HTTP_Request2_Exception::MISSING_VALUE\r
247             );\r
248         }\r
249         if ($secure && !in_array('ssl', stream_get_transports())) {\r
250             throw new HTTP_Request2_LogicException(\r
251                 'Need OpenSSL support for https:// requests',\r
252                 HTTP_Request2_Exception::MISCONFIGURATION\r
253             );\r
254         }\r
255 \r
256         // RFC 2068, section 19.7.1: A client MUST NOT send the Keep-Alive\r
257         // connection token to a proxy server...\r
258         if ($proxy && !$secure &&\r
259             !empty($headers['connection']) && 'Keep-Alive' == $headers['connection']\r
260         ) {\r
261             $this->request->setHeader('connection');\r
262         }\r
263 \r
264         $keepAlive = ('1.1' == $this->request->getConfig('protocol_version') &&\r
265                       empty($headers['connection'])) ||\r
266                      (!empty($headers['connection']) &&\r
267                       'Keep-Alive' == $headers['connection']);\r
268         $host = ((!$secure || $proxy)? 'tcp://': 'ssl://') . $host;\r
269 \r
270         $options = array();\r
271         if ($secure || $tunnel) {\r
272             foreach ($this->request->getConfig() as $name => $value) {\r
273                 if ('ssl_' == substr($name, 0, 4) && null !== $value) {\r
274                     if ('ssl_verify_host' == $name) {\r
275                         if ($value) {\r
276                             $options['CN_match'] = $reqHost;\r
277                         }\r
278                     } else {\r
279                         $options[substr($name, 4)] = $value;\r
280                     }\r
281                 }\r
282             }\r
283             ksort($options);\r
284         }\r
285 \r
286         // Changing SSL context options after connection is established does *not*\r
287         // work, we need a new connection if options change\r
288         $remote    = $host . ':' . $port;\r
289         $socketKey = $remote . (($secure && $proxy)? "->{$reqHost}:{$reqPort}": '') .\r
290                      (empty($options)? '': ':' . serialize($options));\r
291         unset($this->socket);\r
292 \r
293         // We use persistent connections and have a connected socket?\r
294         // Ensure that the socket is still connected, see bug #16149\r
295         if ($keepAlive && !empty(self::$sockets[$socketKey]) &&\r
296             !feof(self::$sockets[$socketKey])\r
297         ) {\r
298             $this->socket =& self::$sockets[$socketKey];\r
299 \r
300         } elseif ($secure && $proxy && !$tunnel) {\r
301             $this->establishTunnel();\r
302             $this->request->setLastEvent(\r
303                 'connect', "ssl://{$reqHost}:{$reqPort} via {$host}:{$port}"\r
304             );\r
305             self::$sockets[$socketKey] =& $this->socket;\r
306 \r
307         } else {\r
308             // Set SSL context options if doing HTTPS request or creating a tunnel\r
309             $context = stream_context_create();\r
310             foreach ($options as $name => $value) {\r
311                 if (!stream_context_set_option($context, 'ssl', $name, $value)) {\r
312                     throw new HTTP_Request2_LogicException(\r
313                         "Error setting SSL context option '{$name}'"\r
314                     );\r
315                 }\r
316             }\r
317             $track = @ini_set('track_errors', 1);\r
318             $this->socket = @stream_socket_client(\r
319                 $remote, $errno, $errstr,\r
320                 $this->request->getConfig('connect_timeout'),\r
321                 STREAM_CLIENT_CONNECT, $context\r
322             );\r
323             if (!$this->socket) {\r
324                 $e = new HTTP_Request2_ConnectionException(\r
325                     "Unable to connect to {$remote}. Error: "\r
326                      . (empty($errstr)? $php_errormsg: $errstr), 0, $errno\r
327                 );\r
328             }\r
329             @ini_set('track_errors', $track);\r
330             if (isset($e)) {\r
331                 throw $e;\r
332             }\r
333             $this->request->setLastEvent('connect', $remote);\r
334             self::$sockets[$socketKey] =& $this->socket;\r
335         }\r
336         return $keepAlive;\r
337     }\r
338 \r
339    /**\r
340     * Establishes a tunnel to a secure remote server via HTTP CONNECT request\r
341     *\r
342     * This method will fail if 'ssl_verify_peer' is enabled. Probably because PHP\r
343     * sees that we are connected to a proxy server (duh!) rather than the server\r
344     * that presents its certificate.\r
345     *\r
346     * @link     http://tools.ietf.org/html/rfc2817#section-5.2\r
347     * @throws   HTTP_Request2_Exception\r
348     */\r
349     protected function establishTunnel()\r
350     {\r
351         $donor   = new self;\r
352         $connect = new HTTP_Request2(\r
353             $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,\r
354             array_merge($this->request->getConfig(),\r
355                         array('adapter' => $donor))\r
356         );\r
357         $response = $connect->send();\r
358         // Need any successful (2XX) response\r
359         if (200 > $response->getStatus() || 300 <= $response->getStatus()) {\r
360             throw new HTTP_Request2_ConnectionException(\r
361                 'Failed to connect via HTTPS proxy. Proxy response: ' .\r
362                 $response->getStatus() . ' ' . $response->getReasonPhrase()\r
363             );\r
364         }\r
365         $this->socket = $donor->socket;\r
366 \r
367         $modes = array(\r
368             STREAM_CRYPTO_METHOD_TLS_CLIENT,\r
369             STREAM_CRYPTO_METHOD_SSLv3_CLIENT,\r
370             STREAM_CRYPTO_METHOD_SSLv23_CLIENT,\r
371             STREAM_CRYPTO_METHOD_SSLv2_CLIENT\r
372         );\r
373 \r
374         foreach ($modes as $mode) {\r
375             if (stream_socket_enable_crypto($this->socket, true, $mode)) {\r
376                 return;\r
377             }\r
378         }\r
379         throw new HTTP_Request2_ConnectionException(\r
380             'Failed to enable secure connection when connecting through proxy'\r
381         );\r
382     }\r
383 \r
384    /**\r
385     * Checks whether current connection may be reused or should be closed\r
386     *\r
387     * @param    boolean                 whether connection could be persistent\r
388     *                                   in the first place\r
389     * @param    HTTP_Request2_Response  response object to check\r
390     * @return   boolean\r
391     */\r
392     protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)\r
393     {\r
394         // Do not close socket on successful CONNECT request\r
395         if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&\r
396             200 <= $response->getStatus() && 300 > $response->getStatus()\r
397         ) {\r
398             return true;\r
399         }\r
400 \r
401         $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding'))\r
402                        || null !== $response->getHeader('content-length')\r
403                        // no body possible for such responses, see also request #17031\r
404                        || HTTP_Request2::METHOD_HEAD == $this->request->getMethod()\r
405                        || in_array($response->getStatus(), array(204, 304));\r
406         $persistent  = 'keep-alive' == strtolower($response->getHeader('connection')) ||\r
407                        (null === $response->getHeader('connection') &&\r
408                         '1.1' == $response->getVersion());\r
409         return $requestKeepAlive && $lengthKnown && $persistent;\r
410     }\r
411 \r
412    /**\r
413     * Disconnects from the remote server\r
414     */\r
415     protected function disconnect()\r
416     {\r
417         if (is_resource($this->socket)) {\r
418             fclose($this->socket);\r
419             $this->socket = null;\r
420             $this->request->setLastEvent('disconnect');\r
421         }\r
422     }\r
423 \r
424    /**\r
425     * Handles HTTP redirection\r
426     *\r
427     * This method will throw an Exception if redirect to a non-HTTP(S) location\r
428     * is attempted, also if number of redirects performed already is equal to\r
429     * 'max_redirects' configuration parameter.\r
430     *\r
431     * @param    HTTP_Request2               Original request\r
432     * @param    HTTP_Request2_Response      Response containing redirect\r
433     * @return   HTTP_Request2_Response      Response from a new location\r
434     * @throws   HTTP_Request2_Exception\r
435     */\r
436     protected function handleRedirect(HTTP_Request2 $request,\r
437                                       HTTP_Request2_Response $response)\r
438     {\r
439         if (is_null($this->redirectCountdown)) {\r
440             $this->redirectCountdown = $request->getConfig('max_redirects');\r
441         }\r
442         if (0 == $this->redirectCountdown) {\r
443             $this->redirectCountdown = null;\r
444             // Copying cURL behaviour\r
445             throw new HTTP_Request2_MessageException (\r
446                 'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed',\r
447                 HTTP_Request2_Exception::TOO_MANY_REDIRECTS\r
448             );\r
449         }\r
450         $redirectUrl = new Net_URL2(\r
451             $response->getHeader('location'),\r
452             array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))\r
453         );\r
454         // refuse non-HTTP redirect\r
455         if ($redirectUrl->isAbsolute()\r
456             && !in_array($redirectUrl->getScheme(), array('http', 'https'))\r
457         ) {\r
458             $this->redirectCountdown = null;\r
459             throw new HTTP_Request2_MessageException(\r
460                 'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString(),\r
461                 HTTP_Request2_Exception::NON_HTTP_REDIRECT\r
462             );\r
463         }\r
464         // Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),\r
465         // but in practice it is often not\r
466         if (!$redirectUrl->isAbsolute()) {\r
467             $redirectUrl = $request->getUrl()->resolve($redirectUrl);\r
468         }\r
469         $redirect = clone $request;\r
470         $redirect->setUrl($redirectUrl);\r
471         if (303 == $response->getStatus() || (!$request->getConfig('strict_redirects')\r
472              && in_array($response->getStatus(), array(301, 302)))\r
473         ) {\r
474             $redirect->setMethod(HTTP_Request2::METHOD_GET);\r
475             $redirect->setBody('');\r
476         }\r
477 \r
478         if (0 < $this->redirectCountdown) {\r
479             $this->redirectCountdown--;\r
480         }\r
481         return $this->sendRequest($redirect);\r
482     }\r
483 \r
484    /**\r
485     * Checks whether another request should be performed with server digest auth\r
486     *\r
487     * Several conditions should be satisfied for it to return true:\r
488     *   - response status should be 401\r
489     *   - auth credentials should be set in the request object\r
490     *   - response should contain WWW-Authenticate header with digest challenge\r
491     *   - there is either no challenge stored for this URL or new challenge\r
492     *     contains stale=true parameter (in other case we probably just failed\r
493     *     due to invalid username / password)\r
494     *\r
495     * The method stores challenge values in $challenges static property\r
496     *\r
497     * @param    HTTP_Request2_Response  response to check\r
498     * @return   boolean whether another request should be performed\r
499     * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters\r
500     */\r
501     protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)\r
502     {\r
503         // no sense repeating a request if we don't have credentials\r
504         if (401 != $response->getStatus() || !$this->request->getAuth()) {\r
505             return false;\r
506         }\r
507         if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {\r
508             return false;\r
509         }\r
510 \r
511         $url    = $this->request->getUrl();\r
512         $scheme = $url->getScheme();\r
513         $host   = $scheme . '://' . $url->getHost();\r
514         if ($port = $url->getPort()) {\r
515             if ((0 == strcasecmp($scheme, 'http') && 80 != $port) ||\r
516                 (0 == strcasecmp($scheme, 'https') && 443 != $port)\r
517             ) {\r
518                 $host .= ':' . $port;\r
519             }\r
520         }\r
521 \r
522         if (!empty($challenge['domain'])) {\r
523             $prefixes = array();\r
524             foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {\r
525                 // don't bother with different servers\r
526                 if ('/' == substr($prefix, 0, 1)) {\r
527                     $prefixes[] = $host . $prefix;\r
528                 }\r
529             }\r
530         }\r
531         if (empty($prefixes)) {\r
532             $prefixes = array($host . '/');\r
533         }\r
534 \r
535         $ret = true;\r
536         foreach ($prefixes as $prefix) {\r
537             if (!empty(self::$challenges[$prefix]) &&\r
538                 (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))\r
539             ) {\r
540                 // probably credentials are invalid\r
541                 $ret = false;\r
542             }\r
543             self::$challenges[$prefix] =& $challenge;\r
544         }\r
545         return $ret;\r
546     }\r
547 \r
548    /**\r
549     * Checks whether another request should be performed with proxy digest auth\r
550     *\r
551     * Several conditions should be satisfied for it to return true:\r
552     *   - response status should be 407\r
553     *   - proxy auth credentials should be set in the request object\r
554     *   - response should contain Proxy-Authenticate header with digest challenge\r
555     *   - there is either no challenge stored for this proxy or new challenge\r
556     *     contains stale=true parameter (in other case we probably just failed\r
557     *     due to invalid username / password)\r
558     *\r
559     * The method stores challenge values in $challenges static property\r
560     *\r
561     * @param    HTTP_Request2_Response  response to check\r
562     * @return   boolean whether another request should be performed\r
563     * @throws   HTTP_Request2_Exception in case of unsupported challenge parameters\r
564     */\r
565     protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)\r
566     {\r
567         if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {\r
568             return false;\r
569         }\r
570         if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {\r
571             return false;\r
572         }\r
573 \r
574         $key = 'proxy://' . $this->request->getConfig('proxy_host') .\r
575                ':' . $this->request->getConfig('proxy_port');\r
576 \r
577         if (!empty(self::$challenges[$key]) &&\r
578             (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))\r
579         ) {\r
580             $ret = false;\r
581         } else {\r
582             $ret = true;\r
583         }\r
584         self::$challenges[$key] = $challenge;\r
585         return $ret;\r
586     }\r
587 \r
588    /**\r
589     * Extracts digest method challenge from (WWW|Proxy)-Authenticate header value\r
590     *\r
591     * There is a problem with implementation of RFC 2617: several of the parameters\r
592     * are defined as quoted-string there and thus may contain backslash escaped\r
593     * double quotes (RFC 2616, section 2.2). However, RFC 2617 defines unq(X) as\r
594     * just value of quoted-string X without surrounding quotes, it doesn't speak\r
595     * about removing backslash escaping.\r
596     *\r
597     * Now realm parameter is user-defined and human-readable, strange things\r
598     * happen when it contains quotes:\r
599     *   - Apache allows quotes in realm, but apparently uses realm value without\r
600     *     backslashes for digest computation\r
601     *   - Squid allows (manually escaped) quotes there, but it is impossible to\r
602     *     authorize with either escaped or unescaped quotes used in digest,\r
603     *     probably it can't parse the response (?)\r
604     *   - Both IE and Firefox display realm value with backslashes in\r
605     *     the password popup and apparently use the same value for digest\r
606     *\r
607     * HTTP_Request2 follows IE and Firefox (and hopefully RFC 2617) in\r
608     * quoted-string handling, unfortunately that means failure to authorize\r
609     * sometimes\r
610     *\r
611     * @param    string  value of WWW-Authenticate or Proxy-Authenticate header\r
612     * @return   mixed   associative array with challenge parameters, false if\r
613     *                   no challenge is present in header value\r
614     * @throws   HTTP_Request2_NotImplementedException in case of unsupported challenge parameters\r
615     */\r
616     protected function parseDigestChallenge($headerValue)\r
617     {\r
618         $authParam   = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .\r
619                        self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';\r
620         $challenge   = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";\r
621         if (!preg_match($challenge, $headerValue, $matches)) {\r
622             return false;\r
623         }\r
624 \r
625         preg_match_all('!' . $authParam . '!', $matches[0], $params);\r
626         $paramsAry   = array();\r
627         $knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',\r
628                              'algorithm', 'qop');\r
629         for ($i = 0; $i < count($params[0]); $i++) {\r
630             // section 3.2.1: Any unrecognized directive MUST be ignored.\r
631             if (in_array($params[1][$i], $knownParams)) {\r
632                 if ('"' == substr($params[2][$i], 0, 1)) {\r
633                     $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);\r
634                 } else {\r
635                     $paramsAry[$params[1][$i]] = $params[2][$i];\r
636                 }\r
637             }\r
638         }\r
639         // we only support qop=auth\r
640         if (!empty($paramsAry['qop']) &&\r
641             !in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))\r
642         ) {\r
643             throw new HTTP_Request2_NotImplementedException(\r
644                 "Only 'auth' qop is currently supported in digest authentication, " .\r
645                 "server requested '{$paramsAry['qop']}'"\r
646             );\r
647         }\r
648         // we only support algorithm=MD5\r
649         if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {\r
650             throw new HTTP_Request2_NotImplementedException(\r
651                 "Only 'MD5' algorithm is currently supported in digest authentication, " .\r
652                 "server requested '{$paramsAry['algorithm']}'"\r
653             );\r
654         }\r
655 \r
656         return $paramsAry;\r
657     }\r
658 \r
659    /**\r
660     * Parses [Proxy-]Authentication-Info header value and updates challenge\r
661     *\r
662     * @param    array   challenge to update\r
663     * @param    string  value of [Proxy-]Authentication-Info header\r
664     * @todo     validate server rspauth response\r
665     */\r
666     protected function updateChallenge(&$challenge, $headerValue)\r
667     {\r
668         $authParam   = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .\r
669                        self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';\r
670         $paramsAry   = array();\r
671 \r
672         preg_match_all($authParam, $headerValue, $params);\r
673         for ($i = 0; $i < count($params[0]); $i++) {\r
674             if ('"' == substr($params[2][$i], 0, 1)) {\r
675                 $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);\r
676             } else {\r
677                 $paramsAry[$params[1][$i]] = $params[2][$i];\r
678             }\r
679         }\r
680         // for now, just update the nonce value\r
681         if (!empty($paramsAry['nextnonce'])) {\r
682             $challenge['nonce'] = $paramsAry['nextnonce'];\r
683             $challenge['nc']    = 1;\r
684         }\r
685     }\r
686 \r
687    /**\r
688     * Creates a value for [Proxy-]Authorization header when using digest authentication\r
689     *\r
690     * @param    string  user name\r
691     * @param    string  password\r
692     * @param    string  request URL\r
693     * @param    array   digest challenge parameters\r
694     * @return   string  value of [Proxy-]Authorization request header\r
695     * @link     http://tools.ietf.org/html/rfc2617#section-3.2.2\r
696     */\r
697     protected function createDigestResponse($user, $password, $url, &$challenge)\r
698     {\r
699         if (false !== ($q = strpos($url, '?')) &&\r
700             $this->request->getConfig('digest_compat_ie')\r
701         ) {\r
702             $url = substr($url, 0, $q);\r
703         }\r
704 \r
705         $a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);\r
706         $a2 = md5($this->request->getMethod() . ':' . $url);\r
707 \r
708         if (empty($challenge['qop'])) {\r
709             $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);\r
710         } else {\r
711             $challenge['cnonce'] = 'Req2.' . rand();\r
712             if (empty($challenge['nc'])) {\r
713                 $challenge['nc'] = 1;\r
714             }\r
715             $nc     = sprintf('%08x', $challenge['nc']++);\r
716             $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .\r
717                           $challenge['cnonce'] . ':auth:' . $a2);\r
718         }\r
719         return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .\r
720                'realm="' . $challenge['realm'] . '", ' .\r
721                'nonce="' . $challenge['nonce'] . '", ' .\r
722                'uri="' . $url . '", ' .\r
723                'response="' . $digest . '"' .\r
724                (!empty($challenge['opaque'])?\r
725                 ', opaque="' . $challenge['opaque'] . '"':\r
726                 '') .\r
727                (!empty($challenge['qop'])?\r
728                 ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':\r
729                 '');\r
730     }\r
731 \r
732    /**\r
733     * Adds 'Authorization' header (if needed) to request headers array\r
734     *\r
735     * @param    array   request headers\r
736     * @param    string  request host (needed for digest authentication)\r
737     * @param    string  request URL (needed for digest authentication)\r
738     * @throws   HTTP_Request2_NotImplementedException\r
739     */\r
740     protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)\r
741     {\r
742         if (!($auth = $this->request->getAuth())) {\r
743             return;\r
744         }\r
745         switch ($auth['scheme']) {\r
746             case HTTP_Request2::AUTH_BASIC:\r
747                 $headers['authorization'] =\r
748                     'Basic ' . base64_encode($auth['user'] . ':' . $auth['password']);\r
749                 break;\r
750 \r
751             case HTTP_Request2::AUTH_DIGEST:\r
752                 unset($this->serverChallenge);\r
753                 $fullUrl = ('/' == $requestUrl[0])?\r
754                            $this->request->getUrl()->getScheme() . '://' .\r
755                             $requestHost . $requestUrl:\r
756                            $requestUrl;\r
757                 foreach (array_keys(self::$challenges) as $key) {\r
758                     if ($key == substr($fullUrl, 0, strlen($key))) {\r
759                         $headers['authorization'] = $this->createDigestResponse(\r
760                             $auth['user'], $auth['password'],\r
761                             $requestUrl, self::$challenges[$key]\r
762                         );\r
763                         $this->serverChallenge =& self::$challenges[$key];\r
764                         break;\r
765                     }\r
766                 }\r
767                 break;\r
768 \r
769             default:\r
770                 throw new HTTP_Request2_NotImplementedException(\r
771                     "Unknown HTTP authentication scheme '{$auth['scheme']}'"\r
772                 );\r
773         }\r
774     }\r
775 \r
776    /**\r
777     * Adds 'Proxy-Authorization' header (if needed) to request headers array\r
778     *\r
779     * @param    array   request headers\r
780     * @param    string  request URL (needed for digest authentication)\r
781     * @throws   HTTP_Request2_NotImplementedException\r
782     */\r
783     protected function addProxyAuthorizationHeader(&$headers, $requestUrl)\r
784     {\r
785         if (!$this->request->getConfig('proxy_host') ||\r
786             !($user = $this->request->getConfig('proxy_user')) ||\r
787             (0 == strcasecmp('https', $this->request->getUrl()->getScheme()) &&\r
788              HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())\r
789         ) {\r
790             return;\r
791         }\r
792 \r
793         $password = $this->request->getConfig('proxy_password');\r
794         switch ($this->request->getConfig('proxy_auth_scheme')) {\r
795             case HTTP_Request2::AUTH_BASIC:\r
796                 $headers['proxy-authorization'] =\r
797                     'Basic ' . base64_encode($user . ':' . $password);\r
798                 break;\r
799 \r
800             case HTTP_Request2::AUTH_DIGEST:\r
801                 unset($this->proxyChallenge);\r
802                 $proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .\r
803                             ':' . $this->request->getConfig('proxy_port');\r
804                 if (!empty(self::$challenges[$proxyUrl])) {\r
805                     $headers['proxy-authorization'] = $this->createDigestResponse(\r
806                         $user, $password,\r
807                         $requestUrl, self::$challenges[$proxyUrl]\r
808                     );\r
809                     $this->proxyChallenge =& self::$challenges[$proxyUrl];\r
810                 }\r
811                 break;\r
812 \r
813             default:\r
814                 throw new HTTP_Request2_NotImplementedException(\r
815                     "Unknown HTTP authentication scheme '" .\r
816                     $this->request->getConfig('proxy_auth_scheme') . "'"\r
817                 );\r
818         }\r
819     }\r
820 \r
821 \r
822    /**\r
823     * Creates the string with the Request-Line and request headers\r
824     *\r
825     * @return   string\r
826     * @throws   HTTP_Request2_Exception\r
827     */\r
828     protected function prepareHeaders()\r
829     {\r
830         $headers = $this->request->getHeaders();\r
831         $url     = $this->request->getUrl();\r
832         $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();\r
833         $host    = $url->getHost();\r
834 \r
835         $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;\r
836         if (($port = $url->getPort()) && $port != $defaultPort || $connect) {\r
837             $host .= ':' . (empty($port)? $defaultPort: $port);\r
838         }\r
839         // Do not overwrite explicitly set 'Host' header, see bug #16146\r
840         if (!isset($headers['host'])) {\r
841             $headers['host'] = $host;\r
842         }\r
843 \r
844         if ($connect) {\r
845             $requestUrl = $host;\r
846 \r
847         } else {\r
848             if (!$this->request->getConfig('proxy_host') ||\r
849                 0 == strcasecmp($url->getScheme(), 'https')\r
850             ) {\r
851                 $requestUrl = '';\r
852             } else {\r
853                 $requestUrl = $url->getScheme() . '://' . $host;\r
854             }\r
855             $path        = $url->getPath();\r
856             $query       = $url->getQuery();\r
857             $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);\r
858         }\r
859 \r
860         if ('1.1' == $this->request->getConfig('protocol_version') &&\r
861             extension_loaded('zlib') && !isset($headers['accept-encoding'])\r
862         ) {\r
863             $headers['accept-encoding'] = 'gzip, deflate';\r
864         }\r
865         if (($jar = $this->request->getCookieJar())\r
866             && ($cookies = $jar->getMatching($this->request->getUrl(), true))\r
867         ) {\r
868             $headers['cookie'] = (empty($headers['cookie'])? '': $headers['cookie'] . '; ') . $cookies;\r
869         }\r
870 \r
871         $this->addAuthorizationHeader($headers, $host, $requestUrl);\r
872         $this->addProxyAuthorizationHeader($headers, $requestUrl);\r
873         $this->calculateRequestLength($headers);\r
874 \r
875         $headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .\r
876                       $this->request->getConfig('protocol_version') . "\r\n";\r
877         foreach ($headers as $name => $value) {\r
878             $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));\r
879             $headersStr   .= $canonicalName . ': ' . $value . "\r\n";\r
880         }\r
881         return $headersStr . "\r\n";\r
882     }\r
883 \r
884    /**\r
885     * Sends the request body\r
886     *\r
887     * @throws   HTTP_Request2_MessageException\r
888     */\r
889     protected function writeBody()\r
890     {\r
891         if (in_array($this->request->getMethod(), self::$bodyDisallowed) ||\r
892             0 == $this->contentLength\r
893         ) {\r
894             return;\r
895         }\r
896 \r
897         $position   = 0;\r
898         $bufferSize = $this->request->getConfig('buffer_size');\r
899         while ($position < $this->contentLength) {\r
900             if (is_string($this->requestBody)) {\r
901                 $str = substr($this->requestBody, $position, $bufferSize);\r
902             } elseif (is_resource($this->requestBody)) {\r
903                 $str = fread($this->requestBody, $bufferSize);\r
904             } else {\r
905                 $str = $this->requestBody->read($bufferSize);\r
906             }\r
907             if (false === @fwrite($this->socket, $str, strlen($str))) {\r
908                 throw new HTTP_Request2_MessageException('Error writing request');\r
909             }\r
910             // Provide the length of written string to the observer, request #7630\r
911             $this->request->setLastEvent('sentBodyPart', strlen($str));\r
912             $position += strlen($str);\r
913         }\r
914         $this->request->setLastEvent('sentBody', $this->contentLength);\r
915     }\r
916 \r
917    /**\r
918     * Reads the remote server's response\r
919     *\r
920     * @return   HTTP_Request2_Response\r
921     * @throws   HTTP_Request2_Exception\r
922     */\r
923     protected function readResponse()\r
924     {\r
925         $bufferSize = $this->request->getConfig('buffer_size');\r
926 \r
927         do {\r
928             $response = new HTTP_Request2_Response(\r
929                 $this->readLine($bufferSize), true, $this->request->getUrl()\r
930             );\r
931             do {\r
932                 $headerLine = $this->readLine($bufferSize);\r
933                 $response->parseHeaderLine($headerLine);\r
934             } while ('' != $headerLine);\r
935         } while (in_array($response->getStatus(), array(100, 101)));\r
936 \r
937         $this->request->setLastEvent('receivedHeaders', $response);\r
938 \r
939         // No body possible in such responses\r
940         if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod() ||\r
941             (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod() &&\r
942              200 <= $response->getStatus() && 300 > $response->getStatus()) ||\r
943             in_array($response->getStatus(), array(204, 304))\r
944         ) {\r
945             return $response;\r
946         }\r
947 \r
948         $chunked = 'chunked' == $response->getHeader('transfer-encoding');\r
949         $length  = $response->getHeader('content-length');\r
950         $hasBody = false;\r
951         if ($chunked || null === $length || 0 < intval($length)) {\r
952             // RFC 2616, section 4.4:\r
953             // 3. ... If a message is received with both a\r
954             // Transfer-Encoding header field and a Content-Length header field,\r
955             // the latter MUST be ignored.\r
956             $toRead = ($chunked || null === $length)? null: $length;\r
957             $this->chunkLength = 0;\r
958 \r
959             while (!feof($this->socket) && (is_null($toRead) || 0 < $toRead)) {\r
960                 if ($chunked) {\r
961                     $data = $this->readChunked($bufferSize);\r
962                 } elseif (is_null($toRead)) {\r
963                     $data = $this->fread($bufferSize);\r
964                 } else {\r
965                     $data    = $this->fread(min($toRead, $bufferSize));\r
966                     $toRead -= strlen($data);\r
967                 }\r
968                 if ('' == $data && (!$this->chunkLength || feof($this->socket))) {\r
969                     break;\r
970                 }\r
971 \r
972                 $hasBody = true;\r
973                 if ($this->request->getConfig('store_body')) {\r
974                     $response->appendBody($data);\r
975                 }\r
976                 if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {\r
977                     $this->request->setLastEvent('receivedEncodedBodyPart', $data);\r
978                 } else {\r
979                     $this->request->setLastEvent('receivedBodyPart', $data);\r
980                 }\r
981             }\r
982         }\r
983 \r
984         if ($hasBody) {\r
985             $this->request->setLastEvent('receivedBody', $response);\r
986         }\r
987         return $response;\r
988     }\r
989 \r
990    /**\r
991     * Reads until either the end of the socket or a newline, whichever comes first\r
992     *\r
993     * Strips the trailing newline from the returned data, handles global\r
994     * request timeout. Method idea borrowed from Net_Socket PEAR package.\r
995     *\r
996     * @param    int     buffer size to use for reading\r
997     * @return   Available data up to the newline (not including newline)\r
998     * @throws   HTTP_Request2_MessageException     In case of timeout\r
999     */\r
1000     protected function readLine($bufferSize)\r
1001     {\r
1002         $line = '';\r
1003         while (!feof($this->socket)) {\r
1004             if ($this->deadline) {\r
1005                 stream_set_timeout($this->socket, max($this->deadline - time(), 1));\r
1006             }\r
1007             $line .= @fgets($this->socket, $bufferSize);\r
1008             $info  = stream_get_meta_data($this->socket);\r
1009             if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {\r
1010                 $reason = $this->deadline\r
1011                           ? 'after ' . $this->request->getConfig('timeout') . ' second(s)'\r
1012                           : 'due to default_socket_timeout php.ini setting';\r
1013                 throw new HTTP_Request2_MessageException(\r
1014                     "Request timed out {$reason}", HTTP_Request2_Exception::TIMEOUT\r
1015                 );\r
1016             }\r
1017             if (substr($line, -1) == "\n") {\r
1018                 return rtrim($line, "\r\n");\r
1019             }\r
1020         }\r
1021         return $line;\r
1022     }\r
1023 \r
1024    /**\r
1025     * Wrapper around fread(), handles global request timeout\r
1026     *\r
1027     * @param    int     Reads up to this number of bytes\r
1028     * @return   Data read from socket\r
1029     * @throws   HTTP_Request2_MessageException     In case of timeout\r
1030     */\r
1031     protected function fread($length)\r
1032     {\r
1033         if ($this->deadline) {\r
1034             stream_set_timeout($this->socket, max($this->deadline - time(), 1));\r
1035         }\r
1036         $data = fread($this->socket, $length);\r
1037         $info = stream_get_meta_data($this->socket);\r
1038         if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {\r
1039             $reason = $this->deadline\r
1040                       ? 'after ' . $this->request->getConfig('timeout') . ' second(s)'\r
1041                       : 'due to default_socket_timeout php.ini setting';\r
1042             throw new HTTP_Request2_MessageException(\r
1043                 "Request timed out {$reason}", HTTP_Request2_Exception::TIMEOUT\r
1044             );\r
1045         }\r
1046         return $data;\r
1047     }\r
1048 \r
1049    /**\r
1050     * Reads a part of response body encoded with chunked Transfer-Encoding\r
1051     *\r
1052     * @param    int     buffer size to use for reading\r
1053     * @return   string\r
1054     * @throws   HTTP_Request2_MessageException\r
1055     */\r
1056     protected function readChunked($bufferSize)\r
1057     {\r
1058         // at start of the next chunk?\r
1059         if (0 == $this->chunkLength) {\r
1060             $line = $this->readLine($bufferSize);\r
1061             if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {\r
1062                 throw new HTTP_Request2_MessageException(\r
1063                     "Cannot decode chunked response, invalid chunk length '{$line}'",\r
1064                     HTTP_Request2_Exception::DECODE_ERROR\r
1065                 );\r
1066             } else {\r
1067                 $this->chunkLength = hexdec($matches[1]);\r
1068                 // Chunk with zero length indicates the end\r
1069                 if (0 == $this->chunkLength) {\r
1070                     $this->readLine($bufferSize);\r
1071                     return '';\r
1072                 }\r
1073             }\r
1074         }\r
1075         $data = $this->fread(min($this->chunkLength, $bufferSize));\r
1076         $this->chunkLength -= strlen($data);\r
1077         if (0 == $this->chunkLength) {\r
1078             $this->readLine($bufferSize); // Trailing CRLF\r
1079         }\r
1080         return $data;\r
1081     }\r
1082 }\r
1083 \r
1084 ?>