[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/Requests/src/Transport/ -> Fsockopen.php (source)

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


Generated : Thu Nov 19 08:20:01 2026 Cross-referenced by PHPXref