SelfUpdateCommand.php 17 KB

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