FileDownloader.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. /**
  39. * Constructor.
  40. *
  41. * @param IOInterface $io The IO instance
  42. * @param Config $config The config
  43. * @param EventDispatcher $eventDispatcher The event dispatcher
  44. * @param Cache $cache Optional cache instance
  45. * @param RemoteFilesystem $rfs The remote filesystem
  46. * @param Filesystem $filesystem The filesystem
  47. */
  48. public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, RemoteFilesystem $rfs = null, Filesystem $filesystem = null)
  49. {
  50. $this->io = $io;
  51. $this->config = $config;
  52. $this->eventDispatcher = $eventDispatcher;
  53. $this->rfs = $rfs ?: Factory::createRemoteFilesystem($this->io, $config);
  54. $this->filesystem = $filesystem ?: new Filesystem();
  55. $this->cache = $cache;
  56. if ($this->cache && $this->cache->gcIsNecessary()) {
  57. $this->cache->gc($config->get('cache-files-ttl'), $config->get('cache-files-maxsize'));
  58. }
  59. }
  60. /**
  61. * {@inheritDoc}
  62. */
  63. public function getInstallationSource()
  64. {
  65. return 'dist';
  66. }
  67. /**
  68. * {@inheritDoc}
  69. */
  70. public function download(PackageInterface $package, $path)
  71. {
  72. if (!$package->getDistUrl()) {
  73. throw new \InvalidArgumentException('The given package is missing url information');
  74. }
  75. $this->io->writeError(" - Installing <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>)");
  76. $urls = $package->getDistUrls();
  77. while ($url = array_shift($urls)) {
  78. try {
  79. return $this->doDownload($package, $path, $url);
  80. } catch (\Exception $e) {
  81. if ($this->io->isDebug()) {
  82. $this->io->writeError('');
  83. $this->io->writeError('Failed: ['.get_class($e).'] '.$e->getCode().': '.$e->getMessage());
  84. } elseif (count($urls)) {
  85. $this->io->writeError('');
  86. $this->io->writeError(' Failed, trying the next URL ('.$e->getCode().': '.$e->getMessage().')');
  87. }
  88. if (!count($urls)) {
  89. throw $e;
  90. }
  91. }
  92. }
  93. $this->io->writeError('');
  94. }
  95. protected function doDownload(PackageInterface $package, $path, $url)
  96. {
  97. $this->filesystem->emptyDirectory($path);
  98. $fileName = $this->getFileName($package, $path);
  99. $processedUrl = $this->processUrl($package, $url);
  100. $hostname = parse_url($processedUrl, PHP_URL_HOST);
  101. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $processedUrl);
  102. if ($this->eventDispatcher) {
  103. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  104. }
  105. $rfs = $preFileDownloadEvent->getRemoteFilesystem();
  106. try {
  107. $checksum = $package->getDistSha1Checksum();
  108. $cacheKey = $this->getCacheKey($package);
  109. // download if we don't have it in cache or the cache is invalidated
  110. if (!$this->cache || ($checksum && $checksum !== $this->cache->sha1($cacheKey)) || !$this->cache->copyTo($cacheKey, $fileName)) {
  111. if (!$this->outputProgress) {
  112. $this->io->writeError(' Downloading');
  113. }
  114. // try to download 3 times then fail hard
  115. $retries = 3;
  116. while ($retries--) {
  117. try {
  118. $rfs->copy($hostname, $processedUrl, $fileName, $this->outputProgress, $package->getTransportOptions());
  119. break;
  120. } catch (TransportException $e) {
  121. // if we got an http response with a proper code, then requesting again will probably not help, abort
  122. if ((0 !== $e->getCode() && !in_array($e->getCode(), array(500, 502, 503, 504))) || !$retries) {
  123. throw $e;
  124. }
  125. if ($this->io->isVerbose()) {
  126. $this->io->writeError(' Download failed, retrying...');
  127. }
  128. usleep(500000);
  129. }
  130. }
  131. if ($this->cache) {
  132. $this->cache->copyFrom($cacheKey, $fileName);
  133. }
  134. } else {
  135. $this->io->writeError(' Loading from cache');
  136. }
  137. if (!file_exists($fileName)) {
  138. throw new \UnexpectedValueException($url.' could not be saved to '.$fileName.', make sure the'
  139. .' directory is writable and you have internet connectivity');
  140. }
  141. if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
  142. throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from '.$url.')');
  143. }
  144. } catch (\Exception $e) {
  145. // clean up
  146. $this->filesystem->removeDirectory($path);
  147. $this->clearCache($package, $path);
  148. throw $e;
  149. }
  150. return $fileName;
  151. }
  152. /**
  153. * {@inheritDoc}
  154. */
  155. public function setOutputProgress($outputProgress)
  156. {
  157. $this->outputProgress = $outputProgress;
  158. return $this;
  159. }
  160. protected function clearCache(PackageInterface $package, $path)
  161. {
  162. if ($this->cache) {
  163. $fileName = $this->getFileName($package, $path);
  164. $this->cache->remove($this->getCacheKey($package));
  165. }
  166. }
  167. /**
  168. * {@inheritDoc}
  169. */
  170. public function update(PackageInterface $initial, PackageInterface $target, $path)
  171. {
  172. $this->remove($initial, $path);
  173. $this->download($target, $path);
  174. }
  175. /**
  176. * {@inheritDoc}
  177. */
  178. public function remove(PackageInterface $package, $path)
  179. {
  180. $this->io->writeError(" - Removing <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>)");
  181. if (!$this->filesystem->removeDirectory($path)) {
  182. throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
  183. }
  184. }
  185. /**
  186. * Gets file name for specific package
  187. *
  188. * @param PackageInterface $package package instance
  189. * @param string $path download path
  190. * @return string file name
  191. */
  192. protected function getFileName(PackageInterface $package, $path)
  193. {
  194. return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME);
  195. }
  196. /**
  197. * Process the download url
  198. *
  199. * @param PackageInterface $package package the url is coming from
  200. * @param string $url download url
  201. * @throws \RuntimeException If any problem with the url
  202. * @return string url
  203. */
  204. protected function processUrl(PackageInterface $package, $url)
  205. {
  206. if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) {
  207. throw new \RuntimeException('You must enable the openssl extension to download files via https');
  208. }
  209. return $url;
  210. }
  211. private function getCacheKey(PackageInterface $package)
  212. {
  213. if (preg_match('{^[a-f0-9]{40}$}', $package->getDistReference())) {
  214. return $package->getName().'/'.$package->getDistReference().'.'.$package->getDistType();
  215. }
  216. return $package->getName().'/'.$package->getVersion().'-'.$package->getDistReference().'.'.$package->getDistType();
  217. }
  218. }