9ea8c569d1a5df22408386bb5ef7b1fa6aef0d2d
[lhc/web/wiklou.git] / includes / libs / http / MultiHttpClient.php
1 <?php
2 /**
3 * HTTP service client
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Class to handle multiple HTTP requests
30 *
31 * If curl is available, requests will be made concurrently.
32 * Otherwise, they will be made serially.
33 *
34 * HTTP request maps are arrays that use the following format:
35 * - method : GET/HEAD/PUT/POST/DELETE
36 * - url : HTTP/HTTPS URL
37 * - query : <query parameter field/value associative array> (uses RFC 3986)
38 * - headers : <header name/value associative array>
39 * - body : source to get the HTTP request body from;
40 * this can simply be a string (always), a resource for
41 * PUT requests, and a field/value array for POST request;
42 * array bodies are encoded as multipart/form-data and strings
43 * use application/x-www-form-urlencoded (headers sent automatically)
44 * - stream : resource to stream the HTTP response body to
45 * - proxy : HTTP proxy to use
46 * - flags : map of boolean flags which supports:
47 * - relayResponseHeaders : write out header via header()
48 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
49 *
50 * @since 1.23
51 */
52 class MultiHttpClient implements LoggerAwareInterface {
53 /** @var resource curl_multi_init() handle */
54 protected $cmh;
55 /** @var string|null SSL certificates path */
56 protected $caBundlePath;
57 /** @var float */
58 protected $connTimeout = 10;
59 /** @var float */
60 protected $reqTimeout = 900;
61 /** @var bool */
62 protected $usePipelining = false;
63 /** @var int */
64 protected $maxConnsPerHost = 50;
65 /** @var string|null proxy */
66 protected $proxy;
67 /** @var string */
68 protected $userAgent = 'wikimedia/multi-http-client v1.0';
69 /** @var LoggerInterface */
70 protected $logger;
71
72 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
73 // timeouts are periodically polled instead of being accurately respected.
74 // The select timeout is set to the minimum timeout multiplied by this factor.
75 const TIMEOUT_ACCURACY_FACTOR = 0.1;
76
77 /**
78 * @param array $options
79 * - connTimeout : default connection timeout (seconds)
80 * - reqTimeout : default request timeout (seconds)
81 * - proxy : HTTP proxy to use
82 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
83 * - maxConnsPerHost : maximum number of concurrent connections (per host)
84 * - userAgent : The User-Agent header value to send
85 * - logger : a \Psr\Log\LoggerInterface instance for debug logging
86 * - caBundlePath : path to specific Certificate Authority bundle (if any)
87 * @throws Exception
88 */
89 public function __construct( array $options ) {
90 if ( isset( $options['caBundlePath'] ) ) {
91 $this->caBundlePath = $options['caBundlePath'];
92 if ( !file_exists( $this->caBundlePath ) ) {
93 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
94 }
95 }
96 static $opts = [
97 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
98 'proxy', 'userAgent', 'logger'
99 ];
100 foreach ( $opts as $key ) {
101 if ( isset( $options[$key] ) ) {
102 $this->$key = $options[$key];
103 }
104 }
105 if ( $this->logger === null ) {
106 $this->logger = new NullLogger;
107 }
108 }
109
110 /**
111 * Execute an HTTP(S) request
112 *
113 * This method returns a response map of:
114 * - code : HTTP response code or 0 if there was a serious error
115 * - reason : HTTP response reason (empty if there was a serious error)
116 * - headers : <header name/value associative array>
117 * - body : HTTP response body or resource (if "stream" was set)
118 * - error : Any error string
119 * The map also stores integer-indexed copies of these values. This lets callers do:
120 * @code
121 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
122 * @endcode
123 * @param array $req HTTP request array
124 * @param array $opts
125 * - connTimeout : connection timeout per request (seconds)
126 * - reqTimeout : post-connection timeout per request (seconds)
127 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
128 * - maxConnsPerHost : maximum number of concurrent connections (per host)
129 * @return array Response array for request
130 */
131 public function run( array $req, array $opts = [] ) {
132 return $this->runMulti( [ $req ], $opts )[0]['response'];
133 }
134
135 /**
136 * Execute a set of HTTP(S) requests.
137 *
138 * If curl is available, requests will be made concurrently.
139 * Otherwise, they will be made serially.
140 *
141 * The maps are returned by this method with the 'response' field set to a map of:
142 * - code : HTTP response code or 0 if there was a serious error
143 * - reason : HTTP response reason (empty if there was a serious error)
144 * - headers : <header name/value associative array>
145 * - body : HTTP response body or resource (if "stream" was set)
146 * - error : Any error string
147 * The map also stores integer-indexed copies of these values. This lets callers do:
148 * @code
149 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
150 * @endcode
151 * All headers in the 'headers' field are normalized to use lower case names.
152 * This is true for the request headers and the response headers. Integer-indexed
153 * method/URL entries will also be changed to use the corresponding string keys.
154 *
155 * @param array[] $reqs Map of HTTP request arrays
156 * @param array $opts Options
157 * - connTimeout : connection timeout per request (seconds)
158 * - reqTimeout : post-connection timeout per request (seconds)
159 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
160 * - maxConnsPerHost : maximum number of concurrent connections (per host)
161 * @return array $reqs With response array populated for each
162 * @throws Exception
163 */
164 public function runMulti( array $reqs, array $opts = [] ) {
165 $this->normalizeRequests( $reqs );
166 $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
167
168 if ( $this->isCurlEnabled() ) {
169 return $this->runMultiCurl( $reqs, $opts );
170 } else {
171 return $this->runMultiHttp( $reqs, $opts );
172 }
173 }
174
175 /**
176 * Determines if the curl extension is available
177 *
178 * @return bool true if curl is available, false otherwise.
179 */
180 protected function isCurlEnabled() {
181 return extension_loaded( 'curl' );
182 }
183
184 /**
185 * Execute a set of HTTP(S) requests concurrently
186 *
187 * @see MultiHttpClient::runMulti()
188 *
189 * @param array[] $reqs Map of HTTP request arrays
190 * @param array $opts
191 * - connTimeout : connection timeout per request (seconds)
192 * - reqTimeout : post-connection timeout per request (seconds)
193 * - usePipelining : whether to use HTTP pipelining if possible
194 * - maxConnsPerHost : maximum number of concurrent connections (per host)
195 * @codingStandardsIgnoreStart
196 * @phan-param array{connTimeout?:int,reqTimeout?:int,usePipelining?:bool,maxConnsPerHost?:int} $opts
197 * @codingStandardsIgnoreEnd
198 * @return array $reqs With response array populated for each
199 * @throws Exception
200 * @suppress PhanTypeInvalidDimOffset
201 */
202 private function runMultiCurl( array $reqs, array $opts ) {
203 $chm = $this->getCurlMulti( $opts );
204
205 $selectTimeout = $this->getSelectTimeout( $opts );
206
207 // Add all of the required cURL handles...
208 $handles = [];
209 foreach ( $reqs as $index => &$req ) {
210 $handles[$index] = $this->getCurlHandle( $req, $opts );
211 curl_multi_add_handle( $chm, $handles[$index] );
212 }
213 unset( $req ); // don't assign over this by accident
214
215 $infos = [];
216 // Execute the cURL handles concurrently...
217 $active = null; // handles still being processed
218 do {
219 // Do any available work...
220 do {
221 $mrc = curl_multi_exec( $chm, $active );
222 $info = curl_multi_info_read( $chm );
223 if ( $info !== false ) {
224 $infos[(int)$info['handle']] = $info;
225 }
226 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
227 // Wait (if possible) for available work...
228 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
229 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
230 usleep( 5000 ); // 5ms
231 }
232 } while ( $active > 0 && $mrc == CURLM_OK );
233
234 // Remove all of the added cURL handles and check for errors...
235 foreach ( $reqs as $index => &$req ) {
236 $ch = $handles[$index];
237 curl_multi_remove_handle( $chm, $ch );
238
239 if ( isset( $infos[(int)$ch] ) ) {
240 $info = $infos[(int)$ch];
241 $errno = $info['result'];
242 if ( $errno !== 0 ) {
243 $req['response']['error'] = "(curl error: $errno)";
244 if ( function_exists( 'curl_strerror' ) ) {
245 $req['response']['error'] .= " " . curl_strerror( $errno );
246 }
247 $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
248 $req['response']['error'] );
249 }
250 } else {
251 $req['response']['error'] = "(curl error: no status set)";
252 }
253
254 // For convenience with the list() operator
255 $req['response'][0] = $req['response']['code'];
256 $req['response'][1] = $req['response']['reason'];
257 $req['response'][2] = $req['response']['headers'];
258 $req['response'][3] = $req['response']['body'];
259 $req['response'][4] = $req['response']['error'];
260 curl_close( $ch );
261 // Close any string wrapper file handles
262 if ( isset( $req['_closeHandle'] ) ) {
263 fclose( $req['_closeHandle'] );
264 unset( $req['_closeHandle'] );
265 }
266 }
267 unset( $req ); // don't assign over this by accident
268
269 return $reqs;
270 }
271
272 /**
273 * @param array &$req HTTP request map
274 * @codingStandardsIgnoreStart
275 * @phan-param array{url:string,proxy?:?string,query:mixed,method:string,body:string|resource,headers:string[],stream?:resource,flags:array} $req
276 * @codingStandardsIgnoreEnd
277 * @param array $opts
278 * - connTimeout : default connection timeout
279 * - reqTimeout : default request timeout
280 * @return resource
281 * @throws Exception
282 */
283 protected function getCurlHandle( array &$req, array $opts ) {
284 $ch = curl_init();
285
286 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
287 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
288 curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
289 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
290 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
291 curl_setopt( $ch, CURLOPT_HEADER, 0 );
292 if ( !is_null( $this->caBundlePath ) ) {
293 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
294 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
295 }
296 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
297
298 $url = $req['url'];
299 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
300 if ( $query != '' ) {
301 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
302 }
303 curl_setopt( $ch, CURLOPT_URL, $url );
304 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
305 curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
306
307 if ( $req['method'] === 'PUT' ) {
308 curl_setopt( $ch, CURLOPT_PUT, 1 );
309 if ( is_resource( $req['body'] ) ) {
310 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
311 if ( isset( $req['headers']['content-length'] ) ) {
312 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
313 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
314 $req['headers']['transfer-encoding'] === 'chunks'
315 ) {
316 curl_setopt( $ch, CURLOPT_UPLOAD, true );
317 } else {
318 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
319 }
320 } elseif ( $req['body'] !== '' ) {
321 $fp = fopen( "php://temp", "wb+" );
322 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
323 rewind( $fp );
324 curl_setopt( $ch, CURLOPT_INFILE, $fp );
325 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
326 $req['_closeHandle'] = $fp; // remember to close this later
327 } else {
328 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
329 }
330 curl_setopt( $ch, CURLOPT_READFUNCTION,
331 function ( $ch, $fd, $length ) {
332 return (string)fread( $fd, $length );
333 }
334 );
335 } elseif ( $req['method'] === 'POST' ) {
336 curl_setopt( $ch, CURLOPT_POST, 1 );
337 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
338 } else {
339 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
340 throw new Exception( "HTTP body specified for a non PUT/POST request." );
341 }
342 $req['headers']['content-length'] = 0;
343 }
344
345 if ( !isset( $req['headers']['user-agent'] ) ) {
346 $req['headers']['user-agent'] = $this->userAgent;
347 }
348
349 $headers = [];
350 foreach ( $req['headers'] as $name => $value ) {
351 if ( strpos( $name, ': ' ) ) {
352 throw new Exception( "Headers cannot have ':' in the name." );
353 }
354 $headers[] = $name . ': ' . trim( $value );
355 }
356 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
357
358 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
359 function ( $ch, $header ) use ( &$req ) {
360 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
361 header( $header );
362 }
363 $length = strlen( $header );
364 $matches = [];
365 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
366 $req['response']['code'] = (int)$matches[2];
367 $req['response']['reason'] = trim( $matches[3] );
368 return $length;
369 }
370 if ( strpos( $header, ":" ) === false ) {
371 return $length;
372 }
373 list( $name, $value ) = explode( ":", $header, 2 );
374 $name = strtolower( $name );
375 $value = trim( $value );
376 if ( isset( $req['response']['headers'][$name] ) ) {
377 $req['response']['headers'][$name] .= ', ' . $value;
378 } else {
379 $req['response']['headers'][$name] = $value;
380 }
381 return $length;
382 }
383 );
384
385 // This works with both file and php://temp handles (unlike CURLOPT_FILE)
386 $hasOutputStream = isset( $req['stream'] );
387 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
388 function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
389 if ( $hasOutputStream ) {
390 return fwrite( $req['stream'], $data );
391 } else {
392 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
393 $req['response']['body'] .= $data;
394
395 return strlen( $data );
396 }
397 }
398 );
399
400 return $ch;
401 }
402
403 /**
404 * @param array $opts
405 * @return resource
406 * @throws Exception
407 */
408 protected function getCurlMulti( array $opts ) {
409 if ( !$this->cmh ) {
410 if ( !function_exists( 'curl_multi_init' ) ) {
411 throw new Exception( "PHP cURL function curl_multi_init missing. " .
412 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
413 }
414 $cmh = curl_multi_init();
415 // Limit the size of the idle connection cache such that consecutive parallel
416 // request batches to the same host can avoid having to keep making connections
417 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
418 $this->cmh = $cmh;
419 }
420
421 // Limit the number of in-flight requests for any given host
422 $maxHostConns = $opts['maxConnsPerHost'] ?? $this->maxConnsPerHost;
423 curl_multi_setopt( $this->cmh, CURLMOPT_MAX_HOST_CONNECTIONS, (int)$maxHostConns );
424 // Configure when to multiplex multiple requests onto single TCP handles
425 $pipelining = $opts['usePipelining'] ?? $this->usePipelining;
426 curl_multi_setopt( $this->cmh, CURLMOPT_PIPELINING, (int)$pipelining );
427
428 return $this->cmh;
429 }
430
431 /**
432 * Execute a set of HTTP(S) requests sequentially.
433 *
434 * @see MultiHttpClient::runMulti()
435 * @todo Remove dependency on MediaWikiServices: use a separate HTTP client
436 * library or copy code from PhpHttpRequest
437 * @param array $reqs Map of HTTP request arrays
438 * @param array $opts
439 * - connTimeout : connection timeout per request (seconds)
440 * - reqTimeout : post-connection timeout per request (seconds)
441 * @return array $reqs With response array populated for each
442 * @throws Exception
443 */
444 private function runMultiHttp( array $reqs, array $opts = [] ) {
445 $httpOptions = [
446 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
447 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
448 'logger' => $this->logger,
449 'caInfo' => $this->caBundlePath,
450 ];
451 foreach ( $reqs as &$req ) {
452 $reqOptions = $httpOptions + [
453 'method' => $req['method'],
454 'proxy' => $req['proxy'] ?? $this->proxy,
455 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
456 'postData' => $req['body'],
457 ];
458
459 $url = $req['url'];
460 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
461 if ( $query != '' ) {
462 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
463 }
464
465 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
466 $url, $reqOptions );
467 $sv = $httpRequest->execute()->getStatusValue();
468
469 $respHeaders = array_map(
470 function ( $v ) {
471 return implode( ', ', $v );
472 },
473 $httpRequest->getResponseHeaders() );
474
475 $req['response'] = [
476 'code' => $httpRequest->getStatus(),
477 'reason' => '',
478 'headers' => $respHeaders,
479 'body' => $httpRequest->getContent(),
480 'error' => '',
481 ];
482
483 if ( !$sv->isOK() ) {
484 $svErrors = $sv->getErrors();
485 if ( isset( $svErrors[0] ) ) {
486 $req['response']['error'] = $svErrors[0]['message'];
487
488 // param values vary per failure type (ex. unknown host vs unknown page)
489 if ( isset( $svErrors[0]['params'][0] ) ) {
490 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
491 if ( isset( $svErrors[0]['params'][1] ) ) {
492 // @phan-suppress-next-line PhanTypeInvalidDimOffset
493 $req['response']['reason'] = $svErrors[0]['params'][1];
494 }
495 } else {
496 $req['response']['reason'] = $svErrors[0]['params'][0];
497 }
498 }
499 }
500 }
501
502 $req['response'][0] = $req['response']['code'];
503 $req['response'][1] = $req['response']['reason'];
504 $req['response'][2] = $req['response']['headers'];
505 $req['response'][3] = $req['response']['body'];
506 $req['response'][4] = $req['response']['error'];
507 }
508
509 return $reqs;
510 }
511
512 /**
513 * Normalize request information
514 *
515 * @param array[] $reqs the requests to normalize
516 */
517 private function normalizeRequests( array &$reqs ) {
518 foreach ( $reqs as &$req ) {
519 $req['response'] = [
520 'code' => 0,
521 'reason' => '',
522 'headers' => [],
523 'body' => '',
524 'error' => ''
525 ];
526 if ( isset( $req[0] ) ) {
527 $req['method'] = $req[0]; // short-form
528 unset( $req[0] );
529 }
530 if ( isset( $req[1] ) ) {
531 $req['url'] = $req[1]; // short-form
532 unset( $req[1] );
533 }
534 if ( !isset( $req['method'] ) ) {
535 throw new Exception( "Request has no 'method' field set." );
536 } elseif ( !isset( $req['url'] ) ) {
537 throw new Exception( "Request has no 'url' field set." );
538 }
539 $this->logger->debug( "{$req['method']}: {$req['url']}" );
540 $req['query'] = $req['query'] ?? [];
541 $headers = []; // normalized headers
542 if ( isset( $req['headers'] ) ) {
543 foreach ( $req['headers'] as $name => $value ) {
544 $headers[strtolower( $name )] = $value;
545 }
546 }
547 $req['headers'] = $headers;
548 if ( !isset( $req['body'] ) ) {
549 $req['body'] = '';
550 $req['headers']['content-length'] = 0;
551 }
552 $req['flags'] = $req['flags'] ?? [];
553 }
554 }
555
556 /**
557 * Get a suitable select timeout for the given options.
558 *
559 * @param array $opts
560 * @return float
561 */
562 private function getSelectTimeout( $opts ) {
563 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
564 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
565 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
566 if ( count( $timeouts ) === 0 ) {
567 return 1;
568 }
569
570 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
571 // Minimum 10us for sanity
572 if ( $selectTimeout < 10e-6 ) {
573 $selectTimeout = 10e-6;
574 }
575 return $selectTimeout;
576 }
577
578 /**
579 * Register a logger
580 *
581 * @param LoggerInterface $logger
582 */
583 public function setLogger( LoggerInterface $logger ) {
584 $this->logger = $logger;
585 }
586
587 function __destruct() {
588 if ( $this->cmh ) {
589 curl_multi_close( $this->cmh );
590 }
591 }
592 }