/wp-includes/class-wp-http-streams.php

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