SelfUpdateCommand.php 18 KB

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