Response.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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-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. /**
  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.2.1
  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. * Decodes the message-body encoded by gzip
  429. *
  430. * The real decoding work is done by gzinflate() built-in function, this
  431. * method only parses the header and checks data for compliance with
  432. * RFC 1952
  433. *
  434. * @param string $data gzip-encoded data
  435. *
  436. * @return string decoded data
  437. * @throws HTTP_Request2_LogicException
  438. * @throws HTTP_Request2_MessageException
  439. * @link http://tools.ietf.org/html/rfc1952
  440. */
  441. public static function decodeGzip($data)
  442. {
  443. $length = strlen($data);
  444. // If it doesn't look like gzip-encoded data, don't bother
  445. if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
  446. return $data;
  447. }
  448. if (!function_exists('gzinflate')) {
  449. throw new HTTP_Request2_LogicException(
  450. 'Unable to decode body: gzip extension not available',
  451. HTTP_Request2_Exception::MISCONFIGURATION
  452. );
  453. }
  454. $method = ord(substr($data, 2, 1));
  455. if (8 != $method) {
  456. throw new HTTP_Request2_MessageException(
  457. 'Error parsing gzip header: unknown compression method',
  458. HTTP_Request2_Exception::DECODE_ERROR
  459. );
  460. }
  461. $flags = ord(substr($data, 3, 1));
  462. if ($flags & 224) {
  463. throw new HTTP_Request2_MessageException(
  464. 'Error parsing gzip header: reserved bits are set',
  465. HTTP_Request2_Exception::DECODE_ERROR
  466. );
  467. }
  468. // header is 10 bytes minimum. may be longer, though.
  469. $headerLength = 10;
  470. // extra fields, need to skip 'em
  471. if ($flags & 4) {
  472. if ($length - $headerLength - 2 < 8) {
  473. throw new HTTP_Request2_MessageException(
  474. 'Error parsing gzip header: data too short',
  475. HTTP_Request2_Exception::DECODE_ERROR
  476. );
  477. }
  478. $extraLength = unpack('v', substr($data, 10, 2));
  479. if ($length - $headerLength - 2 - $extraLength[1] < 8) {
  480. throw new HTTP_Request2_MessageException(
  481. 'Error parsing gzip header: data too short',
  482. HTTP_Request2_Exception::DECODE_ERROR
  483. );
  484. }
  485. $headerLength += $extraLength[1] + 2;
  486. }
  487. // file name, need to skip that
  488. if ($flags & 8) {
  489. if ($length - $headerLength - 1 < 8) {
  490. throw new HTTP_Request2_MessageException(
  491. 'Error parsing gzip header: data too short',
  492. HTTP_Request2_Exception::DECODE_ERROR
  493. );
  494. }
  495. $filenameLength = strpos(substr($data, $headerLength), chr(0));
  496. if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {
  497. throw new HTTP_Request2_MessageException(
  498. 'Error parsing gzip header: data too short',
  499. HTTP_Request2_Exception::DECODE_ERROR
  500. );
  501. }
  502. $headerLength += $filenameLength + 1;
  503. }
  504. // comment, need to skip that also
  505. if ($flags & 16) {
  506. if ($length - $headerLength - 1 < 8) {
  507. throw new HTTP_Request2_MessageException(
  508. 'Error parsing gzip header: data too short',
  509. HTTP_Request2_Exception::DECODE_ERROR
  510. );
  511. }
  512. $commentLength = strpos(substr($data, $headerLength), chr(0));
  513. if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {
  514. throw new HTTP_Request2_MessageException(
  515. 'Error parsing gzip header: data too short',
  516. HTTP_Request2_Exception::DECODE_ERROR
  517. );
  518. }
  519. $headerLength += $commentLength + 1;
  520. }
  521. // have a CRC for header. let's check
  522. if ($flags & 2) {
  523. if ($length - $headerLength - 2 < 8) {
  524. throw new HTTP_Request2_MessageException(
  525. 'Error parsing gzip header: data too short',
  526. HTTP_Request2_Exception::DECODE_ERROR
  527. );
  528. }
  529. $crcReal = 0xffff & crc32(substr($data, 0, $headerLength));
  530. $crcStored = unpack('v', substr($data, $headerLength, 2));
  531. if ($crcReal != $crcStored[1]) {
  532. throw new HTTP_Request2_MessageException(
  533. 'Header CRC check failed',
  534. HTTP_Request2_Exception::DECODE_ERROR
  535. );
  536. }
  537. $headerLength += 2;
  538. }
  539. // unpacked data CRC and size at the end of encoded data
  540. $tmp = unpack('V2', substr($data, -8));
  541. $dataCrc = $tmp[1];
  542. $dataSize = $tmp[2];
  543. // finally, call the gzinflate() function
  544. // don't pass $dataSize to gzinflate, see bugs #13135, #14370
  545. $unpacked = gzinflate(substr($data, $headerLength, -8));
  546. if (false === $unpacked) {
  547. throw new HTTP_Request2_MessageException(
  548. 'gzinflate() call failed',
  549. HTTP_Request2_Exception::DECODE_ERROR
  550. );
  551. } elseif ($dataSize != strlen($unpacked)) {
  552. throw new HTTP_Request2_MessageException(
  553. 'Data size check failed',
  554. HTTP_Request2_Exception::DECODE_ERROR
  555. );
  556. } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {
  557. throw new HTTP_Request2_Exception(
  558. 'Data CRC check failed',
  559. HTTP_Request2_Exception::DECODE_ERROR
  560. );
  561. }
  562. return $unpacked;
  563. }
  564. /**
  565. * Decodes the message-body encoded by deflate
  566. *
  567. * @param string $data deflate-encoded data
  568. *
  569. * @return string decoded data
  570. * @throws HTTP_Request2_LogicException
  571. */
  572. public static function decodeDeflate($data)
  573. {
  574. if (!function_exists('gzuncompress')) {
  575. throw new HTTP_Request2_LogicException(
  576. 'Unable to decode body: gzip extension not available',
  577. HTTP_Request2_Exception::MISCONFIGURATION
  578. );
  579. }
  580. // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,
  581. // while many applications send raw deflate stream from RFC 1951.
  582. // We should check for presence of zlib header and use gzuncompress() or
  583. // gzinflate() as needed. See bug #15305
  584. $header = unpack('n', substr($data, 0, 2));
  585. return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);
  586. }
  587. }
  588. ?>