Response.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. <?php
  2. /**
  3. * Class representing a HTTP response
  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. /**
  21. * Exception class for HTTP_Request2 package
  22. */
  23. require_once 'HTTP/Request2/Exception.php';
  24. /**
  25. * Class representing a HTTP response
  26. *
  27. * The class is designed to be used in "streaming" scenario, building the
  28. * response as it is being received:
  29. * <code>
  30. * $statusLine = read_status_line();
  31. * $response = new HTTP_Request2_Response($statusLine);
  32. * do {
  33. * $headerLine = read_header_line();
  34. * $response->parseHeaderLine($headerLine);
  35. * } while ($headerLine != '');
  36. *
  37. * while ($chunk = read_body()) {
  38. * $response->appendBody($chunk);
  39. * }
  40. *
  41. * var_dump($response->getHeader(), $response->getCookies(), $response->getBody());
  42. * </code>
  43. *
  44. * @category HTTP
  45. * @package HTTP_Request2
  46. * @author Alexey Borzov <avb@php.net>
  47. * @license http://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License
  48. * @version Release: 2.3.0
  49. * @link http://pear.php.net/package/HTTP_Request2
  50. * @link http://tools.ietf.org/html/rfc2616#section-6
  51. */
  52. class HTTP_Request2_Response
  53. {
  54. /**
  55. * HTTP protocol version (e.g. 1.0, 1.1)
  56. * @var string
  57. */
  58. protected $version;
  59. /**
  60. * Status code
  61. * @var integer
  62. * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
  63. */
  64. protected $code;
  65. /**
  66. * Reason phrase
  67. * @var string
  68. * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
  69. */
  70. protected $reasonPhrase;
  71. /**
  72. * Effective URL (may be different from original request URL in case of redirects)
  73. * @var string
  74. */
  75. protected $effectiveUrl;
  76. /**
  77. * Associative array of response headers
  78. * @var array
  79. */
  80. protected $headers = array();
  81. /**
  82. * Cookies set in the response
  83. * @var array
  84. */
  85. protected $cookies = array();
  86. /**
  87. * Name of last header processed by parseHederLine()
  88. *
  89. * Used to handle the headers that span multiple lines
  90. *
  91. * @var string
  92. */
  93. protected $lastHeader = null;
  94. /**
  95. * Response body
  96. * @var string
  97. */
  98. protected $body = '';
  99. /**
  100. * Whether the body is still encoded by Content-Encoding
  101. *
  102. * cURL provides the decoded body to the callback; if we are reading from
  103. * socket the body is still gzipped / deflated
  104. *
  105. * @var bool
  106. */
  107. protected $bodyEncoded;
  108. /**
  109. * Associative array of HTTP status code / reason phrase.
  110. *
  111. * @var array
  112. * @link http://tools.ietf.org/html/rfc2616#section-10
  113. */
  114. protected static $phrases = array(
  115. // 1xx: Informational - Request received, continuing process
  116. 100 => 'Continue',
  117. 101 => 'Switching Protocols',
  118. // 2xx: Success - The action was successfully received, understood and
  119. // accepted
  120. 200 => 'OK',
  121. 201 => 'Created',
  122. 202 => 'Accepted',
  123. 203 => 'Non-Authoritative Information',
  124. 204 => 'No Content',
  125. 205 => 'Reset Content',
  126. 206 => 'Partial Content',
  127. // 3xx: Redirection - Further action must be taken in order to complete
  128. // the request
  129. 300 => 'Multiple Choices',
  130. 301 => 'Moved Permanently',
  131. 302 => 'Found', // 1.1
  132. 303 => 'See Other',
  133. 304 => 'Not Modified',
  134. 305 => 'Use Proxy',
  135. 307 => 'Temporary Redirect',
  136. // 4xx: Client Error - The request contains bad syntax or cannot be
  137. // fulfilled
  138. 400 => 'Bad Request',
  139. 401 => 'Unauthorized',
  140. 402 => 'Payment Required',
  141. 403 => 'Forbidden',
  142. 404 => 'Not Found',
  143. 405 => 'Method Not Allowed',
  144. 406 => 'Not Acceptable',
  145. 407 => 'Proxy Authentication Required',
  146. 408 => 'Request Timeout',
  147. 409 => 'Conflict',
  148. 410 => 'Gone',
  149. 411 => 'Length Required',
  150. 412 => 'Precondition Failed',
  151. 413 => 'Request Entity Too Large',
  152. 414 => 'Request-URI Too Long',
  153. 415 => 'Unsupported Media Type',
  154. 416 => 'Requested Range Not Satisfiable',
  155. 417 => 'Expectation Failed',
  156. // 5xx: Server Error - The server failed to fulfill an apparently
  157. // valid request
  158. 500 => 'Internal Server Error',
  159. 501 => 'Not Implemented',
  160. 502 => 'Bad Gateway',
  161. 503 => 'Service Unavailable',
  162. 504 => 'Gateway Timeout',
  163. 505 => 'HTTP Version Not Supported',
  164. 509 => 'Bandwidth Limit Exceeded',
  165. );
  166. /**
  167. * Returns the default reason phrase for the given code or all reason phrases
  168. *
  169. * @param int $code Response code
  170. *
  171. * @return string|array|null Default reason phrase for $code if $code is given
  172. * (null if no phrase is available), array of all
  173. * reason phrases if $code is null
  174. * @link http://pear.php.net/bugs/18716
  175. */
  176. public static function getDefaultReasonPhrase($code = null)
  177. {
  178. if (null === $code) {
  179. return self::$phrases;
  180. } else {
  181. return isset(self::$phrases[$code]) ? self::$phrases[$code] : null;
  182. }
  183. }
  184. /**
  185. * Constructor, parses the response status line
  186. *
  187. * @param string $statusLine Response status line (e.g. "HTTP/1.1 200 OK")
  188. * @param bool $bodyEncoded Whether body is still encoded by Content-Encoding
  189. * @param string $effectiveUrl Effective URL of the response
  190. *
  191. * @throws HTTP_Request2_MessageException if status line is invalid according to spec
  192. */
  193. public function __construct($statusLine, $bodyEncoded = true, $effectiveUrl = null)
  194. {
  195. if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {
  196. throw new HTTP_Request2_MessageException(
  197. "Malformed response: {$statusLine}",
  198. HTTP_Request2_Exception::MALFORMED_RESPONSE
  199. );
  200. }
  201. $this->version = $m[1];
  202. $this->code = intval($m[2]);
  203. $this->reasonPhrase = !empty($m[3]) ? trim($m[3]) : self::getDefaultReasonPhrase($this->code);
  204. $this->bodyEncoded = (bool)$bodyEncoded;
  205. $this->effectiveUrl = (string)$effectiveUrl;
  206. }
  207. /**
  208. * Parses the line from HTTP response filling $headers array
  209. *
  210. * The method should be called after reading the line from socket or receiving
  211. * it into cURL callback. Passing an empty string here indicates the end of
  212. * response headers and triggers additional processing, so be sure to pass an
  213. * empty string in the end.
  214. *
  215. * @param string $headerLine Line from HTTP response
  216. */
  217. public function parseHeaderLine($headerLine)
  218. {
  219. $headerLine = trim($headerLine, "\r\n");
  220. if ('' == $headerLine) {
  221. // empty string signals the end of headers, process the received ones
  222. if (!empty($this->headers['set-cookie'])) {
  223. $cookies = is_array($this->headers['set-cookie'])?
  224. $this->headers['set-cookie']:
  225. array($this->headers['set-cookie']);
  226. foreach ($cookies as $cookieString) {
  227. $this->parseCookie($cookieString);
  228. }
  229. unset($this->headers['set-cookie']);
  230. }
  231. foreach (array_keys($this->headers) as $k) {
  232. if (is_array($this->headers[$k])) {
  233. $this->headers[$k] = implode(', ', $this->headers[$k]);
  234. }
  235. }
  236. } elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {
  237. // string of the form header-name: header value
  238. $name = strtolower($m[1]);
  239. $value = trim($m[2]);
  240. if (empty($this->headers[$name])) {
  241. $this->headers[$name] = $value;
  242. } else {
  243. if (!is_array($this->headers[$name])) {
  244. $this->headers[$name] = array($this->headers[$name]);
  245. }
  246. $this->headers[$name][] = $value;
  247. }
  248. $this->lastHeader = $name;
  249. } elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {
  250. // continuation of a previous header
  251. if (!is_array($this->headers[$this->lastHeader])) {
  252. $this->headers[$this->lastHeader] .= ' ' . trim($m[1]);
  253. } else {
  254. $key = count($this->headers[$this->lastHeader]) - 1;
  255. $this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);
  256. }
  257. }
  258. }
  259. /**
  260. * Parses a Set-Cookie header to fill $cookies array
  261. *
  262. * @param string $cookieString value of Set-Cookie header
  263. *
  264. * @link http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html
  265. */
  266. protected function parseCookie($cookieString)
  267. {
  268. $cookie = array(
  269. 'expires' => null,
  270. 'domain' => null,
  271. 'path' => null,
  272. 'secure' => false
  273. );
  274. if (!strpos($cookieString, ';')) {
  275. // Only a name=value pair
  276. $pos = strpos($cookieString, '=');
  277. $cookie['name'] = trim(substr($cookieString, 0, $pos));
  278. $cookie['value'] = trim(substr($cookieString, $pos + 1));
  279. } else {
  280. // Some optional parameters are supplied
  281. $elements = explode(';', $cookieString);
  282. $pos = strpos($elements[0], '=');
  283. $cookie['name'] = trim(substr($elements[0], 0, $pos));
  284. $cookie['value'] = trim(substr($elements[0], $pos + 1));
  285. for ($i = 1; $i < count($elements); $i++) {
  286. if (false === strpos($elements[$i], '=')) {
  287. $elName = trim($elements[$i]);
  288. $elValue = null;
  289. } else {
  290. list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
  291. }
  292. $elName = strtolower($elName);
  293. if ('secure' == $elName) {
  294. $cookie['secure'] = true;
  295. } elseif ('expires' == $elName) {
  296. $cookie['expires'] = str_replace('"', '', $elValue);
  297. } elseif ('path' == $elName || 'domain' == $elName) {
  298. $cookie[$elName] = urldecode($elValue);
  299. } else {
  300. $cookie[$elName] = $elValue;
  301. }
  302. }
  303. }
  304. $this->cookies[] = $cookie;
  305. }
  306. /**
  307. * Appends a string to the response body
  308. *
  309. * @param string $bodyChunk part of response body
  310. */
  311. public function appendBody($bodyChunk)
  312. {
  313. $this->body .= $bodyChunk;
  314. }
  315. /**
  316. * Returns the effective URL of the response
  317. *
  318. * This may be different from the request URL if redirects were followed.
  319. *
  320. * @return string
  321. * @link http://pear.php.net/bugs/bug.php?id=18412
  322. */
  323. public function getEffectiveUrl()
  324. {
  325. return $this->effectiveUrl;
  326. }
  327. /**
  328. * Returns the status code
  329. *
  330. * @return integer
  331. */
  332. public function getStatus()
  333. {
  334. return $this->code;
  335. }
  336. /**
  337. * Returns the reason phrase
  338. *
  339. * @return string
  340. */
  341. public function getReasonPhrase()
  342. {
  343. return $this->reasonPhrase;
  344. }
  345. /**
  346. * Whether response is a redirect that can be automatically handled by HTTP_Request2
  347. *
  348. * @return bool
  349. */
  350. public function isRedirect()
  351. {
  352. return in_array($this->code, array(300, 301, 302, 303, 307))
  353. && isset($this->headers['location']);
  354. }
  355. /**
  356. * Returns either the named header or all response headers
  357. *
  358. * @param string $headerName Name of header to return
  359. *
  360. * @return string|array Value of $headerName header (null if header is
  361. * not present), array of all response headers if
  362. * $headerName is null
  363. */
  364. public function getHeader($headerName = null)
  365. {
  366. if (null === $headerName) {
  367. return $this->headers;
  368. } else {
  369. $headerName = strtolower($headerName);
  370. return isset($this->headers[$headerName])? $this->headers[$headerName]: null;
  371. }
  372. }
  373. /**
  374. * Returns cookies set in response
  375. *
  376. * @return array
  377. */
  378. public function getCookies()
  379. {
  380. return $this->cookies;
  381. }
  382. /**
  383. * Returns the body of the response
  384. *
  385. * @return string
  386. * @throws HTTP_Request2_Exception if body cannot be decoded
  387. */
  388. public function getBody()
  389. {
  390. if (0 == strlen($this->body) || !$this->bodyEncoded
  391. || !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))
  392. ) {
  393. return $this->body;
  394. } else {
  395. if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
  396. $oldEncoding = mb_internal_encoding();
  397. mb_internal_encoding('8bit');
  398. }
  399. try {
  400. switch (strtolower($this->getHeader('content-encoding'))) {
  401. case 'gzip':
  402. $decoded = self::decodeGzip($this->body);
  403. break;
  404. case 'deflate':
  405. $decoded = self::decodeDeflate($this->body);
  406. }
  407. } catch (Exception $e) {
  408. }
  409. if (!empty($oldEncoding)) {
  410. mb_internal_encoding($oldEncoding);
  411. }
  412. if (!empty($e)) {
  413. throw $e;
  414. }
  415. return $decoded;
  416. }
  417. }
  418. /**
  419. * Get the HTTP version of the response
  420. *
  421. * @return string
  422. */
  423. public function getVersion()
  424. {
  425. return $this->version;
  426. }
  427. /**
  428. * Checks whether data starts with GZIP format identification bytes from RFC 1952
  429. *
  430. * @param string $data gzip-encoded (presumably) data
  431. *
  432. * @return bool
  433. */
  434. public static function hasGzipIdentification($data)
  435. {
  436. return 0 === strcmp(substr($data, 0, 2), "\x1f\x8b");
  437. }
  438. /**
  439. * Tries to parse GZIP format header in the given string
  440. *
  441. * If the header conforms to RFC 1952, its length is returned. If any
  442. * sanity check fails, HTTP_Request2_MessageException is thrown.
  443. *
  444. * Note: This function might be usable outside of HTTP_Request2 so it might
  445. * be good idea to be moved to some common package. (Delian Krustev)
  446. *
  447. * @param string $data Either the complete response body or
  448. * the leading part of it
  449. * @param boolean $dataComplete Whether $data contains complete response body
  450. *
  451. * @return int gzip header length in bytes
  452. * @throws HTTP_Request2_MessageException
  453. * @link http://tools.ietf.org/html/rfc1952
  454. */
  455. public static function parseGzipHeader($data, $dataComplete = false)
  456. {
  457. // if data is complete, trailing 8 bytes should be present for size and crc32
  458. $length = strlen($data) - ($dataComplete ? 8 : 0);
  459. if ($length < 10 || !self::hasGzipIdentification($data)) {
  460. throw new HTTP_Request2_MessageException(
  461. 'The data does not seem to contain a valid gzip header',
  462. HTTP_Request2_Exception::DECODE_ERROR
  463. );
  464. }
  465. $method = ord(substr($data, 2, 1));
  466. if (8 != $method) {
  467. throw new HTTP_Request2_MessageException(
  468. 'Error parsing gzip header: unknown compression method',
  469. HTTP_Request2_Exception::DECODE_ERROR
  470. );
  471. }
  472. $flags = ord(substr($data, 3, 1));
  473. if ($flags & 224) {
  474. throw new HTTP_Request2_MessageException(
  475. 'Error parsing gzip header: reserved bits are set',
  476. HTTP_Request2_Exception::DECODE_ERROR
  477. );
  478. }
  479. // header is 10 bytes minimum. may be longer, though.
  480. $headerLength = 10;
  481. // extra fields, need to skip 'em
  482. if ($flags & 4) {
  483. if ($length - $headerLength - 2 < 0) {
  484. throw new HTTP_Request2_MessageException(
  485. 'Error parsing gzip header: data too short',
  486. HTTP_Request2_Exception::DECODE_ERROR
  487. );
  488. }
  489. $extraLength = unpack('v', substr($data, 10, 2));
  490. if ($length - $headerLength - 2 - $extraLength[1] < 0) {
  491. throw new HTTP_Request2_MessageException(
  492. 'Error parsing gzip header: data too short',
  493. HTTP_Request2_Exception::DECODE_ERROR
  494. );
  495. }
  496. $headerLength += $extraLength[1] + 2;
  497. }
  498. // file name, need to skip that
  499. if ($flags & 8) {
  500. if ($length - $headerLength - 1 < 0) {
  501. throw new HTTP_Request2_MessageException(
  502. 'Error parsing gzip header: data too short',
  503. HTTP_Request2_Exception::DECODE_ERROR
  504. );
  505. }
  506. $filenameLength = strpos(substr($data, $headerLength), chr(0));
  507. if (false === $filenameLength
  508. || $length - $headerLength - $filenameLength - 1 < 0
  509. ) {
  510. throw new HTTP_Request2_MessageException(
  511. 'Error parsing gzip header: data too short',
  512. HTTP_Request2_Exception::DECODE_ERROR
  513. );
  514. }
  515. $headerLength += $filenameLength + 1;
  516. }
  517. // comment, need to skip that also
  518. if ($flags & 16) {
  519. if ($length - $headerLength - 1 < 0) {
  520. throw new HTTP_Request2_MessageException(
  521. 'Error parsing gzip header: data too short',
  522. HTTP_Request2_Exception::DECODE_ERROR
  523. );
  524. }
  525. $commentLength = strpos(substr($data, $headerLength), chr(0));
  526. if (false === $commentLength
  527. || $length - $headerLength - $commentLength - 1 < 0
  528. ) {
  529. throw new HTTP_Request2_MessageException(
  530. 'Error parsing gzip header: data too short',
  531. HTTP_Request2_Exception::DECODE_ERROR
  532. );
  533. }
  534. $headerLength += $commentLength + 1;
  535. }
  536. // have a CRC for header. let's check
  537. if ($flags & 2) {
  538. if ($length - $headerLength - 2 < 0) {
  539. throw new HTTP_Request2_MessageException(
  540. 'Error parsing gzip header: data too short',
  541. HTTP_Request2_Exception::DECODE_ERROR
  542. );
  543. }
  544. $crcReal = 0xffff & crc32(substr($data, 0, $headerLength));
  545. $crcStored = unpack('v', substr($data, $headerLength, 2));
  546. if ($crcReal != $crcStored[1]) {
  547. throw new HTTP_Request2_MessageException(
  548. 'Header CRC check failed',
  549. HTTP_Request2_Exception::DECODE_ERROR
  550. );
  551. }
  552. $headerLength += 2;
  553. }
  554. return $headerLength;
  555. }
  556. /**
  557. * Decodes the message-body encoded by gzip
  558. *
  559. * The real decoding work is done by gzinflate() built-in function, this
  560. * method only parses the header and checks data for compliance with
  561. * RFC 1952
  562. *
  563. * @param string $data gzip-encoded data
  564. *
  565. * @return string decoded data
  566. * @throws HTTP_Request2_LogicException
  567. * @throws HTTP_Request2_MessageException
  568. * @link http://tools.ietf.org/html/rfc1952
  569. */
  570. public static function decodeGzip($data)
  571. {
  572. // If it doesn't look like gzip-encoded data, don't bother
  573. if (!self::hasGzipIdentification($data)) {
  574. return $data;
  575. }
  576. if (!function_exists('gzinflate')) {
  577. throw new HTTP_Request2_LogicException(
  578. 'Unable to decode body: gzip extension not available',
  579. HTTP_Request2_Exception::MISCONFIGURATION
  580. );
  581. }
  582. // unpacked data CRC and size at the end of encoded data
  583. $tmp = unpack('V2', substr($data, -8));
  584. $dataCrc = $tmp[1];
  585. $dataSize = $tmp[2];
  586. $headerLength = self::parseGzipHeader($data, true);
  587. // don't pass $dataSize to gzinflate, see bugs #13135, #14370
  588. $unpacked = gzinflate(substr($data, $headerLength, -8));
  589. if (false === $unpacked) {
  590. throw new HTTP_Request2_MessageException(
  591. 'gzinflate() call failed',
  592. HTTP_Request2_Exception::DECODE_ERROR
  593. );
  594. } elseif ($dataSize != strlen($unpacked)) {
  595. throw new HTTP_Request2_MessageException(
  596. 'Data size check failed',
  597. HTTP_Request2_Exception::DECODE_ERROR
  598. );
  599. } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {
  600. throw new HTTP_Request2_MessageException(
  601. 'Data CRC check failed',
  602. HTTP_Request2_Exception::DECODE_ERROR
  603. );
  604. }
  605. return $unpacked;
  606. }
  607. /**
  608. * Decodes the message-body encoded by deflate
  609. *
  610. * @param string $data deflate-encoded data
  611. *
  612. * @return string decoded data
  613. * @throws HTTP_Request2_LogicException
  614. */
  615. public static function decodeDeflate($data)
  616. {
  617. if (!function_exists('gzuncompress')) {
  618. throw new HTTP_Request2_LogicException(
  619. 'Unable to decode body: gzip extension not available',
  620. HTTP_Request2_Exception::MISCONFIGURATION
  621. );
  622. }
  623. // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,
  624. // while many applications send raw deflate stream from RFC 1951.
  625. // We should check for presence of zlib header and use gzuncompress() or
  626. // gzinflate() as needed. See bug #15305
  627. $header = unpack('n', substr($data, 0, 2));
  628. return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);
  629. }
  630. }
  631. ?>