6 * @subpackage Transport
13 * @subpackage Transport
15 class Requests_Transport_cURL implements Requests_Transport {
16 const CURL_7_10_5 = 0x070A05;
17 const CURL_7_16_2 = 0x071002;
31 public $response_data = '';
34 * Information on the current request
36 * @var array cURL information array, see {@see https://secure.php.net/curl_getinfo}
55 * Hook dispatcher instance
62 * Have we finished the headers yet?
66 protected $done_headers = false;
69 * If streaming to a file, keep the file pointer
73 protected $stream_handle;
76 * How many bytes are in the response body?
80 protected $response_bytes;
83 * What's the maximum number of bytes we should keep?
85 * @var int|bool Byte count, or false if no limit.
87 protected $response_byte_limit;
92 public function __construct() {
93 $curl = curl_version();
94 $this->version = $curl['version_number'];
95 $this->handle = curl_init();
97 curl_setopt($this->handle, CURLOPT_HEADER, false);
98 curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, 1);
99 if ($this->version >= self::CURL_7_10_5) {
100 curl_setopt($this->handle, CURLOPT_ENCODING, '');
102 if (defined('CURLOPT_PROTOCOLS')) {
103 curl_setopt($this->handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
105 if (defined('CURLOPT_REDIR_PROTOCOLS')) {
106 curl_setopt($this->handle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
113 public function __destruct() {
114 if (is_resource($this->handle)) {
115 curl_close($this->handle);
122 * @throws Requests_Exception On a cURL error (`curlerror`)
124 * @param string $url URL to request
125 * @param array $headers Associative array of request headers
126 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
127 * @param array $options Request options, see {@see Requests::response()} for documentation
128 * @return string Raw HTTP result
130 public function request($url, $headers = array(), $data = array(), $options = array()) {
131 $this->hooks = $options['hooks'];
133 $this->setup_handle($url, $headers, $data, $options);
135 $options['hooks']->dispatch('curl.before_send', array(&$this->handle));
137 if ($options['filename'] !== false) {
138 $this->stream_handle = fopen($options['filename'], 'wb');
141 $this->response_data = '';
142 $this->response_bytes = 0;
143 $this->response_byte_limit = false;
144 if ($options['max_bytes'] !== false) {
145 $this->response_byte_limit = $options['max_bytes'];
148 if (isset($options['verify'])) {
149 if ($options['verify'] === false) {
150 curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
151 curl_setopt($this->handle, CURLOPT_SSL_VERIFYPEER, 0);
153 elseif (is_string($options['verify'])) {
154 curl_setopt($this->handle, CURLOPT_CAINFO, $options['verify']);
158 if (isset($options['verifyname']) && $options['verifyname'] === false) {
159 curl_setopt($this->handle, CURLOPT_SSL_VERIFYHOST, 0);
162 curl_exec($this->handle);
163 $response = $this->response_data;
165 $options['hooks']->dispatch('curl.after_send', array());
167 if (curl_errno($this->handle) === 23 || curl_errno($this->handle) === 61) {
168 // Reset encoding and try again
169 curl_setopt($this->handle, CURLOPT_ENCODING, 'none');
171 $this->response_data = '';
172 $this->response_bytes = 0;
173 curl_exec($this->handle);
174 $response = $this->response_data;
177 $this->process_response($response, $options);
179 // Need to remove the $this reference from the curl handle.
180 // Otherwise Requests_Transport_cURL wont be garbage collected and the curl_close() will never be called.
181 curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, null);
182 curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, null);
184 return $this->headers;
188 * Send multiple requests simultaneously
190 * @param array $requests Request data
191 * @param array $options Global options
192 * @return array Array of Requests_Response objects (may contain Requests_Exception or string responses as well)
194 public function request_multiple($requests, $options) {
195 // If you're not requesting, we can't get any responses ¯\_(ツ)_/¯
196 if (empty($requests)) {
200 $multihandle = curl_multi_init();
201 $subrequests = array();
202 $subhandles = array();
204 $class = get_class($this);
205 foreach ($requests as $id => $request) {
206 $subrequests[$id] = new $class();
207 $subhandles[$id] = $subrequests[$id]->get_subrequest_handle($request['url'], $request['headers'], $request['data'], $request['options']);
208 $request['options']['hooks']->dispatch('curl.before_multi_add', array(&$subhandles[$id]));
209 curl_multi_add_handle($multihandle, $subhandles[$id]);
213 $responses = array();
215 $request['options']['hooks']->dispatch('curl.before_multi_exec', array(&$multihandle));
221 $status = curl_multi_exec($multihandle, $active);
223 while ($status === CURLM_CALL_MULTI_PERFORM);
225 $to_process = array();
227 // Read the information as needed
228 while ($done = curl_multi_info_read($multihandle)) {
229 $key = array_search($done['handle'], $subhandles, true);
230 if (!isset($to_process[$key])) {
231 $to_process[$key] = $done;
235 // Parse the finished requests before we start getting the new ones
236 foreach ($to_process as $key => $done) {
237 $options = $requests[$key]['options'];
238 if (CURLE_OK !== $done['result']) {
239 //get error string for handle.
240 $reason = curl_error($done['handle']);
241 $exception = new Requests_Exception_Transport_cURL(
243 Requests_Exception_Transport_cURL::EASY,
247 $responses[$key] = $exception;
248 $options['hooks']->dispatch('transport.internal.parse_error', array(&$responses[$key], $requests[$key]));
251 $responses[$key] = $subrequests[$key]->process_response($subrequests[$key]->response_data, $options);
253 $options['hooks']->dispatch('transport.internal.parse_response', array(&$responses[$key], $requests[$key]));
256 curl_multi_remove_handle($multihandle, $done['handle']);
257 curl_close($done['handle']);
259 if (!is_string($responses[$key])) {
260 $options['hooks']->dispatch('multiple.request.complete', array(&$responses[$key], $key));
265 while ($active || $completed < count($subrequests));
267 $request['options']['hooks']->dispatch('curl.after_multi_exec', array(&$multihandle));
269 curl_multi_close($multihandle);
275 * Get the cURL handle for use in a multi-request
277 * @param string $url URL to request
278 * @param array $headers Associative array of request headers
279 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
280 * @param array $options Request options, see {@see Requests::response()} for documentation
281 * @return resource Subrequest's cURL handle
283 public function &get_subrequest_handle($url, $headers, $data, $options) {
284 $this->setup_handle($url, $headers, $data, $options);
286 if ($options['filename'] !== false) {
287 $this->stream_handle = fopen($options['filename'], 'wb');
290 $this->response_data = '';
291 $this->response_bytes = 0;
292 $this->response_byte_limit = false;
293 if ($options['max_bytes'] !== false) {
294 $this->response_byte_limit = $options['max_bytes'];
296 $this->hooks = $options['hooks'];
298 return $this->handle;
302 * Setup the cURL handle for the given data
304 * @param string $url URL to request
305 * @param array $headers Associative array of request headers
306 * @param string|array $data Data to send either as the POST body, or as parameters in the URL for a GET/HEAD
307 * @param array $options Request options, see {@see Requests::response()} for documentation
309 protected function setup_handle($url, $headers, $data, $options) {
310 $options['hooks']->dispatch('curl.before_request', array(&$this->handle));
312 // Force closing the connection for old versions of cURL (<7.22).
313 if ( ! isset( $headers['Connection'] ) ) {
314 $headers['Connection'] = 'close';
317 $headers = Requests::flatten($headers);
320 $data_format = $options['data_format'];
322 if ($data_format === 'query') {
323 $url = self::format_get($url, $data);
326 elseif (!is_string($data)) {
327 $data = http_build_query($data, null, '&');
331 switch ($options['type']) {
333 curl_setopt($this->handle, CURLOPT_POST, true);
334 curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
337 curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
338 curl_setopt($this->handle, CURLOPT_NOBODY, true);
340 case Requests::TRACE:
341 curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
343 case Requests::PATCH:
345 case Requests::DELETE:
346 case Requests::OPTIONS:
348 curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, $options['type']);
350 curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
354 // cURL requires a minimum timeout of 1 second when using the system
355 // DNS resolver, as it uses `alarm()`, which is second resolution only.
356 // There's no way to detect which DNS resolver is being used from our
357 // end, so we need to round up regardless of the supplied timeout.
359 // https://github.com/curl/curl/blob/4f45240bc84a9aa648c8f7243be7b79e9f9323a5/lib/hostip.c#L606-L609
360 $timeout = max($options['timeout'], 1);
362 if (is_int($timeout) || $this->version < self::CURL_7_16_2) {
363 curl_setopt($this->handle, CURLOPT_TIMEOUT, ceil($timeout));
366 curl_setopt($this->handle, CURLOPT_TIMEOUT_MS, round($timeout * 1000));
369 if (is_int($options['connect_timeout']) || $this->version < self::CURL_7_16_2) {
370 curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT, ceil($options['connect_timeout']));
373 curl_setopt($this->handle, CURLOPT_CONNECTTIMEOUT_MS, round($options['connect_timeout'] * 1000));
375 curl_setopt($this->handle, CURLOPT_URL, $url);
376 curl_setopt($this->handle, CURLOPT_REFERER, $url);
377 curl_setopt($this->handle, CURLOPT_USERAGENT, $options['useragent']);
378 if (!empty($headers)) {
379 curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers);
381 if ($options['protocol_version'] === 1.1) {
382 curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
385 curl_setopt($this->handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
388 if (true === $options['blocking']) {
389 curl_setopt($this->handle, CURLOPT_HEADERFUNCTION, array(&$this, 'stream_headers'));
390 curl_setopt($this->handle, CURLOPT_WRITEFUNCTION, array(&$this, 'stream_body'));
391 curl_setopt($this->handle, CURLOPT_BUFFERSIZE, Requests::BUFFER_SIZE);
398 * @param string $response Response data from the body
399 * @param array $options Request options
400 * @return string HTTP response data including headers
402 public function process_response($response, $options) {
403 if ($options['blocking'] === false) {
405 $options['hooks']->dispatch('curl.after_request', array(&$fake_headers));
408 if ($options['filename'] !== false) {
409 fclose($this->stream_handle);
410 $this->headers = trim($this->headers);
413 $this->headers .= $response;
416 if (curl_errno($this->handle)) {
419 curl_errno($this->handle),
420 curl_error($this->handle)
422 throw new Requests_Exception($error, 'curlerror', $this->handle);
424 $this->info = curl_getinfo($this->handle);
426 $options['hooks']->dispatch('curl.after_request', array(&$this->headers, &$this->info));
427 return $this->headers;
431 * Collect the headers as they are received
433 * @param resource $handle cURL resource
434 * @param string $headers Header string
435 * @return integer Length of provided header
437 public function stream_headers($handle, $headers) {
438 // Why do we do this? cURL will send both the final response and any
439 // interim responses, such as a 100 Continue. We don't need that.
440 // (We may want to keep this somewhere just in case)
441 if ($this->done_headers) {
443 $this->done_headers = false;
445 $this->headers .= $headers;
447 if ($headers === "\r\n") {
448 $this->done_headers = true;
450 return strlen($headers);
454 * Collect data as it's received
458 * @param resource $handle cURL resource
459 * @param string $data Body data
460 * @return integer Length of provided data
462 public function stream_body($handle, $data) {
463 $this->hooks->dispatch('request.progress', array($data, $this->response_bytes, $this->response_byte_limit));
464 $data_length = strlen($data);
466 // Are we limiting the response size?
467 if ($this->response_byte_limit) {
468 if ($this->response_bytes === $this->response_byte_limit) {
469 // Already at maximum, move on
473 if (($this->response_bytes + $data_length) > $this->response_byte_limit) {
475 $limited_length = ($this->response_byte_limit - $this->response_bytes);
476 $data = substr($data, 0, $limited_length);
480 if ($this->stream_handle) {
481 fwrite($this->stream_handle, $data);
484 $this->response_data .= $data;
487 $this->response_bytes += strlen($data);
492 * Format a URL given GET data
495 * @param array|object $data Data to build query using, see {@see https://secure.php.net/http_build_query}
496 * @return string URL with data
498 protected static function format_get($url, $data) {
500 $url_parts = parse_url($url);
501 if (empty($url_parts['query'])) {
502 $query = $url_parts['query'] = '';
505 $query = $url_parts['query'];
508 $query .= '&' . http_build_query($data, null, '&');
509 $query = trim($query, '&');
511 if (empty($url_parts['query'])) {
512 $url .= '?' . $query;
515 $url = str_replace($url_parts['query'], $query, $url);
522 * Whether this transport is valid
524 * @codeCoverageIgnore
525 * @return boolean True if the transport is valid, false otherwise.
527 public static function test($capabilities = array()) {
528 if (!function_exists('curl_init') || !function_exists('curl_exec')) {
532 // If needed, check that our installed curl version supports SSL
533 if (isset($capabilities['ssl']) && $capabilities['ssl']) {
534 $curl_version = curl_version();
535 if (!(CURL_VERSION_SSL & $curl_version['features'])) {