[ Index ]

PHP Cross Reference of WordPress

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


Generated: Tue Dec 24 01:00:02 2024 Cross-referenced by PHPXref 0.7.1