class-wp-http-streams.php 16 KB

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