RemoteFilesystem.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. /**
  37. * Constructor.
  38. *
  39. * @param IOInterface $io The IO instance
  40. * @param Config $config The config
  41. * @param array $options The options
  42. */
  43. public function __construct(IOInterface $io, Config $config = null, array $options = array())
  44. {
  45. $this->io = $io;
  46. $this->config = $config;
  47. $this->options = $options;
  48. }
  49. /**
  50. * Copy the remote file in local.
  51. *
  52. * @param string $originUrl The origin URL
  53. * @param string $fileUrl The file URL
  54. * @param string $fileName the local filename
  55. * @param boolean $progress Display the progression
  56. * @param array $options Additional context options
  57. *
  58. * @return bool true
  59. */
  60. public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
  61. {
  62. return $this->get($originUrl, $fileUrl, $options, $fileName, $progress);
  63. }
  64. /**
  65. * Get the content.
  66. *
  67. * @param string $originUrl The origin URL
  68. * @param string $fileUrl The file URL
  69. * @param boolean $progress Display the progression
  70. * @param array $options Additional context options
  71. *
  72. * @return bool|string The content
  73. */
  74. public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
  75. {
  76. return $this->get($originUrl, $fileUrl, $options, null, $progress);
  77. }
  78. /**
  79. * Retrieve the options set in the constructor
  80. *
  81. * @return array Options
  82. */
  83. public function getOptions()
  84. {
  85. return $this->options;
  86. }
  87. /**
  88. * Returns the headers of the last request
  89. *
  90. * @return array
  91. */
  92. public function getLastHeaders()
  93. {
  94. return $this->lastHeaders;
  95. }
  96. /**
  97. * Get file content or copy action.
  98. *
  99. * @param string $originUrl The origin URL
  100. * @param string $fileUrl The file URL
  101. * @param array $additionalOptions context options
  102. * @param string $fileName the local filename
  103. * @param boolean $progress Display the progression
  104. *
  105. * @throws TransportException|\Exception
  106. * @throws TransportException When the file could not be downloaded
  107. *
  108. * @return bool|string
  109. */
  110. protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true)
  111. {
  112. if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) {
  113. $originUrl = 'github.com';
  114. }
  115. $this->bytesMax = 0;
  116. $this->originUrl = $originUrl;
  117. $this->fileUrl = $fileUrl;
  118. $this->fileName = $fileName;
  119. $this->progress = $progress;
  120. $this->lastProgress = null;
  121. $this->retryAuthFailure = true;
  122. $this->lastHeaders = array();
  123. // capture username/password from URL if there is one
  124. if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) {
  125. $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2]));
  126. }
  127. if (isset($additionalOptions['retry-auth-failure'])) {
  128. $this->retryAuthFailure = (bool) $additionalOptions['retry-auth-failure'];
  129. unset($additionalOptions['retry-auth-failure']);
  130. }
  131. $options = $this->getOptionsForUrl($originUrl, $additionalOptions);
  132. if (isset($options['retry-auth-failure'])) {
  133. $this->retryAuthFailure = (bool) $options['retry-auth-failure'];
  134. unset($options['retry-auth-failure']);
  135. }
  136. if ($this->io->isDebug()) {
  137. $this->io->writeError((substr($fileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $fileUrl);
  138. }
  139. if (isset($options['github-token'])) {
  140. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token'];
  141. unset($options['github-token']);
  142. }
  143. if (isset($options['gitlab-token'])) {
  144. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['gitlab-token'];
  145. unset($options['gitlab-token']);
  146. }
  147. if (isset($options['http'])) {
  148. $options['http']['ignore_errors'] = true;
  149. }
  150. $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet')));
  151. if ($this->progress) {
  152. $this->io->writeError(" Downloading: <comment>connection...</comment>", false);
  153. }
  154. $errorMessage = '';
  155. $errorCode = 0;
  156. $result = false;
  157. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  158. if ($errorMessage) {
  159. $errorMessage .= "\n";
  160. }
  161. $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg);
  162. });
  163. try {
  164. $result = file_get_contents($fileUrl, false, $ctx);
  165. } catch (\Exception $e) {
  166. if ($e instanceof TransportException && !empty($http_response_header[0])) {
  167. $e->setHeaders($http_response_header);
  168. }
  169. if ($e instanceof TransportException && $result !== false) {
  170. $e->setResponse($result);
  171. }
  172. $result = false;
  173. }
  174. if ($errorMessage && !ini_get('allow_url_fopen')) {
  175. $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')';
  176. }
  177. restore_error_handler();
  178. if (isset($e) && !$this->retry) {
  179. throw $e;
  180. }
  181. // fail 4xx and 5xx responses and capture the response
  182. if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ ([45]\d\d)}i', $http_response_header[0], $match)) {
  183. $errorCode = $match[1];
  184. if (!$this->retry) {
  185. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $errorCode);
  186. $e->setHeaders($http_response_header);
  187. $e->setResponse($result);
  188. throw $e;
  189. }
  190. $result = false;
  191. }
  192. // decode gzip
  193. if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http') {
  194. $decode = false;
  195. foreach ($http_response_header as $header) {
  196. if (preg_match('{^content-encoding: *gzip *$}i', $header)) {
  197. $decode = true;
  198. continue;
  199. } elseif (preg_match('{^HTTP/}i', $header)) {
  200. $decode = false;
  201. }
  202. }
  203. if ($decode) {
  204. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  205. $result = zlib_decode($result);
  206. } else {
  207. // work around issue with gzuncompress & co that do not work with all gzip checksums
  208. $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));
  209. }
  210. if (!$result) {
  211. throw new TransportException('Failed to decode zlib stream');
  212. }
  213. }
  214. }
  215. if ($this->progress && !$this->retry) {
  216. $this->io->overwriteError(" Downloading: <comment>100%</comment>");
  217. }
  218. // handle copy command if download was successful
  219. if (false !== $result && null !== $fileName) {
  220. if ('' === $result) {
  221. throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response');
  222. }
  223. $errorMessage = '';
  224. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  225. if ($errorMessage) {
  226. $errorMessage .= "\n";
  227. }
  228. $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg);
  229. });
  230. $result = (bool) file_put_contents($fileName, $result);
  231. restore_error_handler();
  232. if (false === $result) {
  233. throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage);
  234. }
  235. }
  236. if ($this->retry) {
  237. $this->retry = false;
  238. $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  239. $authHelper = new AuthHelper($this->io, $this->config);
  240. $authHelper->storeAuth($this->originUrl, $this->storeAuth);
  241. $this->storeAuth = false;
  242. return $result;
  243. }
  244. if (false === $result) {
  245. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode);
  246. if (!empty($http_response_header[0])) {
  247. $e->setHeaders($http_response_header);
  248. }
  249. throw $e;
  250. }
  251. if (!empty($http_response_header[0])) {
  252. $this->lastHeaders = $http_response_header;
  253. }
  254. return $result;
  255. }
  256. /**
  257. * Get notification action.
  258. *
  259. * @param integer $notificationCode The notification code
  260. * @param integer $severity The severity level
  261. * @param string $message The message
  262. * @param integer $messageCode The message code
  263. * @param integer $bytesTransferred The loaded size
  264. * @param integer $bytesMax The total size
  265. * @throws TransportException
  266. */
  267. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  268. {
  269. switch ($notificationCode) {
  270. case STREAM_NOTIFY_FAILURE:
  271. case STREAM_NOTIFY_AUTH_REQUIRED:
  272. if (401 === $messageCode) {
  273. // Bail if the caller is going to handle authentication failures itself.
  274. if (!$this->retryAuthFailure) {
  275. break;
  276. }
  277. $this->promptAuthAndRetry($messageCode);
  278. break;
  279. }
  280. break;
  281. case STREAM_NOTIFY_AUTH_RESULT:
  282. if (403 === $messageCode) {
  283. $this->promptAuthAndRetry($messageCode, $message);
  284. break;
  285. }
  286. break;
  287. case STREAM_NOTIFY_FILE_SIZE_IS:
  288. if ($this->bytesMax < $bytesMax) {
  289. $this->bytesMax = $bytesMax;
  290. }
  291. break;
  292. case STREAM_NOTIFY_PROGRESS:
  293. if ($this->bytesMax > 0 && $this->progress) {
  294. $progression = 0;
  295. if ($this->bytesMax > 0) {
  296. $progression = round($bytesTransferred / $this->bytesMax * 100);
  297. }
  298. if ((0 === $progression % 5) && $progression !== $this->lastProgress) {
  299. $this->lastProgress = $progression;
  300. $this->io->overwriteError(" Downloading: <comment>$progression%</comment>", false);
  301. }
  302. }
  303. break;
  304. default:
  305. break;
  306. }
  307. }
  308. protected function promptAuthAndRetry($httpStatus, $reason = null)
  309. {
  310. if ($this->config && in_array($this->originUrl, $this->config->get('github-domains'), true)) {
  311. $message = "\n".'Could not fetch '.$this->fileUrl.', enter your GitHub credentials '.($httpStatus === 404 ? 'to access private repos' : 'to go over the API rate limit');
  312. $gitHubUtil = new GitHub($this->io, $this->config, null);
  313. if (!$gitHubUtil->authorizeOAuth($this->originUrl)
  314. && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($this->originUrl, $message))
  315. ) {
  316. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  317. }
  318. } else if ($this->config && in_array($this->originUrl, $this->config->get('gitlab-domains'), true)) {
  319. $message = "\n".'Could not fetch '.$this->fileUrl.', enter your ' . $this->config->get('gitlab-domains')[0] . ' credentials ' .($httpStatus === 401 ? 'to access private repos' : 'to go over the API rate limit');
  320. $gitLabUtil = new GitLab($this->io, $this->config, null);
  321. if (!$gitLabUtil->authorizeOAuth($this->originUrl)
  322. && (!$this->io->isInteractive() || !$gitLabUtil->authorizeOAuthInteractively($this->originUrl, $message))
  323. ) {
  324. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  325. }
  326. } else {
  327. // 404s are only handled for github
  328. if ($httpStatus === 404) {
  329. return;
  330. }
  331. // fail if the console is not interactive
  332. if (!$this->io->isInteractive()) {
  333. if ($httpStatus === 401) {
  334. $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console to authenticate";
  335. }
  336. if ($httpStatus === 403) {
  337. $message = "The '" . $this->fileUrl . "' URL could not be accessed: " . $reason;
  338. }
  339. throw new TransportException($message, $httpStatus);
  340. }
  341. // fail if we already have auth
  342. if ($this->io->hasAuthentication($this->originUrl)) {
  343. throw new TransportException("Invalid credentials for '" . $this->fileUrl . "', aborting.", $httpStatus);
  344. }
  345. $this->io->overwriteError(' Authentication required (<info>'.parse_url($this->fileUrl, PHP_URL_HOST).'</info>):');
  346. $username = $this->io->ask(' Username: ');
  347. $password = $this->io->askAndHideAnswer(' Password: ');
  348. $this->io->setAuthentication($this->originUrl, $username, $password);
  349. $this->storeAuth = $this->config->get('store-auths');
  350. }
  351. $this->retry = true;
  352. throw new TransportException('RETRY');
  353. }
  354. protected function getOptionsForUrl($originUrl, $additionalOptions)
  355. {
  356. if (defined('HHVM_VERSION')) {
  357. $phpVersion = 'HHVM ' . HHVM_VERSION;
  358. } else {
  359. $phpVersion = 'PHP ' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;
  360. }
  361. $headers = array(
  362. sprintf(
  363. 'User-Agent: Composer/%s (%s; %s; %s)',
  364. Composer::VERSION === '@package_version@' ? 'source' : Composer::VERSION,
  365. php_uname('s'),
  366. php_uname('r'),
  367. $phpVersion
  368. )
  369. );
  370. if (extension_loaded('zlib')) {
  371. $headers[] = 'Accept-Encoding: gzip';
  372. }
  373. $options = array_replace_recursive($this->options, $additionalOptions);
  374. if ($this->io->hasAuthentication($originUrl)) {
  375. $auth = $this->io->getAuthentication($originUrl);
  376. if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) {
  377. $options['github-token'] = $auth['username'];
  378. } elseif ($originUrl === $this->config->get('gitlab-domains')[0]) {
  379. if($auth['password'] === 'oauth2') {
  380. $headers[] = 'Authorization: Bearer '.$auth['username'];
  381. }
  382. } else {
  383. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  384. $headers[] = 'Authorization: Basic '.$authStr;
  385. }
  386. }
  387. if (isset($options['http']['header']) && !is_array($options['http']['header'])) {
  388. $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n"));
  389. }
  390. foreach ($headers as $header) {
  391. $options['http']['header'][] = $header;
  392. }
  393. if($this->config && $this->config->get('gitlab-domains') && $originUrl == $this->config->get('gitlab-domains')[0]) {
  394. $options['retry-auth-failure'] = false;
  395. }
  396. return $options;
  397. }
  398. }