Bez popisu

class-wp-http-streams.php 16KB

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