RemoteFilesystem.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Util;
  12. use Composer\Composer;
  13. use Composer\Config;
  14. use Composer\IO\IOInterface;
  15. use Composer\Downloader\TransportException;
  16. /**
  17. * @author François Pluchino <francois.pluchino@opendisplay.com>
  18. * @author Jordi Boggiano <j.boggiano@seld.be>
  19. * @author Nils Adermann <naderman@naderman.de>
  20. */
  21. class RemoteFilesystem
  22. {
  23. private $io;
  24. private $config;
  25. private $bytesMax;
  26. private $originUrl;
  27. private $fileUrl;
  28. private $fileName;
  29. private $retry;
  30. private $progress;
  31. private $lastProgress;
  32. private $options;
  33. private $retryAuthFailure;
  34. private $lastHeaders;
  35. private $storeAuth;
  36. private $degradedMode = false;
  37. /**
  38. * Constructor.
  39. *
  40. * @param IOInterface $io The IO instance
  41. * @param Config $config The config
  42. * @param array $options The options
  43. */
  44. public function __construct(IOInterface $io, Config $config = null, array $options = array())
  45. {
  46. $this->io = $io;
  47. $this->config = $config;
  48. $this->options = $options;
  49. }
  50. /**
  51. * Copy the remote file in local.
  52. *
  53. * @param string $originUrl The origin URL
  54. * @param string $fileUrl The file URL
  55. * @param string $fileName the local filename
  56. * @param bool $progress Display the progression
  57. * @param array $options Additional context options
  58. *
  59. * @return bool true
  60. */
  61. public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
  62. {
  63. return $this->get($originUrl, $fileUrl, $options, $fileName, $progress);
  64. }
  65. /**
  66. * Get the content.
  67. *
  68. * @param string $originUrl The origin URL
  69. * @param string $fileUrl The file URL
  70. * @param bool $progress Display the progression
  71. * @param array $options Additional context options
  72. *
  73. * @return bool|string The content
  74. */
  75. public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
  76. {
  77. return $this->get($originUrl, $fileUrl, $options, null, $progress);
  78. }
  79. /**
  80. * Retrieve the options set in the constructor
  81. *
  82. * @return array Options
  83. */
  84. public function getOptions()
  85. {
  86. return $this->options;
  87. }
  88. /**
  89. * Returns the headers of the last request
  90. *
  91. * @return array
  92. */
  93. public function getLastHeaders()
  94. {
  95. return $this->lastHeaders;
  96. }
  97. /**
  98. * Get file content or copy action.
  99. *
  100. * @param string $originUrl The origin URL
  101. * @param string $fileUrl The file URL
  102. * @param array $additionalOptions context options
  103. * @param string $fileName the local filename
  104. * @param bool $progress Display the progression
  105. *
  106. * @throws TransportException|\Exception
  107. * @throws TransportException When the file could not be downloaded
  108. *
  109. * @return bool|string
  110. */
  111. protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true)
  112. {
  113. if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) {
  114. $originUrl = 'github.com';
  115. }
  116. $this->scheme = parse_url($fileUrl, PHP_URL_SCHEME);
  117. $this->bytesMax = 0;
  118. $this->originUrl = $originUrl;
  119. $this->fileUrl = $fileUrl;
  120. $this->fileName = $fileName;
  121. $this->progress = $progress;
  122. $this->lastProgress = null;
  123. $this->retryAuthFailure = true;
  124. $this->lastHeaders = array();
  125. // capture username/password from URL if there is one
  126. if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) {
  127. $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2]));
  128. }
  129. if (isset($additionalOptions['retry-auth-failure'])) {
  130. $this->retryAuthFailure = (bool) $additionalOptions['retry-auth-failure'];
  131. unset($additionalOptions['retry-auth-failure']);
  132. }
  133. $options = $this->getOptionsForUrl($originUrl, $additionalOptions);
  134. if ($this->io->isDebug()) {
  135. $this->io->writeError((substr($fileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $fileUrl);
  136. }
  137. if (isset($options['github-token'])) {
  138. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token'];
  139. unset($options['github-token']);
  140. }
  141. if (isset($options['gitlab-token'])) {
  142. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['gitlab-token'];
  143. unset($options['gitlab-token']);
  144. }
  145. if (isset($options['http'])) {
  146. $options['http']['ignore_errors'] = true;
  147. }
  148. if ($this->degradedMode && substr($fileUrl, 0, 21) === 'http://packagist.org/') {
  149. // access packagist using the resolved IPv4 instead of the hostname to force IPv4 protocol
  150. $fileUrl = 'http://' . gethostbyname('packagist.org') . substr($fileUrl, 20);
  151. }
  152. $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet')));
  153. if ($this->progress) {
  154. $this->io->writeError(" Downloading: <comment>Connecting...</comment>", false);
  155. }
  156. $errorMessage = '';
  157. $errorCode = 0;
  158. $result = false;
  159. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  160. if ($errorMessage) {
  161. $errorMessage .= "\n";
  162. }
  163. $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg);
  164. });
  165. try {
  166. $result = file_get_contents($fileUrl, false, $ctx);
  167. } catch (\Exception $e) {
  168. if ($e instanceof TransportException && !empty($http_response_header[0])) {
  169. $e->setHeaders($http_response_header);
  170. }
  171. if ($e instanceof TransportException && $result !== false) {
  172. $e->setResponse($result);
  173. }
  174. $result = false;
  175. }
  176. if ($errorMessage && !ini_get('allow_url_fopen')) {
  177. $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')';
  178. }
  179. restore_error_handler();
  180. if (isset($e) && !$this->retry) {
  181. if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) {
  182. $this->degradedMode = true;
  183. $this->io->writeError(array(
  184. '<error>'.$e->getMessage().'</error>',
  185. '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>',
  186. ));
  187. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  188. }
  189. throw $e;
  190. }
  191. // fail 4xx and 5xx responses and capture the response
  192. if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ ([45]\d\d)}i', $http_response_header[0], $match)) {
  193. $errorCode = $match[1];
  194. if (!$this->retry) {
  195. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $errorCode);
  196. $e->setHeaders($http_response_header);
  197. $e->setResponse($result);
  198. throw $e;
  199. }
  200. $result = false;
  201. }
  202. if ($this->progress && !$this->retry) {
  203. $this->io->overwriteError(" Downloading: <comment>100%</comment>");
  204. }
  205. // decode gzip
  206. if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http') {
  207. $decode = false;
  208. foreach ($http_response_header as $header) {
  209. if (preg_match('{^content-encoding: *gzip *$}i', $header)) {
  210. $decode = true;
  211. } elseif (preg_match('{^HTTP/}i', $header)) {
  212. // In case of redirects, http_response_headers contains the headers of all responses
  213. // so we reset the flag when a new response is being parsed as we are only interested in the last response
  214. $decode = false;
  215. }
  216. }
  217. if ($decode) {
  218. try {
  219. if (PHP_VERSION_ID >= 50400) {
  220. $result = zlib_decode($result);
  221. } else {
  222. // work around issue with gzuncompress & co that do not work with all gzip checksums
  223. $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));
  224. }
  225. if (!$result) {
  226. throw new TransportException('Failed to decode zlib stream');
  227. }
  228. } catch (\Exception $e) {
  229. if ($this->degradedMode) {
  230. throw $e;
  231. }
  232. $this->degradedMode = true;
  233. $this->io->writeError(array(
  234. '<error>Failed to decode response: '.$e->getMessage().'</error>',
  235. '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>',
  236. ));
  237. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  238. }
  239. }
  240. }
  241. // handle copy command if download was successful
  242. if (false !== $result && null !== $fileName) {
  243. if ('' === $result) {
  244. throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response');
  245. }
  246. $errorMessage = '';
  247. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  248. if ($errorMessage) {
  249. $errorMessage .= "\n";
  250. }
  251. $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg);
  252. });
  253. $result = (bool) file_put_contents($fileName, $result);
  254. restore_error_handler();
  255. if (false === $result) {
  256. throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage);
  257. }
  258. }
  259. if ($this->retry) {
  260. $this->retry = false;
  261. $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  262. $authHelper = new AuthHelper($this->io, $this->config);
  263. $authHelper->storeAuth($this->originUrl, $this->storeAuth);
  264. $this->storeAuth = false;
  265. return $result;
  266. }
  267. if (false === $result) {
  268. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode);
  269. if (!empty($http_response_header[0])) {
  270. $e->setHeaders($http_response_header);
  271. }
  272. if (!$this->degradedMode && false !== strpos($e->getMessage(), 'Operation timed out')) {
  273. $this->degradedMode = true;
  274. $this->io->writeError(array(
  275. '<error>'.$e->getMessage().'</error>',
  276. '<error>Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info</error>',
  277. ));
  278. return $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  279. }
  280. throw $e;
  281. }
  282. if (!empty($http_response_header[0])) {
  283. $this->lastHeaders = $http_response_header;
  284. }
  285. return $result;
  286. }
  287. /**
  288. * Get notification action.
  289. *
  290. * @param int $notificationCode The notification code
  291. * @param int $severity The severity level
  292. * @param string $message The message
  293. * @param int $messageCode The message code
  294. * @param int $bytesTransferred The loaded size
  295. * @param int $bytesMax The total size
  296. * @throws TransportException
  297. */
  298. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  299. {
  300. switch ($notificationCode) {
  301. case STREAM_NOTIFY_FAILURE:
  302. if (400 === $messageCode) {
  303. // This might happen if your host is secured by ssl client certificate authentication
  304. // but you do not send an appropriate certificate
  305. throw new TransportException("The '" . $this->fileUrl . "' URL could not be accessed: " . $message, $messageCode);
  306. }
  307. // intentional fallthrough to the next case as the notificationCode
  308. // isn't always consistent and we should inspect the messageCode for 401s
  309. case STREAM_NOTIFY_AUTH_REQUIRED:
  310. if (401 === $messageCode) {
  311. // Bail if the caller is going to handle authentication failures itself.
  312. if (!$this->retryAuthFailure) {
  313. break;
  314. }
  315. $this->promptAuthAndRetry($messageCode);
  316. }
  317. break;
  318. case STREAM_NOTIFY_AUTH_RESULT:
  319. if (403 === $messageCode) {
  320. // Bail if the caller is going to handle authentication failures itself.
  321. if (!$this->retryAuthFailure) {
  322. break;
  323. }
  324. $this->promptAuthAndRetry($messageCode, $message);
  325. }
  326. break;
  327. case STREAM_NOTIFY_FILE_SIZE_IS:
  328. if ($this->bytesMax < $bytesMax) {
  329. $this->bytesMax = $bytesMax;
  330. }
  331. break;
  332. case STREAM_NOTIFY_PROGRESS:
  333. if ($this->bytesMax > 0 && $this->progress) {
  334. $progression = round($bytesTransferred / $this->bytesMax * 100);
  335. if ((0 === $progression % 5) && 100 !== $progression && $progression !== $this->lastProgress) {
  336. $this->lastProgress = $progression;
  337. $this->io->overwriteError(" Downloading: <comment>$progression%</comment>", false);
  338. }
  339. }
  340. break;
  341. default:
  342. break;
  343. }
  344. }
  345. protected function promptAuthAndRetry($httpStatus, $reason = null)
  346. {
  347. if ($this->config && in_array($this->originUrl, $this->config->get('github-domains'), true)) {
  348. $message = "\n".'Could not fetch '.$this->fileUrl.', please create a GitHub OAuth token '.($httpStatus === 404 ? 'to access private repos' : 'to go over the API rate limit');
  349. $gitHubUtil = new GitHub($this->io, $this->config, null);
  350. if (!$gitHubUtil->authorizeOAuth($this->originUrl)
  351. && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($this->originUrl, $message))
  352. ) {
  353. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  354. }
  355. } elseif ($this->config && in_array($this->originUrl, $this->config->get('gitlab-domains'), true)) {
  356. $message = "\n".'Could not fetch '.$this->fileUrl.', enter your ' . $this->originUrl . ' credentials ' .($httpStatus === 401 ? 'to access private repos' : 'to go over the API rate limit');
  357. $gitLabUtil = new GitLab($this->io, $this->config, null);
  358. if (!$gitLabUtil->authorizeOAuth($this->originUrl)
  359. && (!$this->io->isInteractive() || !$gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, $message))
  360. ) {
  361. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  362. }
  363. } else {
  364. // 404s are only handled for github
  365. if ($httpStatus === 404) {
  366. return;
  367. }
  368. // fail if the console is not interactive
  369. if (!$this->io->isInteractive()) {
  370. if ($httpStatus === 401) {
  371. $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console to authenticate";
  372. }
  373. if ($httpStatus === 403) {
  374. $message = "The '" . $this->fileUrl . "' URL could not be accessed: " . $reason;
  375. }
  376. throw new TransportException($message, $httpStatus);
  377. }
  378. // fail if we already have auth
  379. if ($this->io->hasAuthentication($this->originUrl)) {
  380. throw new TransportException("Invalid credentials for '" . $this->fileUrl . "', aborting.", $httpStatus);
  381. }
  382. $this->io->overwriteError(' Authentication required (<info>'.parse_url($this->fileUrl, PHP_URL_HOST).'</info>):');
  383. $username = $this->io->ask(' Username: ');
  384. $password = $this->io->askAndHideAnswer(' Password: ');
  385. $this->io->setAuthentication($this->originUrl, $username, $password);
  386. $this->storeAuth = $this->config->get('store-auths');
  387. }
  388. $this->retry = true;
  389. throw new TransportException('RETRY');
  390. }
  391. protected function getOptionsForUrl($originUrl, $additionalOptions)
  392. {
  393. $headers = array();
  394. if (extension_loaded('zlib')) {
  395. $headers[] = 'Accept-Encoding: gzip';
  396. }
  397. $options = array_replace_recursive($this->options, $additionalOptions);
  398. if (!$this->degradedMode) {
  399. // degraded mode disables HTTP/1.1 which causes issues with some bad
  400. // proxies/software due to the use of chunked encoding
  401. $options['http']['protocol_version'] = 1.1;
  402. $headers[] = 'Connection: close';
  403. }
  404. if ($this->io->hasAuthentication($originUrl)) {
  405. $auth = $this->io->getAuthentication($originUrl);
  406. if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) {
  407. $options['github-token'] = $auth['username'];
  408. } elseif ($this->config && in_array($originUrl, $this->config->get('gitlab-domains'), true)) {
  409. if ($auth['password'] === 'oauth2') {
  410. $headers[] = 'Authorization: Bearer '.$auth['username'];
  411. }
  412. } else {
  413. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  414. $headers[] = 'Authorization: Basic '.$authStr;
  415. }
  416. }
  417. if (isset($options['http']['header']) && !is_array($options['http']['header'])) {
  418. $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n"));
  419. }
  420. foreach ($headers as $header) {
  421. $options['http']['header'][] = $header;
  422. }
  423. return $options;
  424. }
  425. }