httpclient.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Utility for doing HTTP-related things
  6. *
  7. * PHP version 5
  8. *
  9. * LICENCE: This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. * @category Action
  23. * @package StatusNet
  24. * @author Evan Prodromou <evan@status.net>
  25. * @copyright 2009 StatusNet, Inc.
  26. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  27. * @link http://status.net/
  28. */
  29. if (!defined('GNUSOCIAL')) { exit(1); }
  30. /**
  31. * Useful structure for HTTP responses
  32. *
  33. * We make HTTP calls in several places, and we have several different
  34. * ways of doing them. This class hides the specifics of what underlying
  35. * library (curl or PHP-HTTP or whatever) that's used.
  36. *
  37. * This extends the HTTP_Request2_Response class with methods to get info
  38. * about any followed redirects.
  39. *
  40. * Originally used the name 'HTTPResponse' to match earlier code, but
  41. * this conflicts with a class in in the PECL HTTP extension.
  42. *
  43. * @category HTTP
  44. * @package StatusNet
  45. * @author Evan Prodromou <evan@status.net>
  46. * @author Brion Vibber <brion@status.net>
  47. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  48. * @link http://status.net/
  49. */
  50. class GNUsocial_HTTPResponse extends HTTP_Request2_Response
  51. {
  52. function __construct(HTTP_Request2_Response $response, $url, $redirects=0)
  53. {
  54. foreach (get_object_vars($response) as $key => $val) {
  55. $this->$key = $val;
  56. }
  57. $this->url = strval($url);
  58. $this->redirectCount = intval($redirects);
  59. }
  60. /**
  61. * Get the count of redirects that have been followed, if any.
  62. * @return int
  63. */
  64. function getRedirectCount()
  65. {
  66. return $this->redirectCount;
  67. }
  68. /**
  69. * Gets the target URL, before any redirects. Use getEffectiveUrl() for final target.
  70. * @return string URL
  71. */
  72. function getUrl()
  73. {
  74. return $this->url;
  75. }
  76. /**
  77. * Check if the response is OK, generally a 200 or other 2xx status code.
  78. * @return bool
  79. */
  80. function isOk()
  81. {
  82. $status = $this->getStatus();
  83. return ($status >= 200 && $status < 300);
  84. }
  85. }
  86. /**
  87. * Utility class for doing HTTP client stuff
  88. *
  89. * We make HTTP calls in several places, and we have several different
  90. * ways of doing them. This class hides the specifics of what underlying
  91. * library (curl or PHP-HTTP or whatever) that's used.
  92. *
  93. * This extends the PEAR HTTP_Request2 package:
  94. * - sends StatusNet-specific User-Agent header
  95. * - 'follow_redirects' config option, defaulting on
  96. * - 'max_redirs' config option, defaulting to 10
  97. * - extended response class adds getRedirectCount() and getUrl() methods
  98. * - get() and post() convenience functions return body content directly
  99. *
  100. * @category HTTP
  101. * @package StatusNet
  102. * @author Evan Prodromou <evan@status.net>
  103. * @author Brion Vibber <brion@status.net>
  104. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  105. * @link http://status.net/
  106. */
  107. class HTTPClient extends HTTP_Request2
  108. {
  109. function __construct($url=null, $method=self::METHOD_GET, $config=array())
  110. {
  111. $this->config['connect_timeout'] = common_config('http', 'connect_timeout') ?: $this->config['connect_timeout'];
  112. $this->config['max_redirs'] = 10;
  113. $this->config['follow_redirects'] = true;
  114. // We've had some issues with keepalive breaking with
  115. // HEAD requests, such as to youtube which seems to be
  116. // emitting chunked encoding info for an empty body
  117. // instead of not emitting anything. This may be a
  118. // bug on YouTube's end, but the upstream libray
  119. // ought to be investigated to see if we can handle
  120. // it gracefully in that case as well.
  121. $this->config['protocol_version'] = '1.0';
  122. // Default state of OpenSSL seems to have no trusted
  123. // SSL certificate authorities, which breaks hostname
  124. // verification and means we have a hard time communicating
  125. // with other sites' HTTPS interfaces.
  126. //
  127. // Turn off verification unless we've configured a CA bundle.
  128. if (common_config('http', 'ssl_cafile')) {
  129. $this->config['ssl_cafile'] = common_config('http', 'ssl_cafile');
  130. } else {
  131. $this->config['ssl_verify_peer'] = false;
  132. }
  133. // This means "verify the cert hostname against what we connect to", it does not
  134. // imply CA trust or anything like that. Just the hostname.
  135. $this->config['ssl_verify_host'] = common_config('http', 'ssl_verify_host');
  136. if (common_config('http', 'curl') && extension_loaded('curl')) {
  137. $this->config['adapter'] = 'HTTP_Request2_Adapter_Curl';
  138. }
  139. foreach (array('host', 'port', 'user', 'password', 'auth_scheme') as $cf) {
  140. $k = 'proxy_'.$cf;
  141. $v = common_config('http', $k);
  142. if (!empty($v)) {
  143. $this->config[$k] = $v;
  144. }
  145. }
  146. parent::__construct($url, $method, $config);
  147. $this->setHeader('User-Agent', self::userAgent());
  148. }
  149. /**
  150. * Convenience/back-compat instantiator
  151. * @return HTTPClient
  152. */
  153. public static function start()
  154. {
  155. return new HTTPClient();
  156. }
  157. /**
  158. * Quick static function to GET a URL
  159. */
  160. public static function quickGet($url, $accept=null, $params=array())
  161. {
  162. if (!empty($params)) {
  163. $params = http_build_query($params, null, '&');
  164. if (strpos($url, '?') === false) {
  165. $url .= '?' . $params;
  166. } else {
  167. $url .= '&' . $params;
  168. }
  169. }
  170. $client = new HTTPClient();
  171. if (!is_null($accept)) {
  172. $client->setHeader('Accept', $accept);
  173. }
  174. $response = $client->get($url);
  175. if (!$response->isOk()) {
  176. // TRANS: Exception. %s is the URL we tried to GET.
  177. throw new Exception(sprintf(_m('Could not GET URL %s.'), $url), $response->getStatus());
  178. }
  179. return $response->getBody();
  180. }
  181. public static function quickGetJson($url, $params=array())
  182. {
  183. $data = json_decode(self::quickGet($url, null, $params));
  184. if (is_null($data)) {
  185. common_debug('Could not decode JSON data from URL: '.$url);
  186. throw new ServerException('Could not decode JSON data from URL');
  187. }
  188. return $data;
  189. }
  190. /**
  191. * Convenience function to run a GET request.
  192. *
  193. * @return GNUsocial_HTTPResponse
  194. * @throws HTTP_Request2_Exception
  195. */
  196. public function get($url, $headers=array())
  197. {
  198. return $this->doRequest($url, self::METHOD_GET, $headers);
  199. }
  200. /**
  201. * Convenience function to run a HEAD request.
  202. *
  203. * NOTE: Will probably turn into a GET request if you let it follow redirects!
  204. * That option is only there to be flexible and may be removed in the future!
  205. *
  206. * @return GNUsocial_HTTPResponse
  207. * @throws HTTP_Request2_Exception
  208. */
  209. public function head($url, $headers=array(), $follow_redirects=false)
  210. {
  211. // Save the configured value for follow_redirects
  212. $old_follow = $this->config['follow_redirects'];
  213. try {
  214. // Temporarily (possibly) override the follow_redirects setting
  215. $this->config['follow_redirects'] = $follow_redirects;
  216. return $this->doRequest($url, self::METHOD_HEAD, $headers);
  217. } catch (Exception $e) {
  218. // Let the exception go on its merry way.
  219. throw $e;
  220. } finally {
  221. // reset to the old value
  222. $this->config['follow_redirects'] = $old_follow;
  223. }
  224. //we've either returned or thrown exception here
  225. }
  226. /**
  227. * Convenience function to POST form data.
  228. *
  229. * @param string $url
  230. * @param array $headers optional associative array of HTTP headers
  231. * @param array $data optional associative array or blob of form data to submit
  232. * @return GNUsocial_HTTPResponse
  233. * @throws HTTP_Request2_Exception
  234. */
  235. public function post($url, $headers=array(), $data=array())
  236. {
  237. if ($data) {
  238. $this->addPostParameter($data);
  239. }
  240. return $this->doRequest($url, self::METHOD_POST, $headers);
  241. }
  242. /**
  243. * @return GNUsocial_HTTPResponse
  244. * @throws HTTP_Request2_Exception
  245. */
  246. protected function doRequest($url, $method, $headers)
  247. {
  248. $this->setUrl($url);
  249. // Workaround for HTTP_Request2 not setting up SNI in socket contexts;
  250. // This fixes cert validation for SSL virtual hosts using SNI.
  251. // Requires PHP 5.3.2 or later and OpenSSL with SNI support.
  252. if ($this->url->getScheme() == 'https' && defined('OPENSSL_TLSEXT_SERVER_NAME')) {
  253. $this->config['ssl_SNI_enabled'] = true;
  254. $this->config['ssl_SNI_server_name'] = $this->url->getHost();
  255. }
  256. $this->setMethod($method);
  257. if ($headers) {
  258. foreach ($headers as $header) {
  259. $this->setHeader($header);
  260. }
  261. }
  262. $response = $this->send();
  263. if (is_null($response)) {
  264. // TRANS: Failed to retrieve a remote web resource, %s is the target URL.
  265. throw new NoHttpResponseException($url);
  266. }
  267. return $response;
  268. }
  269. protected function log($level, $detail) {
  270. $method = $this->getMethod();
  271. $url = $this->getUrl();
  272. common_log($level, __CLASS__ . ": HTTP $method $url - $detail");
  273. }
  274. /**
  275. * Pulls up GNU Social's customized user-agent string, so services
  276. * we hit can track down the responsible software.
  277. *
  278. * @return string
  279. */
  280. static public function userAgent()
  281. {
  282. return GNUSOCIAL_ENGINE . '/' . GNUSOCIAL_VERSION
  283. . ' (' . GNUSOCIAL_CODENAME . ')';
  284. }
  285. /**
  286. * Actually performs the HTTP request and returns a
  287. * GNUsocial_HTTPResponse object with response body and header info.
  288. *
  289. * Wraps around parent send() to add logging and redirection processing.
  290. *
  291. * @return GNUsocial_HTTPResponse
  292. * @throw HTTP_Request2_Exception
  293. */
  294. public function send()
  295. {
  296. $maxRedirs = intval($this->config['max_redirs']);
  297. if (empty($this->config['max_redirs'])) {
  298. $maxRedirs = 0;
  299. }
  300. $redirs = 0;
  301. $redirUrls = array();
  302. do {
  303. try {
  304. $response = parent::send();
  305. } catch (Exception $e) {
  306. $this->log(LOG_ERR, $e->getMessage());
  307. throw $e;
  308. }
  309. $code = $response->getStatus();
  310. $effectiveUrl = $response->getEffectiveUrl();
  311. $redirUrls[] = $effectiveUrl;
  312. $response->redirUrls = $redirUrls;
  313. if ($code >= 200 && $code < 300) {
  314. $reason = $response->getReasonPhrase();
  315. $this->log(LOG_INFO, "$code $reason");
  316. } elseif ($code >= 300 && $code < 400) {
  317. $url = $this->getUrl();
  318. $target = $response->getHeader('Location');
  319. if (++$redirs >= $maxRedirs) {
  320. common_log(LOG_ERR, __CLASS__ . ": Too many redirects: skipping $code redirect from $url to $target");
  321. break;
  322. }
  323. try {
  324. $this->setUrl($target);
  325. $this->setHeader('Referer', $url);
  326. common_log(LOG_INFO, __CLASS__ . ": Following $code redirect from $url to $target");
  327. continue;
  328. } catch (HTTP_Request2_Exception $e) {
  329. common_log(LOG_ERR, __CLASS__ . ": Invalid $code redirect from $url to $target");
  330. }
  331. } else {
  332. $reason = $response->getReasonPhrase();
  333. $this->log(LOG_ERR, "$code $reason");
  334. }
  335. break;
  336. } while ($maxRedirs);
  337. return new GNUsocial_HTTPResponse($response, $this->getUrl(), $redirs);
  338. }
  339. }