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