FileDownloader.php 11 KB

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