/wp-includes/Requests/Transport/fsockopen.php

  1. <?php 
  2. /** 
  3. * fsockopen HTTP transport 
  4. * 
  5. * @package Requests 
  6. * @subpackage Transport 
  7. */ 
  8.  
  9. /** 
  10. * fsockopen HTTP transport 
  11. * 
  12. * @package Requests 
  13. * @subpackage Transport 
  14. */ 
  15. class Requests_Transport_fsockopen implements Requests_Transport { 
  16. /** 
  17. * Second to microsecond conversion 
  18. * 
  19. * @var integer 
  20. */ 
  21. const SECOND_IN_MICROSECONDS = 1000000; 
  22.  
  23. /** 
  24. * Raw HTTP data 
  25. * 
  26. * @var string 
  27. */ 
  28. public $headers = ''; 
  29.  
  30. /** 
  31. * Stream metadata 
  32. * 
  33. * @var array Associative array of properties, see {@see https://secure.php.net/stream_get_meta_data} 
  34. */ 
  35. public $info; 
  36.  
  37. /** 
  38. * What's the maximum number of bytes we should keep? 
  39. * 
  40. * @var int|bool Byte count, or false if no limit. 
  41. */ 
  42. protected $max_bytes = false; 
  43.  
  44. protected $connect_error = ''; 
  45.  
  46. /** 
  47. * Perform a request 
  48. * 
  49. * @throws Requests_Exception On failure to connect to socket (`fsockopenerror`) 
  50. * @throws Requests_Exception On socket timeout (`timeout`) 
  51. * 
  52. * @param string $url URL to request 
  53. * @param array $headers Associative array of request headers 
  54. * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD 
  55. * @param array $options Request options, see {@see Requests::response()} for documentation 
  56. * @return string Raw HTTP result 
  57. */ 
  58. public function request($url, $headers = array(), $data = array(), $options = array()) { 
  59. $options['hooks']->dispatch('fsockopen.before_request'); 
  60.  
  61. $url_parts = parse_url($url); 
  62. if (empty($url_parts)) { 
  63. throw new Requests_Exception('Invalid URL.', 'invalidurl', $url); 
  64. $host = $url_parts['host']; 
  65. $context = stream_context_create(); 
  66. $verifyname = false; 
  67. $case_insensitive_headers = new Requests_Utility_CaseInsensitiveDictionary($headers); 
  68.  
  69. // HTTPS support 
  70. if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') { 
  71. $remote_socket = 'ssl://' . $host; 
  72. if (!isset($url_parts['port'])) { 
  73. $url_parts['port'] = 443; 
  74.  
  75. $context_options = array( 
  76. 'verify_peer' => true,  
  77. // 'CN_match' => $host,  
  78. 'capture_peer_cert' => true 
  79. ); 
  80. $verifyname = true; 
  81.  
  82. // SNI, if enabled (OpenSSL >=0.9.8j) 
  83. if (defined('OPENSSL_TLSEXT_SERVER_NAME') && OPENSSL_TLSEXT_SERVER_NAME) { 
  84. $context_options['SNI_enabled'] = true; 
  85. if (isset($options['verifyname']) && $options['verifyname'] === false) { 
  86. $context_options['SNI_enabled'] = false; 
  87.  
  88. if (isset($options['verify'])) { 
  89. if ($options['verify'] === false) { 
  90. $context_options['verify_peer'] = false; 
  91. elseif (is_string($options['verify'])) { 
  92. $context_options['cafile'] = $options['verify']; 
  93.  
  94. if (isset($options['verifyname']) && $options['verifyname'] === false) { 
  95. $context_options['verify_peer_name'] = false; 
  96. $verifyname = false; 
  97.  
  98. stream_context_set_option($context, array('ssl' => $context_options)); 
  99. else { 
  100. $remote_socket = 'tcp://' . $host; 
  101.  
  102. $this->max_bytes = $options['max_bytes']; 
  103.  
  104. if (!isset($url_parts['port'])) { 
  105. $url_parts['port'] = 80; 
  106. $remote_socket .= ':' . $url_parts['port']; 
  107.  
  108. set_error_handler(array($this, 'connect_error_handler'), E_WARNING | E_NOTICE); 
  109.  
  110. $options['hooks']->dispatch('fsockopen.remote_socket', array(&$remote_socket)); 
  111.  
  112. $socket = stream_socket_client($remote_socket, $errno, $errstr, ceil($options['connect_timeout']), STREAM_CLIENT_CONNECT, $context); 
  113.  
  114. restore_error_handler(); 
  115.  
  116. if ($verifyname && !$this->verify_certificate_from_context($host, $context)) { 
  117. throw new Requests_Exception('SSL certificate did not match the requested domain name', 'ssl.no_match'); 
  118.  
  119. if (!$socket) { 
  120. if ($errno === 0) { 
  121. // Connection issue 
  122. throw new Requests_Exception(rtrim($this->connect_error), 'fsockopen.connect_error'); 
  123.  
  124. throw new Requests_Exception($errstr, 'fsockopenerror', null, $errno); 
  125.  
  126. $data_format = $options['data_format']; 
  127.  
  128. if ($data_format === 'query') { 
  129. $path = self::format_get($url_parts, $data); 
  130. $data = ''; 
  131. else { 
  132. $path = self::format_get($url_parts, array()); 
  133.  
  134. $options['hooks']->dispatch('fsockopen.remote_host_path', array(&$path, $url)); 
  135.  
  136. $request_body = ''; 
  137. $out = sprintf("%s %s HTTP/%.1f\r\n", $options['type'], $path, $options['protocol_version']); 
  138.  
  139. if ($options['type'] !== Requests::TRACE) { 
  140. if (is_array($data)) { 
  141. $request_body = http_build_query($data, null, '&'); 
  142. else { 
  143. $request_body = $data; 
  144.  
  145. if (!empty($data)) { 
  146. if (!isset($case_insensitive_headers['Content-Length'])) { 
  147. $headers['Content-Length'] = strlen($request_body); 
  148.  
  149. if (!isset($case_insensitive_headers['Content-Type'])) { 
  150. $headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; 
  151.  
  152. if (!isset($case_insensitive_headers['Host'])) { 
  153. $out .= sprintf('Host: %s', $url_parts['host']); 
  154.  
  155. if (( 'http' === strtolower($url_parts['scheme']) && $url_parts['port'] !== 80 ) || ( 'https' === strtolower($url_parts['scheme']) && $url_parts['port'] !== 443 )) { 
  156. $out .= ':' . $url_parts['port']; 
  157. $out .= "\r\n"; 
  158.  
  159. if (!isset($case_insensitive_headers['User-Agent'])) { 
  160. $out .= sprintf("User-Agent: %s\r\n", $options['useragent']); 
  161.  
  162. $accept_encoding = $this->accept_encoding(); 
  163. if (!isset($case_insensitive_headers['Accept-Encoding']) && !empty($accept_encoding)) { 
  164. $out .= sprintf("Accept-Encoding: %s\r\n", $accept_encoding); 
  165.  
  166. $headers = Requests::flatten($headers); 
  167.  
  168. if (!empty($headers)) { 
  169. $out .= implode($headers, "\r\n") . "\r\n"; 
  170.  
  171. $options['hooks']->dispatch('fsockopen.after_headers', array(&$out)); 
  172.  
  173. if (substr($out, -2) !== "\r\n") { 
  174. $out .= "\r\n"; 
  175.  
  176. if (!isset($case_insensitive_headers['Connection'])) { 
  177. $out .= "Connection: Close\r\n"; 
  178.  
  179. $out .= "\r\n" . $request_body; 
  180.  
  181. $options['hooks']->dispatch('fsockopen.before_send', array(&$out)); 
  182.  
  183. fwrite($socket, $out); 
  184. $options['hooks']->dispatch('fsockopen.after_send', array($out)); 
  185.  
  186. if (!$options['blocking']) { 
  187. fclose($socket); 
  188. $fake_headers = ''; 
  189. $options['hooks']->dispatch('fsockopen.after_request', array(&$fake_headers)); 
  190. return ''; 
  191.  
  192. $timeout_sec = (int) floor($options['timeout']); 
  193. if ($timeout_sec == $options['timeout']) { 
  194. $timeout_msec = 0; 
  195. else { 
  196. $timeout_msec = self::SECOND_IN_MICROSECONDS * $options['timeout'] % self::SECOND_IN_MICROSECONDS; 
  197. stream_set_timeout($socket, $timeout_sec, $timeout_msec); 
  198.  
  199. $response = $body = $headers = ''; 
  200. $this->info = stream_get_meta_data($socket); 
  201. $size = 0; 
  202. $doingbody = false; 
  203. $download = false; 
  204. if ($options['filename']) { 
  205. $download = fopen($options['filename'], 'wb'); 
  206.  
  207. while (!feof($socket)) { 
  208. $this->info = stream_get_meta_data($socket); 
  209. if ($this->info['timed_out']) { 
  210. throw new Requests_Exception('fsocket timed out', 'timeout'); 
  211.  
  212. $block = fread($socket, Requests::BUFFER_SIZE); 
  213. if (!$doingbody) { 
  214. $response .= $block; 
  215. if (strpos($response, "\r\n\r\n")) { 
  216. list($headers, $block) = explode("\r\n\r\n", $response, 2); 
  217. $doingbody = true; 
  218.  
  219. // Are we in body mode now? 
  220. if ($doingbody) { 
  221. $options['hooks']->dispatch('request.progress', array($block, $size, $this->max_bytes)); 
  222. $data_length = strlen($block); 
  223. if ($this->max_bytes) { 
  224. // Have we already hit a limit? 
  225. if ($size === $this->max_bytes) { 
  226. continue; 
  227. if (($size + $data_length) > $this->max_bytes) { 
  228. // Limit the length 
  229. $limited_length = ($this->max_bytes - $size); 
  230. $block = substr($block, 0, $limited_length); 
  231.  
  232. $size += strlen($block); 
  233. if ($download) { 
  234. fwrite($download, $block); 
  235. else { 
  236. $body .= $block; 
  237. $this->headers = $headers; 
  238.  
  239. if ($download) { 
  240. fclose($download); 
  241. else { 
  242. $this->headers .= "\r\n\r\n" . $body; 
  243. fclose($socket); 
  244.  
  245. $options['hooks']->dispatch('fsockopen.after_request', array(&$this->headers, &$this->info)); 
  246. return $this->headers; 
  247.  
  248. /** 
  249. * Send multiple requests simultaneously 
  250. * 
  251. * @param array $requests Request data (array of 'url', 'headers', 'data', 'options') as per {@see Requests_Transport::request} 
  252. * @param array $options Global options, see {@see Requests::response()} for documentation 
  253. * @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well) 
  254. */ 
  255. public function request_multiple($requests, $options) { 
  256. $responses = array(); 
  257. $class = get_class($this); 
  258. foreach ($requests as $id => $request) { 
  259. try { 
  260. $handler = new $class(); 
  261. $responses[$id] = $handler->request($request['url'], $request['headers'], $request['data'], $request['options']); 
  262.  
  263. $request['options']['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$id], $request)); 
  264. catch (Requests_Exception $e) { 
  265. $responses[$id] = $e; 
  266.  
  267. if (!is_string($responses[$id])) { 
  268. $request['options']['hooks']->dispatch('multiple.request.complete', array(&$responses[$id], $id)); 
  269.  
  270. return $responses; 
  271.  
  272. /** 
  273. * Retrieve the encodings we can accept 
  274. * 
  275. * @return string Accept-Encoding header value 
  276. */ 
  277. protected static function accept_encoding() { 
  278. $type = array(); 
  279. if (function_exists('gzinflate')) { 
  280. $type[] = 'deflate;q=1.0'; 
  281.  
  282. if (function_exists('gzuncompress')) { 
  283. $type[] = 'compress;q=0.5'; 
  284.  
  285. $type[] = 'gzip;q=0.5'; 
  286.  
  287. return implode(', ', $type); 
  288.  
  289. /** 
  290. * Format a URL given GET data 
  291. * 
  292. * @param array $url_parts 
  293. * @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query} 
  294. * @return string URL with data 
  295. */ 
  296. protected static function format_get($url_parts, $data) { 
  297. if (!empty($data)) { 
  298. if (empty($url_parts['query'])) { 
  299. $url_parts['query'] = ''; 
  300.  
  301. $url_parts['query'] .= '&' . http_build_query($data, null, '&'); 
  302. $url_parts['query'] = trim($url_parts['query'], '&'); 
  303. if (isset($url_parts['path'])) { 
  304. if (isset($url_parts['query'])) { 
  305. $get = $url_parts['path'] . '?' . $url_parts['query']; 
  306. else { 
  307. $get = $url_parts['path']; 
  308. else { 
  309. $get = '/'; 
  310. return $get; 
  311.  
  312. /** 
  313. * Error handler for stream_socket_client() 
  314. * 
  315. * @param int $errno Error number (e.g. E_WARNING) 
  316. * @param string $errstr Error message 
  317. */ 
  318. public function connect_error_handler($errno, $errstr) { 
  319. // Double-check we can handle it 
  320. if (($errno & E_WARNING) === 0 && ($errno & E_NOTICE) === 0) { 
  321. // Return false to indicate the default error handler should engage 
  322. return false; 
  323.  
  324. $this->connect_error .= $errstr . "\n"; 
  325. return true; 
  326.  
  327. /** 
  328. * Verify the certificate against common name and subject alternative names 
  329. * 
  330. * Unfortunately, PHP doesn't check the certificate against the alternative 
  331. * names, leading things like 'https://www.github.com/' to be invalid. 
  332. * Instead 
  333. * 
  334. * @see https://tools.ietf.org/html/rfc2818#section-3.1 RFC2818, Section 3.1 
  335. * 
  336. * @throws Requests_Exception On failure to connect via TLS (`fsockopen.ssl.connect_error`) 
  337. * @throws Requests_Exception On not obtaining a match for the host (`fsockopen.ssl.no_match`) 
  338. * @param string $host Host name to verify against 
  339. * @param resource $context Stream context 
  340. * @return bool 
  341. */ 
  342. public function verify_certificate_from_context($host, $context) { 
  343. $meta = stream_context_get_options($context); 
  344.  
  345. // If we don't have SSL options, then we couldn't make the connection at 
  346. // all 
  347. if (empty($meta) || empty($meta['ssl']) || empty($meta['ssl']['peer_certificate'])) { 
  348. throw new Requests_Exception(rtrim($this->connect_error), 'ssl.connect_error'); 
  349.  
  350. $cert = openssl_x509_parse($meta['ssl']['peer_certificate']); 
  351.  
  352. return Requests_SSL::verify_certificate($host, $cert); 
  353.  
  354. /** 
  355. * Whether this transport is valid 
  356. * 
  357. * @codeCoverageIgnore 
  358. * @return boolean True if the transport is valid, false otherwise. 
  359. */ 
  360. public static function test($capabilities = array()) { 
  361. if (!function_exists('fsockopen')) { 
  362. return false; 
  363.  
  364. // If needed, check that streams support SSL 
  365. if (isset($capabilities['ssl']) && $capabilities['ssl']) { 
  366. if (!extension_loaded('openssl') || !function_exists('openssl_x509_parse')) { 
  367. return false; 
  368.  
  369. // Currently broken, thanks to https://github.com/facebook/hhvm/issues/2156 
  370. if (defined('HHVM_VERSION')) { 
  371. return false; 
  372.  
  373. return true; 
.