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