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