fsockopen.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. <?php
  2. /**
  3. * fsockopen HTTP transport
  4. *
  5. * @package Requests
  6. * @subpackage Transport
  7. */
  8. /**
  9. * fsockopen HTTP transport
  10. *
  11. * @package Requests
  12. * @subpackage Transport
  13. */
  14. class Requests_Transport_fsockopen implements Requests_Transport {
  15. /**
  16. * Second to microsecond conversion
  17. *
  18. * @var integer
  19. */
  20. const SECOND_IN_MICROSECONDS = 1000000;
  21. /**
  22. * Raw HTTP data
  23. *
  24. * @var string
  25. */
  26. public $headers = '';
  27. /**
  28. * Stream metadata
  29. *
  30. * @var array Associative array of properties, see {@see https://secure.php.net/stream_get_meta_data}
  31. */
  32. public $info;
  33. /**
  34. * What's the maximum number of bytes we should keep?
  35. *
  36. * @var int|bool Byte count, or false if no limit.
  37. */
  38. protected $max_bytes = false;
  39. protected $connect_error = '';
  40. /**
  41. * Perform a request
  42. *
  43. * @throws Requests_Exception On failure to connect to socket (`fsockopenerror`)
  44. * @throws Requests_Exception On socket timeout (`timeout`)
  45. *
  46. * @param string $url URL to request
  47. * @param array $headers Associative array of request headers
  48. * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
  49. * @param array $options Request options, see {@see Requests::response()} for documentation
  50. * @return string Raw HTTP result
  51. */
  52. public function request($url, $headers = array(), $data = array(), $options = array()) {
  53. $options['hooks']->dispatch('fsockopen.before_request');
  54. $url_parts = parse_url($url);
  55. if (empty($url_parts)) {
  56. throw new Requests_Exception('Invalid URL.', 'invalidurl', $url);
  57. }
  58. $host = $url_parts['host'];
  59. $context = stream_context_create();
  60. $verifyname = false;
  61. $case_insensitive_headers = new Requests_Utility_CaseInsensitiveDictionary($headers);
  62. // HTTPS support
  63. if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') {
  64. $remote_socket = 'ssl://' . $host;
  65. if (!isset($url_parts['port'])) {
  66. $url_parts['port'] = 443;
  67. }
  68. $context_options = array(
  69. 'verify_peer' => true,
  70. // 'CN_match' => $host,
  71. 'capture_peer_cert' => true
  72. );
  73. $verifyname = true;
  74. // SNI, if enabled (OpenSSL >=0.9.8j)
  75. if (defined('OPENSSL_TLSEXT_SERVER_NAME') && OPENSSL_TLSEXT_SERVER_NAME) {
  76. $context_options['SNI_enabled'] = true;
  77. if (isset($options['verifyname']) && $options['verifyname'] === false) {
  78. $context_options['SNI_enabled'] = false;
  79. }
  80. }
  81. if (isset($options['verify'])) {
  82. if ($options['verify'] === false) {
  83. $context_options['verify_peer'] = false;
  84. }
  85. elseif (is_string($options['verify'])) {
  86. $context_options['cafile'] = $options['verify'];
  87. }
  88. }
  89. if (isset($options['verifyname']) && $options['verifyname'] === false) {
  90. $context_options['verify_peer_name'] = false;
  91. $verifyname = false;
  92. }
  93. stream_context_set_option($context, array('ssl' => $context_options));
  94. }
  95. else {
  96. $remote_socket = 'tcp://' . $host;
  97. }
  98. $this->max_bytes = $options['max_bytes'];
  99. if (!isset($url_parts['port'])) {
  100. $url_parts['port'] = 80;
  101. }
  102. $remote_socket .= ':' . $url_parts['port'];
  103. set_error_handler(array($this, 'connect_error_handler'), E_WARNING | E_NOTICE);
  104. $options['hooks']->dispatch('fsockopen.remote_socket', array(&$remote_socket));
  105. $socket = stream_socket_client($remote_socket, $errno, $errstr, ceil($options['connect_timeout']), STREAM_CLIENT_CONNECT, $context);
  106. restore_error_handler();
  107. if ($verifyname && !$this->verify_certificate_from_context($host, $context)) {
  108. throw new Requests_Exception('SSL certificate did not match the requested domain name', 'ssl.no_match');
  109. }
  110. if (!$socket) {
  111. if ($errno === 0) {
  112. // Connection issue
  113. throw new Requests_Exception(rtrim($this->connect_error), 'fsockopen.connect_error');
  114. }
  115. throw new Requests_Exception($errstr, 'fsockopenerror', null, $errno);
  116. }
  117. $data_format = $options['data_format'];
  118. if ($data_format === 'query') {
  119. $path = self::format_get($url_parts, $data);
  120. $data = '';
  121. }
  122. else {
  123. $path = self::format_get($url_parts, array());
  124. }
  125. $options['hooks']->dispatch('fsockopen.remote_host_path', array(&$path, $url));
  126. $request_body = '';
  127. $out = sprintf("%s %s HTTP/%.1f\r\n", $options['type'], $path, $options['protocol_version']);
  128. if ($options['type'] !== Requests::TRACE) {
  129. if (is_array($data)) {
  130. $request_body = http_build_query($data, null, '&');
  131. }
  132. else {
  133. $request_body = $data;
  134. }
  135. if (!empty($data)) {
  136. if (!isset($case_insensitive_headers['Content-Length'])) {
  137. $headers['Content-Length'] = strlen($request_body);
  138. }
  139. if (!isset($case_insensitive_headers['Content-Type'])) {
  140. $headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  141. }
  142. }
  143. }
  144. if (!isset($case_insensitive_headers['Host'])) {
  145. $out .= sprintf('Host: %s', $url_parts['host']);
  146. if (( 'http' === strtolower($url_parts['scheme']) && $url_parts['port'] !== 80 ) || ( 'https' === strtolower($url_parts['scheme']) && $url_parts['port'] !== 443 )) {
  147. $out .= ':' . $url_parts['port'];
  148. }
  149. $out .= "\r\n";
  150. }
  151. if (!isset($case_insensitive_headers['User-Agent'])) {
  152. $out .= sprintf("User-Agent: %s\r\n", $options['useragent']);
  153. }
  154. $accept_encoding = $this->accept_encoding();
  155. if (!isset($case_insensitive_headers['Accept-Encoding']) && !empty($accept_encoding)) {
  156. $out .= sprintf("Accept-Encoding: %s\r\n", $accept_encoding);
  157. }
  158. $headers = Requests::flatten($headers);
  159. if (!empty($headers)) {
  160. $out .= implode($headers, "\r\n") . "\r\n";
  161. }
  162. $options['hooks']->dispatch('fsockopen.after_headers', array(&$out));
  163. if (substr($out, -2) !== "\r\n") {
  164. $out .= "\r\n";
  165. }
  166. if (!isset($case_insensitive_headers['Connection'])) {
  167. $out .= "Connection: Close\r\n";
  168. }
  169. $out .= "\r\n" . $request_body;
  170. $options['hooks']->dispatch('fsockopen.before_send', array(&$out));
  171. fwrite($socket, $out);
  172. $options['hooks']->dispatch('fsockopen.after_send', array($out));
  173. if (!$options['blocking']) {
  174. fclose($socket);
  175. $fake_headers = '';
  176. $options['hooks']->dispatch('fsockopen.after_request', array(&$fake_headers));
  177. return '';
  178. }
  179. $timeout_sec = (int) floor($options['timeout']);
  180. if ($timeout_sec == $options['timeout']) {
  181. $timeout_msec = 0;
  182. }
  183. else {
  184. $timeout_msec = self::SECOND_IN_MICROSECONDS * $options['timeout'] % self::SECOND_IN_MICROSECONDS;
  185. }
  186. stream_set_timeout($socket, $timeout_sec, $timeout_msec);
  187. $response = $body = $headers = '';
  188. $this->info = stream_get_meta_data($socket);
  189. $size = 0;
  190. $doingbody = false;
  191. $download = false;
  192. if ($options['filename']) {
  193. $download = fopen($options['filename'], 'wb');
  194. }
  195. while (!feof($socket)) {
  196. $this->info = stream_get_meta_data($socket);
  197. if ($this->info['timed_out']) {
  198. throw new Requests_Exception('fsocket timed out', 'timeout');
  199. }
  200. $block = fread($socket, Requests::BUFFER_SIZE);
  201. if (!$doingbody) {
  202. $response .= $block;
  203. if (strpos($response, "\r\n\r\n")) {
  204. list($headers, $block) = explode("\r\n\r\n", $response, 2);
  205. $doingbody = true;
  206. }
  207. }
  208. // Are we in body mode now?
  209. if ($doingbody) {
  210. $options['hooks']->dispatch('request.progress', array($block, $size, $this->max_bytes));
  211. $data_length = strlen($block);
  212. if ($this->max_bytes) {
  213. // Have we already hit a limit?
  214. if ($size === $this->max_bytes) {
  215. continue;
  216. }
  217. if (($size + $data_length) > $this->max_bytes) {
  218. // Limit the length
  219. $limited_length = ($this->max_bytes - $size);
  220. $block = substr($block, 0, $limited_length);
  221. }
  222. }
  223. $size += strlen($block);
  224. if ($download) {
  225. fwrite($download, $block);
  226. }
  227. else {
  228. $body .= $block;
  229. }
  230. }
  231. }
  232. $this->headers = $headers;
  233. if ($download) {
  234. fclose($download);
  235. }
  236. else {
  237. $this->headers .= "\r\n\r\n" . $body;
  238. }
  239. fclose($socket);
  240. $options['hooks']->dispatch('fsockopen.after_request', array(&$this->headers, &$this->info));
  241. return $this->headers;
  242. }
  243. /**
  244. * Send multiple requests simultaneously
  245. *
  246. * @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see Requests_Transport::request}
  247. * @param array $options Global options, see {@see Requests::response()} for documentation
  248. * @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well)
  249. */
  250. public function request_multiple($requests, $options) {
  251. $responses = array();
  252. $class = get_class($this);
  253. foreach ($requests as $id => $request) {
  254. try {
  255. $handler = new $class();
  256. $responses[$id] = $handler->request($request['url'], $request['headers'], $request['data'], $request['options']);
  257. $request['options']['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$id], $request));
  258. }
  259. catch (Requests_Exception $e) {
  260. $responses[$id] = $e;
  261. }
  262. if (!is_string($responses[$id])) {
  263. $request['options']['hooks']->dispatch('multiple.request.complete', array(&$responses[$id], $id));
  264. }
  265. }
  266. return $responses;
  267. }
  268. /**
  269. * Retrieve the encodings we can accept
  270. *
  271. * @return string Accept-Encoding header value
  272. */
  273. protected static function accept_encoding() {
  274. $type = array();
  275. if (function_exists('gzinflate')) {
  276. $type[] = 'deflate;q=1.0';
  277. }
  278. if (function_exists('gzuncompress')) {
  279. $type[] = 'compress;q=0.5';
  280. }
  281. $type[] = 'gzip;q=0.5';
  282. return implode(', ', $type);
  283. }
  284. /**
  285. * Format a URL given GET data
  286. *
  287. * @param array $url_parts
  288. * @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query}
  289. * @return string URL with data
  290. */
  291. protected static function format_get($url_parts, $data) {
  292. if (!empty($data)) {
  293. if (empty($url_parts['query'])) {
  294. $url_parts['query'] = '';
  295. }
  296. $url_parts['query'] .= '&' . http_build_query($data, null, '&');
  297. $url_parts['query'] = trim($url_parts['query'], '&');
  298. }
  299. if (isset($url_parts['path'])) {
  300. if (isset($url_parts['query'])) {
  301. $get = $url_parts['path'] . '?' . $url_parts['query'];
  302. }
  303. else {
  304. $get = $url_parts['path'];
  305. }
  306. }
  307. else {
  308. $get = '/';
  309. }
  310. return $get;
  311. }
  312. /**
  313. * Error handler for stream_socket_client()
  314. *
  315. * @param int $errno Error number (e.g. E_WARNING)
  316. * @param string $errstr Error message
  317. */
  318. public function connect_error_handler($errno, $errstr) {
  319. // Double-check we can handle it
  320. if (($errno & E_WARNING) === 0 && ($errno & E_NOTICE) === 0) {
  321. // Return false to indicate the default error handler should engage
  322. return false;
  323. }
  324. $this->connect_error .= $errstr . "\n";
  325. return true;
  326. }
  327. /**
  328. * Verify the certificate against common name and subject alternative names
  329. *
  330. * Unfortunately, PHP doesn't check the certificate against the alternative
  331. * names, leading things like 'https://www.github.com/' to be invalid.
  332. * Instead
  333. *
  334. * @see https://tools.ietf.org/html/rfc2818#section-3.1 RFC2818, Section 3.1
  335. *
  336. * @throws Requests_Exception On failure to connect via TLS (`fsockopen.ssl.connect_error`)
  337. * @throws Requests_Exception On not obtaining a match for the host (`fsockopen.ssl.no_match`)
  338. * @param string $host Host name to verify against
  339. * @param resource $context Stream context
  340. * @return bool
  341. */
  342. public function verify_certificate_from_context($host, $context) {
  343. $meta = stream_context_get_options($context);
  344. // If we don't have SSL options, then we couldn't make the connection at
  345. // all
  346. if (empty($meta) || empty($meta['ssl']) || empty($meta['ssl']['peer_certificate'])) {
  347. throw new Requests_Exception(rtrim($this->connect_error), 'ssl.connect_error');
  348. }
  349. $cert = openssl_x509_parse($meta['ssl']['peer_certificate']);
  350. return Requests_SSL::verify_certificate($host, $cert);
  351. }
  352. /**
  353. * Whether this transport is valid
  354. *
  355. * @codeCoverageIgnore
  356. * @return boolean True if the transport is valid, false otherwise.
  357. */
  358. public static function test($capabilities = array()) {
  359. if (!function_exists('fsockopen')) {
  360. return false;
  361. }
  362. // If needed, check that streams support SSL
  363. if (isset($capabilities['ssl']) && $capabilities['ssl']) {
  364. if (!extension_loaded('openssl') || !function_exists('openssl_x509_parse')) {
  365. return false;
  366. }
  367. // Currently broken, thanks to https://github.com/facebook/hhvm/issues/2156
  368. if (defined('HHVM_VERSION')) {
  369. return false;
  370. }
  371. }
  372. return true;
  373. }
  374. }