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