PageRenderTime 30ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

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

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