[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-http-streams.php (source)

   1  <?php
   2  /**
   3   * HTTP API: WP_Http_Streams class
   4   *
   5   * @package WordPress
   6   * @subpackage HTTP
   7   * @since 4.4.0
   8   */
   9  
  10  /**
  11   * Core class used to integrate PHP Streams as an HTTP transport.
  12   *
  13   * @since 2.7.0
  14   * @since 3.7.0 Combined with the fsockopen transport and switched to `stream_socket_client()`.
  15   */
  16  #[AllowDynamicProperties]
  17  class WP_Http_Streams {
  18      /**
  19       * Send a HTTP request to a URI using PHP Streams.
  20       *
  21       * @see WP_Http::request() For default options descriptions.
  22       *
  23       * @since 2.7.0
  24       * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
  25       *
  26       * @param string       $url  The request URL.
  27       * @param string|array $args Optional. Override the defaults.
  28       * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error
  29       */
  30  	public function request( $url, $args = array() ) {
  31          $defaults = array(
  32              'method'      => 'GET',
  33              'timeout'     => 5,
  34              'redirection' => 5,
  35              'httpversion' => '1.0',
  36              'blocking'    => true,
  37              'headers'     => array(),
  38              'body'        => null,
  39              'cookies'     => array(),
  40          );
  41  
  42          $parsed_args = wp_parse_args( $args, $defaults );
  43  
  44          if ( isset( $parsed_args['headers']['User-Agent'] ) ) {
  45              $parsed_args['user-agent'] = $parsed_args['headers']['User-Agent'];
  46              unset( $parsed_args['headers']['User-Agent'] );
  47          } elseif ( isset( $parsed_args['headers']['user-agent'] ) ) {
  48              $parsed_args['user-agent'] = $parsed_args['headers']['user-agent'];
  49              unset( $parsed_args['headers']['user-agent'] );
  50          }
  51  
  52          // Construct Cookie: header if any cookies are set.
  53          WP_Http::buildCookieHeader( $parsed_args );
  54  
  55          $parsed_url = parse_url( $url );
  56  
  57          $connect_host = $parsed_url['host'];
  58  
  59          $secure_transport = ( 'ssl' === $parsed_url['scheme'] || 'https' === $parsed_url['scheme'] );
  60          if ( ! isset( $parsed_url['port'] ) ) {
  61              if ( 'ssl' === $parsed_url['scheme'] || 'https' === $parsed_url['scheme'] ) {
  62                  $parsed_url['port'] = 443;
  63                  $secure_transport   = true;
  64              } else {
  65                  $parsed_url['port'] = 80;
  66              }
  67          }
  68  
  69          // Always pass a path, defaulting to the root in cases such as http://example.com.
  70          if ( ! isset( $parsed_url['path'] ) ) {
  71              $parsed_url['path'] = '/';
  72          }
  73  
  74          if ( isset( $parsed_args['headers']['Host'] ) || isset( $parsed_args['headers']['host'] ) ) {
  75              if ( isset( $parsed_args['headers']['Host'] ) ) {
  76                  $parsed_url['host'] = $parsed_args['headers']['Host'];
  77              } else {
  78                  $parsed_url['host'] = $parsed_args['headers']['host'];
  79              }
  80              unset( $parsed_args['headers']['Host'], $parsed_args['headers']['host'] );
  81          }
  82  
  83          /*
  84           * Certain versions of PHP have issues with 'localhost' and IPv6, It attempts to connect
  85           * to ::1, which fails when the server is not set up for it. For compatibility, always
  86           * connect to the IPv4 address.
  87           */
  88          if ( 'localhost' === strtolower( $connect_host ) ) {
  89              $connect_host = '127.0.0.1';
  90          }
  91  
  92          $connect_host = $secure_transport ? 'ssl://' . $connect_host : 'tcp://' . $connect_host;
  93  
  94          $is_local   = isset( $parsed_args['local'] ) && $parsed_args['local'];
  95          $ssl_verify = isset( $parsed_args['sslverify'] ) && $parsed_args['sslverify'];
  96  
  97          if ( $is_local ) {
  98              /**
  99               * Filters whether SSL should be verified for local HTTP API requests.
 100               *
 101               * @since 2.8.0
 102               * @since 5.1.0 The `$url` parameter was added.
 103               *
 104               * @param bool|string $ssl_verify Boolean to control whether to verify the SSL connection
 105               *                                or path to an SSL certificate.
 106               * @param string      $url        The request URL.
 107               */
 108              $ssl_verify = apply_filters( 'https_local_ssl_verify', $ssl_verify, $url );
 109          } elseif ( ! $is_local ) {
 110              /** This filter is documented in wp-includes/class-wp-http.php */
 111              $ssl_verify = apply_filters( 'https_ssl_verify', $ssl_verify, $url );
 112          }
 113  
 114          $proxy = new WP_HTTP_Proxy();
 115  
 116          $context = stream_context_create(
 117              array(
 118                  'ssl' => array(
 119                      'verify_peer'       => $ssl_verify,
 120                      // 'CN_match' => $parsed_url['host'], // This is handled by self::verify_ssl_certificate().
 121                      'capture_peer_cert' => $ssl_verify,
 122                      'SNI_enabled'       => true,
 123                      'cafile'            => $parsed_args['sslcertificates'],
 124                      'allow_self_signed' => ! $ssl_verify,
 125                  ),
 126              )
 127          );
 128  
 129          $timeout         = (int) floor( $parsed_args['timeout'] );
 130          $utimeout        = $timeout == $parsed_args['timeout'] ? 0 : 1000000 * $parsed_args['timeout'] % 1000000;
 131          $connect_timeout = max( $timeout, 1 );
 132  
 133          // Store error number.
 134          $connection_error = null;
 135  
 136          // Store error string.
 137          $connection_error_str = null;
 138  
 139          if ( ! WP_DEBUG ) {
 140              // In the event that the SSL connection fails, silence the many PHP warnings.
 141              if ( $secure_transport ) {
 142                  $error_reporting = error_reporting( 0 );
 143              }
 144  
 145              if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
 146                  // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
 147                  $handle = @stream_socket_client(
 148                      'tcp://' . $proxy->host() . ':' . $proxy->port(),
 149                      $connection_error,
 150                      $connection_error_str,
 151                      $connect_timeout,
 152                      STREAM_CLIENT_CONNECT,
 153                      $context
 154                  );
 155              } else {
 156                  // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
 157                  $handle = @stream_socket_client(
 158                      $connect_host . ':' . $parsed_url['port'],
 159                      $connection_error,
 160                      $connection_error_str,
 161                      $connect_timeout,
 162                      STREAM_CLIENT_CONNECT,
 163                      $context
 164                  );
 165              }
 166  
 167              if ( $secure_transport ) {
 168                  error_reporting( $error_reporting );
 169              }
 170          } else {
 171              if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) {
 172                  $handle = stream_socket_client(
 173                      'tcp://' . $proxy->host() . ':' . $proxy->port(),
 174                      $connection_error,
 175                      $connection_error_str,
 176                      $connect_timeout,
 177                      STREAM_CLIENT_CONNECT,
 178                      $context
 179                  );
 180              } else {
 181                  $handle = stream_socket_client(
 182                      $connect_host . ':' . $parsed_url['port'],
 183                      $connection_error,
 184                      $connection_error_str,
 185                      $connect_timeout,
 186                      STREAM_CLIENT_CONNECT,
 187                      $context
 188                  );
 189              }
 190          }
 191  
 192          if ( false === $handle ) {
 193              // SSL connection failed due to expired/invalid cert, or, OpenSSL configuration is broken.
 194              if ( $secure_transport && 0 === $connection_error && '' === $connection_error_str ) {
 195                  return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
 196              }
 197  
 198              return new WP_Error( 'http_request_failed', $connection_error . ': ' . $connection_error_str );
 199          }
 200  
 201          // Verify that the SSL certificate is valid for this request.
 202          if ( $secure_transport && $ssl_verify && ! $proxy->is_enabled() ) {
 203              if ( ! self::verify_ssl_certificate( $handle, $parsed_url['host'] ) ) {
 204                  return new WP_Error( 'http_request_failed', __( 'The SSL certificate for the host could not be verified.' ) );
 205              }
 206          }
 207  
 208          stream_set_timeout( $handle, $timeout, $utimeout );
 209  
 210          if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { // Some proxies require full URL in this field.
 211              $request_path = $url;
 212          } else {
 213              $request_path = $parsed_url['path'] . ( isset( $parsed_url['query'] ) ? '?' . $parsed_url['query'] : '' );
 214          }
 215  
 216          $headers = strtoupper( $parsed_args['method'] ) . ' ' . $request_path . ' HTTP/' . $parsed_args['httpversion'] . "\r\n";
 217  
 218          $include_port_in_host_header = (
 219              ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) )
 220              || ( 'http' === $parsed_url['scheme'] && 80 != $parsed_url['port'] )
 221              || ( 'https' === $parsed_url['scheme'] && 443 != $parsed_url['port'] )
 222          );
 223  
 224          if ( $include_port_in_host_header ) {
 225              $headers .= 'Host: ' . $parsed_url['host'] . ':' . $parsed_url['port'] . "\r\n";
 226          } else {
 227              $headers .= 'Host: ' . $parsed_url['host'] . "\r\n";
 228          }
 229  
 230          if ( isset( $parsed_args['user-agent'] ) ) {
 231              $headers .= 'User-agent: ' . $parsed_args['user-agent'] . "\r\n";
 232          }
 233  
 234          if ( is_array( $parsed_args['headers'] ) ) {
 235              foreach ( (array) $parsed_args['headers'] as $header => $header_value ) {
 236                  $headers .= $header . ': ' . $header_value . "\r\n";
 237              }
 238          } else {
 239              $headers .= $parsed_args['headers'];
 240          }
 241  
 242          if ( $proxy->use_authentication() ) {
 243              $headers .= $proxy->authentication_header() . "\r\n";
 244          }
 245  
 246          $headers .= "\r\n";
 247  
 248          if ( ! is_null( $parsed_args['body'] ) ) {
 249              $headers .= $parsed_args['body'];
 250          }
 251  
 252          fwrite( $handle, $headers );
 253  
 254          if ( ! $parsed_args['blocking'] ) {
 255              stream_set_blocking( $handle, 0 );
 256              fclose( $handle );
 257              return array(
 258                  'headers'  => array(),
 259                  'body'     => '',
 260                  'response' => array(
 261                      'code'    => false,
 262                      'message' => false,
 263                  ),
 264                  'cookies'  => array(),
 265              );
 266          }
 267  
 268          $response     = '';
 269          $body_started = false;
 270          $keep_reading = true;
 271          $block_size   = 4096;
 272  
 273          if ( isset( $parsed_args['limit_response_size'] ) ) {
 274              $block_size = min( $block_size, $parsed_args['limit_response_size'] );
 275          }
 276  
 277          // If streaming to a file setup the file handle.
 278          if ( $parsed_args['stream'] ) {
 279              if ( ! WP_DEBUG ) {
 280                  $stream_handle = @fopen( $parsed_args['filename'], 'w+' );
 281              } else {
 282                  $stream_handle = fopen( $parsed_args['filename'], 'w+' );
 283              }
 284  
 285              if ( ! $stream_handle ) {
 286                  return new WP_Error(
 287                      'http_request_failed',
 288                      sprintf(
 289                          /* translators: 1: fopen(), 2: File name. */
 290                          __( 'Could not open handle for %1$s to %2$s.' ),
 291                          'fopen()',
 292                          $parsed_args['filename']
 293                      )
 294                  );
 295              }
 296  
 297              $bytes_written = 0;
 298  
 299              while ( ! feof( $handle ) && $keep_reading ) {
 300                  $block = fread( $handle, $block_size );
 301                  if ( ! $body_started ) {
 302                      $response .= $block;
 303                      if ( strpos( $response, "\r\n\r\n" ) ) {
 304                          $processed_response = WP_Http::processResponse( $response );
 305                          $body_started       = true;
 306                          $block              = $processed_response['body'];
 307                          unset( $response );
 308                          $processed_response['body'] = '';
 309                      }
 310                  }
 311  
 312                  $this_block_size = strlen( $block );
 313  
 314                  if ( isset( $parsed_args['limit_response_size'] )
 315                      && ( $bytes_written + $this_block_size ) > $parsed_args['limit_response_size']
 316                  ) {
 317                      $this_block_size = ( $parsed_args['limit_response_size'] - $bytes_written );
 318                      $block           = substr( $block, 0, $this_block_size );
 319                  }
 320  
 321                  $bytes_written_to_file = fwrite( $stream_handle, $block );
 322  
 323                  if ( $bytes_written_to_file != $this_block_size ) {
 324                      fclose( $handle );
 325                      fclose( $stream_handle );
 326                      return new WP_Error( 'http_request_failed', __( 'Failed to write request to temporary file.' ) );
 327                  }
 328  
 329                  $bytes_written += $bytes_written_to_file;
 330  
 331                  $keep_reading = (
 332                      ! isset( $parsed_args['limit_response_size'] )
 333                      || $bytes_written < $parsed_args['limit_response_size']
 334                  );
 335              }
 336  
 337              fclose( $stream_handle );
 338  
 339          } else {
 340              $header_length = 0;
 341  
 342              while ( ! feof( $handle ) && $keep_reading ) {
 343                  $block     = fread( $handle, $block_size );
 344                  $response .= $block;
 345  
 346                  if ( ! $body_started && strpos( $response, "\r\n\r\n" ) ) {
 347                      $header_length = strpos( $response, "\r\n\r\n" ) + 4;
 348                      $body_started  = true;
 349                  }
 350  
 351                  $keep_reading = (
 352                      ! $body_started
 353                      || ! isset( $parsed_args['limit_response_size'] )
 354                      || strlen( $response ) < ( $header_length + $parsed_args['limit_response_size'] )
 355                  );
 356              }
 357  
 358              $processed_response = WP_Http::processResponse( $response );
 359              unset( $response );
 360  
 361          }
 362  
 363          fclose( $handle );
 364  
 365          $processed_headers = WP_Http::processHeaders( $processed_response['headers'], $url );
 366  
 367          $response = array(
 368              'headers'  => $processed_headers['headers'],
 369              // Not yet processed.
 370              'body'     => null,
 371              'response' => $processed_headers['response'],
 372              'cookies'  => $processed_headers['cookies'],
 373              'filename' => $parsed_args['filename'],
 374          );
 375  
 376          // Handle redirects.
 377          $redirect_response = WP_Http::handle_redirects( $url, $parsed_args, $response );
 378          if ( false !== $redirect_response ) {
 379              return $redirect_response;
 380          }
 381  
 382          // If the body was chunk encoded, then decode it.
 383          if ( ! empty( $processed_response['body'] )
 384              && isset( $processed_headers['headers']['transfer-encoding'] )
 385              && 'chunked' === $processed_headers['headers']['transfer-encoding']
 386          ) {
 387              $processed_response['body'] = WP_Http::chunkTransferDecode( $processed_response['body'] );
 388          }
 389  
 390          if ( true === $parsed_args['decompress']
 391              && true === WP_Http_Encoding::should_decode( $processed_headers['headers'] )
 392          ) {
 393              $processed_response['body'] = WP_Http_Encoding::decompress( $processed_response['body'] );
 394          }
 395  
 396          if ( isset( $parsed_args['limit_response_size'] )
 397              && strlen( $processed_response['body'] ) > $parsed_args['limit_response_size']
 398          ) {
 399              $processed_response['body'] = substr( $processed_response['body'], 0, $parsed_args['limit_response_size'] );
 400          }
 401  
 402          $response['body'] = $processed_response['body'];
 403  
 404          return $response;
 405      }
 406  
 407      /**
 408       * Verifies the received SSL certificate against its Common Names and subjectAltName fields.
 409       *
 410       * PHP's SSL verifications only verify that it's a valid Certificate, it doesn't verify if
 411       * the certificate is valid for the hostname which was requested.
 412       * This function verifies the requested hostname against certificate's subjectAltName field,
 413       * if that is empty, or contains no DNS entries, a fallback to the Common Name field is used.
 414       *
 415       * IP Address support is included if the request is being made to an IP address.
 416       *
 417       * @since 3.7.0
 418       *
 419       * @param resource $stream The PHP Stream which the SSL request is being made over
 420       * @param string   $host   The hostname being requested
 421       * @return bool If the certificate presented in $stream is valid for $host
 422       */
 423  	public static function verify_ssl_certificate( $stream, $host ) {
 424          $context_options = stream_context_get_options( $stream );
 425  
 426          if ( empty( $context_options['ssl']['peer_certificate'] ) ) {
 427              return false;
 428          }
 429  
 430          $cert = openssl_x509_parse( $context_options['ssl']['peer_certificate'] );
 431          if ( ! $cert ) {
 432              return false;
 433          }
 434  
 435          /*
 436           * If the request is being made to an IP address, we'll validate against IP fields
 437           * in the cert (if they exist)
 438           */
 439          $host_type = ( WP_Http::is_ip_address( $host ) ? 'ip' : 'dns' );
 440  
 441          $certificate_hostnames = array();
 442          if ( ! empty( $cert['extensions']['subjectAltName'] ) ) {
 443              $match_against = preg_split( '/,\s*/', $cert['extensions']['subjectAltName'] );
 444              foreach ( $match_against as $match ) {
 445                  list( $match_type, $match_host ) = explode( ':', $match );
 446                  if ( strtolower( trim( $match_type ) ) === $host_type ) { // IP: or DNS:
 447                      $certificate_hostnames[] = strtolower( trim( $match_host ) );
 448                  }
 449              }
 450          } elseif ( ! empty( $cert['subject']['CN'] ) ) {
 451              // Only use the CN when the certificate includes no subjectAltName extension.
 452              $certificate_hostnames[] = strtolower( $cert['subject']['CN'] );
 453          }
 454  
 455          // Exact hostname/IP matches.
 456          if ( in_array( strtolower( $host ), $certificate_hostnames, true ) ) {
 457              return true;
 458          }
 459  
 460          // IP's can't be wildcards, Stop processing.
 461          if ( 'ip' === $host_type ) {
 462              return false;
 463          }
 464  
 465          // Test to see if the domain is at least 2 deep for wildcard support.
 466          if ( substr_count( $host, '.' ) < 2 ) {
 467              return false;
 468          }
 469  
 470          // Wildcard subdomains certs (*.example.com) are valid for a.example.com but not a.b.example.com.
 471          $wildcard_host = preg_replace( '/^[^.]+\./', '*.', $host );
 472  
 473          return in_array( strtolower( $wildcard_host ), $certificate_hostnames, true );
 474      }
 475  
 476      /**
 477       * Determines whether this class can be used for retrieving a URL.
 478       *
 479       * @since 2.7.0
 480       * @since 3.7.0 Combined with the fsockopen transport and switched to stream_socket_client().
 481       *
 482       * @param array $args Optional. Array of request arguments. Default empty array.
 483       * @return bool False means this class can not be used, true means it can.
 484       */
 485  	public static function test( $args = array() ) {
 486          if ( ! function_exists( 'stream_socket_client' ) ) {
 487              return false;
 488          }
 489  
 490          $is_ssl = isset( $args['ssl'] ) && $args['ssl'];
 491  
 492          if ( $is_ssl ) {
 493              if ( ! extension_loaded( 'openssl' ) ) {
 494                  return false;
 495              }
 496              if ( ! function_exists( 'openssl_x509_parse' ) ) {
 497                  return false;
 498              }
 499          }
 500  
 501          /**
 502           * Filters whether streams can be used as a transport for retrieving a URL.
 503           *
 504           * @since 2.7.0
 505           *
 506           * @param bool  $use_class Whether the class can be used. Default true.
 507           * @param array $args      Request arguments.
 508           */
 509          return apply_filters( 'use_streams_transport', true, $args );
 510      }
 511  }
 512  
 513  /**
 514   * Deprecated HTTP Transport method which used fsockopen.
 515   *
 516   * This class is not used, and is included for backward compatibility only.
 517   * All code should make use of WP_Http directly through its API.
 518   *
 519   * @see WP_HTTP::request
 520   *
 521   * @since 2.7.0
 522   * @deprecated 3.7.0 Please use WP_HTTP::request() directly
 523   */
 524  class WP_HTTP_Fsockopen extends WP_Http_Streams {
 525      // For backward compatibility for users who are using the class directly.
 526  }


Generated : Sun Jun 4 08:20:02 2023 Cross-referenced by PHPXref