Socket.php 43 KB

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