SelfUpdateCommand.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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\Util\Filesystem;
  15. use Composer\Util\RemoteFilesystem;
  16. use Composer\Downloader\FilesystemException;
  17. use Composer\Downloader\TransportException;
  18. use Symfony\Component\Console\Input\InputInterface;
  19. use Symfony\Component\Console\Input\InputOption;
  20. use Symfony\Component\Console\Input\InputArgument;
  21. use Symfony\Component\Console\Output\OutputInterface;
  22. /**
  23. * @author Igor Wiedler <igor@wiedler.ch>
  24. * @author Kevin Ran <kran@adobe.com>
  25. * @author Jordi Boggiano <j.boggiano@seld.be>
  26. */
  27. class SelfUpdateCommand extends Command
  28. {
  29. const HOMEPAGE = 'getcomposer.org';
  30. const OLD_INSTALL_EXT = '-old.phar';
  31. protected function configure()
  32. {
  33. $this
  34. ->setName('self-update')
  35. ->setAliases(array('selfupdate'))
  36. ->setDescription('Updates composer.phar to the latest version.')
  37. ->setDefinition(array(
  38. new InputOption('rollback', 'r', InputOption::VALUE_NONE, 'Revert to an older installation of composer'),
  39. 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'),
  40. new InputOption('disable-tls', null, InputOption::VALUE_NONE, 'Disable SSL/TLS protection for HTTPS requests'),
  41. new InputOption('cafile', null, InputOption::VALUE_REQUIRED, 'The path to a valid CA certificate file for SSL/TLS certificate verification'),
  42. new InputArgument('version', InputArgument::OPTIONAL, 'The version to update to'),
  43. ))
  44. ->setHelp(<<<EOT
  45. The <info>self-update</info> command checks getcomposer.org for newer
  46. versions of composer and if found, installs the latest.
  47. <info>php composer.phar self-update</info>
  48. EOT
  49. )
  50. ;
  51. }
  52. protected function execute(InputInterface $input, OutputInterface $output)
  53. {
  54. $config = Factory::createConfig();
  55. $disableTls = false;
  56. if($config->get('disable-tls') === true || $input->getOption('disable-tls')) {
  57. $output->writeln('<warning>You are running Composer with SSL/TLS protection disabled.</warning>');
  58. $baseUrl = 'http://' . self::HOMEPAGE;
  59. $disableTls = true;
  60. } elseif (!extension_loaded('openssl')) {
  61. $output->writeln('<error>The openssl extension is required for SSL/TLS protection.</error>');
  62. $output->writeln('<error>You can disable this error, at your own risk, by enabling the \'disable-tls\' option.</error>');
  63. return 1;
  64. } else {
  65. $baseUrl = 'https://' . self::HOMEPAGE;
  66. }
  67. $remoteFilesystemOptions = array();
  68. if ($disableTls === false) {
  69. if (!is_null($config->get('cafile'))) {
  70. $remoteFilesystemOptions = array('ssl'=>array('cafile'=>$config->get('cafile')));
  71. }
  72. if (!is_null($input->get('cafile'))) {
  73. $remoteFilesystemOptions = array('ssl'=>array('cafile'=>$input->get('cafile')));
  74. }
  75. }
  76. try {
  77. $remoteFilesystem = new RemoteFilesystem($this->getIO(), $remoteFilesystemOptions, $disableTls);
  78. } catch (TransportException $e) {
  79. if (preg_match('|cafile|', $e->getMessage())) {
  80. $output->writeln('<error>' . $e->getMessage() . '</error>');
  81. $output->writeln('<error>Unable to locate a valid CA certificate file. You must set a valid \'cafile\' option.</error>');
  82. $output->writeln('<error>You can alternatively disable this error, at your own risk, by enabling the \'disable-tls\' option.</error>');
  83. return 1;
  84. } else {
  85. throw $e;
  86. }
  87. }
  88. $cacheDir = $config->get('cache-dir');
  89. $rollbackDir = $config->get('home');
  90. $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
  91. // check if current dir is writable and if not try the cache dir from settings
  92. $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir;
  93. // check for permissions in local filesystem before start connection process
  94. if (!is_writable($tmpDir)) {
  95. throw new FilesystemException('Composer update failed: the "'.$tmpDir.'" directory used to download the temp file could not be written');
  96. }
  97. if (!is_writable($localFilename)) {
  98. throw new FilesystemException('Composer update failed: the "'.$localFilename.'" file could not be written');
  99. }
  100. if ($input->getOption('rollback')) {
  101. return $this->rollback($output, $rollbackDir, $localFilename);
  102. }
  103. $latestVersion = trim($remoteFilesystem->getContents(self::HOMEPAGE, $baseUrl. '/version', false));
  104. $updateVersion = $input->getArgument('version') ?: $latestVersion;
  105. if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) {
  106. $output->writeln('<error>You can not update to a specific SHA-1 as those phars are not available for download</error>');
  107. return 1;
  108. }
  109. if (Composer::VERSION === $updateVersion) {
  110. $output->writeln('<info>You are already using composer version '.$updateVersion.'.</info>');
  111. return 0;
  112. }
  113. $tempFilename = $tmpDir . '/' . basename($localFilename, '.phar').'-temp.phar';
  114. $backupFile = sprintf(
  115. '%s/%s-%s%s',
  116. $rollbackDir,
  117. strtr(Composer::RELEASE_DATE, ' :', '_-'),
  118. preg_replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Composer::VERSION),
  119. self::OLD_INSTALL_EXT
  120. );
  121. $output->writeln(sprintf("Updating to version <info>%s</info>.", $updateVersion));
  122. $remoteFilename = $baseUrl . (preg_match('{^[0-9a-f]{40}$}', $updateVersion) ? '/composer.phar' : "/download/{$updateVersion}/composer.phar");
  123. $remoteFilesystem->copy(self::HOMEPAGE, $remoteFilename, $tempFilename);
  124. if (!file_exists($tempFilename)) {
  125. $output->writeln('<error>The download of the new composer version failed for an unexpected reason</error>');
  126. return 1;
  127. }
  128. // remove saved installations of composer
  129. if ($input->getOption('clean-backups')) {
  130. $files = $this->getOldInstallationFiles($rollbackDir);
  131. if (!empty($files)) {
  132. $fs = new Filesystem;
  133. foreach ($files as $file) {
  134. $output->writeln('<info>Removing: '.$file.'</info>');
  135. $fs->remove($file);
  136. }
  137. }
  138. }
  139. if ($err = $this->setLocalPhar($localFilename, $tempFilename, $backupFile)) {
  140. $output->writeln('<error>The file is corrupted ('.$err->getMessage().').</error>');
  141. $output->writeln('<error>Please re-run the self-update command to try again.</error>');
  142. return 1;
  143. }
  144. if (file_exists($backupFile)) {
  145. $output->writeln('Use <info>composer self-update --rollback</info> to return to version '.Composer::VERSION);
  146. } else {
  147. $output->writeln('<warning>A backup of the current version could not be written to '.$backupFile.', no rollback possible</warning>');
  148. }
  149. }
  150. protected function rollback(OutputInterface $output, $rollbackDir, $localFilename)
  151. {
  152. $rollbackVersion = $this->getLastBackupVersion($rollbackDir);
  153. if (!$rollbackVersion) {
  154. throw new \UnexpectedValueException('Composer rollback failed: no installation to roll back to in "'.$rollbackDir.'"');
  155. }
  156. if (!is_writable($rollbackDir)) {
  157. throw new FilesystemException('Composer rollback failed: the "'.$rollbackDir.'" dir could not be written to');
  158. }
  159. $old = $rollbackDir . '/' . $rollbackVersion . self::OLD_INSTALL_EXT;
  160. if (!is_file($old)) {
  161. throw new FilesystemException('Composer rollback failed: "'.$old.'" could not be found');
  162. }
  163. if (!is_readable($old)) {
  164. throw new FilesystemException('Composer rollback failed: "'.$old.'" could not be read');
  165. }
  166. $oldFile = $rollbackDir . "/{$rollbackVersion}" . self::OLD_INSTALL_EXT;
  167. $output->writeln(sprintf("Rolling back to version <info>%s</info>.", $rollbackVersion));
  168. if ($err = $this->setLocalPhar($localFilename, $oldFile)) {
  169. $output->writeln('<error>The backup file was corrupted ('.$err->getMessage().') and has been removed.</error>');
  170. return 1;
  171. }
  172. return 0;
  173. }
  174. protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null)
  175. {
  176. try {
  177. @chmod($newFilename, 0777 & ~umask());
  178. // test the phar validity
  179. $phar = new \Phar($newFilename);
  180. // free the variable to unlock the file
  181. unset($phar);
  182. // copy current file into installations dir
  183. if ($backupTarget && file_exists($localFilename)) {
  184. @copy($localFilename, $backupTarget);
  185. }
  186. unset($phar);
  187. rename($newFilename, $localFilename);
  188. } catch (\Exception $e) {
  189. if ($backupTarget) {
  190. @unlink($newFilename);
  191. }
  192. if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
  193. throw $e;
  194. }
  195. return $e;
  196. }
  197. }
  198. protected function getLastBackupVersion($rollbackDir)
  199. {
  200. $files = $this->getOldInstallationFiles($rollbackDir);
  201. if (empty($files)) {
  202. return false;
  203. }
  204. sort($files);
  205. return basename(end($files), self::OLD_INSTALL_EXT);
  206. }
  207. protected function getOldInstallationFiles($rollbackDir)
  208. {
  209. return glob($rollbackDir . '/*' . self::OLD_INSTALL_EXT) ?: array();
  210. }
  211. }