SelfUpdateCommand.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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\Command;
  12. use Composer\Composer;
  13. use Composer\Factory;
  14. use Composer\Config;
  15. use Composer\Util\Filesystem;
  16. use Composer\Util\Keys;
  17. use Composer\IO\IOInterface;
  18. use Composer\Downloader\FilesystemException;
  19. use Symfony\Component\Console\Input\InputInterface;
  20. use Symfony\Component\Console\Input\InputOption;
  21. use Symfony\Component\Console\Input\InputArgument;
  22. use Symfony\Component\Console\Output\OutputInterface;
  23. use Symfony\Component\Finder\Finder;
  24. /**
  25. * @author Igor Wiedler <igor@wiedler.ch>
  26. * @author Kevin Ran <kran@adobe.com>
  27. * @author Jordi Boggiano <j.boggiano@seld.be>
  28. */
  29. class SelfUpdateCommand extends BaseCommand
  30. {
  31. const HOMEPAGE = 'getcomposer.org';
  32. const OLD_INSTALL_EXT = '-old.phar';
  33. protected function configure()
  34. {
  35. $this
  36. ->setName('self-update')
  37. ->setAliases(array('selfupdate'))
  38. ->setDescription('Updates composer.phar to the latest version.')
  39. ->setDefinition(array(
  40. new InputOption('rollback', 'r', InputOption::VALUE_NONE, 'Revert to an older installation of composer'),
  41. new InputOption('clean-backups', null, InputOption::VALUE_NONE, 'Delete old backups during an update. This makes the current version of composer the only backup available after the update'),
  42. new InputArgument('version', InputArgument::OPTIONAL, 'The version to update to'),
  43. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  44. new InputOption('update-keys', null, InputOption::VALUE_NONE, 'Prompt user for a key update'),
  45. ))
  46. ->setHelp(<<<EOT
  47. The <info>self-update</info> command checks getcomposer.org for newer
  48. versions of composer and if found, installs the latest.
  49. <info>php composer.phar self-update</info>
  50. EOT
  51. )
  52. ;
  53. }
  54. protected function execute(InputInterface $input, OutputInterface $output)
  55. {
  56. $config = Factory::createConfig();
  57. if ($config->get('disable-tls') === true) {
  58. $baseUrl = 'http://' . self::HOMEPAGE;
  59. } else {
  60. $baseUrl = 'https://' . self::HOMEPAGE;
  61. }
  62. $io = $this->getIO();
  63. $remoteFilesystem = Factory::createRemoteFilesystem($io, $config);
  64. $cacheDir = $config->get('cache-dir');
  65. $rollbackDir = $config->get('data-dir');
  66. $home = $config->get('home');
  67. $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
  68. if ($input->getOption('update-keys')) {
  69. return $this->fetchKeys($io, $config);
  70. }
  71. // check if current dir is writable and if not try the cache dir from settings
  72. $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir;
  73. // check for permissions in local filesystem before start connection process
  74. if (!is_writable($tmpDir)) {
  75. throw new FilesystemException('Composer update failed: the "'.$tmpDir.'" directory used to download the temp file could not be written');
  76. }
  77. if ($input->getOption('rollback')) {
  78. return $this->rollback($output, $rollbackDir, $localFilename);
  79. }
  80. $latestVersion = trim($remoteFilesystem->getContents(self::HOMEPAGE, $baseUrl. '/version', false));
  81. $updateVersion = $input->getArgument('version') ?: $latestVersion;
  82. if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) {
  83. $io->writeError('<error>You can not update to a specific SHA-1 as those phars are not available for download</error>');
  84. return 1;
  85. }
  86. if (Composer::VERSION === $updateVersion) {
  87. $io->writeError('<info>You are already using composer version '.$updateVersion.'.</info>');
  88. // remove all backups except for the most recent, if any
  89. if ($input->getOption('clean-backups')) {
  90. $this->cleanBackups($rollbackDir, $this->getLastBackupVersion());
  91. }
  92. return 0;
  93. }
  94. $tempFilename = $tmpDir . '/' . basename($localFilename, '.phar').'-temp.phar';
  95. $backupFile = sprintf(
  96. '%s/%s-%s%s',
  97. $rollbackDir,
  98. strtr(Composer::RELEASE_DATE, ' :', '_-'),
  99. preg_replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Composer::VERSION),
  100. self::OLD_INSTALL_EXT
  101. );
  102. $updatingToTag = !preg_match('{^[0-9a-f]{40}$}', $updateVersion);
  103. $io->write(sprintf("Updating to version <info>%s</info>.", $updateVersion));
  104. $remoteFilename = $baseUrl . ($updatingToTag ? "/download/{$updateVersion}/composer.phar" : '/composer.phar');
  105. $signature = $remoteFilesystem->getContents(self::HOMEPAGE, $remoteFilename.'.sig', false);
  106. $remoteFilesystem->copy(self::HOMEPAGE, $remoteFilename, $tempFilename, !$input->getOption('no-progress'));
  107. if (!file_exists($tempFilename) || !$signature) {
  108. $io->writeError('<error>The download of the new composer version failed for an unexpected reason</error>');
  109. return 1;
  110. }
  111. // verify phar signature
  112. if (!extension_loaded('openssl') && $config->get('disable-tls')) {
  113. $io->writeError('<warning>Skipping phar signature verification as you have disabled OpenSSL via config.disable-tls</warning>');
  114. } else {
  115. if (!extension_loaded('openssl')) {
  116. throw new \RuntimeException('The openssl extension is required for phar signatures to be verified but it is not available. '
  117. . 'If you can not enable the openssl extension, you can disable this error, at your own risk, by setting the \'disable-tls\' option to true.');
  118. }
  119. $sigFile = 'file://'.$home.'/' . ($updatingToTag ? 'keys.tags.pub' : 'keys.dev.pub');
  120. if (!file_exists($sigFile)) {
  121. file_put_contents($home.'/keys.dev.pub', <<<DEVPUBKEY
  122. -----BEGIN PUBLIC KEY-----
  123. MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAnBDHjZS6e0ZMoK3xTD7f
  124. FNCzlXjX/Aie2dit8QXA03pSrOTbaMnxON3hUL47Lz3g1SC6YJEMVHr0zYq4elWi
  125. i3ecFEgzLcj+pZM5X6qWu2Ozz4vWx3JYo1/a/HYdOuW9e3lwS8VtS0AVJA+U8X0A
  126. hZnBmGpltHhO8hPKHgkJtkTUxCheTcbqn4wGHl8Z2SediDcPTLwqezWKUfrYzu1f
  127. o/j3WFwFs6GtK4wdYtiXr+yspBZHO3y1udf8eFFGcb2V3EaLOrtfur6XQVizjOuk
  128. 8lw5zzse1Qp/klHqbDRsjSzJ6iL6F4aynBc6Euqt/8ccNAIz0rLjLhOraeyj4eNn
  129. 8iokwMKiXpcrQLTKH+RH1JCuOVxQ436bJwbSsp1VwiqftPQieN+tzqy+EiHJJmGf
  130. TBAbWcncicCk9q2md+AmhNbvHO4PWbbz9TzC7HJb460jyWeuMEvw3gNIpEo2jYa9
  131. pMV6cVqnSa+wOc0D7pC9a6bne0bvLcm3S+w6I5iDB3lZsb3A9UtRiSP7aGSo7D72
  132. 8tC8+cIgZcI7k9vjvOqH+d7sdOU2yPCnRY6wFh62/g8bDnUpr56nZN1G89GwM4d4
  133. r/TU7BQQIzsZgAiqOGXvVklIgAMiV0iucgf3rNBLjjeNEwNSTTG9F0CtQ+7JLwaE
  134. wSEuAuRm+pRqi8BRnQ/GKUcCAwEAAQ==
  135. -----END PUBLIC KEY-----
  136. DEVPUBKEY
  137. );
  138. file_put_contents($home.'/keys.tags.pub', <<<TAGSPUBKEY
  139. -----BEGIN PUBLIC KEY-----
  140. MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0Vi/2K6apCVj76nCnCl2
  141. MQUPdK+A9eqkYBacXo2wQBYmyVlXm2/n/ZsX6pCLYPQTHyr5jXbkQzBw8SKqPdlh
  142. vA7NpbMeNCz7wP/AobvUXM8xQuXKbMDTY2uZ4O7sM+PfGbptKPBGLe8Z8d2sUnTO
  143. bXtX6Lrj13wkRto7st/w/Yp33RHe9SlqkiiS4MsH1jBkcIkEHsRaveZzedUaxY0M
  144. mba0uPhGUInpPzEHwrYqBBEtWvP97t2vtfx8I5qv28kh0Y6t+jnjL1Urid2iuQZf
  145. noCMFIOu4vksK5HxJxxrN0GOmGmwVQjOOtxkwikNiotZGPR4KsVj8NnBrLX7oGuM
  146. nQvGciiu+KoC2r3HDBrpDeBVdOWxDzT5R4iI0KoLzFh2pKqwbY+obNPS2bj+2dgJ
  147. rV3V5Jjry42QOCBN3c88wU1PKftOLj2ECpewY6vnE478IipiEu7EAdK8Zwj2LmTr
  148. RKQUSa9k7ggBkYZWAeO/2Ag0ey3g2bg7eqk+sHEq5ynIXd5lhv6tC5PBdHlWipDK
  149. tl2IxiEnejnOmAzGVivE1YGduYBjN+mjxDVy8KGBrjnz1JPgAvgdwJ2dYw4Rsc/e
  150. TzCFWGk/HM6a4f0IzBWbJ5ot0PIi4amk07IotBXDWwqDiQTwyuGCym5EqWQ2BD95
  151. RGv89BPD+2DLnJysngsvVaUCAwEAAQ==
  152. -----END PUBLIC KEY-----
  153. TAGSPUBKEY
  154. );
  155. }
  156. $pubkeyid = openssl_pkey_get_public($sigFile);
  157. $algo = defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'SHA384';
  158. if (!in_array('SHA384', openssl_get_md_methods())) {
  159. throw new \RuntimeException('SHA384 is not supported by your openssl extension, could not verify the phar file integrity');
  160. }
  161. $signature = json_decode($signature, true);
  162. $signature = base64_decode($signature['sha384']);
  163. $verified = 1 === openssl_verify(file_get_contents($tempFilename), $signature, $pubkeyid, $algo);
  164. openssl_free_key($pubkeyid);
  165. if (!$verified) {
  166. throw new \RuntimeException('The phar signature did not match the file you downloaded, this means your public keys are outdated or that the phar file is corrupt/has been modified');
  167. }
  168. }
  169. // remove saved installations of composer
  170. if ($input->getOption('clean-backups')) {
  171. $this->cleanBackups($rollbackDir);
  172. }
  173. if ($err = $this->setLocalPhar($localFilename, $tempFilename, $backupFile)) {
  174. @unlink($tempFilename);
  175. $io->writeError('<error>The file is corrupted ('.$err->getMessage().').</error>');
  176. $io->writeError('<error>Please re-run the self-update command to try again.</error>');
  177. return 1;
  178. }
  179. if (file_exists($backupFile)) {
  180. $io->writeError('Use <info>composer self-update --rollback</info> to return to version '.Composer::VERSION);
  181. } else {
  182. $io->writeError('<warning>A backup of the current version could not be written to '.$backupFile.', no rollback possible</warning>');
  183. }
  184. }
  185. protected function fetchKeys(IOInterface $io, Config $config)
  186. {
  187. if (!$io->isInteractive()) {
  188. throw new \RuntimeException('Public keys can not be fetched in non-interactive mode, please run Composer interactively');
  189. }
  190. $io->write('Open <info>https://composer.github.io/pubkeys.html</info> to find the latest keys');
  191. $validator = function ($value) {
  192. if (!preg_match('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) {
  193. throw new \UnexpectedValueException('Invalid input');
  194. }
  195. return trim($value)."\n";
  196. };
  197. $devKey = '';
  198. while (!preg_match('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $devKey, $match)) {
  199. $devKey = $io->askAndValidate('Enter Dev / Snapshot Public Key (including lines with -----): ', $validator);
  200. while ($line = $io->ask('')) {
  201. $devKey .= trim($line)."\n";
  202. if (trim($line) === '-----END PUBLIC KEY-----') {
  203. break;
  204. }
  205. }
  206. }
  207. file_put_contents($keyPath = $config->get('home').'/keys.dev.pub', $match[0]);
  208. $io->write('Stored key with fingerprint: ' . Keys::fingerprint($keyPath));
  209. $tagsKey = '';
  210. while (!preg_match('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $tagsKey, $match)) {
  211. $tagsKey = $io->askAndValidate('Enter Tags Public Key (including lines with -----): ', $validator);
  212. while ($line = $io->ask('')) {
  213. $tagsKey .= trim($line)."\n";
  214. if (trim($line) === '-----END PUBLIC KEY-----') {
  215. break;
  216. }
  217. }
  218. }
  219. file_put_contents($keyPath = $config->get('home').'/keys.tags.pub', $match[0]);
  220. $io->write('Stored key with fingerprint: ' . Keys::fingerprint($keyPath));
  221. $io->write('Public keys stored in '.$config->get('home'));
  222. }
  223. protected function rollback(OutputInterface $output, $rollbackDir, $localFilename)
  224. {
  225. $rollbackVersion = $this->getLastBackupVersion($rollbackDir);
  226. if (!$rollbackVersion) {
  227. throw new \UnexpectedValueException('Composer rollback failed: no installation to roll back to in "'.$rollbackDir.'"');
  228. }
  229. $oldFile = $rollbackDir . '/' . $rollbackVersion . self::OLD_INSTALL_EXT;
  230. if (!is_file($oldFile)) {
  231. throw new FilesystemException('Composer rollback failed: "'.$oldFile.'" could not be found');
  232. }
  233. if (!is_readable($oldFile)) {
  234. throw new FilesystemException('Composer rollback failed: "'.$oldFile.'" could not be read');
  235. }
  236. $io = $this->getIO();
  237. $io->writeError(sprintf("Rolling back to version <info>%s</info>.", $rollbackVersion));
  238. if ($err = $this->setLocalPhar($localFilename, $oldFile)) {
  239. $io->writeError('<error>The backup file was corrupted ('.$err->getMessage().').</error>');
  240. return 1;
  241. }
  242. return 0;
  243. }
  244. /**
  245. * @param string $localFilename
  246. * @param string $newFilename
  247. * @param string $backupTarget
  248. */
  249. protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null)
  250. {
  251. try {
  252. @chmod($newFilename, fileperms($localFilename));
  253. if (!ini_get('phar.readonly')) {
  254. // test the phar validity
  255. $phar = new \Phar($newFilename);
  256. // free the variable to unlock the file
  257. unset($phar);
  258. }
  259. // copy current file into installations dir
  260. if ($backupTarget && file_exists($localFilename)) {
  261. @copy($localFilename, $backupTarget);
  262. }
  263. rename($newFilename, $localFilename);
  264. } catch (\Exception $e) {
  265. if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
  266. throw $e;
  267. }
  268. return $e;
  269. }
  270. }
  271. protected function cleanBackups($rollbackDir, $except = null)
  272. {
  273. $finder = $this->getOldInstallationFinder($rollbackDir);
  274. $io = $this->getIO();
  275. $fs = new Filesystem;
  276. foreach ($finder as $file) {
  277. if ($except && $file->getBasename(self::OLD_INSTALL_EXT) === $except) {
  278. continue;
  279. }
  280. $file = (string) $file;
  281. $io->writeError('<info>Removing: '.$file.'</info>');
  282. $fs->remove($file);
  283. }
  284. }
  285. protected function getLastBackupVersion($rollbackDir)
  286. {
  287. $finder = $this->getOldInstallationFinder($rollbackDir);
  288. $finder->sortByName();
  289. $files = iterator_to_array($finder);
  290. if (count($files)) {
  291. return basename(end($files), self::OLD_INSTALL_EXT);
  292. }
  293. return false;
  294. }
  295. protected function getOldInstallationFinder($rollbackDir)
  296. {
  297. $finder = Finder::create()
  298. ->depth(0)
  299. ->files()
  300. ->name('*' . self::OLD_INSTALL_EXT)
  301. ->in($rollbackDir);
  302. return $finder;
  303. }
  304. }