Merge "docs: Ignore .md from resources/lib in Doxyfile"
[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 */
54 protected $multiHandle = null; // curl_multi handle
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 * @return array Response array for request
128 */
129 public function run( array $req, array $opts = [] ) {
130 return $this->runMulti( [ $req ], $opts )[0]['response'];
131 }
132
133 /**
134 * Execute a set of HTTP(S) requests.
135 *
136 * If curl is available, requests will be made concurrently.
137 * Otherwise, they will be made serially.
138 *
139 * The maps are returned by this method with the 'response' field set to a map of:
140 * - code : HTTP response code or 0 if there was a serious error
141 * - reason : HTTP response reason (empty if there was a serious error)
142 * - headers : <header name/value associative array>
143 * - body : HTTP response body or resource (if "stream" was set)
144 * - error : Any error string
145 * The map also stores integer-indexed copies of these values. This lets callers do:
146 * @code
147 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
148 * @endcode
149 * All headers in the 'headers' field are normalized to use lower case names.
150 * This is true for the request headers and the response headers. Integer-indexed
151 * method/URL entries will also be changed to use the corresponding string keys.
152 *
153 * @param array[] $reqs Map of HTTP request arrays
154 * @param array $opts
155 * - connTimeout : connection timeout per request (seconds)
156 * - reqTimeout : post-connection timeout per request (seconds)
157 * - usePipelining : whether to use HTTP pipelining if possible
158 * - maxConnsPerHost : maximum number of concurrent connections (per host)
159 * @return array $reqs With response array populated for each
160 * @throws Exception
161 */
162 public function runMulti( array $reqs, array $opts = [] ) {
163 $this->normalizeRequests( $reqs );
164 $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
165
166 if ( $this->isCurlEnabled() ) {
167 return $this->runMultiCurl( $reqs, $opts );
168 } else {
169 return $this->runMultiHttp( $reqs, $opts );
170 }
171 }
172
173 /**
174 * Determines if the curl extension is available
175 *
176 * @return bool true if curl is available, false otherwise.
177 */
178 protected function isCurlEnabled() {
179 return extension_loaded( 'curl' );
180 }
181
182 /**
183 * Execute a set of HTTP(S) requests concurrently
184 *
185 * @see MultiHttpClient::runMulti()
186 *
187 * @param array[] $reqs Map of HTTP request arrays
188 * @param array $opts
189 * - connTimeout : connection timeout per request (seconds)
190 * - reqTimeout : post-connection timeout per request (seconds)
191 * - usePipelining : whether to use HTTP pipelining if possible
192 * - maxConnsPerHost : maximum number of concurrent connections (per host)
193 * @codingStandardsIgnoreStart
194 * @phan-param array{connTimeout?:int,reqTimeout?:int,usePipelining?:bool,maxConnsPerHost?:int} $opts
195 * @codingStandardsIgnoreEnd
196 * @return array $reqs With response array populated for each
197 * @throws Exception
198 * @suppress PhanTypeInvalidDimOffset
199 */
200 private function runMultiCurl( array $reqs, array $opts ) {
201 $chm = $this->getCurlMulti();
202
203 $selectTimeout = $this->getSelectTimeout( $opts );
204
205 // Add all of the required cURL handles...
206 $handles = [];
207 foreach ( $reqs as $index => &$req ) {
208 $handles[$index] = $this->getCurlHandle( $req, $opts );
209 if ( count( $reqs ) > 1 ) {
210 // https://github.com/guzzle/guzzle/issues/349
211 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
212 }
213 }
214 unset( $req ); // don't assign over this by accident
215
216 $indexes = array_keys( $reqs );
217 if ( isset( $opts['usePipelining'] ) ) {
218 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
219 }
220 if ( isset( $opts['maxConnsPerHost'] ) ) {
221 // Keep these sockets around as they may be needed later in the request
222 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
223 }
224
225 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
226 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
227 $infos = [];
228
229 foreach ( $batches as $batch ) {
230 // Attach all cURL handles for this batch
231 foreach ( $batch as $index ) {
232 curl_multi_add_handle( $chm, $handles[$index] );
233 }
234 // Execute the cURL handles concurrently...
235 $active = null; // handles still being processed
236 do {
237 // Do any available work...
238 do {
239 $mrc = curl_multi_exec( $chm, $active );
240 $info = curl_multi_info_read( $chm );
241 if ( $info !== false ) {
242 $infos[(int)$info['handle']] = $info;
243 }
244 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
245 // Wait (if possible) for available work...
246 if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
247 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
248 usleep( 5000 ); // 5ms
249 }
250 } while ( $active > 0 && $mrc == CURLM_OK );
251 }
252
253 // Remove all of the added cURL handles and check for errors...
254 foreach ( $reqs as $index => &$req ) {
255 $ch = $handles[$index];
256 curl_multi_remove_handle( $chm, $ch );
257
258 if ( isset( $infos[(int)$ch] ) ) {
259 $info = $infos[(int)$ch];
260 $errno = $info['result'];
261 if ( $errno !== 0 ) {
262 $req['response']['error'] = "(curl error: $errno)";
263 if ( function_exists( 'curl_strerror' ) ) {
264 $req['response']['error'] .= " " . curl_strerror( $errno );
265 }
266 $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
267 $req['response']['error'] );
268 }
269 } else {
270 $req['response']['error'] = "(curl error: no status set)";
271 }
272
273 // For convenience with the list() operator
274 $req['response'][0] = $req['response']['code'];
275 $req['response'][1] = $req['response']['reason'];
276 $req['response'][2] = $req['response']['headers'];
277 $req['response'][3] = $req['response']['body'];
278 $req['response'][4] = $req['response']['error'];
279 curl_close( $ch );
280 // Close any string wrapper file handles
281 if ( isset( $req['_closeHandle'] ) ) {
282 fclose( $req['_closeHandle'] );
283 unset( $req['_closeHandle'] );
284 }
285 }
286 unset( $req ); // don't assign over this by accident
287
288 // Restore the default settings
289 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
290 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
291
292 return $reqs;
293 }
294
295 /**
296 * @param array &$req HTTP request map
297 * @param array $opts
298 * - connTimeout : default connection timeout
299 * - reqTimeout : default request timeout
300 * @return resource
301 * @throws Exception
302 * @suppress PhanTypeMismatchArgumentInternal
303 */
304 protected function getCurlHandle( array &$req, array $opts ) {
305 $ch = curl_init();
306
307 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
308 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
309 curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
310 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
311 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
312 curl_setopt( $ch, CURLOPT_HEADER, 0 );
313 if ( !is_null( $this->caBundlePath ) ) {
314 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
315 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
316 }
317 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
318
319 $url = $req['url'];
320 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
321 if ( $query != '' ) {
322 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
323 }
324 curl_setopt( $ch, CURLOPT_URL, $url );
325 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
326 curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
327
328 if ( $req['method'] === 'PUT' ) {
329 curl_setopt( $ch, CURLOPT_PUT, 1 );
330 if ( is_resource( $req['body'] ) ) {
331 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
332 if ( isset( $req['headers']['content-length'] ) ) {
333 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
334 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
335 $req['headers']['transfer-encoding'] === 'chunks'
336 ) {
337 curl_setopt( $ch, CURLOPT_UPLOAD, true );
338 } else {
339 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
340 }
341 } elseif ( $req['body'] !== '' ) {
342 $fp = fopen( "php://temp", "wb+" );
343 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
344 rewind( $fp );
345 curl_setopt( $ch, CURLOPT_INFILE, $fp );
346 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
347 $req['_closeHandle'] = $fp; // remember to close this later
348 } else {
349 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
350 }
351 curl_setopt( $ch, CURLOPT_READFUNCTION,
352 function ( $ch, $fd, $length ) {
353 return (string)fread( $fd, $length );
354 }
355 );
356 } elseif ( $req['method'] === 'POST' ) {
357 curl_setopt( $ch, CURLOPT_POST, 1 );
358 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
359 } else {
360 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
361 throw new Exception( "HTTP body specified for a non PUT/POST request." );
362 }
363 $req['headers']['content-length'] = 0;
364 }
365
366 if ( !isset( $req['headers']['user-agent'] ) ) {
367 $req['headers']['user-agent'] = $this->userAgent;
368 }
369
370 $headers = [];
371 foreach ( $req['headers'] as $name => $value ) {
372 if ( strpos( $name, ': ' ) ) {
373 throw new Exception( "Headers cannot have ':' in the name." );
374 }
375 $headers[] = $name . ': ' . trim( $value );
376 }
377 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
378
379 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
380 function ( $ch, $header ) use ( &$req ) {
381 if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
382 header( $header );
383 }
384 $length = strlen( $header );
385 $matches = [];
386 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
387 $req['response']['code'] = (int)$matches[2];
388 $req['response']['reason'] = trim( $matches[3] );
389 return $length;
390 }
391 if ( strpos( $header, ":" ) === false ) {
392 return $length;
393 }
394 list( $name, $value ) = explode( ":", $header, 2 );
395 $name = strtolower( $name );
396 $value = trim( $value );
397 if ( isset( $req['response']['headers'][$name] ) ) {
398 $req['response']['headers'][$name] .= ', ' . $value;
399 } else {
400 $req['response']['headers'][$name] = $value;
401 }
402 return $length;
403 }
404 );
405
406 // This works with both file and php://temp handles (unlike CURLOPT_FILE)
407 $hasOutputStream = isset( $req['stream'] );
408 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
409 function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
410 if ( $hasOutputStream ) {
411 return fwrite( $req['stream'], $data );
412 } else {
413 $req['response']['body'] .= $data;
414
415 return strlen( $data );
416 }
417 }
418 );
419
420 return $ch;
421 }
422
423 /**
424 * @return resource
425 * @throws Exception
426 */
427 protected function getCurlMulti() {
428 if ( !$this->multiHandle ) {
429 if ( !function_exists( 'curl_multi_init' ) ) {
430 throw new Exception( "PHP cURL function curl_multi_init missing. " .
431 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
432 }
433 $cmh = curl_multi_init();
434 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
435 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
436 $this->multiHandle = $cmh;
437 }
438 return $this->multiHandle;
439 }
440
441 /**
442 * Execute a set of HTTP(S) requests sequentially.
443 *
444 * @see MultiHttpClient::runMulti()
445 * @todo Remove dependency on MediaWikiServices: use a separate HTTP client
446 * library or copy code from PhpHttpRequest
447 * @param array $reqs Map of HTTP request arrays
448 * @param array $opts
449 * - connTimeout : connection timeout per request (seconds)
450 * - reqTimeout : post-connection timeout per request (seconds)
451 * @return array $reqs With response array populated for each
452 * @throws Exception
453 */
454 private function runMultiHttp( array $reqs, array $opts = [] ) {
455 $httpOptions = [
456 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
457 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
458 'logger' => $this->logger,
459 'caInfo' => $this->caBundlePath,
460 ];
461 foreach ( $reqs as &$req ) {
462 $reqOptions = $httpOptions + [
463 'method' => $req['method'],
464 'proxy' => $req['proxy'] ?? $this->proxy,
465 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
466 'postData' => $req['body'],
467 ];
468
469 $url = $req['url'];
470 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
471 if ( $query != '' ) {
472 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
473 }
474
475 $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
476 $url, $reqOptions );
477 $sv = $httpRequest->execute()->getStatusValue();
478
479 $respHeaders = array_map(
480 function ( $v ) {
481 return implode( ', ', $v );
482 },
483 $httpRequest->getResponseHeaders() );
484
485 $req['response'] = [
486 'code' => $httpRequest->getStatus(),
487 'reason' => '',
488 'headers' => $respHeaders,
489 'body' => $httpRequest->getContent(),
490 'error' => '',
491 ];
492
493 if ( !$sv->isOK() ) {
494 $svErrors = $sv->getErrors();
495 if ( isset( $svErrors[0] ) ) {
496 $req['response']['error'] = $svErrors[0]['message'];
497
498 // param values vary per failure type (ex. unknown host vs unknown page)
499 if ( isset( $svErrors[0]['params'][0] ) ) {
500 if ( is_numeric( $svErrors[0]['params'][0] ) ) {
501 if ( isset( $svErrors[0]['params'][1] ) ) {
502 // @phan-suppress-next-line PhanTypeInvalidDimOffset
503 $req['response']['reason'] = $svErrors[0]['params'][1];
504 }
505 } else {
506 $req['response']['reason'] = $svErrors[0]['params'][0];
507 }
508 }
509 }
510 }
511
512 $req['response'][0] = $req['response']['code'];
513 $req['response'][1] = $req['response']['reason'];
514 $req['response'][2] = $req['response']['headers'];
515 $req['response'][3] = $req['response']['body'];
516 $req['response'][4] = $req['response']['error'];
517 }
518
519 return $reqs;
520 }
521
522 /**
523 * Normalize request information
524 *
525 * @param array[] $reqs the requests to normalize
526 */
527 private function normalizeRequests( array &$reqs ) {
528 foreach ( $reqs as &$req ) {
529 $req['response'] = [
530 'code' => 0,
531 'reason' => '',
532 'headers' => [],
533 'body' => '',
534 'error' => ''
535 ];
536 if ( isset( $req[0] ) ) {
537 $req['method'] = $req[0]; // short-form
538 unset( $req[0] );
539 }
540 if ( isset( $req[1] ) ) {
541 $req['url'] = $req[1]; // short-form
542 unset( $req[1] );
543 }
544 if ( !isset( $req['method'] ) ) {
545 throw new Exception( "Request has no 'method' field set." );
546 } elseif ( !isset( $req['url'] ) ) {
547 throw new Exception( "Request has no 'url' field set." );
548 }
549 $this->logger->debug( "{$req['method']}: {$req['url']}" );
550 $req['query'] = $req['query'] ?? [];
551 $headers = []; // normalized headers
552 if ( isset( $req['headers'] ) ) {
553 foreach ( $req['headers'] as $name => $value ) {
554 $headers[strtolower( $name )] = $value;
555 }
556 }
557 $req['headers'] = $headers;
558 if ( !isset( $req['body'] ) ) {
559 $req['body'] = '';
560 $req['headers']['content-length'] = 0;
561 }
562 $req['flags'] = $req['flags'] ?? [];
563 }
564 }
565
566 /**
567 * Get a suitable select timeout for the given options.
568 *
569 * @param array $opts
570 * @return float
571 */
572 private function getSelectTimeout( $opts ) {
573 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
574 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
575 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
576 if ( count( $timeouts ) === 0 ) {
577 return 1;
578 }
579
580 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
581 // Minimum 10us for sanity
582 if ( $selectTimeout < 10e-6 ) {
583 $selectTimeout = 10e-6;
584 }
585 return $selectTimeout;
586 }
587
588 /**
589 * Register a logger
590 *
591 * @param LoggerInterface $logger
592 */
593 public function setLogger( LoggerInterface $logger ) {
594 $this->logger = $logger;
595 }
596
597 function __destruct() {
598 if ( $this->multiHandle ) {
599 curl_multi_close( $this->multiHandle );
600 }
601 }
602 }