Socket.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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-2016 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.3.0
  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);
  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 (version_compare(phpversion(), '5.6', '<')) {
  235. if ($value) {
  236. $options['ssl']['CN_match'] = $reqHost;
  237. }
  238. } else {
  239. $options['ssl']['verify_peer_name'] = $value;
  240. $options['ssl']['peer_name'] = $reqHost;
  241. }
  242. } else {
  243. $options['ssl'][substr($name, 4)] = $value;
  244. }
  245. }
  246. }
  247. ksort($options['ssl']);
  248. }
  249. // Use global request timeout if given, see feature requests #5735, #8964
  250. if ($timeout = $this->request->getConfig('timeout')) {
  251. $deadline = time() + $timeout;
  252. } else {
  253. $deadline = null;
  254. }
  255. // Changing SSL context options after connection is established does *not*
  256. // work, we need a new connection if options change
  257. $remote = ((!$secure || $httpProxy || $socksProxy)? 'tcp://': 'tls://')
  258. . $host . ':' . $port;
  259. $socketKey = $remote . (
  260. ($secure && $httpProxy || $socksProxy)
  261. ? "->{$reqHost}:{$reqPort}" : ''
  262. ) . (empty($options)? '': ':' . serialize($options));
  263. unset($this->socket);
  264. // We use persistent connections and have a connected socket?
  265. // Ensure that the socket is still connected, see bug #16149
  266. if ($keepAlive && !empty(self::$sockets[$socketKey])
  267. && !self::$sockets[$socketKey]->eof()
  268. ) {
  269. $this->socket =& self::$sockets[$socketKey];
  270. } else {
  271. if ($socksProxy) {
  272. require_once 'HTTP/Request2/SOCKS5.php';
  273. $this->socket = new HTTP_Request2_SOCKS5(
  274. $remote, $this->request->getConfig('connect_timeout'),
  275. $options, $this->request->getConfig('proxy_user'),
  276. $this->request->getConfig('proxy_password')
  277. );
  278. // handle request timeouts ASAP
  279. $this->socket->setDeadline($deadline, $this->request->getConfig('timeout'));
  280. $this->socket->connect($reqHost, $reqPort);
  281. if (!$secure) {
  282. $conninfo = "tcp://{$reqHost}:{$reqPort} via {$remote}";
  283. } else {
  284. $this->socket->enableCrypto();
  285. $conninfo = "tls://{$reqHost}:{$reqPort} via {$remote}";
  286. }
  287. } elseif ($secure && $httpProxy && !$tunnel) {
  288. $this->establishTunnel();
  289. $conninfo = "tls://{$reqHost}:{$reqPort} via {$remote}";
  290. } else {
  291. $this->socket = new HTTP_Request2_SocketWrapper(
  292. $remote, $this->request->getConfig('connect_timeout'), $options
  293. );
  294. }
  295. $this->request->setLastEvent('connect', empty($conninfo)? $remote: $conninfo);
  296. self::$sockets[$socketKey] =& $this->socket;
  297. }
  298. $this->socket->setDeadline($deadline, $this->request->getConfig('timeout'));
  299. return $keepAlive;
  300. }
  301. /**
  302. * Establishes a tunnel to a secure remote server via HTTP CONNECT request
  303. *
  304. * This method will fail if 'ssl_verify_peer' is enabled. Probably because PHP
  305. * sees that we are connected to a proxy server (duh!) rather than the server
  306. * that presents its certificate.
  307. *
  308. * @link http://tools.ietf.org/html/rfc2817#section-5.2
  309. * @throws HTTP_Request2_Exception
  310. */
  311. protected function establishTunnel()
  312. {
  313. $donor = new self;
  314. $connect = new HTTP_Request2(
  315. $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
  316. array_merge($this->request->getConfig(), array('adapter' => $donor))
  317. );
  318. $response = $connect->send();
  319. // Need any successful (2XX) response
  320. if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
  321. throw new HTTP_Request2_ConnectionException(
  322. 'Failed to connect via HTTPS proxy. Proxy response: ' .
  323. $response->getStatus() . ' ' . $response->getReasonPhrase()
  324. );
  325. }
  326. $this->socket = $donor->socket;
  327. $this->socket->enableCrypto();
  328. }
  329. /**
  330. * Checks whether current connection may be reused or should be closed
  331. *
  332. * @param boolean $requestKeepAlive whether connection could
  333. * be persistent in the first place
  334. * @param HTTP_Request2_Response $response response object to check
  335. *
  336. * @return boolean
  337. */
  338. protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
  339. {
  340. // Do not close socket on successful CONNECT request
  341. if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod()
  342. && 200 <= $response->getStatus() && 300 > $response->getStatus()
  343. ) {
  344. return true;
  345. }
  346. $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding'))
  347. || null !== $response->getHeader('content-length')
  348. // no body possible for such responses, see also request #17031
  349. || HTTP_Request2::METHOD_HEAD == $this->request->getMethod()
  350. || in_array($response->getStatus(), array(204, 304));
  351. $persistent = 'keep-alive' == strtolower($response->getHeader('connection')) ||
  352. (null === $response->getHeader('connection') &&
  353. '1.1' == $response->getVersion());
  354. return $requestKeepAlive && $lengthKnown && $persistent;
  355. }
  356. /**
  357. * Disconnects from the remote server
  358. */
  359. protected function disconnect()
  360. {
  361. if (!empty($this->socket)) {
  362. $this->socket = null;
  363. $this->request->setLastEvent('disconnect');
  364. }
  365. }
  366. /**
  367. * Handles HTTP redirection
  368. *
  369. * This method will throw an Exception if redirect to a non-HTTP(S) location
  370. * is attempted, also if number of redirects performed already is equal to
  371. * 'max_redirects' configuration parameter.
  372. *
  373. * @param HTTP_Request2 $request Original request
  374. * @param HTTP_Request2_Response $response Response containing redirect
  375. *
  376. * @return HTTP_Request2_Response Response from a new location
  377. * @throws HTTP_Request2_Exception
  378. */
  379. protected function handleRedirect(
  380. HTTP_Request2 $request, HTTP_Request2_Response $response
  381. ) {
  382. if (is_null($this->redirectCountdown)) {
  383. $this->redirectCountdown = $request->getConfig('max_redirects');
  384. }
  385. if (0 == $this->redirectCountdown) {
  386. $this->redirectCountdown = null;
  387. // Copying cURL behaviour
  388. throw new HTTP_Request2_MessageException(
  389. 'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed',
  390. HTTP_Request2_Exception::TOO_MANY_REDIRECTS
  391. );
  392. }
  393. $redirectUrl = new Net_URL2(
  394. $response->getHeader('location'),
  395. array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))
  396. );
  397. // refuse non-HTTP redirect
  398. if ($redirectUrl->isAbsolute()
  399. && !in_array($redirectUrl->getScheme(), array('http', 'https'))
  400. ) {
  401. $this->redirectCountdown = null;
  402. throw new HTTP_Request2_MessageException(
  403. 'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString(),
  404. HTTP_Request2_Exception::NON_HTTP_REDIRECT
  405. );
  406. }
  407. // Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),
  408. // but in practice it is often not
  409. if (!$redirectUrl->isAbsolute()) {
  410. $redirectUrl = $request->getUrl()->resolve($redirectUrl);
  411. }
  412. $redirect = clone $request;
  413. $redirect->setUrl($redirectUrl);
  414. if (303 == $response->getStatus()
  415. || (!$request->getConfig('strict_redirects')
  416. && in_array($response->getStatus(), array(301, 302)))
  417. ) {
  418. $redirect->setMethod(HTTP_Request2::METHOD_GET);
  419. $redirect->setBody('');
  420. }
  421. if (0 < $this->redirectCountdown) {
  422. $this->redirectCountdown--;
  423. }
  424. return $this->sendRequest($redirect);
  425. }
  426. /**
  427. * Checks whether another request should be performed with server digest auth
  428. *
  429. * Several conditions should be satisfied for it to return true:
  430. * - response status should be 401
  431. * - auth credentials should be set in the request object
  432. * - response should contain WWW-Authenticate header with digest challenge
  433. * - there is either no challenge stored for this URL or new challenge
  434. * contains stale=true parameter (in other case we probably just failed
  435. * due to invalid username / password)
  436. *
  437. * The method stores challenge values in $challenges static property
  438. *
  439. * @param HTTP_Request2_Response $response response to check
  440. *
  441. * @return boolean whether another request should be performed
  442. * @throws HTTP_Request2_Exception in case of unsupported challenge parameters
  443. */
  444. protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)
  445. {
  446. // no sense repeating a request if we don't have credentials
  447. if (401 != $response->getStatus() || !$this->request->getAuth()) {
  448. return false;
  449. }
  450. if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
  451. return false;
  452. }
  453. $url = $this->request->getUrl();
  454. $scheme = $url->getScheme();
  455. $host = $scheme . '://' . $url->getHost();
  456. if ($port = $url->getPort()) {
  457. if ((0 == strcasecmp($scheme, 'http') && 80 != $port)
  458. || (0 == strcasecmp($scheme, 'https') && 443 != $port)
  459. ) {
  460. $host .= ':' . $port;
  461. }
  462. }
  463. if (!empty($challenge['domain'])) {
  464. $prefixes = array();
  465. foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
  466. // don't bother with different servers
  467. if ('/' == substr($prefix, 0, 1)) {
  468. $prefixes[] = $host . $prefix;
  469. }
  470. }
  471. }
  472. if (empty($prefixes)) {
  473. $prefixes = array($host . '/');
  474. }
  475. $ret = true;
  476. foreach ($prefixes as $prefix) {
  477. if (!empty(self::$challenges[$prefix])
  478. && (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
  479. ) {
  480. // probably credentials are invalid
  481. $ret = false;
  482. }
  483. self::$challenges[$prefix] =& $challenge;
  484. }
  485. return $ret;
  486. }
  487. /**
  488. * Checks whether another request should be performed with proxy digest auth
  489. *
  490. * Several conditions should be satisfied for it to return true:
  491. * - response status should be 407
  492. * - proxy auth credentials should be set in the request object
  493. * - response should contain Proxy-Authenticate header with digest challenge
  494. * - there is either no challenge stored for this proxy or new challenge
  495. * contains stale=true parameter (in other case we probably just failed
  496. * due to invalid username / password)
  497. *
  498. * The method stores challenge values in $challenges static property
  499. *
  500. * @param HTTP_Request2_Response $response response to check
  501. *
  502. * @return boolean whether another request should be performed
  503. * @throws HTTP_Request2_Exception in case of unsupported challenge parameters
  504. */
  505. protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
  506. {
  507. if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
  508. return false;
  509. }
  510. if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
  511. return false;
  512. }
  513. $key = 'proxy://' . $this->request->getConfig('proxy_host') .
  514. ':' . $this->request->getConfig('proxy_port');
  515. if (!empty(self::$challenges[$key])
  516. && (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
  517. ) {
  518. $ret = false;
  519. } else {
  520. $ret = true;
  521. }
  522. self::$challenges[$key] = $challenge;
  523. return $ret;
  524. }
  525. /**
  526. * Extracts digest method challenge from (WWW|Proxy)-Authenticate header value
  527. *
  528. * There is a problem with implementation of RFC 2617: several of the parameters
  529. * are defined as quoted-string there and thus may contain backslash escaped
  530. * double quotes (RFC 2616, section 2.2). However, RFC 2617 defines unq(X) as
  531. * just value of quoted-string X without surrounding quotes, it doesn't speak
  532. * about removing backslash escaping.
  533. *
  534. * Now realm parameter is user-defined and human-readable, strange things
  535. * happen when it contains quotes:
  536. * - Apache allows quotes in realm, but apparently uses realm value without
  537. * backslashes for digest computation
  538. * - Squid allows (manually escaped) quotes there, but it is impossible to
  539. * authorize with either escaped or unescaped quotes used in digest,
  540. * probably it can't parse the response (?)
  541. * - Both IE and Firefox display realm value with backslashes in
  542. * the password popup and apparently use the same value for digest
  543. *
  544. * HTTP_Request2 follows IE and Firefox (and hopefully RFC 2617) in
  545. * quoted-string handling, unfortunately that means failure to authorize
  546. * sometimes
  547. *
  548. * @param string $headerValue value of WWW-Authenticate or Proxy-Authenticate header
  549. *
  550. * @return mixed associative array with challenge parameters, false if
  551. * no challenge is present in header value
  552. * @throws HTTP_Request2_NotImplementedException in case of unsupported challenge parameters
  553. */
  554. protected function parseDigestChallenge($headerValue)
  555. {
  556. $authParam = '(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
  557. self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')';
  558. $challenge = "!(?<=^|\\s|,)Digest ({$authParam}\\s*(,\\s*|$))+!";
  559. if (!preg_match($challenge, $headerValue, $matches)) {
  560. return false;
  561. }
  562. preg_match_all('!' . $authParam . '!', $matches[0], $params);
  563. $paramsAry = array();
  564. $knownParams = array('realm', 'domain', 'nonce', 'opaque', 'stale',
  565. 'algorithm', 'qop');
  566. for ($i = 0; $i < count($params[0]); $i++) {
  567. // section 3.2.1: Any unrecognized directive MUST be ignored.
  568. if (in_array($params[1][$i], $knownParams)) {
  569. if ('"' == substr($params[2][$i], 0, 1)) {
  570. $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
  571. } else {
  572. $paramsAry[$params[1][$i]] = $params[2][$i];
  573. }
  574. }
  575. }
  576. // we only support qop=auth
  577. if (!empty($paramsAry['qop'])
  578. && !in_array('auth', array_map('trim', explode(',', $paramsAry['qop'])))
  579. ) {
  580. throw new HTTP_Request2_NotImplementedException(
  581. "Only 'auth' qop is currently supported in digest authentication, " .
  582. "server requested '{$paramsAry['qop']}'"
  583. );
  584. }
  585. // we only support algorithm=MD5
  586. if (!empty($paramsAry['algorithm']) && 'MD5' != $paramsAry['algorithm']) {
  587. throw new HTTP_Request2_NotImplementedException(
  588. "Only 'MD5' algorithm is currently supported in digest authentication, " .
  589. "server requested '{$paramsAry['algorithm']}'"
  590. );
  591. }
  592. return $paramsAry;
  593. }
  594. /**
  595. * Parses [Proxy-]Authentication-Info header value and updates challenge
  596. *
  597. * @param array &$challenge challenge to update
  598. * @param string $headerValue value of [Proxy-]Authentication-Info header
  599. *
  600. * @todo validate server rspauth response
  601. */
  602. protected function updateChallenge(&$challenge, $headerValue)
  603. {
  604. $authParam = '!(' . self::REGEXP_TOKEN . ')\\s*=\\s*(' .
  605. self::REGEXP_TOKEN . '|' . self::REGEXP_QUOTED_STRING . ')!';
  606. $paramsAry = array();
  607. preg_match_all($authParam, $headerValue, $params);
  608. for ($i = 0; $i < count($params[0]); $i++) {
  609. if ('"' == substr($params[2][$i], 0, 1)) {
  610. $paramsAry[$params[1][$i]] = substr($params[2][$i], 1, -1);
  611. } else {
  612. $paramsAry[$params[1][$i]] = $params[2][$i];
  613. }
  614. }
  615. // for now, just update the nonce value
  616. if (!empty($paramsAry['nextnonce'])) {
  617. $challenge['nonce'] = $paramsAry['nextnonce'];
  618. $challenge['nc'] = 1;
  619. }
  620. }
  621. /**
  622. * Creates a value for [Proxy-]Authorization header when using digest authentication
  623. *
  624. * @param string $user user name
  625. * @param string $password password
  626. * @param string $url request URL
  627. * @param array &$challenge digest challenge parameters
  628. *
  629. * @return string value of [Proxy-]Authorization request header
  630. * @link http://tools.ietf.org/html/rfc2617#section-3.2.2
  631. */
  632. protected function createDigestResponse($user, $password, $url, &$challenge)
  633. {
  634. if (false !== ($q = strpos($url, '?'))
  635. && $this->request->getConfig('digest_compat_ie')
  636. ) {
  637. $url = substr($url, 0, $q);
  638. }
  639. $a1 = md5($user . ':' . $challenge['realm'] . ':' . $password);
  640. $a2 = md5($this->request->getMethod() . ':' . $url);
  641. if (empty($challenge['qop'])) {
  642. $digest = md5($a1 . ':' . $challenge['nonce'] . ':' . $a2);
  643. } else {
  644. $challenge['cnonce'] = 'Req2.' . rand();
  645. if (empty($challenge['nc'])) {
  646. $challenge['nc'] = 1;
  647. }
  648. $nc = sprintf('%08x', $challenge['nc']++);
  649. $digest = md5(
  650. $a1 . ':' . $challenge['nonce'] . ':' . $nc . ':' .
  651. $challenge['cnonce'] . ':auth:' . $a2
  652. );
  653. }
  654. return 'Digest username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $user) . '", ' .
  655. 'realm="' . $challenge['realm'] . '", ' .
  656. 'nonce="' . $challenge['nonce'] . '", ' .
  657. 'uri="' . $url . '", ' .
  658. 'response="' . $digest . '"' .
  659. (!empty($challenge['opaque'])?
  660. ', opaque="' . $challenge['opaque'] . '"':
  661. '') .
  662. (!empty($challenge['qop'])?
  663. ', qop="auth", nc=' . $nc . ', cnonce="' . $challenge['cnonce'] . '"':
  664. '');
  665. }
  666. /**
  667. * Adds 'Authorization' header (if needed) to request headers array
  668. *
  669. * @param array &$headers request headers
  670. * @param string $requestHost request host (needed for digest authentication)
  671. * @param string $requestUrl request URL (needed for digest authentication)
  672. *
  673. * @throws HTTP_Request2_NotImplementedException
  674. */
  675. protected function addAuthorizationHeader(&$headers, $requestHost, $requestUrl)
  676. {
  677. if (!($auth = $this->request->getAuth())) {
  678. return;
  679. }
  680. switch ($auth['scheme']) {
  681. case HTTP_Request2::AUTH_BASIC:
  682. $headers['authorization'] = 'Basic ' . base64_encode(
  683. $auth['user'] . ':' . $auth['password']
  684. );
  685. break;
  686. case HTTP_Request2::AUTH_DIGEST:
  687. unset($this->serverChallenge);
  688. $fullUrl = ('/' == $requestUrl[0])?
  689. $this->request->getUrl()->getScheme() . '://' .
  690. $requestHost . $requestUrl:
  691. $requestUrl;
  692. foreach (array_keys(self::$challenges) as $key) {
  693. if ($key == substr($fullUrl, 0, strlen($key))) {
  694. $headers['authorization'] = $this->createDigestResponse(
  695. $auth['user'], $auth['password'],
  696. $requestUrl, self::$challenges[$key]
  697. );
  698. $this->serverChallenge =& self::$challenges[$key];
  699. break;
  700. }
  701. }
  702. break;
  703. default:
  704. throw new HTTP_Request2_NotImplementedException(
  705. "Unknown HTTP authentication scheme '{$auth['scheme']}'"
  706. );
  707. }
  708. }
  709. /**
  710. * Adds 'Proxy-Authorization' header (if needed) to request headers array
  711. *
  712. * @param array &$headers request headers
  713. * @param string $requestUrl request URL (needed for digest authentication)
  714. *
  715. * @throws HTTP_Request2_NotImplementedException
  716. */
  717. protected function addProxyAuthorizationHeader(&$headers, $requestUrl)
  718. {
  719. if (!$this->request->getConfig('proxy_host')
  720. || !($user = $this->request->getConfig('proxy_user'))
  721. || (0 == strcasecmp('https', $this->request->getUrl()->getScheme())
  722. && HTTP_Request2::METHOD_CONNECT != $this->request->getMethod())
  723. ) {
  724. return;
  725. }
  726. $password = $this->request->getConfig('proxy_password');
  727. switch ($this->request->getConfig('proxy_auth_scheme')) {
  728. case HTTP_Request2::AUTH_BASIC:
  729. $headers['proxy-authorization'] = 'Basic ' . base64_encode(
  730. $user . ':' . $password
  731. );
  732. break;
  733. case HTTP_Request2::AUTH_DIGEST:
  734. unset($this->proxyChallenge);
  735. $proxyUrl = 'proxy://' . $this->request->getConfig('proxy_host') .
  736. ':' . $this->request->getConfig('proxy_port');
  737. if (!empty(self::$challenges[$proxyUrl])) {
  738. $headers['proxy-authorization'] = $this->createDigestResponse(
  739. $user, $password,
  740. $requestUrl, self::$challenges[$proxyUrl]
  741. );
  742. $this->proxyChallenge =& self::$challenges[$proxyUrl];
  743. }
  744. break;
  745. default:
  746. throw new HTTP_Request2_NotImplementedException(
  747. "Unknown HTTP authentication scheme '" .
  748. $this->request->getConfig('proxy_auth_scheme') . "'"
  749. );
  750. }
  751. }
  752. /**
  753. * Creates the string with the Request-Line and request headers
  754. *
  755. * @return string
  756. * @throws HTTP_Request2_Exception
  757. */
  758. protected function prepareHeaders()
  759. {
  760. $headers = $this->request->getHeaders();
  761. $url = $this->request->getUrl();
  762. $connect = HTTP_Request2::METHOD_CONNECT == $this->request->getMethod();
  763. $host = $url->getHost();
  764. $defaultPort = 0 == strcasecmp($url->getScheme(), 'https')? 443: 80;
  765. if (($port = $url->getPort()) && $port != $defaultPort || $connect) {
  766. $host .= ':' . (empty($port)? $defaultPort: $port);
  767. }
  768. // Do not overwrite explicitly set 'Host' header, see bug #16146
  769. if (!isset($headers['host'])) {
  770. $headers['host'] = $host;
  771. }
  772. if ($connect) {
  773. $requestUrl = $host;
  774. } else {
  775. if (!$this->request->getConfig('proxy_host')
  776. || 'http' != $this->request->getConfig('proxy_type')
  777. || 0 == strcasecmp($url->getScheme(), 'https')
  778. ) {
  779. $requestUrl = '';
  780. } else {
  781. $requestUrl = $url->getScheme() . '://' . $host;
  782. }
  783. $path = $url->getPath();
  784. $query = $url->getQuery();
  785. $requestUrl .= (empty($path)? '/': $path) . (empty($query)? '': '?' . $query);
  786. }
  787. if ('1.1' == $this->request->getConfig('protocol_version')
  788. && extension_loaded('zlib') && !isset($headers['accept-encoding'])
  789. ) {
  790. $headers['accept-encoding'] = 'gzip, deflate';
  791. }
  792. if (($jar = $this->request->getCookieJar())
  793. && ($cookies = $jar->getMatching($this->request->getUrl(), true))
  794. ) {
  795. $headers['cookie'] = (empty($headers['cookie'])? '': $headers['cookie'] . '; ') . $cookies;
  796. }
  797. $this->addAuthorizationHeader($headers, $host, $requestUrl);
  798. $this->addProxyAuthorizationHeader($headers, $requestUrl);
  799. $this->calculateRequestLength($headers);
  800. if ('1.1' == $this->request->getConfig('protocol_version')) {
  801. $this->updateExpectHeader($headers);
  802. } else {
  803. $this->expect100Continue = false;
  804. }
  805. $headersStr = $this->request->getMethod() . ' ' . $requestUrl . ' HTTP/' .
  806. $this->request->getConfig('protocol_version') . "\r\n";
  807. foreach ($headers as $name => $value) {
  808. $canonicalName = implode('-', array_map('ucfirst', explode('-', $name)));
  809. $headersStr .= $canonicalName . ': ' . $value . "\r\n";
  810. }
  811. return $headersStr . "\r\n";
  812. }
  813. /**
  814. * Adds or removes 'Expect: 100-continue' header from request headers
  815. *
  816. * Also sets the $expect100Continue property. Parsing of existing header
  817. * is somewhat needed due to its complex structure and due to the
  818. * requirement in section 8.2.3 of RFC 2616:
  819. * > A client MUST NOT send an Expect request-header field (section
  820. * > 14.20) with the "100-continue" expectation if it does not intend
  821. * > to send a request body.
  822. *
  823. * @param array &$headers Array of headers prepared for the request
  824. *
  825. * @throws HTTP_Request2_LogicException
  826. * @link http://pear.php.net/bugs/bug.php?id=19233
  827. * @link http://tools.ietf.org/html/rfc2616#section-8.2.3
  828. */
  829. protected function updateExpectHeader(&$headers)
  830. {
  831. $this->expect100Continue = false;
  832. $expectations = array();
  833. if (isset($headers['expect'])) {
  834. if ('' === $headers['expect']) {
  835. // empty 'Expect' header is technically invalid, so just get rid of it
  836. unset($headers['expect']);
  837. return;
  838. }
  839. // build regexp to parse the value of existing Expect header
  840. $expectParam = ';\s*' . self::REGEXP_TOKEN . '(?:\s*=\s*(?:'
  841. . self::REGEXP_TOKEN . '|'
  842. . self::REGEXP_QUOTED_STRING . '))?\s*';
  843. $expectExtension = self::REGEXP_TOKEN . '(?:\s*=\s*(?:'
  844. . self::REGEXP_TOKEN . '|'
  845. . self::REGEXP_QUOTED_STRING . ')\s*(?:'
  846. . $expectParam . ')*)?';
  847. $expectItem = '!(100-continue|' . $expectExtension . ')!A';
  848. $pos = 0;
  849. $length = strlen($headers['expect']);
  850. while ($pos < $length) {
  851. $pos += strspn($headers['expect'], " \t", $pos);
  852. if (',' === substr($headers['expect'], $pos, 1)) {
  853. $pos++;
  854. continue;
  855. } elseif (!preg_match($expectItem, $headers['expect'], $m, 0, $pos)) {
  856. throw new HTTP_Request2_LogicException(
  857. "Cannot parse value '{$headers['expect']}' of Expect header",
  858. HTTP_Request2_Exception::INVALID_ARGUMENT
  859. );
  860. } else {
  861. $pos += strlen($m[0]);
  862. if (strcasecmp('100-continue', $m[0])) {
  863. $expectations[] = $m[0];
  864. }
  865. }
  866. }
  867. }
  868. if (1024 < $this->contentLength) {
  869. $expectations[] = '100-continue';
  870. $this->expect100Continue = true;
  871. }
  872. if (empty($expectations)) {
  873. unset($headers['expect']);
  874. } else {
  875. $headers['expect'] = implode(',', $expectations);
  876. }
  877. }
  878. /**
  879. * Sends the request body
  880. *
  881. * @throws HTTP_Request2_MessageException
  882. */
  883. protected function writeBody()
  884. {
  885. if (in_array($this->request->getMethod(), self::$bodyDisallowed)
  886. || 0 == $this->contentLength
  887. ) {
  888. return;
  889. }
  890. $position = 0;
  891. $bufferSize = $this->request->getConfig('buffer_size');
  892. $headers = $this->request->getHeaders();
  893. $chunked = isset($headers['transfer-encoding']);
  894. while ($position < $this->contentLength) {
  895. if (is_string($this->requestBody)) {
  896. $str = substr($this->requestBody, $position, $bufferSize);
  897. } elseif (is_resource($this->requestBody)) {
  898. $str = fread($this->requestBody, $bufferSize);
  899. } else {
  900. $str = $this->requestBody->read($bufferSize);
  901. }
  902. if (!$chunked) {
  903. $this->socket->write($str);
  904. } else {
  905. $this->socket->write(dechex(strlen($str)) . "\r\n{$str}\r\n");
  906. }
  907. // Provide the length of written string to the observer, request #7630
  908. $this->request->setLastEvent('sentBodyPart', strlen($str));
  909. $position += strlen($str);
  910. }
  911. // write zero-length chunk
  912. if ($chunked) {
  913. $this->socket->write("0\r\n\r\n");
  914. }
  915. $this->request->setLastEvent('sentBody', $this->contentLength);
  916. }
  917. /**
  918. * Reads the remote server's response
  919. *
  920. * @return HTTP_Request2_Response
  921. * @throws HTTP_Request2_Exception
  922. */
  923. protected function readResponse()
  924. {
  925. $bufferSize = $this->request->getConfig('buffer_size');
  926. // http://tools.ietf.org/html/rfc2616#section-8.2.3
  927. // ...the client SHOULD NOT wait for an indefinite period before sending the request body
  928. $timeout = $this->expect100Continue ? 1 : null;
  929. do {
  930. try {
  931. $response = new HTTP_Request2_Response(
  932. $this->socket->readLine($bufferSize, $timeout), true, $this->request->getUrl()
  933. );
  934. do {
  935. $headerLine = $this->socket->readLine($bufferSize);
  936. $response->parseHeaderLine($headerLine);
  937. } while ('' != $headerLine);
  938. } catch (HTTP_Request2_MessageException $e) {
  939. if (HTTP_Request2_Exception::TIMEOUT === $e->getCode()
  940. && $this->expect100Continue
  941. ) {
  942. return null;
  943. }
  944. throw $e;
  945. }
  946. if ($this->expect100Continue && 100 == $response->getStatus()) {
  947. return $response;
  948. }
  949. } while (in_array($response->getStatus(), array(100, 101)));
  950. $this->request->setLastEvent('receivedHeaders', $response);
  951. // No body possible in such responses
  952. if (HTTP_Request2::METHOD_HEAD == $this->request->getMethod()
  953. || (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod()
  954. && 200 <= $response->getStatus() && 300 > $response->getStatus())
  955. || in_array($response->getStatus(), array(204, 304))
  956. ) {
  957. return $response;
  958. }
  959. $chunked = 'chunked' == $response->getHeader('transfer-encoding');
  960. $length = $response->getHeader('content-length');
  961. $hasBody = false;
  962. // RFC 2616, section 4.4:
  963. // 3. ... If a message is received with both a
  964. // Transfer-Encoding header field and a Content-Length header field,
  965. // the latter MUST be ignored.
  966. $toRead = ($chunked || null === $length)? null: $length;
  967. $this->chunkLength = 0;
  968. if ($chunked || null === $length || 0 < intval($length)) {
  969. while (!$this->socket->eof() && (is_null($toRead) || 0 < $toRead)) {
  970. if ($chunked) {
  971. $data = $this->readChunked($bufferSize);
  972. } elseif (is_null($toRead)) {
  973. $data = $this->socket->read($bufferSize);
  974. } else {
  975. $data = $this->socket->read(min($toRead, $bufferSize));
  976. $toRead -= strlen($data);
  977. }
  978. if ('' == $data && (!$this->chunkLength || $this->socket->eof())) {
  979. break;
  980. }
  981. $hasBody = true;
  982. if ($this->request->getConfig('store_body')) {
  983. $response->appendBody($data);
  984. }
  985. if (!in_array($response->getHeader('content-encoding'), array('identity', null))) {
  986. $this->request->setLastEvent('receivedEncodedBodyPart', $data);
  987. } else {
  988. $this->request->setLastEvent('receivedBodyPart', $data);
  989. }
  990. }
  991. }
  992. if (0 !== $this->chunkLength || null !== $toRead && $toRead > 0) {
  993. $this->request->setLastEvent(
  994. 'warning', 'transfer closed with outstanding read data remaining'
  995. );
  996. }
  997. if ($hasBody) {
  998. $this->request->setLastEvent('receivedBody', $response);
  999. }
  1000. return $response;
  1001. }
  1002. /**
  1003. * Reads a part of response body encoded with chunked Transfer-Encoding
  1004. *
  1005. * @param int $bufferSize buffer size to use for reading
  1006. *
  1007. * @return string
  1008. * @throws HTTP_Request2_MessageException
  1009. */
  1010. protected function readChunked($bufferSize)
  1011. {
  1012. // at start of the next chunk?
  1013. if (0 == $this->chunkLength) {
  1014. $line = $this->socket->readLine($bufferSize);
  1015. if ('' === $line && $this->socket->eof()) {
  1016. $this->chunkLength = -1; // indicate missing chunk
  1017. return '';
  1018. } elseif (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
  1019. throw new HTTP_Request2_MessageException(
  1020. "Cannot decode chunked response, invalid chunk length '{$line}'",
  1021. HTTP_Request2_Exception::DECODE_ERROR
  1022. );
  1023. } else {
  1024. $this->chunkLength = hexdec($matches[1]);
  1025. // Chunk with zero length indicates the end
  1026. if (0 == $this->chunkLength) {
  1027. $this->socket->readLine($bufferSize);
  1028. return '';
  1029. }
  1030. }
  1031. }
  1032. $data = $this->socket->read(min($this->chunkLength, $bufferSize));
  1033. $this->chunkLength -= strlen($data);
  1034. if (0 == $this->chunkLength) {
  1035. $this->socket->readLine($bufferSize); // Trailing CRLF
  1036. }
  1037. return $data;
  1038. }
  1039. }
  1040. ?>