FileDownloader.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. $fileName = $this->doDownload($package, $path, $url);
  84. break;
  85. } catch (\Exception $e) {
  86. if ($this->io->isDebug()) {
  87. $this->io->writeError('');
  88. $this->io->writeError('Failed: ['.get_class($e).'] '.$e->getCode().': '.$e->getMessage());
  89. } elseif (count($urls)) {
  90. $this->io->writeError('');
  91. $this->io->writeError(' Failed, trying the next URL ('.$e->getCode().': '.$e->getMessage().')', false);
  92. }
  93. if (!count($urls)) {
  94. throw $e;
  95. }
  96. }
  97. }
  98. if ($output) {
  99. $this->io->writeError('');
  100. }
  101. return $fileName;
  102. }
  103. protected function doDownload(PackageInterface $package, $path, $url)
  104. {
  105. $this->filesystem->emptyDirectory($path);
  106. $fileName = $this->getFileName($package, $path);
  107. $processedUrl = $this->processUrl($package, $url);
  108. $hostname = parse_url($processedUrl, PHP_URL_HOST);
  109. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $processedUrl);
  110. if ($this->eventDispatcher) {
  111. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  112. }
  113. $rfs = $preFileDownloadEvent->getRemoteFilesystem();
  114. try {
  115. $checksum = $package->getDistSha1Checksum();
  116. $cacheKey = $this->getCacheKey($package, $processedUrl);
  117. // download if we don't have it in cache or the cache is invalidated
  118. if (!$this->cache || ($checksum && $checksum !== $this->cache->sha1($cacheKey)) || !$this->cache->copyTo($cacheKey, $fileName)) {
  119. if (!$this->outputProgress) {
  120. $this->io->writeError('Downloading', false);
  121. }
  122. // try to download 3 times then fail hard
  123. $retries = 3;
  124. while ($retries--) {
  125. try {
  126. $rfs->copy($hostname, $processedUrl, $fileName, $this->outputProgress, $package->getTransportOptions());
  127. break;
  128. } catch (TransportException $e) {
  129. // if we got an http response with a proper code, then requesting again will probably not help, abort
  130. if ((0 !== $e->getCode() && !in_array($e->getCode(), array(500, 502, 503, 504))) || !$retries) {
  131. throw $e;
  132. }
  133. $this->io->writeError('');
  134. $this->io->writeError(' Download failed, retrying...', true, IOInterface::VERBOSE);
  135. usleep(500000);
  136. }
  137. }
  138. if (!$this->outputProgress) {
  139. $this->io->writeError(' (<comment>100%</comment>)', false);
  140. }
  141. if ($this->cache) {
  142. $this->lastCacheWrites[$package->getName()] = $cacheKey;
  143. $this->cache->copyFrom($cacheKey, $fileName);
  144. }
  145. } else {
  146. $this->io->writeError('Loading from cache', false);
  147. }
  148. if (!file_exists($fileName)) {
  149. throw new \UnexpectedValueException($url.' could not be saved to '.$fileName.', make sure the'
  150. .' directory is writable and you have internet connectivity');
  151. }
  152. if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
  153. throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from '.$url.')');
  154. }
  155. } catch (\Exception $e) {
  156. // clean up
  157. $this->filesystem->removeDirectory($path);
  158. $this->clearLastCacheWrite($package);
  159. throw $e;
  160. }
  161. return $fileName;
  162. }
  163. /**
  164. * {@inheritDoc}
  165. */
  166. public function setOutputProgress($outputProgress)
  167. {
  168. $this->outputProgress = $outputProgress;
  169. return $this;
  170. }
  171. protected function clearLastCacheWrite(PackageInterface $package)
  172. {
  173. if ($this->cache && isset($this->lastCacheWrites[$package->getName()])) {
  174. $this->cache->remove($this->lastCacheWrites[$package->getName()]);
  175. unset($this->lastCacheWrites[$package->getName()]);
  176. }
  177. }
  178. /**
  179. * {@inheritDoc}
  180. */
  181. public function update(PackageInterface $initial, PackageInterface $target, $path)
  182. {
  183. $name = $target->getName();
  184. $from = $initial->getPrettyVersion();
  185. $to = $target->getPrettyVersion();
  186. $this->io->writeError(" - Updating <info>" . $name . "</info> (<comment>" . $from . "</comment> => <comment>" . $to . "</comment>): ", false);
  187. $this->remove($initial, $path, false);
  188. $this->download($target, $path, false);
  189. $this->io->writeError('');
  190. }
  191. /**
  192. * {@inheritDoc}
  193. */
  194. public function remove(PackageInterface $package, $path, $output = true)
  195. {
  196. if ($output) {
  197. $this->io->writeError(" - Removing <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>)");
  198. }
  199. if (!$this->filesystem->removeDirectory($path)) {
  200. throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
  201. }
  202. }
  203. /**
  204. * Gets file name for specific package
  205. *
  206. * @param PackageInterface $package package instance
  207. * @param string $path download path
  208. * @return string file name
  209. */
  210. protected function getFileName(PackageInterface $package, $path)
  211. {
  212. return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME);
  213. }
  214. /**
  215. * Process the download url
  216. *
  217. * @param PackageInterface $package package the url is coming from
  218. * @param string $url download url
  219. * @throws \RuntimeException If any problem with the url
  220. * @return string url
  221. */
  222. protected function processUrl(PackageInterface $package, $url)
  223. {
  224. if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) {
  225. throw new \RuntimeException('You must enable the openssl extension to download files via https');
  226. }
  227. return $url;
  228. }
  229. private function getCacheKey(PackageInterface $package, $processedUrl)
  230. {
  231. // we use the complete download url here to avoid conflicting entries
  232. // from different packages, which would potentially allow a given package
  233. // in a third party repo to pre-populate the cache for the same package in
  234. // packagist for example.
  235. $cacheKey = sha1($processedUrl);
  236. return $package->getName().'/'.$cacheKey.'.'.$package->getDistType();
  237. }
  238. }