source: externals/php/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.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: 13.4 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\Promise\PromiseInterface;
9use GuzzleHttp\Psr7;
10use Psr\Http\Message\RequestInterface;
11use Psr\Http\Message\StreamInterface;
12
13/**
14 * HTTP handler that uses PHP's HTTP stream wrapper.
15 */
16class StreamHandler
17{
18 private $lastHeaders = [];
19
20 /**
21 * Sends an HTTP request.
22 *
23 * @param RequestInterface $request Request to send.
24 * @param array $options Request transfer options.
25 *
26 * @return PromiseInterface
27 */
28 public function __invoke(RequestInterface $request, array $options)
29 {
30 // Sleep if there is a delay specified.
31 if (isset($options['delay'])) {
32 usleep($options['delay'] * 1000);
33 }
34
35 try {
36 // Does not support the expect header.
37 $request = $request->withoutHeader('Expect');
38 $stream = $this->createStream($request, $options);
39 return $this->createResponse($request, $options, $stream);
40 } catch (\InvalidArgumentException $e) {
41 throw $e;
42 } catch (\Exception $e) {
43 // Determine if the error was a networking error.
44 $message = $e->getMessage();
45 // This list can probably get more comprehensive.
46 if (strpos($message, 'getaddrinfo') // DNS lookup failed
47 || strpos($message, 'Connection refused')
48 || strpos($message, "couldn't connect to host") // error on HHVM
49 ) {
50 $e = new ConnectException($e->getMessage(), $request, $e);
51 }
52 return new RejectedPromise(
53 RequestException::wrapException($request, $e)
54 );
55 }
56 }
57
58 private function createResponse(
59 RequestInterface $request,
60 array $options,
61 $stream
62 ) {
63 $hdrs = $this->lastHeaders;
64 $this->lastHeaders = [];
65 $parts = explode(' ', array_shift($hdrs), 3);
66 $ver = explode('/', $parts[0])[1];
67 $status = $parts[1];
68 $reason = isset($parts[2]) ? $parts[2] : null;
69 $headers = \GuzzleHttp\headers_from_lines($hdrs);
70 list ($stream, $headers) = $this->checkDecode($options, $headers, $stream);
71 $stream = Psr7\stream_for($stream);
72 $sink = $this->createSink($stream, $options);
73 $response = new Psr7\Response($status, $headers, $sink, $ver, $reason);
74
75 if (isset($options['on_headers'])) {
76 try {
77 $options['on_headers']($response);
78 } catch (\Exception $e) {
79 $msg = 'An error was encountered during the on_headers event';
80 $ex = new RequestException($msg, $request, $response, $e);
81 return new RejectedPromise($ex);
82 }
83 }
84
85 if ($sink !== $stream) {
86 $this->drain($stream, $sink);
87 }
88
89 return new FulfilledPromise($response);
90 }
91
92 private function createSink(StreamInterface $stream, array $options)
93 {
94 if (!empty($options['stream'])) {
95 return $stream;
96 }
97
98 $sink = isset($options['sink'])
99 ? $options['sink']
100 : fopen('php://temp', 'r+');
101
102 return is_string($sink)
103 ? new Psr7\Stream(Psr7\try_fopen($sink, 'r+'))
104 : Psr7\stream_for($sink);
105 }
106
107 private function checkDecode(array $options, array $headers, $stream)
108 {
109 // Automatically decode responses when instructed.
110 if (!empty($options['decode_content'])) {
111 $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers);
112 if (isset($normalizedKeys['content-encoding'])) {
113 $encoding = $headers[$normalizedKeys['content-encoding']];
114 if ($encoding[0] == 'gzip' || $encoding[0] == 'deflate') {
115 $stream = new Psr7\InflateStream(
116 Psr7\stream_for($stream)
117 );
118 // Remove content-encoding header
119 unset($headers[$normalizedKeys['content-encoding']]);
120 // Fix content-length header
121 if (isset($normalizedKeys['content-length'])) {
122 $length = (int) $stream->getSize();
123 if ($length == 0) {
124 unset($headers[$normalizedKeys['content-length']]);
125 } else {
126 $headers[$normalizedKeys['content-length']] = [$length];
127 }
128 }
129 }
130 }
131 }
132
133 return [$stream, $headers];
134 }
135
136 /**
137 * Drains the source stream into the "sink" client option.
138 *
139 * @param StreamInterface $source
140 * @param StreamInterface $sink
141 *
142 * @return StreamInterface
143 * @throws \RuntimeException when the sink option is invalid.
144 */
145 private function drain(StreamInterface $source, StreamInterface $sink)
146 {
147 Psr7\copy_to_stream($source, $sink);
148 $sink->seek(0);
149 $source->close();
150
151 return $sink;
152 }
153
154 /**
155 * Create a resource and check to ensure it was created successfully
156 *
157 * @param callable $callback Callable that returns stream resource
158 *
159 * @return resource
160 * @throws \RuntimeException on error
161 */
162 private function createResource(callable $callback)
163 {
164 $errors = null;
165 set_error_handler(function ($_, $msg, $file, $line) use (&$errors) {
166 $errors[] = [
167 'message' => $msg,
168 'file' => $file,
169 'line' => $line
170 ];
171 return true;
172 });
173
174 $resource = $callback();
175 restore_error_handler();
176
177 if (!$resource) {
178 $message = 'Error creating resource: ';
179 foreach ($errors as $err) {
180 foreach ($err as $key => $value) {
181 $message .= "[$key] $value" . PHP_EOL;
182 }
183 }
184 throw new \RuntimeException(trim($message));
185 }
186
187 return $resource;
188 }
189
190 private function createStream(RequestInterface $request, array $options)
191 {
192 static $methods;
193 if (!$methods) {
194 $methods = array_flip(get_class_methods(__CLASS__));
195 }
196
197 // HTTP/1.1 streams using the PHP stream wrapper require a
198 // Connection: close header
199 if ($request->getProtocolVersion() == '1.1'
200 && !$request->hasHeader('Connection')
201 ) {
202 $request = $request->withHeader('Connection', 'close');
203 }
204
205 // Ensure SSL is verified by default
206 if (!isset($options['verify'])) {
207 $options['verify'] = true;
208 }
209
210 $params = [];
211 $context = $this->getDefaultContext($request, $options);
212
213 if (isset($options['on_headers']) && !is_callable($options['on_headers'])) {
214 throw new \InvalidArgumentException('on_headers must be callable');
215 }
216
217 if (!empty($options)) {
218 foreach ($options as $key => $value) {
219 $method = "add_{$key}";
220 if (isset($methods[$method])) {
221 $this->{$method}($request, $context, $value, $params);
222 }
223 }
224 }
225
226 if (isset($options['stream_context'])) {
227 if (!is_array($options['stream_context'])) {
228 throw new \InvalidArgumentException('stream_context must be an array');
229 }
230 $context = array_replace_recursive(
231 $context,
232 $options['stream_context']
233 );
234 }
235
236 $context = $this->createResource(
237 function () use ($context, $params) {
238 return stream_context_create($context, $params);
239 }
240 );
241
242 return $this->createResource(
243 function () use ($request, &$http_response_header, $context) {
244 $resource = fopen($request->getUri(), 'r', null, $context);
245 $this->lastHeaders = $http_response_header;
246 return $resource;
247 }
248 );
249 }
250
251 private function getDefaultContext(RequestInterface $request)
252 {
253 $headers = '';
254 foreach ($request->getHeaders() as $name => $value) {
255 foreach ($value as $val) {
256 $headers .= "$name: $val\r\n";
257 }
258 }
259
260 $context = [
261 'http' => [
262 'method' => $request->getMethod(),
263 'header' => $headers,
264 'protocol_version' => $request->getProtocolVersion(),
265 'ignore_errors' => true,
266 'follow_location' => 0,
267 ],
268 ];
269
270 $body = (string) $request->getBody();
271
272 if (!empty($body)) {
273 $context['http']['content'] = $body;
274 // Prevent the HTTP handler from adding a Content-Type header.
275 if (!$request->hasHeader('Content-Type')) {
276 $context['http']['header'] .= "Content-Type:\r\n";
277 }
278 }
279
280 $context['http']['header'] = rtrim($context['http']['header']);
281
282 return $context;
283 }
284
285 private function add_proxy(RequestInterface $request, &$options, $value, &$params)
286 {
287 if (!is_array($value)) {
288 $options['http']['proxy'] = $value;
289 } else {
290 $scheme = $request->getUri()->getScheme();
291 if (isset($value[$scheme])) {
292 $options['http']['proxy'] = $value[$scheme];
293 }
294 }
295 }
296
297 private function add_timeout(RequestInterface $request, &$options, $value, &$params)
298 {
299 $options['http']['timeout'] = $value;
300 }
301
302 private function add_verify(RequestInterface $request, &$options, $value, &$params)
303 {
304 if ($value === true) {
305 // PHP 5.6 or greater will find the system cert by default. When
306 // < 5.6, use the Guzzle bundled cacert.
307 if (PHP_VERSION_ID < 50600) {
308 $options['ssl']['cafile'] = \GuzzleHttp\default_ca_bundle();
309 }
310 } elseif (is_string($value)) {
311 $options['ssl']['cafile'] = $value;
312 if (!file_exists($value)) {
313 throw new \RuntimeException("SSL CA bundle not found: $value");
314 }
315 } elseif ($value === false) {
316 $options['ssl']['verify_peer'] = false;
317 return;
318 } else {
319 throw new \InvalidArgumentException('Invalid verify request option');
320 }
321
322 $options['ssl']['verify_peer'] = true;
323 $options['ssl']['allow_self_signed'] = false;
324 }
325
326 private function add_cert(RequestInterface $request, &$options, $value, &$params)
327 {
328 if (is_array($value)) {
329 $options['ssl']['passphrase'] = $value[1];
330 $value = $value[0];
331 }
332
333 if (!file_exists($value)) {
334 throw new \RuntimeException("SSL certificate not found: {$value}");
335 }
336
337 $options['ssl']['local_cert'] = $value;
338 }
339
340 private function add_progress(RequestInterface $request, &$options, $value, &$params)
341 {
342 $this->addNotification(
343 $params,
344 function ($code, $a, $b, $c, $transferred, $total) use ($value) {
345 if ($code == STREAM_NOTIFY_PROGRESS) {
346 $value($total, $transferred, null, null);
347 }
348 }
349 );
350 }
351
352 private function add_debug(RequestInterface $request, &$options, $value, &$params)
353 {
354 if ($value === false) {
355 return;
356 }
357
358 static $map = [
359 STREAM_NOTIFY_CONNECT => 'CONNECT',
360 STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
361 STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
362 STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
363 STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
364 STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
365 STREAM_NOTIFY_PROGRESS => 'PROGRESS',
366 STREAM_NOTIFY_FAILURE => 'FAILURE',
367 STREAM_NOTIFY_COMPLETED => 'COMPLETED',
368 STREAM_NOTIFY_RESOLVE => 'RESOLVE',
369 ];
370 static $args = ['severity', 'message', 'message_code',
371 'bytes_transferred', 'bytes_max'];
372
373 $value = \GuzzleHttp\debug_resource($value);
374 $ident = $request->getMethod() . ' ' . $request->getUri();
375 $this->addNotification(
376 $params,
377 function () use ($ident, $value, $map, $args) {
378 $passed = func_get_args();
379 $code = array_shift($passed);
380 fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
381 foreach (array_filter($passed) as $i => $v) {
382 fwrite($value, $args[$i] . ': "' . $v . '" ');
383 }
384 fwrite($value, "\n");
385 }
386 );
387 }
388
389 private function addNotification(array &$params, callable $notify)
390 {
391 // Wrap the existing function if needed.
392 if (!isset($params['notification'])) {
393 $params['notification'] = $notify;
394 } else {
395 $params['notification'] = $this->callArray([
396 $params['notification'],
397 $notify
398 ]);
399 }
400 }
401
402 private function callArray(array $functions)
403 {
404 return function () use ($functions) {
405 $args = func_get_args();
406 foreach ($functions as $fn) {
407 call_user_func_array($fn, $args);
408 }
409 };
410 }
411}
Note: See TracBrowser for help on using the repository browser.