FileDownloader.php 14 KB

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