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