Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[lhc/web/wiklou.git] / includes / libs / 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
27 /**
28 * Class to handle concurrent HTTP requests
29 *
30 * HTTP request maps are arrays that use the following format:
31 * - method : GET/HEAD/PUT/POST/DELETE
32 * - url : HTTP/HTTPS URL
33 * - query : <query parameter field/value associative array> (uses RFC 3986)
34 * - headers : <header name/value associative array>
35 * - body : source to get the HTTP request body from;
36 * this can simply be a string (always), a resource for
37 * PUT requests, and a field/value array for POST request;
38 * array bodies are encoded as multipart/form-data and strings
39 * use application/x-www-form-urlencoded (headers sent automatically)
40 * - stream : resource to stream the HTTP response body to
41 * - proxy : HTTP proxy to use
42 * - flags : map of boolean flags which supports:
43 * - relayResponseHeaders : write out header via header()
44 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
45 *
46 * @since 1.23
47 */
48 class MultiHttpClient implements LoggerAwareInterface {
49 /** @var resource */
50 protected $multiHandle = null; // curl_multi handle
51 /** @var string|null SSL certificates path */
52 protected $caBundlePath;
53 /** @var float */
54 protected $connTimeout = 10;
55 /** @var float */
56 protected $reqTimeout = 300;
57 /** @var bool */
58 protected $usePipelining = false;
59 /** @var int */
60 protected $maxConnsPerHost = 50;
61 /** @var string|null proxy */
62 protected $proxy;
63 /** @var string */
64 protected $userAgent = 'wikimedia/multi-http-client v1.0';
65 /** @var LoggerInterface */
66 protected $logger;
67
68 // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
69 // timeouts are periodically polled instead of being accurately respected.
70 // The select timeout is set to the minimum timeout multiplied by this factor.
71 const TIMEOUT_ACCURACY_FACTOR = 0.1;
72
73 /**
74 * @param array $options
75 * - connTimeout : default connection timeout (seconds)
76 * - reqTimeout : default request timeout (seconds)
77 * - proxy : HTTP proxy to use
78 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
79 * - maxConnsPerHost : maximum number of concurrent connections (per host)
80 * - userAgent : The User-Agent header value to send
81 * @throws Exception
82 */
83 public function __construct( array $options ) {
84 if ( isset( $options['caBundlePath'] ) ) {
85 $this->caBundlePath = $options['caBundlePath'];
86 if ( !file_exists( $this->caBundlePath ) ) {
87 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
88 }
89 }
90 static $opts = [
91 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
92 'proxy', 'userAgent', 'logger'
93 ];
94 foreach ( $opts as $key ) {
95 if ( isset( $options[$key] ) ) {
96 $this->$key = $options[$key];
97 }
98 }
99 if ( $this->logger === null ) {
100 $this->logger = new NullLogger;
101 }
102 }
103
104 /**
105 * Execute an HTTP(S) request
106 *
107 * This method returns a response map of:
108 * - code : HTTP response code or 0 if there was a serious cURL error
109 * - reason : HTTP response reason (empty if there was a serious cURL error)
110 * - headers : <header name/value associative array>
111 * - body : HTTP response body or resource (if "stream" was set)
112 * - error : Any cURL error string
113 * The map also stores integer-indexed copies of these values. This lets callers do:
114 * @code
115 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
116 * @endcode
117 * @param array $req HTTP request array
118 * @param array $opts
119 * - connTimeout : connection timeout per request (seconds)
120 * - reqTimeout : post-connection timeout per request (seconds)
121 * @return array Response array for request
122 */
123 public function run( array $req, array $opts = [] ) {
124 return $this->runMulti( [ $req ], $opts )[0]['response'];
125 }
126
127 /**
128 * Execute a set of HTTP(S) requests concurrently
129 *
130 * The maps are returned by this method with the 'response' field set to a map of:
131 * - code : HTTP response code or 0 if there was a serious cURL error
132 * - reason : HTTP response reason (empty if there was a serious cURL error)
133 * - headers : <header name/value associative array>
134 * - body : HTTP response body or resource (if "stream" was set)
135 * - error : Any cURL error string
136 * The map also stores integer-indexed copies of these values. This lets callers do:
137 * @code
138 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
139 * @endcode
140 * All headers in the 'headers' field are normalized to use lower case names.
141 * This is true for the request headers and the response headers. Integer-indexed
142 * method/URL entries will also be changed to use the corresponding string keys.
143 *
144 * @param array $reqs Map of HTTP request arrays
145 * @param array $opts
146 * - connTimeout : connection timeout per request (seconds)
147 * - reqTimeout : post-connection timeout per request (seconds)
148 * - usePipelining : whether to use HTTP pipelining if possible
149 * - maxConnsPerHost : maximum number of concurrent connections (per host)
150 * @return array $reqs With response array populated for each
151 * @throws Exception
152 */
153 public function runMulti( array $reqs, array $opts = [] ) {
154 $chm = $this->getCurlMulti();
155
156 $selectTimeout = $this->getSelectTimeout( $opts );
157
158 // Normalize $reqs and add all of the required cURL handles...
159 $handles = [];
160 foreach ( $reqs as $index => &$req ) {
161 $req['response'] = [
162 'code' => 0,
163 'reason' => '',
164 'headers' => [],
165 'body' => '',
166 'error' => ''
167 ];
168 if ( isset( $req[0] ) ) {
169 $req['method'] = $req[0]; // short-form
170 unset( $req[0] );
171 }
172 if ( isset( $req[1] ) ) {
173 $req['url'] = $req[1]; // short-form
174 unset( $req[1] );
175 }
176 if ( !isset( $req['method'] ) ) {
177 throw new Exception( "Request has no 'method' field set." );
178 } elseif ( !isset( $req['url'] ) ) {
179 throw new Exception( "Request has no 'url' field set." );
180 }
181 $this->logger->debug( "{$req['method']}: {$req['url']}" );
182 $req['query'] = $req['query'] ?? [];
183 $headers = []; // normalized headers
184 if ( isset( $req['headers'] ) ) {
185 foreach ( $req['headers'] as $name => $value ) {
186 $headers[strtolower( $name )] = $value;
187 }
188 }
189 $req['headers'] = $headers;
190 if ( !isset( $req['body'] ) ) {
191 $req['body'] = '';
192 $req['headers']['content-length'] = 0;
193 }
194 $req['flags'] = $req['flags'] ?? [];
195 $handles[$index] = $this->getCurlHandle( $req, $opts );
196 if ( count( $reqs ) > 1 ) {
197 // https://github.com/guzzle/guzzle/issues/349
198 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
199 }
200 }
201 unset( $req ); // don't assign over this by accident
202
203 $indexes = array_keys( $reqs );
204 if ( isset( $opts['usePipelining'] ) ) {
205 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
206 }
207 if ( isset( $opts['maxConnsPerHost'] ) ) {
208 // Keep these sockets around as they may be needed later in the request
209 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
210 }
211
212 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
213 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
214 $infos = [];
215
216 foreach ( $batches as $batch ) {
217 // Attach all cURL handles for this batch
218 foreach ( $batch as $index ) {
219 curl_multi_add_handle( $chm, $handles[$index] );
220 }
221 // Execute the cURL handles concurrently...
222 $active = null; // handles still being processed
223 do {
224 // Do any available work...
225 do {
226 $mrc = curl_multi_exec( $chm, $active );
227 $info = curl_multi_info_read( $chm );
228 if ( $info !== false ) {
229 $infos[(int)$info['handle']] = $info;
230 }
231 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
232 // Wait (if possible) for available work...
233 if ( $active > 0 && $mrc == CURLM_OK ) {
234 if ( curl_multi_select( $chm, $selectTimeout ) == -1 ) {
235 // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
236 usleep( 5000 ); // 5ms
237 }
238 }
239 } while ( $active > 0 && $mrc == CURLM_OK );
240 }
241
242 // Remove all of the added cURL handles and check for errors...
243 foreach ( $reqs as $index => &$req ) {
244 $ch = $handles[$index];
245 curl_multi_remove_handle( $chm, $ch );
246
247 if ( isset( $infos[(int)$ch] ) ) {
248 $info = $infos[(int)$ch];
249 $errno = $info['result'];
250 if ( $errno !== 0 ) {
251 $req['response']['error'] = "(curl error: $errno)";
252 if ( function_exists( 'curl_strerror' ) ) {
253 $req['response']['error'] .= " " . curl_strerror( $errno );
254 }
255 $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
256 $req['response']['error'] );
257 }
258 } else {
259 $req['response']['error'] = "(curl error: no status set)";
260 }
261
262 // For convenience with the list() operator
263 $req['response'][0] = $req['response']['code'];
264 $req['response'][1] = $req['response']['reason'];
265 $req['response'][2] = $req['response']['headers'];
266 $req['response'][3] = $req['response']['body'];
267 $req['response'][4] = $req['response']['error'];
268 curl_close( $ch );
269 // Close any string wrapper file handles
270 if ( isset( $req['_closeHandle'] ) ) {
271 fclose( $req['_closeHandle'] );
272 unset( $req['_closeHandle'] );
273 }
274 }
275 unset( $req ); // don't assign over this by accident
276
277 // Restore the default settings
278 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
279 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
280
281 return $reqs;
282 }
283
284 /**
285 * @param array &$req HTTP request map
286 * @param array $opts
287 * - connTimeout : default connection timeout
288 * - reqTimeout : default request timeout
289 * @return resource
290 * @throws Exception
291 */
292 protected function getCurlHandle( array &$req, array $opts = [] ) {
293 $ch = curl_init();
294
295 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS,
296 ( $opts['connTimeout'] ?? $this->connTimeout ) * 1000 );
297 curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
298 curl_setopt( $ch, CURLOPT_TIMEOUT_MS,
299 ( $opts['reqTimeout'] ?? $this->reqTimeout ) * 1000 );
300 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
301 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
302 curl_setopt( $ch, CURLOPT_HEADER, 0 );
303 if ( !is_null( $this->caBundlePath ) ) {
304 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
305 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
306 }
307 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
308
309 $url = $req['url'];
310 $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
311 if ( $query != '' ) {
312 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
313 }
314 curl_setopt( $ch, CURLOPT_URL, $url );
315
316 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
317 if ( $req['method'] === 'HEAD' ) {
318 curl_setopt( $ch, CURLOPT_NOBODY, 1 );
319 }
320
321 if ( $req['method'] === 'PUT' ) {
322 curl_setopt( $ch, CURLOPT_PUT, 1 );
323 if ( is_resource( $req['body'] ) ) {
324 curl_setopt( $ch, CURLOPT_INFILE, $req['body'] );
325 if ( isset( $req['headers']['content-length'] ) ) {
326 curl_setopt( $ch, CURLOPT_INFILESIZE, $req['headers']['content-length'] );
327 } elseif ( isset( $req['headers']['transfer-encoding'] ) &&
328 $req['headers']['transfer-encoding'] === 'chunks'
329 ) {
330 curl_setopt( $ch, CURLOPT_UPLOAD, true );
331 } else {
332 throw new Exception( "Missing 'Content-Length' or 'Transfer-Encoding' header." );
333 }
334 } elseif ( $req['body'] !== '' ) {
335 $fp = fopen( "php://temp", "wb+" );
336 fwrite( $fp, $req['body'], strlen( $req['body'] ) );
337 rewind( $fp );
338 curl_setopt( $ch, CURLOPT_INFILE, $fp );
339 curl_setopt( $ch, CURLOPT_INFILESIZE, strlen( $req['body'] ) );
340 $req['_closeHandle'] = $fp; // remember to close this later
341 } else {
342 curl_setopt( $ch, CURLOPT_INFILESIZE, 0 );
343 }
344 curl_setopt( $ch, CURLOPT_READFUNCTION,
345 function ( $ch, $fd, $length ) {
346 $data = fread( $fd, $length );
347 $len = strlen( $data );
348 return $data;
349 }
350 );
351 } elseif ( $req['method'] === 'POST' ) {
352 curl_setopt( $ch, CURLOPT_POST, 1 );
353 // Don't interpret POST parameters starting with '@' as file uploads, because this
354 // makes it impossible to POST plain values starting with '@' (and causes security
355 // issues potentially exposing the contents of local files).
356 curl_setopt( $ch, CURLOPT_SAFE_UPLOAD, true );
357 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
358 } else {
359 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
360 throw new Exception( "HTTP body specified for a non PUT/POST request." );
361 }
362 $req['headers']['content-length'] = 0;
363 }
364
365 if ( !isset( $req['headers']['user-agent'] ) ) {
366 $req['headers']['user-agent'] = $this->userAgent;
367 }
368
369 $headers = [];
370 foreach ( $req['headers'] as $name => $value ) {
371 if ( strpos( $name, ': ' ) ) {
372 throw new Exception( "Headers cannot have ':' in the name." );
373 }
374 $headers[] = $name . ': ' . trim( $value );
375 }
376 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
377
378 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
379 function ( $ch, $header ) use ( &$req ) {
380 if ( !empty( $req['flags']['relayResponseHeaders'] ) ) {
381 header( $header );
382 }
383 $length = strlen( $header );
384 $matches = [];
385 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
386 $req['response']['code'] = (int)$matches[2];
387 $req['response']['reason'] = trim( $matches[3] );
388 return $length;
389 }
390 if ( strpos( $header, ":" ) === false ) {
391 return $length;
392 }
393 list( $name, $value ) = explode( ":", $header, 2 );
394 $req['response']['headers'][strtolower( $name )] = trim( $value );
395 return $length;
396 }
397 );
398
399 if ( isset( $req['stream'] ) ) {
400 // Don't just use CURLOPT_FILE as that might give:
401 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
402 // The callback here handles both normal files and php://temp handles.
403 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
404 function ( $ch, $data ) use ( &$req ) {
405 return fwrite( $req['stream'], $data );
406 }
407 );
408 } else {
409 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
410 function ( $ch, $data ) use ( &$req ) {
411 $req['response']['body'] .= $data;
412 return strlen( $data );
413 }
414 );
415 }
416
417 return $ch;
418 }
419
420 /**
421 * Get a suitable select timeout for the given options.
422 *
423 * @param array $opts
424 * @return float
425 */
426 private function getSelectTimeout( $opts ) {
427 $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
428 $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
429 $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
430 if ( count( $timeouts ) === 0 ) {
431 return 1;
432 }
433
434 $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
435 // Minimum 10us for sanity
436 if ( $selectTimeout < 10e-6 ) {
437 $selectTimeout = 10e-6;
438 }
439 return $selectTimeout;
440 }
441
442 /**
443 * @return resource
444 * @throws Exception
445 */
446 protected function getCurlMulti() {
447 if ( !$this->multiHandle ) {
448 if ( !function_exists( 'curl_multi_init' ) ) {
449 throw new Exception( "PHP cURL extension missing. " .
450 "Check https://www.mediawiki.org/wiki/Manual:CURL" );
451 }
452 $cmh = curl_multi_init();
453 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
454 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
455 $this->multiHandle = $cmh;
456 }
457 return $this->multiHandle;
458 }
459
460 /**
461 * Register a logger
462 *
463 * @param LoggerInterface $logger
464 */
465 public function setLogger( LoggerInterface $logger ) {
466 $this->logger = $logger;
467 }
468
469 function __destruct() {
470 if ( $this->multiHandle ) {
471 curl_multi_close( $this->multiHandle );
472 }
473 }
474 }