2 namespace GuzzleHttp\Handler;
4 use GuzzleHttp\Exception\RequestException;
5 use GuzzleHttp\Exception\ConnectException;
6 use GuzzleHttp\Promise\FulfilledPromise;
7 use GuzzleHttp\Promise\RejectedPromise;
9 use GuzzleHttp\Psr7\LazyOpenStream;
10 use GuzzleHttp\TransferStats;
11 use Psr\Http\Message\RequestInterface;
14 * Creates curl resources from a request
16 class CurlFactory implements CurlFactoryInterface
19 private $handles = [];
21 /** @var int Total number of idle handles to keep in cache */
25 * @param int $maxHandles Maximum number of idle handles.
27 public function __construct($maxHandles)
29 $this->maxHandles = $maxHandles;
32 public function create(RequestInterface $request, array $options)
34 if (isset($options['curl']['body_as_string'])) {
35 $options['_body_as_string'] = $options['curl']['body_as_string'];
36 unset($options['curl']['body_as_string']);
39 $easy = new EasyHandle;
40 $easy->request = $request;
41 $easy->options = $options;
42 $conf = $this->getDefaultConf($easy);
43 $this->applyMethod($easy, $conf);
44 $this->applyHandlerOptions($easy, $conf);
45 $this->applyHeaders($easy, $conf);
46 unset($conf['_headers']);
48 // Add handler options from the request configuration options
49 if (isset($options['curl'])) {
50 $conf = array_replace($conf, $options['curl']);
53 $conf[CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
54 $easy->handle = $this->handles
55 ? array_pop($this->handles)
57 curl_setopt_array($easy->handle, $conf);
62 public function release(EasyHandle $easy)
64 $resource = $easy->handle;
67 if (count($this->handles) >= $this->maxHandles) {
68 curl_close($resource);
70 // Remove all callback functions as they can hold onto references
71 // and are not cleaned up by curl_reset. Using curl_setopt_array
72 // does not work for some reason, so removing each one
74 curl_setopt($resource, CURLOPT_HEADERFUNCTION, null);
75 curl_setopt($resource, CURLOPT_READFUNCTION, null);
76 curl_setopt($resource, CURLOPT_WRITEFUNCTION, null);
77 curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, null);
78 curl_reset($resource);
79 $this->handles[] = $resource;
84 * Completes a cURL transaction, either returning a response promise or a
87 * @param callable $handler
88 * @param EasyHandle $easy
89 * @param CurlFactoryInterface $factory Dictates how the handle is released
91 * @return \GuzzleHttp\Promise\PromiseInterface
93 public static function finish(
96 CurlFactoryInterface $factory
98 if (isset($easy->options['on_stats'])) {
99 self::invokeStats($easy);
102 if (!$easy->response || $easy->errno) {
103 return self::finishError($handler, $easy, $factory);
106 // Return the response if it is present and there is no error.
107 $factory->release($easy);
109 // Rewind the body of the response if possible.
110 $body = $easy->response->getBody();
111 if ($body->isSeekable()) {
115 return new FulfilledPromise($easy->response);
118 private static function invokeStats(EasyHandle $easy)
120 $curlStats = curl_getinfo($easy->handle);
121 $stats = new TransferStats(
124 $curlStats['total_time'],
128 call_user_func($easy->options['on_stats'], $stats);
131 private static function finishError(
134 CurlFactoryInterface $factory
136 // Get error information and release the handle to the factory.
138 'errno' => $easy->errno,
139 'error' => curl_error($easy->handle),
140 ] + curl_getinfo($easy->handle);
141 $factory->release($easy);
143 // Retry when nothing is present or when curl failed to rewind.
144 if (empty($easy->options['_err_message'])
145 && (!$easy->errno || $easy->errno == 65)
147 return self::retryFailedRewind($handler, $easy, $ctx);
150 return self::createRejection($easy, $ctx);
153 private static function createRejection(EasyHandle $easy, array $ctx)
155 static $connectionErrors = [
156 CURLE_OPERATION_TIMEOUTED => true,
157 CURLE_COULDNT_RESOLVE_HOST => true,
158 CURLE_COULDNT_CONNECT => true,
159 CURLE_SSL_CONNECT_ERROR => true,
160 CURLE_GOT_NOTHING => true,
163 // If an exception was encountered during the onHeaders event, then
164 // return a rejected promise that wraps that exception.
165 if ($easy->onHeadersException) {
166 return \GuzzleHttp\Promise\rejection_for(
167 new RequestException(
168 'An error was encountered during the on_headers event',
171 $easy->onHeadersException,
178 'cURL error %s: %s (%s)',
181 'see http://curl.haxx.se/libcurl/c/libcurl-errors.html'
184 // Create a connection exception if it was a specific error code.
185 $error = isset($connectionErrors[$easy->errno])
186 ? new ConnectException($message, $easy->request, null, $ctx)
187 : new RequestException($message, $easy->request, $easy->response, null, $ctx);
189 return \GuzzleHttp\Promise\rejection_for($error);
192 private function getDefaultConf(EasyHandle $easy)
195 '_headers' => $easy->request->getHeaders(),
196 CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
197 CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''),
198 CURLOPT_RETURNTRANSFER => false,
199 CURLOPT_HEADER => false,
200 CURLOPT_CONNECTTIMEOUT => 150,
203 if (defined('CURLOPT_PROTOCOLS')) {
204 $conf[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
207 $version = $easy->request->getProtocolVersion();
208 if ($version == 1.1) {
209 $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
210 } elseif ($version == 2.0) {
211 $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0;
213 $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
219 private function applyMethod(EasyHandle $easy, array &$conf)
221 $body = $easy->request->getBody();
222 $size = $body->getSize();
224 if ($size === null || $size > 0) {
225 $this->applyBody($easy->request, $easy->options, $conf);
229 $method = $easy->request->getMethod();
230 if ($method === 'PUT' || $method === 'POST') {
231 // See http://tools.ietf.org/html/rfc7230#section-3.3.2
232 if (!$easy->request->hasHeader('Content-Length')) {
233 $conf[CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
235 } elseif ($method === 'HEAD') {
236 $conf[CURLOPT_NOBODY] = true;
238 $conf[CURLOPT_WRITEFUNCTION],
239 $conf[CURLOPT_READFUNCTION],
241 $conf[CURLOPT_INFILE]
246 private function applyBody(RequestInterface $request, array $options, array &$conf)
248 $size = $request->hasHeader('Content-Length')
249 ? (int) $request->getHeaderLine('Content-Length')
252 // Send the body as a string if the size is less than 1MB OR if the
253 // [curl][body_as_string] request value is set.
254 if (($size !== null && $size < 1000000) ||
255 !empty($options['_body_as_string'])
257 $conf[CURLOPT_POSTFIELDS] = (string) $request->getBody();
258 // Don't duplicate the Content-Length header
259 $this->removeHeader('Content-Length', $conf);
260 $this->removeHeader('Transfer-Encoding', $conf);
262 $conf[CURLOPT_UPLOAD] = true;
263 if ($size !== null) {
264 $conf[CURLOPT_INFILESIZE] = $size;
265 $this->removeHeader('Content-Length', $conf);
267 $body = $request->getBody();
268 if ($body->isSeekable()) {
271 $conf[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) {
272 return $body->read($length);
276 // If the Expect header is not present, prevent curl from adding it
277 if (!$request->hasHeader('Expect')) {
278 $conf[CURLOPT_HTTPHEADER][] = 'Expect:';
281 // cURL sometimes adds a content-type by default. Prevent this.
282 if (!$request->hasHeader('Content-Type')) {
283 $conf[CURLOPT_HTTPHEADER][] = 'Content-Type:';
287 private function applyHeaders(EasyHandle $easy, array &$conf)
289 foreach ($conf['_headers'] as $name => $values) {
290 foreach ($values as $value) {
291 $conf[CURLOPT_HTTPHEADER][] = "$name: $value";
295 // Remove the Accept header if one was not set
296 if (!$easy->request->hasHeader('Accept')) {
297 $conf[CURLOPT_HTTPHEADER][] = 'Accept:';
302 * Remove a header from the options array.
304 * @param string $name Case-insensitive header to remove
305 * @param array $options Array of options to modify
307 private function removeHeader($name, array &$options)
309 foreach (array_keys($options['_headers']) as $key) {
310 if (!strcasecmp($key, $name)) {
311 unset($options['_headers'][$key]);
317 private function applyHandlerOptions(EasyHandle $easy, array &$conf)
319 $options = $easy->options;
320 if (isset($options['verify'])) {
321 if ($options['verify'] === false) {
322 unset($conf[CURLOPT_CAINFO]);
323 $conf[CURLOPT_SSL_VERIFYHOST] = 0;
324 $conf[CURLOPT_SSL_VERIFYPEER] = false;
326 $conf[CURLOPT_SSL_VERIFYHOST] = 2;
327 $conf[CURLOPT_SSL_VERIFYPEER] = true;
328 if (is_string($options['verify'])) {
329 // Throw an error if the file/folder/link path is not valid or doesn't exist.
330 if (!file_exists($options['verify'])) {
331 throw new \InvalidArgumentException(
332 "SSL CA bundle not found: {$options['verify']}"
335 // If it's a directory or a link to a directory use CURLOPT_CAPATH.
336 // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO.
337 if (is_dir($options['verify']) ||
338 (is_link($options['verify']) && is_dir(readlink($options['verify'])))) {
339 $conf[CURLOPT_CAPATH] = $options['verify'];
341 $conf[CURLOPT_CAINFO] = $options['verify'];
347 if (!empty($options['decode_content'])) {
348 $accept = $easy->request->getHeaderLine('Accept-Encoding');
350 $conf[CURLOPT_ENCODING] = $accept;
352 $conf[CURLOPT_ENCODING] = '';
353 // Don't let curl send the header over the wire
354 $conf[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
358 if (isset($options['sink'])) {
359 $sink = $options['sink'];
360 if (!is_string($sink)) {
361 $sink = \GuzzleHttp\Psr7\stream_for($sink);
362 } elseif (!is_dir(dirname($sink))) {
363 // Ensure that the directory exists before failing in curl.
364 throw new \RuntimeException(sprintf(
365 'Directory %s does not exist for sink value of %s',
370 $sink = new LazyOpenStream($sink, 'w+');
373 $conf[CURLOPT_WRITEFUNCTION] = function ($ch, $write) use ($sink) {
374 return $sink->write($write);
377 // Use a default temp stream if no sink was set.
378 $conf[CURLOPT_FILE] = fopen('php://temp', 'w+');
379 $easy->sink = Psr7\stream_for($conf[CURLOPT_FILE]);
381 $timeoutRequiresNoSignal = false;
382 if (isset($options['timeout'])) {
383 $timeoutRequiresNoSignal |= $options['timeout'] < 1;
384 $conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
387 // CURL default value is CURL_IPRESOLVE_WHATEVER
388 if (isset($options['force_ip_resolve'])) {
389 if ('v4' === $options['force_ip_resolve']) {
390 $conf[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
391 } else if ('v6' === $options['force_ip_resolve']) {
392 $conf[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V6;
396 if (isset($options['connect_timeout'])) {
397 $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1;
398 $conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
401 if ($timeoutRequiresNoSignal && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
402 $conf[CURLOPT_NOSIGNAL] = true;
405 if (isset($options['proxy'])) {
406 if (!is_array($options['proxy'])) {
407 $conf[CURLOPT_PROXY] = $options['proxy'];
409 $scheme = $easy->request->getUri()->getScheme();
410 if (isset($options['proxy'][$scheme])) {
411 $host = $easy->request->getUri()->getHost();
412 if (!isset($options['proxy']['no']) ||
413 !\GuzzleHttp\is_host_in_noproxy($host, $options['proxy']['no'])
415 $conf[CURLOPT_PROXY] = $options['proxy'][$scheme];
421 if (isset($options['cert'])) {
422 $cert = $options['cert'];
423 if (is_array($cert)) {
424 $conf[CURLOPT_SSLCERTPASSWD] = $cert[1];
427 if (!file_exists($cert)) {
428 throw new \InvalidArgumentException(
429 "SSL certificate not found: {$cert}"
432 $conf[CURLOPT_SSLCERT] = $cert;
435 if (isset($options['ssl_key'])) {
436 $sslKey = $options['ssl_key'];
437 if (is_array($sslKey)) {
438 $conf[CURLOPT_SSLKEYPASSWD] = $sslKey[1];
439 $sslKey = $sslKey[0];
441 if (!file_exists($sslKey)) {
442 throw new \InvalidArgumentException(
443 "SSL private key not found: {$sslKey}"
446 $conf[CURLOPT_SSLKEY] = $sslKey;
449 if (isset($options['progress'])) {
450 $progress = $options['progress'];
451 if (!is_callable($progress)) {
452 throw new \InvalidArgumentException(
453 'progress client option must be callable'
456 $conf[CURLOPT_NOPROGRESS] = false;
457 $conf[CURLOPT_PROGRESSFUNCTION] = function () use ($progress) {
458 $args = func_get_args();
459 // PHP 5.5 pushed the handle onto the start of the args
460 if (is_resource($args[0])) {
463 call_user_func_array($progress, $args);
467 if (!empty($options['debug'])) {
468 $conf[CURLOPT_STDERR] = \GuzzleHttp\debug_resource($options['debug']);
469 $conf[CURLOPT_VERBOSE] = true;
474 * This function ensures that a response was set on a transaction. If one
475 * was not set, then the request is retried if possible. This error
476 * typically means you are sending a payload, curl encountered a
477 * "Connection died, retrying a fresh connect" error, tried to rewind the
478 * stream, and then encountered a "necessary data rewind wasn't possible"
479 * error, causing the request to be sent through curl_multi_info_read()
480 * without an error status.
482 private static function retryFailedRewind(
488 // Only rewind if the body has been read from.
489 $body = $easy->request->getBody();
490 if ($body->tell() > 0) {
493 } catch (\RuntimeException $e) {
494 $ctx['error'] = 'The connection unexpectedly failed without '
495 . 'providing an error. The request would have been retried, '
496 . 'but attempting to rewind the request body failed. '
497 . 'Exception: ' . $e;
498 return self::createRejection($easy, $ctx);
501 // Retry no more than 3 times before giving up.
502 if (!isset($easy->options['_curl_retries'])) {
503 $easy->options['_curl_retries'] = 1;
504 } elseif ($easy->options['_curl_retries'] == 2) {
505 $ctx['error'] = 'The cURL request was retried 3 times '
506 . 'and did not succeed. The most likely reason for the failure '
507 . 'is that cURL was unable to rewind the body of the request '
508 . 'and subsequent retries resulted in the same error. Turn on '
509 . 'the debug option to see what went wrong. See '
510 . 'https://bugs.php.net/bug.php?id=47204 for more information.';
511 return self::createRejection($easy, $ctx);
513 $easy->options['_curl_retries']++;
516 return $handler($easy->request, $easy->options);
519 private function createHeaderFn(EasyHandle $easy)
521 if (isset($easy->options['on_headers'])) {
522 $onHeaders = $easy->options['on_headers'];
524 if (!is_callable($onHeaders)) {
525 throw new \InvalidArgumentException('on_headers must be callable');
531 return function ($ch, $h) use (
538 $startingResponse = true;
539 $easy->createResponse();
540 if ($onHeaders !== null) {
542 $onHeaders($easy->response);
543 } catch (\Exception $e) {
544 // Associate the exception with the handle and trigger
545 // a curl header write error by returning 0.
546 $easy->onHeadersException = $e;
550 } elseif ($startingResponse) {
551 $startingResponse = false;
552 $easy->headers = [$value];
554 $easy->headers[] = $value;