source: externals/php/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php@ 1ebaa4f

Last change on this file since 1ebaa4f was 01a620f, checked in by Joachim Langenbach <joachim.langenbach@…>, 11 years ago

Removed submodules for php externals and use composer to provide them and versioned them afterwards

  • Property mode set to 100644
File size: 17.7 KB
Line 
1<?php
2namespace GuzzleHttp\Handler;
3
4use GuzzleHttp\Exception\RequestException;
5use GuzzleHttp\Exception\ConnectException;
6use GuzzleHttp\Promise\FulfilledPromise;
7use GuzzleHttp\Promise\RejectedPromise;
8use GuzzleHttp\Psr7;
9use GuzzleHttp\Psr7\LazyOpenStream;
10use Psr\Http\Message\RequestInterface;
11
12/**
13 * Creates curl resources from a request
14 */
15class CurlFactory implements CurlFactoryInterface
16{
17 /** @var array */
18 private $handles;
19
20 /** @var int Total number of idle handles to keep in cache */
21 private $maxHandles;
22
23 /**
24 * @param int $maxHandles Maximum number of idle handles.
25 */
26 public function __construct($maxHandles)
27 {
28 $this->maxHandles = $maxHandles;
29 }
30
31 public function create(RequestInterface $request, array $options)
32 {
33 $easy = new EasyHandle;
34 $easy->request = $request;
35 $easy->options = $options;
36 $conf = $this->getDefaultConf($easy);
37 $this->applyMethod($easy, $conf);
38 $this->applyHandlerOptions($easy, $conf);
39 $this->applyHeaders($easy, $conf);
40 unset($conf['_headers']);
41
42 if (isset($options['curl']['body_as_string'])) {
43 $options['_body_as_string'] = $options['curl']['body_as_string'];
44 unset($options['curl']['body_as_string']);
45 }
46
47 // Add handler options from the request configuration options
48 if (isset($options['curl'])) {
49 $conf += $options['curl'];
50 }
51
52 $conf[CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
53 $easy->handle = $this->handles
54 ? array_pop($this->handles)
55 : curl_init();
56 curl_setopt_array($easy->handle, $conf);
57
58 return $easy;
59 }
60
61 public function release(EasyHandle $easy)
62 {
63 $resource = $easy->handle;
64 unset($easy->handle);
65
66 if (count($this->handles) >= $this->maxHandles) {
67 curl_close($resource);
68 } else {
69 // Remove all callback functions as they can hold onto references
70 // and are not cleaned up by curl_reset. Using curl_setopt_array
71 // does not work for some reason, so removing each one
72 // individually.
73 curl_setopt($resource, CURLOPT_HEADERFUNCTION, null);
74 curl_setopt($resource, CURLOPT_READFUNCTION, null);
75 curl_setopt($resource, CURLOPT_WRITEFUNCTION, null);
76 curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, null);
77 curl_reset($resource);
78 $this->handles[] = $resource;
79 }
80 }
81
82 /**
83 * Completes a cURL transaction, either returning a response promise or a
84 * rejected promise.
85 *
86 * @param callable $handler
87 * @param EasyHandle $easy
88 * @param CurlFactoryInterface $factory Dictates how the handle is released
89 *
90 * @return \GuzzleHttp\Promise\PromiseInterface
91 */
92 public static function finish(
93 callable $handler,
94 EasyHandle $easy,
95 CurlFactoryInterface $factory
96 ) {
97 if (!$easy->response || $easy->errno) {
98 return self::finishError($handler, $easy, $factory);
99 }
100
101 // Return the response if it is present and there is no error.
102 $factory->release($easy);
103
104 // Rewind the body of the response if possible.
105 $body = $easy->response->getBody();
106 if ($body->isSeekable()) {
107 $body->rewind();
108 }
109
110 return new FulfilledPromise($easy->response);
111 }
112
113 private static function finishError(
114 callable $handler,
115 EasyHandle $easy,
116 CurlFactoryInterface $factory
117 ) {
118 // Get error information and release the handle to the factory.
119 $ctx = [
120 'errno' => $easy->errno,
121 'error' => curl_error($easy->handle),
122 ] + curl_getinfo($easy->handle);
123 $factory->release($easy);
124
125 // Retry when nothing is present or when curl failed to rewind.
126 if (empty($easy->options['_err_message'])
127 && (!$easy->errno || $easy->errno == 65)
128 ) {
129 return self::retryFailedRewind($handler, $easy, $ctx);
130 }
131
132 return self::createRejection($easy, $ctx);
133 }
134
135 private static function createRejection(EasyHandle $easy, array $ctx)
136 {
137 static $connectionErrors = [
138 CURLE_OPERATION_TIMEOUTED => true,
139 CURLE_COULDNT_RESOLVE_HOST => true,
140 CURLE_COULDNT_CONNECT => true,
141 CURLE_SSL_CONNECT_ERROR => true,
142 CURLE_GOT_NOTHING => true,
143 ];
144
145 // If an exception was encountered during the onHeaders event, then
146 // return a rejected promise that wraps that exception.
147 if ($easy->onHeadersException) {
148 return new RejectedPromise(
149 new RequestException(
150 'An error was encountered during the on_headers event',
151 $easy->request,
152 $easy->response,
153 $easy->onHeadersException,
154 $ctx
155 )
156 );
157 }
158
159 $message = sprintf(
160 'cURL error %s: %s (%s)',
161 $ctx['errno'],
162 $ctx['error'],
163 'see http://curl.haxx.se/libcurl/c/libcurl-errors.html'
164 );
165
166 // Create a connection exception if it was a specific error code.
167 $error = isset($connectionErrors[$easy->errno])
168 ? new ConnectException($message, $easy->request, null, $ctx)
169 : new RequestException($message, $easy->request, $easy->response, null, $ctx);
170
171 return new RejectedPromise($error);
172 }
173
174 private function getDefaultConf(EasyHandle $easy)
175 {
176 $conf = [
177 '_headers' => $easy->request->getHeaders(),
178 CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
179 CURLOPT_URL => (string) $easy->request->getUri(),
180 CURLOPT_RETURNTRANSFER => false,
181 CURLOPT_HEADER => false,
182 CURLOPT_CONNECTTIMEOUT => 150,
183 ];
184
185 if (defined('CURLOPT_PROTOCOLS')) {
186 $conf[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
187 }
188
189 $version = $easy->request->getProtocolVersion();
190 if ($version == 1.1) {
191 $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
192 } elseif ($version == 2.0) {
193 $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0;
194 } else {
195 $conf[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
196 }
197
198 return $conf;
199 }
200
201 private function applyMethod(EasyHandle $easy, array &$conf)
202 {
203 $body = $easy->request->getBody();
204 $size = $body->getSize();
205
206 if ($size === null || $size > 0) {
207 $this->applyBody($easy->request, $easy->options, $conf);
208 return;
209 }
210
211 $method = $easy->request->getMethod();
212 if ($method === 'PUT' || $method === 'POST') {
213 // See http://tools.ietf.org/html/rfc7230#section-3.3.2
214 if (!$easy->request->hasHeader('Content-Length')) {
215 $conf[CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
216 }
217 } elseif ($method === 'HEAD') {
218 $conf[CURLOPT_NOBODY] = true;
219 unset(
220 $conf[CURLOPT_WRITEFUNCTION],
221 $conf[CURLOPT_READFUNCTION],
222 $conf[CURLOPT_FILE],
223 $conf[CURLOPT_INFILE]
224 );
225 }
226 }
227
228 private function applyBody(RequestInterface $request, array $options, array &$conf)
229 {
230 $size = $request->hasHeader('Content-Length')
231 ? (int) $request->getHeaderLine('Content-Length')
232 : null;
233
234 // Send the body as a string if the size is less than 1MB OR if the
235 // [curl][body_as_string] request value is set.
236 if (($size !== null && $size < 1000000) ||
237 !empty($options['_body_as_string'])
238 ) {
239 $conf[CURLOPT_POSTFIELDS] = (string) $request->getBody();
240 // Don't duplicate the Content-Length header
241 $this->removeHeader('Content-Length', $conf);
242 $this->removeHeader('Transfer-Encoding', $conf);
243 } else {
244 $conf[CURLOPT_UPLOAD] = true;
245 if ($size !== null) {
246 $conf[CURLOPT_INFILESIZE] = $size;
247 $this->removeHeader('Content-Length', $conf);
248 }
249 $body = $request->getBody();
250 $conf[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) {
251 return $body->read($length);
252 };
253 }
254
255 // If the Expect header is not present, prevent curl from adding it
256 if (!$request->hasHeader('Expect')) {
257 $conf[CURLOPT_HTTPHEADER][] = 'Expect:';
258 }
259
260 // cURL sometimes adds a content-type by default. Prevent this.
261 if (!$request->hasHeader('Content-Type')) {
262 $conf[CURLOPT_HTTPHEADER][] = 'Content-Type:';
263 }
264 }
265
266 private function applyHeaders(EasyHandle $easy, array &$conf)
267 {
268 foreach ($conf['_headers'] as $name => $values) {
269 foreach ($values as $value) {
270 $conf[CURLOPT_HTTPHEADER][] = "$name: $value";
271 }
272 }
273
274 // Remove the Accept header if one was not set
275 if (!$easy->request->hasHeader('Accept')) {
276 $conf[CURLOPT_HTTPHEADER][] = 'Accept:';
277 }
278 }
279
280 /**
281 * Remove a header from the options array.
282 *
283 * @param string $name Case-insensitive header to remove
284 * @param array $options Array of options to modify
285 */
286 private function removeHeader($name, array &$options)
287 {
288 foreach (array_keys($options['_headers']) as $key) {
289 if (!strcasecmp($key, $name)) {
290 unset($options['_headers'][$key]);
291 return;
292 }
293 }
294 }
295
296 private function applyHandlerOptions(EasyHandle $easy, array &$conf)
297 {
298 $options = $easy->options;
299 if (isset($options['verify'])) {
300 if ($options['verify'] === false) {
301 unset($conf[CURLOPT_CAINFO]);
302 $conf[CURLOPT_SSL_VERIFYHOST] = 0;
303 $conf[CURLOPT_SSL_VERIFYPEER] = false;
304 } else {
305 $conf[CURLOPT_SSL_VERIFYHOST] = 2;
306 $conf[CURLOPT_SSL_VERIFYPEER] = true;
307 if (is_string($options['verify'])) {
308 $conf[CURLOPT_CAINFO] = $options['verify'];
309 if (!file_exists($options['verify'])) {
310 throw new \InvalidArgumentException(
311 "SSL CA bundle not found: {$options['verify']}"
312 );
313 }
314 }
315 }
316 }
317
318 if (!empty($options['decode_content'])) {
319 $accept = $easy->request->getHeaderLine('Accept-Encoding');
320 if ($accept) {
321 $conf[CURLOPT_ENCODING] = $accept;
322 } else {
323 $conf[CURLOPT_ENCODING] = '';
324 // Don't let curl send the header over the wire
325 $conf[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
326 }
327 }
328
329 if (isset($options['sink'])) {
330 $sink = $options['sink'];
331 if (!is_string($sink)) {
332 $sink = \GuzzleHttp\Psr7\stream_for($sink);
333 } elseif (!is_dir(dirname($sink))) {
334 // Ensure that the directory exists before failing in curl.
335 throw new \RuntimeException(sprintf(
336 'Directory %s does not exist for sink value of %s',
337 dirname($sink),
338 $sink
339 ));
340 } else {
341 $sink = new LazyOpenStream($sink, 'w+');
342 }
343 $easy->sink = $sink;
344 $conf[CURLOPT_WRITEFUNCTION] = function ($ch, $write) use ($sink) {
345 return $sink->write($write);
346 };
347 } else {
348 // Use a default temp stream if no sink was set.
349 $conf[CURLOPT_FILE] = fopen('php://temp', 'w+');
350 $easy->sink = Psr7\stream_for($conf[CURLOPT_FILE]);
351 }
352
353 if (isset($options['timeout'])) {
354 $conf[CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
355 }
356
357 if (isset($options['connect_timeout'])) {
358 $conf[CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
359 }
360
361 if (isset($options['proxy'])) {
362 if (!is_array($options['proxy'])) {
363 $conf[CURLOPT_PROXY] = $options['proxy'];
364 } elseif ($scheme = $easy->request->getUri()->getScheme()) {
365 if (isset($options['proxy'][$scheme])) {
366 $conf[CURLOPT_PROXY] = $options['proxy'][$scheme];
367 }
368 }
369 }
370
371 if (isset($options['cert'])) {
372 $cert = $options['cert'];
373 if (is_array($cert)) {
374 $conf[CURLOPT_SSLCERTPASSWD] = $cert[1];
375 $cert = $cert[0];
376 }
377 if (!file_exists($cert)) {
378 throw new \InvalidArgumentException(
379 "SSL certificate not found: {$cert}"
380 );
381 }
382 $conf[CURLOPT_SSLCERT] = $cert;
383 }
384
385 if (isset($options['ssl_key'])) {
386 $sslKey = $options['ssl_key'];
387 if (is_array($sslKey)) {
388 $conf[CURLOPT_SSLKEYPASSWD] = $sslKey[1];
389 $sslKey = $sslKey[0];
390 }
391 if (!file_exists($sslKey)) {
392 throw new \InvalidArgumentException(
393 "SSL private key not found: {$sslKey}"
394 );
395 }
396 $conf[CURLOPT_SSLKEY] = $sslKey;
397 }
398
399 if (isset($options['progress'])) {
400 $progress = $options['progress'];
401 if (!is_callable($progress)) {
402 throw new \InvalidArgumentException(
403 'progress client option must be callable'
404 );
405 }
406 $conf[CURLOPT_NOPROGRESS] = false;
407 $conf[CURLOPT_PROGRESSFUNCTION] = function () use ($progress) {
408 $args = func_get_args();
409 // PHP 5.5 pushed the handle onto the start of the args
410 if (is_resource($args[0])) {
411 array_shift($args);
412 }
413 call_user_func_array($progress, $args);
414 };
415 }
416
417 if (!empty($options['debug'])) {
418 $conf[CURLOPT_STDERR] = \GuzzleHttp\debug_resource($options['debug']);
419 $conf[CURLOPT_VERBOSE] = true;
420 }
421 }
422
423 /**
424 * This function ensures that a response was set on a transaction. If one
425 * was not set, then the request is retried if possible. This error
426 * typically means you are sending a payload, curl encountered a
427 * "Connection died, retrying a fresh connect" error, tried to rewind the
428 * stream, and then encountered a "necessary data rewind wasn't possible"
429 * error, causing the request to be sent through curl_multi_info_read()
430 * without an error status.
431 */
432 private static function retryFailedRewind(
433 callable $handler,
434 EasyHandle $easy,
435 array $ctx
436 ) {
437 try {
438 // Only rewind if the body has been read from.
439 $body = $easy->request->getBody();
440 if ($body->tell() > 0) {
441 $body->rewind();
442 }
443 } catch (\RuntimeException $e) {
444 $ctx['error'] = 'The connection unexpectedly failed without '
445 . 'providing an error. The request would have been retried, '
446 . 'but attempting to rewind the request body failed. '
447 . 'Exception: ' . $e;
448 return self::createRejection($easy, $ctx);
449 }
450
451 // Retry no more than 3 times before giving up.
452 if (!isset($easy->options['_curl_retries'])) {
453 $easy->options['_curl_retries'] = 1;
454 } elseif ($easy->options['_curl_retries'] == 2) {
455 $ctx['error'] = 'The cURL request was retried 3 times '
456 . 'and did not succeed. The most likely reason for the failure '
457 . 'is that cURL was unable to rewind the body of the request '
458 . 'and subsequent retries resulted in the same error. Turn on '
459 . 'the debug option to see what went wrong. See '
460 . 'https://bugs.php.net/bug.php?id=47204 for more information.';
461 return self::createRejection($easy, $ctx);
462 } else {
463 $easy->options['_curl_retries']++;
464 }
465
466 return $handler($easy->request, $easy->options);
467 }
468
469 private function createHeaderFn(EasyHandle $easy)
470 {
471 if (!isset($easy->options['on_headers'])) {
472 $onHeaders = null;
473 } elseif (!is_callable($easy->options['on_headers'])) {
474 throw new \InvalidArgumentException('on_headers must be callable');
475 } else {
476 $onHeaders = $easy->options['on_headers'];
477 }
478
479 return function ($ch, $h) use (
480 $onHeaders,
481 $easy,
482 &$startingResponse
483 ) {
484 $value = trim($h);
485 if ($value === '') {
486 $startingResponse = true;
487 $easy->createResponse();
488 if ($onHeaders) {
489 try {
490 $onHeaders($easy->response);
491 } catch (\Exception $e) {
492 // Associate the exception with the handle and trigger
493 // a curl header write error by returning 0.
494 $easy->onHeadersException = $e;
495 return -1;
496 }
497 }
498 } elseif ($startingResponse) {
499 $startingResponse = false;
500 $easy->headers = [$value];
501 } else {
502 $easy->headers[] = $value;
503 }
504 return strlen($h);
505 };
506 }
507}
Note: See TracBrowser for help on using the repository browser.