FileDownloader.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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\Downloader;
  12. use Composer\Config;
  13. use Composer\Cache;
  14. use Composer\Factory;
  15. use Composer\IO\IOInterface;
  16. use Composer\IO\NullIO;
  17. use Composer\Package\Comparer\Comparer;
  18. use Composer\Package\PackageInterface;
  19. use Composer\Package\Version\VersionParser;
  20. use Composer\Plugin\PluginEvents;
  21. use Composer\Plugin\PreFileDownloadEvent;
  22. use Composer\EventDispatcher\EventDispatcher;
  23. use Composer\Util\Filesystem;
  24. use Composer\Util\HttpDownloader;
  25. use Composer\Util\Url as UrlUtil;
  26. use Composer\Downloader\TransportException;
  27. /**
  28. * Base downloader for files
  29. *
  30. * @author Kirill chEbba Chebunin <iam@chebba.org>
  31. * @author Jordi Boggiano <j.boggiano@seld.be>
  32. * @author François Pluchino <francois.pluchino@opendisplay.com>
  33. * @author Nils Adermann <naderman@naderman.de>
  34. */
  35. class FileDownloader implements DownloaderInterface, ChangeReportInterface
  36. {
  37. protected $io;
  38. protected $config;
  39. protected $httpDownloader;
  40. protected $filesystem;
  41. protected $cache;
  42. /**
  43. * @private this is only public for php 5.3 support in closures
  44. */
  45. public $lastCacheWrites = array();
  46. private $eventDispatcher;
  47. /**
  48. * Constructor.
  49. *
  50. * @param IOInterface $io The IO instance
  51. * @param Config $config The config
  52. * @param HttpDownloader $httpDownloader The remote filesystem
  53. * @param EventDispatcher $eventDispatcher The event dispatcher
  54. * @param Cache $cache Cache instance
  55. * @param Filesystem $filesystem The filesystem
  56. */
  57. public function __construct(IOInterface $io, Config $config, HttpDownloader $httpDownloader, EventDispatcher $eventDispatcher = null, Cache $cache = null, Filesystem $filesystem = null)
  58. {
  59. $this->io = $io;
  60. $this->config = $config;
  61. $this->eventDispatcher = $eventDispatcher;
  62. $this->httpDownloader = $httpDownloader;
  63. $this->filesystem = $filesystem ?: new Filesystem();
  64. $this->cache = $cache;
  65. if ($this->cache && $this->cache->gcIsNecessary()) {
  66. $this->cache->gc($config->get('cache-files-ttl'), $config->get('cache-files-maxsize'));
  67. }
  68. }
  69. /**
  70. * {@inheritDoc}
  71. */
  72. public function getInstallationSource()
  73. {
  74. return 'dist';
  75. }
  76. /**
  77. * {@inheritDoc}
  78. */
  79. public function download(PackageInterface $package, $path, $output = true)
  80. {
  81. if (!$package->getDistUrl()) {
  82. throw new \InvalidArgumentException('The given package is missing url information');
  83. }
  84. $retries = 3;
  85. $urls = $package->getDistUrls();
  86. foreach ($urls as $index => $url) {
  87. $processedUrl = $this->processUrl($package, $url);
  88. $urls[$index] = array(
  89. 'base' => $url,
  90. 'processed' => $processedUrl,
  91. 'cacheKey' => $this->getCacheKey($package, $processedUrl)
  92. );
  93. }
  94. $this->filesystem->emptyDirectory($path);
  95. $fileName = $this->getFileName($package, $path);
  96. $io = $this->io;
  97. $cache = $this->cache;
  98. $httpDownloader = $this->httpDownloader;
  99. $eventDispatcher = $this->eventDispatcher;
  100. $filesystem = $this->filesystem;
  101. $self = $this;
  102. $accept = null;
  103. $reject = null;
  104. $download = function () use ($io, $output, $httpDownloader, $cache, $eventDispatcher, $package, $fileName, $path, &$urls, &$accept, &$reject) {
  105. $url = reset($urls);
  106. if ($eventDispatcher) {
  107. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $httpDownloader, $url['processed']);
  108. $eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  109. }
  110. $checksum = $package->getDistSha1Checksum();
  111. $cacheKey = $url['cacheKey'];
  112. // use from cache if it is present and has a valid checksum or we have no checksum to check against
  113. if ($cache && (!$checksum || $checksum === $cache->sha1($cacheKey)) && $cache->copyTo($cacheKey, $fileName)) {
  114. if ($output) {
  115. $io->writeError(" - Loading <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>) from cache");
  116. }
  117. $result = \React\Promise\resolve($fileName);
  118. } else {
  119. if ($output) {
  120. $io->writeError(" - Downloading <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>)");
  121. }
  122. $result = $httpDownloader->addCopy($url['processed'], $fileName, $package->getTransportOptions())
  123. ->then($accept, $reject);
  124. }
  125. return $result->then(function ($result) use ($fileName, $checksum, $url) {
  126. // in case of retry, the first call's Promise chain finally calls this twice at the end,
  127. // once with $result being the returned $fileName from $accept, and then once for every
  128. // failed request with a null result, which can be skipped.
  129. if (null === $result) {
  130. return $fileName;
  131. }
  132. if (!file_exists($fileName)) {
  133. throw new \UnexpectedValueException($url['base'].' could not be saved to '.$fileName.', make sure the'
  134. .' directory is writable and you have internet connectivity');
  135. }
  136. if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
  137. throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from '.$url['base'].')');
  138. }
  139. return $fileName;
  140. });
  141. };
  142. $accept = function ($response) use ($io, $cache, $package, $fileName, $path, $self, &$urls) {
  143. $url = reset($urls);
  144. $cacheKey = $url['cacheKey'];
  145. if ($cache) {
  146. $self->lastCacheWrites[$package->getName()] = $cacheKey;
  147. $cache->copyFrom($cacheKey, $fileName);
  148. }
  149. $response->collect();
  150. return $fileName;
  151. };
  152. $reject = function ($e) use ($io, &$urls, $download, $fileName, $path, $package, &$retries, $filesystem, $self) {
  153. // clean up
  154. $filesystem->removeDirectory($path);
  155. $self->clearLastCacheWrite($package);
  156. if ($e instanceof TransportException) {
  157. // if we got an http response with a proper code, then requesting again will probably not help, abort
  158. if ((0 !== $e->getCode() && !in_array($e->getCode(), array(500, 502, 503, 504))) || !$retries) {
  159. $retries = 0;
  160. }
  161. }
  162. // special error code returned when network is being artificially disabled
  163. if ($e instanceof TransportException && $e->getStatusCode() === 499) {
  164. $retries = 0;
  165. $urls = array();
  166. }
  167. if ($retries) {
  168. usleep(500000);
  169. $retries--;
  170. return $download();
  171. }
  172. array_shift($urls);
  173. if ($urls) {
  174. if ($io->isDebug()) {
  175. $io->writeError(' Failed downloading '.$package->getName().': ['.get_class($e).'] '.$e->getCode().': '.$e->getMessage());
  176. $io->writeError(' Trying the next URL for '.$package->getName());
  177. } elseif (count($urls)) {
  178. $io->writeError(' Failed downloading '.$package->getName().', trying the next URL ('.$e->getCode().': '.$e->getMessage().')');
  179. }
  180. $retries = 3;
  181. usleep(100000);
  182. return $download();
  183. }
  184. throw $e;
  185. };
  186. return $download();
  187. }
  188. /**
  189. * {@inheritDoc}
  190. */
  191. public function install(PackageInterface $package, $path, $output = true)
  192. {
  193. if ($output) {
  194. $this->io->writeError(" - Installing <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>)");
  195. }
  196. $this->filesystem->ensureDirectoryExists($path);
  197. $this->filesystem->rename($this->getFileName($package, $path), $path . pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME));
  198. }
  199. /**
  200. * TODO mark private in v3
  201. * @protected This is public due to PHP 5.3
  202. */
  203. public function clearLastCacheWrite(PackageInterface $package)
  204. {
  205. if ($this->cache && isset($this->lastCacheWrites[$package->getName()])) {
  206. $this->cache->remove($this->lastCacheWrites[$package->getName()]);
  207. unset($this->lastCacheWrites[$package->getName()]);
  208. }
  209. }
  210. /**
  211. * {@inheritDoc}
  212. */
  213. public function update(PackageInterface $initial, PackageInterface $target, $path)
  214. {
  215. $name = $target->getName();
  216. $from = $initial->getPrettyVersion();
  217. $to = $target->getPrettyVersion();
  218. $actionName = VersionParser::isUpgrade($initial->getVersion(), $target->getVersion()) ? 'Updating' : 'Downgrading';
  219. $this->io->writeError(" - " . $actionName . " <info>" . $name . "</info> (<comment>" . $from . "</comment> => <comment>" . $to . "</comment>): ", false);
  220. $this->remove($initial, $path, false);
  221. $this->install($target, $path, false);
  222. $this->io->writeError('');
  223. }
  224. /**
  225. * {@inheritDoc}
  226. */
  227. public function remove(PackageInterface $package, $path, $output = true)
  228. {
  229. if ($output) {
  230. $this->io->writeError(" - Removing <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>)");
  231. }
  232. if (!$this->filesystem->removeDirectory($path)) {
  233. throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
  234. }
  235. }
  236. /**
  237. * Gets file name for specific package
  238. *
  239. * @param PackageInterface $package package instance
  240. * @param string $path download path
  241. * @return string file name
  242. */
  243. protected function getFileName(PackageInterface $package, $path)
  244. {
  245. return $path.'_'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME);
  246. }
  247. /**
  248. * Process the download url
  249. *
  250. * @param PackageInterface $package package the url is coming from
  251. * @param string $url download url
  252. * @throws \RuntimeException If any problem with the url
  253. * @return string url
  254. */
  255. protected function processUrl(PackageInterface $package, $url)
  256. {
  257. if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) {
  258. throw new \RuntimeException('You must enable the openssl extension to download files via https');
  259. }
  260. if ($package->getDistReference()) {
  261. $url = UrlUtil::updateDistReference($this->config, $url, $package->getDistReference());
  262. }
  263. return $url;
  264. }
  265. private function getCacheKey(PackageInterface $package, $processedUrl)
  266. {
  267. // we use the complete download url here to avoid conflicting entries
  268. // from different packages, which would potentially allow a given package
  269. // in a third party repo to pre-populate the cache for the same package in
  270. // packagist for example.
  271. $cacheKey = sha1($processedUrl);
  272. return $package->getName().'/'.$cacheKey.'.'.$package->getDistType();
  273. }
  274. /**
  275. * {@inheritDoc}
  276. * @throws \RuntimeException
  277. */
  278. public function getLocalChanges(PackageInterface $package, $targetDir)
  279. {
  280. $prevIO = $this->io;
  281. $this->io = new NullIO;
  282. $this->io->loadConfiguration($this->config);
  283. $e = null;
  284. try {
  285. $res = $this->download($package, $targetDir.'_compare', false);
  286. $this->httpDownloader->wait();
  287. $res = $this->install($package, $targetDir.'_compare', false);
  288. $comparer = new Comparer();
  289. $comparer->setSource($targetDir.'_compare');
  290. $comparer->setUpdate($targetDir);
  291. $comparer->doCompare();
  292. $output = $comparer->getChanged(true, true);
  293. $this->filesystem->removeDirectory($targetDir.'_compare');
  294. } catch (\Exception $e) {
  295. }
  296. $this->io = $prevIO;
  297. if ($e) {
  298. throw $e;
  299. }
  300. return trim($output);
  301. }
  302. }