MultiHttpClient: Don't use "MW" in User-Agent
[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 /**
24 * Class to handle concurrent HTTP requests
25 *
26 * HTTP request maps are arrays that use the following format:
27 * - method : GET/HEAD/PUT/POST/DELETE
28 * - url : HTTP/HTTPS URL
29 * - query : <query parameter field/value associative array> (uses RFC 3986)
30 * - headers : <header name/value associative array>
31 * - body : source to get the HTTP request body from;
32 * this can simply be a string (always), a resource for
33 * PUT requests, and a field/value array for POST request;
34 * array bodies are encoded as multipart/form-data and strings
35 * use application/x-www-form-urlencoded (headers sent automatically)
36 * - stream : resource to stream the HTTP response body to
37 * - proxy : HTTP proxy to use
38 * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
39 *
40 * @author Aaron Schulz
41 * @since 1.23
42 */
43 class MultiHttpClient {
44 /** @var resource */
45 protected $multiHandle = null; // curl_multi handle
46 /** @var string|null SSL certificates path */
47 protected $caBundlePath;
48 /** @var integer */
49 protected $connTimeout = 10;
50 /** @var integer */
51 protected $reqTimeout = 300;
52 /** @var bool */
53 protected $usePipelining = false;
54 /** @var integer */
55 protected $maxConnsPerHost = 50;
56 /** @var string|null proxy */
57 protected $proxy;
58
59 /**
60 * @param array $options
61 * - connTimeout : default connection timeout (seconds)
62 * - reqTimeout : default request timeout (seconds)
63 * - proxy : HTTP proxy to use
64 * - usePipelining : whether to use HTTP pipelining if possible (for all hosts)
65 * - maxConnsPerHost : maximum number of concurrent connections (per host)
66 * - userAgent : The User-Agent header value to send
67 * @throws Exception
68 */
69 public function __construct( array $options ) {
70 if ( isset( $options['caBundlePath'] ) ) {
71 $this->caBundlePath = $options['caBundlePath'];
72 if ( !file_exists( $this->caBundlePath ) ) {
73 throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
74 }
75 }
76 static $opts = array(
77 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost', 'proxy', 'userAgent'
78 );
79 foreach ( $opts as $key ) {
80 if ( isset( $options[$key] ) ) {
81 $this->$key = $options[$key];
82 }
83 }
84 }
85
86 /**
87 * Execute an HTTP(S) request
88 *
89 * This method returns a response map of:
90 * - code : HTTP response code or 0 if there was a serious cURL error
91 * - reason : HTTP response reason (empty if there was a serious cURL error)
92 * - headers : <header name/value associative array>
93 * - body : HTTP response body or resource (if "stream" was set)
94 * - error : Any cURL error string
95 * The map also stores integer-indexed copies of these values. This lets callers do:
96 * @code
97 * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
98 * @endcode
99 * @param array $req HTTP request array
100 * @param array $opts
101 * - connTimeout : connection timeout per request (seconds)
102 * - reqTimeout : post-connection timeout per request (seconds)
103 * @return array Response array for request
104 */
105 final public function run( array $req, array $opts = array() ) {
106 $req = $this->runMulti( array( $req ), $opts );
107 return $req[0]['response'];
108 }
109
110 /**
111 * Execute a set of HTTP(S) requests concurrently
112 *
113 * The maps are returned by this method with the 'response' field set to a map of:
114 * - code : HTTP response code or 0 if there was a serious cURL error
115 * - reason : HTTP response reason (empty if there was a serious cURL error)
116 * - headers : <header name/value associative array>
117 * - body : HTTP response body or resource (if "stream" was set)
118 * - error : Any cURL 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 ) = $req['response'];
122 * @endcode
123 * All headers in the 'headers' field are normalized to use lower case names.
124 * This is true for the request headers and the response headers. Integer-indexed
125 * method/URL entries will also be changed to use the corresponding string keys.
126 *
127 * @param array $reqs Map of HTTP request arrays
128 * @param array $opts
129 * - connTimeout : connection timeout per request (seconds)
130 * - reqTimeout : post-connection timeout per request (seconds)
131 * - usePipelining : whether to use HTTP pipelining if possible
132 * - maxConnsPerHost : maximum number of concurrent connections (per host)
133 * @return array $reqs With response array populated for each
134 * @throws Exception
135 */
136 public function runMulti( array $reqs, array $opts = array() ) {
137 $chm = $this->getCurlMulti();
138
139 // Normalize $reqs and add all of the required cURL handles...
140 $handles = array();
141 foreach ( $reqs as $index => &$req ) {
142 $req['response'] = array(
143 'code' => 0,
144 'reason' => '',
145 'headers' => array(),
146 'body' => '',
147 'error' => ''
148 );
149 if ( isset( $req[0] ) ) {
150 $req['method'] = $req[0]; // short-form
151 unset( $req[0] );
152 }
153 if ( isset( $req[1] ) ) {
154 $req['url'] = $req[1]; // short-form
155 unset( $req[1] );
156 }
157 if ( !isset( $req['method'] ) ) {
158 throw new Exception( "Request has no 'method' field set." );
159 } elseif ( !isset( $req['url'] ) ) {
160 throw new Exception( "Request has no 'url' field set." );
161 }
162 $req['query'] = isset( $req['query'] ) ? $req['query'] : array();
163 $headers = array(); // normalized headers
164 if ( isset( $req['headers'] ) ) {
165 foreach ( $req['headers'] as $name => $value ) {
166 $headers[strtolower( $name )] = $value;
167 }
168 }
169 $req['headers'] = $headers;
170 if ( !isset( $req['body'] ) ) {
171 $req['body'] = '';
172 $req['headers']['content-length'] = 0;
173 }
174 $handles[$index] = $this->getCurlHandle( $req, $opts );
175 if ( count( $reqs ) > 1 ) {
176 // https://github.com/guzzle/guzzle/issues/349
177 curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
178 }
179 }
180 unset( $req ); // don't assign over this by accident
181
182 $indexes = array_keys( $reqs );
183 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
184 if ( isset( $opts['usePipelining'] ) ) {
185 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
186 }
187 if ( isset( $opts['maxConnsPerHost'] ) ) {
188 // Keep these sockets around as they may be needed later in the request
189 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
190 }
191 }
192
193 // @TODO: use a per-host rolling handle window (e.g. CURLMOPT_MAX_HOST_CONNECTIONS)
194 $batches = array_chunk( $indexes, $this->maxConnsPerHost );
195 $infos = array();
196
197 foreach ( $batches as $batch ) {
198 // Attach all cURL handles for this batch
199 foreach ( $batch as $index ) {
200 curl_multi_add_handle( $chm, $handles[$index] );
201 }
202 // Execute the cURL handles concurrently...
203 $active = null; // handles still being processed
204 do {
205 // Do any available work...
206 do {
207 $mrc = curl_multi_exec( $chm, $active );
208 $info = curl_multi_info_read( $chm );
209 if ( $info !== false ) {
210 $infos[(int)$info['handle']] = $info;
211 }
212 } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
213 // Wait (if possible) for available work...
214 if ( $active > 0 && $mrc == CURLM_OK ) {
215 if ( curl_multi_select( $chm, 10 ) == -1 ) {
216 // PHP bug 63411; http://curl.haxx.se/libcurl/c/curl_multi_fdset.html
217 usleep( 5000 ); // 5ms
218 }
219 }
220 } while ( $active > 0 && $mrc == CURLM_OK );
221 }
222
223 // Remove all of the added cURL handles and check for errors...
224 foreach ( $reqs as $index => &$req ) {
225 $ch = $handles[$index];
226 curl_multi_remove_handle( $chm, $ch );
227
228 if ( isset( $infos[(int)$ch] ) ) {
229 $info = $infos[(int)$ch];
230 $errno = $info['result'];
231 if ( $errno !== 0 ) {
232 $req['response']['error'] = "(curl error: $errno)";
233 if ( function_exists( 'curl_strerror' ) ) {
234 $req['response']['error'] .= " " . curl_strerror( $errno );
235 }
236 }
237 } else {
238 $req['response']['error'] = "(curl error: no status set)";
239 }
240
241 // For convenience with the list() operator
242 $req['response'][0] = $req['response']['code'];
243 $req['response'][1] = $req['response']['reason'];
244 $req['response'][2] = $req['response']['headers'];
245 $req['response'][3] = $req['response']['body'];
246 $req['response'][4] = $req['response']['error'];
247 curl_close( $ch );
248 // Close any string wrapper file handles
249 if ( isset( $req['_closeHandle'] ) ) {
250 fclose( $req['_closeHandle'] );
251 unset( $req['_closeHandle'] );
252 }
253 }
254 unset( $req ); // don't assign over this by accident
255
256 // Restore the default settings
257 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
258 curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
259 curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
260 }
261
262 return $reqs;
263 }
264
265 /**
266 * @param array $req HTTP request map
267 * @param array $opts
268 * - connTimeout : default connection timeout
269 * - reqTimeout : default request timeout
270 * @return resource
271 * @throws Exception
272 */
273 protected function getCurlHandle( array &$req, array $opts = array() ) {
274 $ch = curl_init();
275
276 curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT,
277 isset( $opts['connTimeout'] ) ? $opts['connTimeout'] : $this->connTimeout );
278 curl_setopt( $ch, CURLOPT_PROXY, isset( $req['proxy'] ) ? $req['proxy'] : $this->proxy );
279 curl_setopt( $ch, CURLOPT_TIMEOUT,
280 isset( $opts['reqTimeout'] ) ? $opts['reqTimeout'] : $this->reqTimeout );
281 curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
282 curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
283 curl_setopt( $ch, CURLOPT_HEADER, 0 );
284 if ( !is_null( $this->caBundlePath ) ) {
285 curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
286 curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
287 }
288 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
289
290 $url = $req['url'];
291 // PHP_QUERY_RFC3986 is PHP 5.4+ only
292 $query = str_replace(
293 array( '+', '%7E' ),
294 array( '%20', '~' ),
295 http_build_query( $req['query'], '', '&' )
296 );
297 if ( $query != '' ) {
298 $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
299 }
300 curl_setopt( $ch, CURLOPT_URL, $url );
301
302 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
303 if ( $req['method'] === 'HEAD' ) {
304 curl_setopt( $ch, CURLOPT_NOBODY, 1 );
305 }
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 $data = fread( $fd, $length );
333 $len = strlen( $data );
334 return $data;
335 }
336 );
337 } elseif ( $req['method'] === 'POST' ) {
338 curl_setopt( $ch, CURLOPT_POST, 1 );
339 curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
340 } else {
341 if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
342 throw new Exception( "HTTP body specified for a non PUT/POST request." );
343 }
344 $req['headers']['content-length'] = 0;
345 }
346
347 if ( !isset( $req['headers']['user-agent'] ) ) {
348 $req['headers']['user-agent'] = self::userAgent();
349 }
350
351 $headers = array();
352 foreach ( $req['headers'] as $name => $value ) {
353 if ( strpos( $name, ': ' ) ) {
354 throw new Exception( "Headers cannot have ':' in the name." );
355 }
356 $headers[] = $name . ': ' . trim( $value );
357 }
358 curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
359
360 curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
361 function ( $ch, $header ) use ( &$req ) {
362 $length = strlen( $header );
363 $matches = array();
364 if ( preg_match( "/^(HTTP\/1\.[01]) (\d{3}) (.*)/", $header, $matches ) ) {
365 $req['response']['code'] = (int)$matches[2];
366 $req['response']['reason'] = trim( $matches[3] );
367 return $length;
368 }
369 if ( strpos( $header, ":" ) === false ) {
370 return $length;
371 }
372 list( $name, $value ) = explode( ":", $header, 2 );
373 $req['response']['headers'][strtolower( $name )] = trim( $value );
374 return $length;
375 }
376 );
377
378 if ( isset( $req['stream'] ) ) {
379 // Don't just use CURLOPT_FILE as that might give:
380 // curl_setopt(): cannot represent a stream of type Output as a STDIO FILE*
381 // The callback here handles both normal files and php://temp handles.
382 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
383 function ( $ch, $data ) use ( &$req ) {
384 return fwrite( $req['stream'], $data );
385 }
386 );
387 } else {
388 curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
389 function ( $ch, $data ) use ( &$req ) {
390 $req['response']['body'] .= $data;
391 return strlen( $data );
392 }
393 );
394 }
395
396 return $ch;
397 }
398
399 /**
400 * @return resource
401 */
402 protected function getCurlMulti() {
403 if ( !$this->multiHandle ) {
404 $cmh = curl_multi_init();
405 if ( function_exists( 'curl_multi_setopt' ) ) { // PHP 5.5
406 curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
407 curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
408 }
409 $this->multiHandle = $cmh;
410 }
411 return $this->multiHandle;
412 }
413
414 function __destruct() {
415 if ( $this->multiHandle ) {
416 curl_multi_close( $this->multiHandle );
417 }
418 }
419
420 /**
421 * The default User-Agent for requests.
422 * @return string
423 */
424 public static function userAgent() {
425 return 'wikimedia/multi-http-client v1.0';
426 }
427 }