Requests_Transport_fsockopen

Fsockopen HTTP transport.

Defined (1)

The class is defined in the following location(s).

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