Fsockopen.php 15 KB

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