FileDownloader.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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\IO\IOInterface;
  15. use Composer\Package\PackageInterface;
  16. use Composer\Package\Version\VersionParser;
  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 ?: new RemoteFilesystem($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->write(" - Installing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</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->write('');
  83. $this->io->write('Failed: ['.get_class($e).'] '.$e->getMessage());
  84. } elseif (count($urls)) {
  85. $this->io->write('');
  86. $this->io->write(' Failed, trying the next URL');
  87. }
  88. if (!count($urls)) {
  89. throw $e;
  90. }
  91. }
  92. }
  93. }
  94. protected function doDownload(PackageInterface $package, $path, $url)
  95. {
  96. $this->filesystem->emptyDirectory($path);
  97. $fileName = $this->getFileName($package, $path);
  98. $processedUrl = $this->processUrl($package, $url);
  99. $hostname = parse_url($processedUrl, PHP_URL_HOST);
  100. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $processedUrl);
  101. if ($this->eventDispatcher) {
  102. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  103. }
  104. $rfs = $preFileDownloadEvent->getRemoteFilesystem();
  105. try {
  106. $checksum = $package->getDistSha1Checksum();
  107. $cacheKey = $this->getCacheKey($package);
  108. // download if we don't have it in cache or the cache is invalidated
  109. if (!$this->cache || ($checksum && $checksum !== $this->cache->sha1($cacheKey)) || !$this->cache->copyTo($cacheKey, $fileName)) {
  110. if (!$this->outputProgress) {
  111. $this->io->write(' Downloading');
  112. }
  113. // try to download 3 times then fail hard
  114. $retries = 3;
  115. while ($retries--) {
  116. try {
  117. $rfs->copy($hostname, $processedUrl, $fileName, $this->outputProgress, $package->getTransportOptions());
  118. break;
  119. } catch (TransportException $e) {
  120. // if we got an http response with a proper code, then requesting again will probably not help, abort
  121. if ((0 !== $e->getCode() && !in_array($e->getCode(),array(500, 502, 503, 504))) || !$retries) {
  122. throw $e;
  123. }
  124. if ($this->io->isVerbose()) {
  125. $this->io->write(' Download failed, retrying...');
  126. }
  127. usleep(500000);
  128. }
  129. }
  130. if ($this->cache) {
  131. $this->cache->copyFrom($cacheKey, $fileName);
  132. }
  133. } else {
  134. $this->io->write(' Loading from cache');
  135. }
  136. if (!file_exists($fileName)) {
  137. throw new \UnexpectedValueException($url.' could not be saved to '.$fileName.', make sure the'
  138. .' directory is writable and you have internet connectivity');
  139. }
  140. if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
  141. throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from '.$url.')');
  142. }
  143. } catch (\Exception $e) {
  144. // clean up
  145. $this->filesystem->removeDirectory($path);
  146. $this->clearCache($package, $path);
  147. throw $e;
  148. }
  149. return $fileName;
  150. }
  151. /**
  152. * {@inheritDoc}
  153. */
  154. public function setOutputProgress($outputProgress)
  155. {
  156. $this->outputProgress = $outputProgress;
  157. return $this;
  158. }
  159. protected function clearCache(PackageInterface $package, $path)
  160. {
  161. if ($this->cache) {
  162. $fileName = $this->getFileName($package, $path);
  163. $this->cache->remove($this->getCacheKey($package));
  164. }
  165. }
  166. /**
  167. * {@inheritDoc}
  168. */
  169. public function update(PackageInterface $initial, PackageInterface $target, $path)
  170. {
  171. $this->remove($initial, $path);
  172. $this->download($target, $path);
  173. }
  174. /**
  175. * {@inheritDoc}
  176. */
  177. public function remove(PackageInterface $package, $path)
  178. {
  179. $this->io->write(" - Removing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</comment>)");
  180. if (!$this->filesystem->removeDirectory($path)) {
  181. throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
  182. }
  183. }
  184. /**
  185. * Gets file name for specific package
  186. *
  187. * @param PackageInterface $package package instance
  188. * @param string $path download path
  189. * @return string file name
  190. */
  191. protected function getFileName(PackageInterface $package, $path)
  192. {
  193. return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME);
  194. }
  195. /**
  196. * Process the download url
  197. *
  198. * @param PackageInterface $package package the url is coming from
  199. * @param string $url download url
  200. * @return string url
  201. *
  202. * @throws \RuntimeException If any problem with the 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. }