FileDownloader.php 9.5 KB

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