MultiHttpClient.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. use Psr\Log\LoggerAwareInterface;
  23. use Psr\Log\LoggerInterface;
  24. use Psr\Log\NullLogger;
  25. use MediaWiki\MediaWikiServices;
  26. /**
  27. * Class to handle multiple HTTP requests
  28. *
  29. * If curl is available, requests will be made concurrently.
  30. * Otherwise, they will be made serially.
  31. *
  32. * HTTP request maps are arrays that use the following format:
  33. * - method : GET/HEAD/PUT/POST/DELETE
  34. * - url : HTTP/HTTPS URL
  35. * - query : <query parameter field/value associative array> (uses RFC 3986)
  36. * - headers : <header name/value associative array>
  37. * - body : source to get the HTTP request body from;
  38. * this can simply be a string (always), a resource for
  39. * PUT requests, and a field/value array for POST request;
  40. * array bodies are encoded as multipart/form-data and strings
  41. * use application/x-www-form-urlencoded (headers sent automatically)
  42. * - stream : resource to stream the HTTP response body to
  43. * - proxy : HTTP proxy to use
  44. * - flags : map of boolean flags which supports:
  45. * - relayResponseHeaders : write out header via header()
  46. * Request maps can use integer index 0 instead of 'method' and 1 instead of 'url'.
  47. *
  48. * @since 1.23
  49. */
  50. class MultiHttpClient implements LoggerAwareInterface {
  51. /** @var resource */
  52. protected $multiHandle = null; // curl_multi handle
  53. /** @var string|null SSL certificates path */
  54. protected $caBundlePath;
  55. /** @var float */
  56. protected $connTimeout = 10;
  57. /** @var float */
  58. protected $reqTimeout = 900;
  59. /** @var bool */
  60. protected $usePipelining = false;
  61. /** @var int */
  62. protected $maxConnsPerHost = 50;
  63. /** @var string|null proxy */
  64. protected $proxy;
  65. /** @var string */
  66. protected $userAgent = 'wikimedia/multi-http-client v1.0';
  67. /** @var LoggerInterface */
  68. protected $logger;
  69. // In PHP 7 due to https://bugs.php.net/bug.php?id=76480 the request/connect
  70. // timeouts are periodically polled instead of being accurately respected.
  71. // The select timeout is set to the minimum timeout multiplied by this factor.
  72. const TIMEOUT_ACCURACY_FACTOR = 0.1;
  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. * - logger : a \Psr\Log\LoggerInterface instance for debug logging
  82. * - caBundlePath : path to specific Certificate Authority bundle (if any)
  83. * @throws Exception
  84. */
  85. public function __construct( array $options ) {
  86. if ( isset( $options['caBundlePath'] ) ) {
  87. $this->caBundlePath = $options['caBundlePath'];
  88. if ( !file_exists( $this->caBundlePath ) ) {
  89. throw new Exception( "Cannot find CA bundle: " . $this->caBundlePath );
  90. }
  91. }
  92. static $opts = [
  93. 'connTimeout', 'reqTimeout', 'usePipelining', 'maxConnsPerHost',
  94. 'proxy', 'userAgent', 'logger'
  95. ];
  96. foreach ( $opts as $key ) {
  97. if ( isset( $options[$key] ) ) {
  98. $this->$key = $options[$key];
  99. }
  100. }
  101. if ( $this->logger === null ) {
  102. $this->logger = new NullLogger;
  103. }
  104. }
  105. /**
  106. * Execute an HTTP(S) request
  107. *
  108. * This method returns a response map of:
  109. * - code : HTTP response code or 0 if there was a serious error
  110. * - reason : HTTP response reason (empty if there was a serious error)
  111. * - headers : <header name/value associative array>
  112. * - body : HTTP response body or resource (if "stream" was set)
  113. * - error : Any error string
  114. * The map also stores integer-indexed copies of these values. This lets callers do:
  115. * @code
  116. * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $http->run( $req );
  117. * @endcode
  118. * @param array $req HTTP request array
  119. * @param array $opts
  120. * - connTimeout : connection timeout per request (seconds)
  121. * - reqTimeout : post-connection timeout per request (seconds)
  122. * @return array Response array for request
  123. */
  124. public function run( array $req, array $opts = [] ) {
  125. return $this->runMulti( [ $req ], $opts )[0]['response'];
  126. }
  127. /**
  128. * Execute a set of HTTP(S) requests.
  129. *
  130. * If curl is available, requests will be made concurrently.
  131. * Otherwise, they will be made serially.
  132. *
  133. * The maps are returned by this method with the 'response' field set to a map of:
  134. * - code : HTTP response code or 0 if there was a serious error
  135. * - reason : HTTP response reason (empty if there was a serious error)
  136. * - headers : <header name/value associative array>
  137. * - body : HTTP response body or resource (if "stream" was set)
  138. * - error : Any error string
  139. * The map also stores integer-indexed copies of these values. This lets callers do:
  140. * @code
  141. * list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $req['response'];
  142. * @endcode
  143. * All headers in the 'headers' field are normalized to use lower case names.
  144. * This is true for the request headers and the response headers. Integer-indexed
  145. * method/URL entries will also be changed to use the corresponding string keys.
  146. *
  147. * @param array[] $reqs Map of HTTP request arrays
  148. * @param array $opts
  149. * - connTimeout : connection timeout per request (seconds)
  150. * - reqTimeout : post-connection timeout per request (seconds)
  151. * - usePipelining : whether to use HTTP pipelining if possible
  152. * - maxConnsPerHost : maximum number of concurrent connections (per host)
  153. * @return array $reqs With response array populated for each
  154. * @throws Exception
  155. */
  156. public function runMulti( array $reqs, array $opts = [] ) {
  157. $this->normalizeRequests( $reqs );
  158. $opts += [ 'connTimeout' => $this->connTimeout, 'reqTimeout' => $this->reqTimeout ];
  159. if ( $this->isCurlEnabled() ) {
  160. return $this->runMultiCurl( $reqs, $opts );
  161. } else {
  162. return $this->runMultiHttp( $reqs, $opts );
  163. }
  164. }
  165. /**
  166. * Determines if the curl extension is available
  167. *
  168. * @return bool true if curl is available, false otherwise.
  169. */
  170. protected function isCurlEnabled() {
  171. return extension_loaded( 'curl' );
  172. }
  173. /**
  174. * Execute a set of HTTP(S) requests concurrently
  175. *
  176. * @see MultiHttpClient::runMulti()
  177. *
  178. * @param array[] $reqs Map of HTTP request arrays
  179. * @param array $opts
  180. * - connTimeout : connection timeout per request (seconds)
  181. * - reqTimeout : post-connection timeout per request (seconds)
  182. * - usePipelining : whether to use HTTP pipelining if possible
  183. * - maxConnsPerHost : maximum number of concurrent connections (per host)
  184. * @codingStandardsIgnoreStart
  185. * @phan-param array{connTimeout?:int,reqTimeout?:int,usePipelining?:bool,maxConnsPerHost?:int} $opts
  186. * @codingStandardsIgnoreEnd
  187. * @return array $reqs With response array populated for each
  188. * @throws Exception
  189. * @suppress PhanTypeInvalidDimOffset
  190. */
  191. private function runMultiCurl( array $reqs, array $opts ) {
  192. $chm = $this->getCurlMulti();
  193. $selectTimeout = $this->getSelectTimeout( $opts );
  194. // Add all of the required cURL handles...
  195. $handles = [];
  196. foreach ( $reqs as $index => &$req ) {
  197. $handles[$index] = $this->getCurlHandle( $req, $opts );
  198. if ( count( $reqs ) > 1 ) {
  199. // https://github.com/guzzle/guzzle/issues/349
  200. curl_setopt( $handles[$index], CURLOPT_FORBID_REUSE, true );
  201. }
  202. }
  203. unset( $req ); // don't assign over this by accident
  204. $indexes = array_keys( $reqs );
  205. if ( isset( $opts['usePipelining'] ) ) {
  206. curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$opts['usePipelining'] );
  207. }
  208. if ( isset( $opts['maxConnsPerHost'] ) ) {
  209. // Keep these sockets around as they may be needed later in the request
  210. curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$opts['maxConnsPerHost'] );
  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. foreach ( $batches as $batch ) {
  216. // Attach all cURL handles for this batch
  217. foreach ( $batch as $index ) {
  218. curl_multi_add_handle( $chm, $handles[$index] );
  219. }
  220. // Execute the cURL handles concurrently...
  221. $active = null; // handles still being processed
  222. do {
  223. // Do any available work...
  224. do {
  225. $mrc = curl_multi_exec( $chm, $active );
  226. $info = curl_multi_info_read( $chm );
  227. if ( $info !== false ) {
  228. $infos[(int)$info['handle']] = $info;
  229. }
  230. } while ( $mrc == CURLM_CALL_MULTI_PERFORM );
  231. // Wait (if possible) for available work...
  232. if ( $active > 0 && $mrc == CURLM_OK && curl_multi_select( $chm, $selectTimeout ) == -1 ) {
  233. // PHP bug 63411; https://curl.haxx.se/libcurl/c/curl_multi_fdset.html
  234. usleep( 5000 ); // 5ms
  235. }
  236. } while ( $active > 0 && $mrc == CURLM_OK );
  237. }
  238. // Remove all of the added cURL handles and check for errors...
  239. foreach ( $reqs as $index => &$req ) {
  240. $ch = $handles[$index];
  241. curl_multi_remove_handle( $chm, $ch );
  242. if ( isset( $infos[(int)$ch] ) ) {
  243. $info = $infos[(int)$ch];
  244. $errno = $info['result'];
  245. if ( $errno !== 0 ) {
  246. $req['response']['error'] = "(curl error: $errno)";
  247. if ( function_exists( 'curl_strerror' ) ) {
  248. $req['response']['error'] .= " " . curl_strerror( $errno );
  249. }
  250. $this->logger->warning( "Error fetching URL \"{$req['url']}\": " .
  251. $req['response']['error'] );
  252. }
  253. } else {
  254. $req['response']['error'] = "(curl error: no status set)";
  255. }
  256. // For convenience with the list() operator
  257. $req['response'][0] = $req['response']['code'];
  258. $req['response'][1] = $req['response']['reason'];
  259. $req['response'][2] = $req['response']['headers'];
  260. $req['response'][3] = $req['response']['body'];
  261. $req['response'][4] = $req['response']['error'];
  262. curl_close( $ch );
  263. // Close any string wrapper file handles
  264. if ( isset( $req['_closeHandle'] ) ) {
  265. fclose( $req['_closeHandle'] );
  266. unset( $req['_closeHandle'] );
  267. }
  268. }
  269. unset( $req ); // don't assign over this by accident
  270. // Restore the default settings
  271. curl_multi_setopt( $chm, CURLMOPT_PIPELINING, (int)$this->usePipelining );
  272. curl_multi_setopt( $chm, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
  273. return $reqs;
  274. }
  275. /**
  276. * @param array &$req HTTP request map
  277. * @codingStandardsIgnoreStart
  278. * @phan-param array{url:string,proxy?:?string,query:mixed,method:string,body:string|resource,headers:string[],stream?:resource,flags:array} $req
  279. * @codingStandardsIgnoreEnd
  280. * @param array $opts
  281. * - connTimeout : default connection timeout
  282. * - reqTimeout : default request timeout
  283. * @return resource
  284. * @throws Exception
  285. */
  286. protected function getCurlHandle( array &$req, array $opts ) {
  287. $ch = curl_init();
  288. curl_setopt( $ch, CURLOPT_PROXY, $req['proxy'] ?? $this->proxy );
  289. curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT_MS, intval( $opts['connTimeout'] * 1e3 ) );
  290. curl_setopt( $ch, CURLOPT_TIMEOUT_MS, intval( $opts['reqTimeout'] * 1e3 ) );
  291. curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
  292. curl_setopt( $ch, CURLOPT_MAXREDIRS, 4 );
  293. curl_setopt( $ch, CURLOPT_HEADER, 0 );
  294. if ( !is_null( $this->caBundlePath ) ) {
  295. curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, true );
  296. curl_setopt( $ch, CURLOPT_CAINFO, $this->caBundlePath );
  297. }
  298. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
  299. $url = $req['url'];
  300. $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
  301. if ( $query != '' ) {
  302. $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
  303. }
  304. curl_setopt( $ch, CURLOPT_URL, $url );
  305. curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $req['method'] );
  306. curl_setopt( $ch, CURLOPT_NOBODY, ( $req['method'] === 'HEAD' ) );
  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. return (string)fread( $fd, $length );
  333. }
  334. );
  335. } elseif ( $req['method'] === 'POST' ) {
  336. curl_setopt( $ch, CURLOPT_POST, 1 );
  337. curl_setopt( $ch, CURLOPT_POSTFIELDS, $req['body'] );
  338. } else {
  339. if ( is_resource( $req['body'] ) || $req['body'] !== '' ) {
  340. throw new Exception( "HTTP body specified for a non PUT/POST request." );
  341. }
  342. $req['headers']['content-length'] = 0;
  343. }
  344. if ( !isset( $req['headers']['user-agent'] ) ) {
  345. $req['headers']['user-agent'] = $this->userAgent;
  346. }
  347. $headers = [];
  348. foreach ( $req['headers'] as $name => $value ) {
  349. if ( strpos( $name, ': ' ) ) {
  350. throw new Exception( "Headers cannot have ':' in the name." );
  351. }
  352. $headers[] = $name . ': ' . trim( $value );
  353. }
  354. curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
  355. curl_setopt( $ch, CURLOPT_HEADERFUNCTION,
  356. function ( $ch, $header ) use ( &$req ) {
  357. if ( !empty( $req['flags']['relayResponseHeaders'] ) && trim( $header ) !== '' ) {
  358. header( $header );
  359. }
  360. $length = strlen( $header );
  361. $matches = [];
  362. if ( preg_match( "/^(HTTP\/(?:1\.[01]|2)) (\d{3}) (.*)/", $header, $matches ) ) {
  363. $req['response']['code'] = (int)$matches[2];
  364. $req['response']['reason'] = trim( $matches[3] );
  365. return $length;
  366. }
  367. if ( strpos( $header, ":" ) === false ) {
  368. return $length;
  369. }
  370. list( $name, $value ) = explode( ":", $header, 2 );
  371. $name = strtolower( $name );
  372. $value = trim( $value );
  373. if ( isset( $req['response']['headers'][$name] ) ) {
  374. $req['response']['headers'][$name] .= ', ' . $value;
  375. } else {
  376. $req['response']['headers'][$name] = $value;
  377. }
  378. return $length;
  379. }
  380. );
  381. // This works with both file and php://temp handles (unlike CURLOPT_FILE)
  382. $hasOutputStream = isset( $req['stream'] );
  383. curl_setopt( $ch, CURLOPT_WRITEFUNCTION,
  384. function ( $ch, $data ) use ( &$req, $hasOutputStream ) {
  385. if ( $hasOutputStream ) {
  386. return fwrite( $req['stream'], $data );
  387. } else {
  388. // @phan-suppress-next-line PhanTypeArraySuspiciousNullable
  389. $req['response']['body'] .= $data;
  390. return strlen( $data );
  391. }
  392. }
  393. );
  394. return $ch;
  395. }
  396. /**
  397. * @return resource
  398. * @throws Exception
  399. */
  400. protected function getCurlMulti() {
  401. if ( !$this->multiHandle ) {
  402. if ( !function_exists( 'curl_multi_init' ) ) {
  403. throw new Exception( "PHP cURL function curl_multi_init missing. " .
  404. "Check https://www.mediawiki.org/wiki/Manual:CURL" );
  405. }
  406. $cmh = curl_multi_init();
  407. curl_multi_setopt( $cmh, CURLMOPT_PIPELINING, (int)$this->usePipelining );
  408. curl_multi_setopt( $cmh, CURLMOPT_MAXCONNECTS, (int)$this->maxConnsPerHost );
  409. $this->multiHandle = $cmh;
  410. }
  411. return $this->multiHandle;
  412. }
  413. /**
  414. * Execute a set of HTTP(S) requests sequentially.
  415. *
  416. * @see MultiHttpClient::runMulti()
  417. * @todo Remove dependency on MediaWikiServices: use a separate HTTP client
  418. * library or copy code from PhpHttpRequest
  419. * @param array $reqs Map of HTTP request arrays
  420. * @param array $opts
  421. * - connTimeout : connection timeout per request (seconds)
  422. * - reqTimeout : post-connection timeout per request (seconds)
  423. * @return array $reqs With response array populated for each
  424. * @throws Exception
  425. */
  426. private function runMultiHttp( array $reqs, array $opts = [] ) {
  427. $httpOptions = [
  428. 'timeout' => $opts['reqTimeout'] ?? $this->reqTimeout,
  429. 'connectTimeout' => $opts['connTimeout'] ?? $this->connTimeout,
  430. 'logger' => $this->logger,
  431. 'caInfo' => $this->caBundlePath,
  432. ];
  433. foreach ( $reqs as &$req ) {
  434. $reqOptions = $httpOptions + [
  435. 'method' => $req['method'],
  436. 'proxy' => $req['proxy'] ?? $this->proxy,
  437. 'userAgent' => $req['headers']['user-agent'] ?? $this->userAgent,
  438. 'postData' => $req['body'],
  439. ];
  440. $url = $req['url'];
  441. $query = http_build_query( $req['query'], '', '&', PHP_QUERY_RFC3986 );
  442. if ( $query != '' ) {
  443. $url .= strpos( $req['url'], '?' ) === false ? "?$query" : "&$query";
  444. }
  445. $httpRequest = MediaWikiServices::getInstance()->getHttpRequestFactory()->create(
  446. $url, $reqOptions );
  447. $sv = $httpRequest->execute()->getStatusValue();
  448. $respHeaders = array_map(
  449. function ( $v ) {
  450. return implode( ', ', $v );
  451. },
  452. $httpRequest->getResponseHeaders() );
  453. $req['response'] = [
  454. 'code' => $httpRequest->getStatus(),
  455. 'reason' => '',
  456. 'headers' => $respHeaders,
  457. 'body' => $httpRequest->getContent(),
  458. 'error' => '',
  459. ];
  460. if ( !$sv->isOK() ) {
  461. $svErrors = $sv->getErrors();
  462. if ( isset( $svErrors[0] ) ) {
  463. $req['response']['error'] = $svErrors[0]['message'];
  464. // param values vary per failure type (ex. unknown host vs unknown page)
  465. if ( isset( $svErrors[0]['params'][0] ) ) {
  466. if ( is_numeric( $svErrors[0]['params'][0] ) ) {
  467. if ( isset( $svErrors[0]['params'][1] ) ) {
  468. // @phan-suppress-next-line PhanTypeInvalidDimOffset
  469. $req['response']['reason'] = $svErrors[0]['params'][1];
  470. }
  471. } else {
  472. $req['response']['reason'] = $svErrors[0]['params'][0];
  473. }
  474. }
  475. }
  476. }
  477. $req['response'][0] = $req['response']['code'];
  478. $req['response'][1] = $req['response']['reason'];
  479. $req['response'][2] = $req['response']['headers'];
  480. $req['response'][3] = $req['response']['body'];
  481. $req['response'][4] = $req['response']['error'];
  482. }
  483. return $reqs;
  484. }
  485. /**
  486. * Normalize request information
  487. *
  488. * @param array[] $reqs the requests to normalize
  489. */
  490. private function normalizeRequests( array &$reqs ) {
  491. foreach ( $reqs as &$req ) {
  492. $req['response'] = [
  493. 'code' => 0,
  494. 'reason' => '',
  495. 'headers' => [],
  496. 'body' => '',
  497. 'error' => ''
  498. ];
  499. if ( isset( $req[0] ) ) {
  500. $req['method'] = $req[0]; // short-form
  501. unset( $req[0] );
  502. }
  503. if ( isset( $req[1] ) ) {
  504. $req['url'] = $req[1]; // short-form
  505. unset( $req[1] );
  506. }
  507. if ( !isset( $req['method'] ) ) {
  508. throw new Exception( "Request has no 'method' field set." );
  509. } elseif ( !isset( $req['url'] ) ) {
  510. throw new Exception( "Request has no 'url' field set." );
  511. }
  512. $this->logger->debug( "{$req['method']}: {$req['url']}" );
  513. $req['query'] = $req['query'] ?? [];
  514. $headers = []; // normalized headers
  515. if ( isset( $req['headers'] ) ) {
  516. foreach ( $req['headers'] as $name => $value ) {
  517. $headers[strtolower( $name )] = $value;
  518. }
  519. }
  520. $req['headers'] = $headers;
  521. if ( !isset( $req['body'] ) ) {
  522. $req['body'] = '';
  523. $req['headers']['content-length'] = 0;
  524. }
  525. $req['flags'] = $req['flags'] ?? [];
  526. }
  527. }
  528. /**
  529. * Get a suitable select timeout for the given options.
  530. *
  531. * @param array $opts
  532. * @return float
  533. */
  534. private function getSelectTimeout( $opts ) {
  535. $connTimeout = $opts['connTimeout'] ?? $this->connTimeout;
  536. $reqTimeout = $opts['reqTimeout'] ?? $this->reqTimeout;
  537. $timeouts = array_filter( [ $connTimeout, $reqTimeout ] );
  538. if ( count( $timeouts ) === 0 ) {
  539. return 1;
  540. }
  541. $selectTimeout = min( $timeouts ) * self::TIMEOUT_ACCURACY_FACTOR;
  542. // Minimum 10us for sanity
  543. if ( $selectTimeout < 10e-6 ) {
  544. $selectTimeout = 10e-6;
  545. }
  546. return $selectTimeout;
  547. }
  548. /**
  549. * Register a logger
  550. *
  551. * @param LoggerInterface $logger
  552. */
  553. public function setLogger( LoggerInterface $logger ) {
  554. $this->logger = $logger;
  555. }
  556. function __destruct() {
  557. if ( $this->multiHandle ) {
  558. curl_multi_close( $this->multiHandle );
  559. }
  560. }
  561. }