Installer.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC;
  9. use Doctrine\DBAL\Exception\TableExistsException;
  10. use OC\App\AppStore\Bundles\Bundle;
  11. use OC\App\AppStore\Fetcher\AppFetcher;
  12. use OC\AppFramework\Bootstrap\Coordinator;
  13. use OC\Archive\TAR;
  14. use OC\DB\Connection;
  15. use OC\DB\MigrationService;
  16. use OC_App;
  17. use OC_Helper;
  18. use OCP\App\IAppManager;
  19. use OCP\HintException;
  20. use OCP\Http\Client\IClientService;
  21. use OCP\IConfig;
  22. use OCP\ITempManager;
  23. use OCP\Migration\IOutput;
  24. use phpseclib\File\X509;
  25. use Psr\Log\LoggerInterface;
  26. /**
  27. * This class provides the functionality needed to install, update and remove apps
  28. */
  29. class Installer {
  30. private ?bool $isInstanceReadyForUpdates = null;
  31. private ?array $apps = null;
  32. public function __construct(
  33. private AppFetcher $appFetcher,
  34. private IClientService $clientService,
  35. private ITempManager $tempManager,
  36. private LoggerInterface $logger,
  37. private IConfig $config,
  38. private bool $isCLI,
  39. ) {
  40. }
  41. /**
  42. * Installs an app that is located in one of the app folders already
  43. *
  44. * @param string $appId App to install
  45. * @param bool $forceEnable
  46. * @throws \Exception
  47. * @return string app ID
  48. */
  49. public function installApp(string $appId, bool $forceEnable = false): string {
  50. $app = \OC_App::findAppInDirectories($appId);
  51. if ($app === false) {
  52. throw new \Exception('App not found in any app directory');
  53. }
  54. $basedir = $app['path'].'/'.$appId;
  55. if (is_file($basedir . '/appinfo/database.xml')) {
  56. throw new \Exception('The appinfo/database.xml file is not longer supported. Used in ' . $appId);
  57. }
  58. $l = \OCP\Util::getL10N('core');
  59. $info = \OCP\Server::get(IAppManager::class)->getAppInfo($basedir . '/appinfo/info.xml', true, $l->getLanguageCode());
  60. if (!is_array($info)) {
  61. throw new \Exception(
  62. $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
  63. [$appId]
  64. )
  65. );
  66. }
  67. $ignoreMaxApps = $this->config->getSystemValue('app_install_overwrite', []);
  68. $ignoreMax = $forceEnable || in_array($appId, $ignoreMaxApps, true);
  69. $version = implode('.', \OCP\Util::getVersion());
  70. if (!\OC_App::isAppCompatible($version, $info, $ignoreMax)) {
  71. throw new \Exception(
  72. // TODO $l
  73. $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
  74. [$info['name']]
  75. )
  76. );
  77. }
  78. // check for required dependencies
  79. \OC_App::checkAppDependencies($this->config, $l, $info, $ignoreMax);
  80. /** @var Coordinator $coordinator */
  81. $coordinator = \OC::$server->get(Coordinator::class);
  82. $coordinator->runLazyRegistration($appId);
  83. \OC_App::registerAutoloading($appId, $basedir);
  84. $previousVersion = $this->config->getAppValue($info['id'], 'installed_version', false);
  85. if ($previousVersion) {
  86. OC_App::executeRepairSteps($appId, $info['repair-steps']['pre-migration']);
  87. }
  88. //install the database
  89. $ms = new MigrationService($info['id'], \OCP\Server::get(Connection::class));
  90. $ms->migrate('latest', !$previousVersion);
  91. if ($previousVersion) {
  92. OC_App::executeRepairSteps($appId, $info['repair-steps']['post-migration']);
  93. }
  94. \OC_App::setupBackgroundJobs($info['background-jobs']);
  95. //run appinfo/install.php
  96. self::includeAppScript($basedir . '/appinfo/install.php');
  97. OC_App::executeRepairSteps($appId, $info['repair-steps']['install']);
  98. $config = \OCP\Server::get(IConfig::class);
  99. //set the installed version
  100. $config->setAppValue($info['id'], 'installed_version', \OCP\Server::get(IAppManager::class)->getAppVersion($info['id'], false));
  101. $config->setAppValue($info['id'], 'enabled', 'no');
  102. //set remote/public handlers
  103. foreach ($info['remote'] as $name => $path) {
  104. $config->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
  105. }
  106. foreach ($info['public'] as $name => $path) {
  107. $config->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
  108. }
  109. OC_App::setAppTypes($info['id']);
  110. return $info['id'];
  111. }
  112. /**
  113. * Updates the specified app from the appstore
  114. *
  115. * @param bool $allowUnstable Allow unstable releases
  116. */
  117. public function updateAppstoreApp(string $appId, bool $allowUnstable = false): bool {
  118. if ($this->isUpdateAvailable($appId, $allowUnstable)) {
  119. try {
  120. $this->downloadApp($appId, $allowUnstable);
  121. } catch (\Exception $e) {
  122. $this->logger->error($e->getMessage(), [
  123. 'exception' => $e,
  124. ]);
  125. return false;
  126. }
  127. return OC_App::updateApp($appId);
  128. }
  129. return false;
  130. }
  131. /**
  132. * Split the certificate file in individual certs
  133. *
  134. * @param string $cert
  135. * @return string[]
  136. */
  137. private function splitCerts(string $cert): array {
  138. preg_match_all('([\-]{3,}[\S\ ]+?[\-]{3,}[\S\s]+?[\-]{3,}[\S\ ]+?[\-]{3,})', $cert, $matches);
  139. return $matches[0];
  140. }
  141. /**
  142. * Downloads an app and puts it into the app directory
  143. *
  144. * @param string $appId
  145. * @param bool [$allowUnstable]
  146. *
  147. * @throws \Exception If the installation was not successful
  148. */
  149. public function downloadApp(string $appId, bool $allowUnstable = false): void {
  150. $appId = strtolower($appId);
  151. $apps = $this->appFetcher->get($allowUnstable);
  152. foreach ($apps as $app) {
  153. if ($app['id'] === $appId) {
  154. // Load the certificate
  155. $certificate = new X509();
  156. $rootCrt = file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt');
  157. $rootCrts = $this->splitCerts($rootCrt);
  158. foreach ($rootCrts as $rootCrt) {
  159. $certificate->loadCA($rootCrt);
  160. }
  161. $loadedCertificate = $certificate->loadX509($app['certificate']);
  162. // Verify if the certificate has been revoked
  163. $crl = new X509();
  164. foreach ($rootCrts as $rootCrt) {
  165. $crl->loadCA($rootCrt);
  166. }
  167. $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
  168. if ($crl->validateSignature() !== true) {
  169. throw new \Exception('Could not validate CRL signature');
  170. }
  171. $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
  172. $revoked = $crl->getRevoked($csn);
  173. if ($revoked !== false) {
  174. throw new \Exception(
  175. sprintf(
  176. 'Certificate "%s" has been revoked',
  177. $csn
  178. )
  179. );
  180. }
  181. // Verify if the certificate has been issued by the Nextcloud Code Authority CA
  182. if ($certificate->validateSignature() !== true) {
  183. throw new \Exception(
  184. sprintf(
  185. 'App with id %s has a certificate not issued by a trusted Code Signing Authority',
  186. $appId
  187. )
  188. );
  189. }
  190. // Verify if the certificate is issued for the requested app id
  191. $certInfo = openssl_x509_parse($app['certificate']);
  192. if (!isset($certInfo['subject']['CN'])) {
  193. throw new \Exception(
  194. sprintf(
  195. 'App with id %s has a cert with no CN',
  196. $appId
  197. )
  198. );
  199. }
  200. if ($certInfo['subject']['CN'] !== $appId) {
  201. throw new \Exception(
  202. sprintf(
  203. 'App with id %s has a cert issued to %s',
  204. $appId,
  205. $certInfo['subject']['CN']
  206. )
  207. );
  208. }
  209. // Download the release
  210. $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
  211. $timeout = $this->isCLI ? 0 : 120;
  212. $client = $this->clientService->newClient();
  213. $client->get($app['releases'][0]['download'], ['sink' => $tempFile, 'timeout' => $timeout]);
  214. // Check if the signature actually matches the downloaded content
  215. $certificate = openssl_get_publickey($app['certificate']);
  216. $verified = openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512) === 1;
  217. if ($verified === true) {
  218. // Seems to match, let's proceed
  219. $extractDir = $this->tempManager->getTemporaryFolder();
  220. $archive = new TAR($tempFile);
  221. if (!$archive->extract($extractDir)) {
  222. $errorMessage = 'Could not extract app ' . $appId;
  223. $archiveError = $archive->getError();
  224. if ($archiveError instanceof \PEAR_Error) {
  225. $errorMessage .= ': ' . $archiveError->getMessage();
  226. }
  227. throw new \Exception($errorMessage);
  228. }
  229. $allFiles = scandir($extractDir);
  230. $folders = array_diff($allFiles, ['.', '..']);
  231. $folders = array_values($folders);
  232. if (count($folders) < 1) {
  233. throw new \Exception(
  234. sprintf(
  235. 'Extracted app %s has no folders',
  236. $appId
  237. )
  238. );
  239. }
  240. if (count($folders) > 1) {
  241. throw new \Exception(
  242. sprintf(
  243. 'Extracted app %s has more than 1 folder',
  244. $appId
  245. )
  246. );
  247. }
  248. // Check if appinfo/info.xml has the same app ID as well
  249. $xml = simplexml_load_string(file_get_contents($extractDir . '/' . $folders[0] . '/appinfo/info.xml'));
  250. if ($xml === false) {
  251. throw new \Exception(
  252. sprintf(
  253. 'Failed to load info.xml for app id %s',
  254. $appId,
  255. )
  256. );
  257. }
  258. if ((string)$xml->id !== $appId) {
  259. throw new \Exception(
  260. sprintf(
  261. 'App for id %s has a wrong app ID in info.xml: %s',
  262. $appId,
  263. (string)$xml->id
  264. )
  265. );
  266. }
  267. // Check if the version is lower than before
  268. $currentVersion = \OCP\Server::get(IAppManager::class)->getAppVersion($appId, true);
  269. $newVersion = (string)$xml->version;
  270. if (version_compare($currentVersion, $newVersion) === 1) {
  271. throw new \Exception(
  272. sprintf(
  273. 'App for id %s has version %s and tried to update to lower version %s',
  274. $appId,
  275. $currentVersion,
  276. $newVersion
  277. )
  278. );
  279. }
  280. $baseDir = OC_App::getInstallPath() . '/' . $appId;
  281. // Remove old app with the ID if existent
  282. OC_Helper::rmdirr($baseDir);
  283. // Move to app folder
  284. if (@mkdir($baseDir)) {
  285. $extractDir .= '/' . $folders[0];
  286. OC_Helper::copyr($extractDir, $baseDir);
  287. }
  288. OC_Helper::copyr($extractDir, $baseDir);
  289. OC_Helper::rmdirr($extractDir);
  290. return;
  291. }
  292. // Signature does not match
  293. throw new \Exception(
  294. sprintf(
  295. 'App with id %s has invalid signature',
  296. $appId
  297. )
  298. );
  299. }
  300. }
  301. throw new \Exception(
  302. sprintf(
  303. 'Could not download app %s',
  304. $appId
  305. )
  306. );
  307. }
  308. /**
  309. * Check if an update for the app is available
  310. *
  311. * @param string $appId
  312. * @param bool $allowUnstable
  313. * @return string|false false or the version number of the update
  314. */
  315. public function isUpdateAvailable($appId, $allowUnstable = false): string|false {
  316. if ($this->isInstanceReadyForUpdates === null) {
  317. $installPath = OC_App::getInstallPath();
  318. if ($installPath === null) {
  319. $this->isInstanceReadyForUpdates = false;
  320. } else {
  321. $this->isInstanceReadyForUpdates = true;
  322. }
  323. }
  324. if ($this->isInstanceReadyForUpdates === false) {
  325. return false;
  326. }
  327. if ($this->isInstalledFromGit($appId) === true) {
  328. return false;
  329. }
  330. if ($this->apps === null) {
  331. $this->apps = $this->appFetcher->get($allowUnstable);
  332. }
  333. foreach ($this->apps as $app) {
  334. if ($app['id'] === $appId) {
  335. $currentVersion = \OCP\Server::get(IAppManager::class)->getAppVersion($appId, true);
  336. if (!isset($app['releases'][0]['version'])) {
  337. return false;
  338. }
  339. $newestVersion = $app['releases'][0]['version'];
  340. if ($currentVersion !== '0' && version_compare($newestVersion, $currentVersion, '>')) {
  341. return $newestVersion;
  342. } else {
  343. return false;
  344. }
  345. }
  346. }
  347. return false;
  348. }
  349. /**
  350. * Check if app has been installed from git
  351. *
  352. * The function will check if the path contains a .git folder
  353. */
  354. private function isInstalledFromGit(string $appId): bool {
  355. $app = \OC_App::findAppInDirectories($appId);
  356. if ($app === false) {
  357. return false;
  358. }
  359. $basedir = $app['path'].'/'.$appId;
  360. return file_exists($basedir.'/.git/');
  361. }
  362. /**
  363. * Check if app is already downloaded
  364. *
  365. * The function will check if the app is already downloaded in the apps repository
  366. */
  367. public function isDownloaded(string $name): bool {
  368. foreach (\OC::$APPSROOTS as $dir) {
  369. $dirToTest = $dir['path'];
  370. $dirToTest .= '/';
  371. $dirToTest .= $name;
  372. $dirToTest .= '/';
  373. if (is_dir($dirToTest)) {
  374. return true;
  375. }
  376. }
  377. return false;
  378. }
  379. /**
  380. * Removes an app
  381. *
  382. * This function works as follows
  383. * -# call uninstall repair steps
  384. * -# removing the files
  385. *
  386. * The function will not delete preferences, tables and the configuration,
  387. * this has to be done by the function oc_app_uninstall().
  388. */
  389. public function removeApp(string $appId): bool {
  390. if ($this->isDownloaded($appId)) {
  391. if (\OCP\Server::get(IAppManager::class)->isShipped($appId)) {
  392. return false;
  393. }
  394. $appDir = OC_App::getInstallPath() . '/' . $appId;
  395. OC_Helper::rmdirr($appDir);
  396. return true;
  397. } else {
  398. $this->logger->error('can\'t remove app '.$appId.'. It is not installed.');
  399. return false;
  400. }
  401. }
  402. /**
  403. * Installs the app within the bundle and marks the bundle as installed
  404. *
  405. * @throws \Exception If app could not get installed
  406. */
  407. public function installAppBundle(Bundle $bundle): void {
  408. $appIds = $bundle->getAppIdentifiers();
  409. foreach ($appIds as $appId) {
  410. if (!$this->isDownloaded($appId)) {
  411. $this->downloadApp($appId);
  412. }
  413. $this->installApp($appId);
  414. $app = new OC_App();
  415. $app->enable($appId);
  416. }
  417. $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
  418. $bundles[] = $bundle->getIdentifier();
  419. $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
  420. }
  421. /**
  422. * Installs shipped apps
  423. *
  424. * This function installs all apps found in the 'apps' directory that should be enabled by default;
  425. * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
  426. * working ownCloud at the end instead of an aborted update.
  427. * @return array Array of error messages (appid => Exception)
  428. */
  429. public static function installShippedApps(bool $softErrors = false, ?IOutput $output = null): array {
  430. if ($output instanceof IOutput) {
  431. $output->debug('Installing shipped apps');
  432. }
  433. $appManager = \OCP\Server::get(IAppManager::class);
  434. $config = \OCP\Server::get(IConfig::class);
  435. $errors = [];
  436. foreach (\OC::$APPSROOTS as $app_dir) {
  437. if ($dir = opendir($app_dir['path'])) {
  438. while (false !== ($filename = readdir($dir))) {
  439. if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
  440. if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
  441. if ($config->getAppValue($filename, "installed_version", null) === null) {
  442. $enabled = $appManager->isDefaultEnabled($filename);
  443. if (($enabled || in_array($filename, $appManager->getAlwaysEnabledApps()))
  444. && $config->getAppValue($filename, 'enabled') !== 'no') {
  445. if ($softErrors) {
  446. try {
  447. Installer::installShippedApp($filename, $output);
  448. } catch (HintException $e) {
  449. if ($e->getPrevious() instanceof TableExistsException) {
  450. $errors[$filename] = $e;
  451. continue;
  452. }
  453. throw $e;
  454. }
  455. } else {
  456. Installer::installShippedApp($filename, $output);
  457. }
  458. $config->setAppValue($filename, 'enabled', 'yes');
  459. }
  460. }
  461. }
  462. }
  463. }
  464. closedir($dir);
  465. }
  466. }
  467. return $errors;
  468. }
  469. /**
  470. * install an app already placed in the app folder
  471. */
  472. public static function installShippedApp(string $app, ?IOutput $output = null): string|false {
  473. if ($output instanceof IOutput) {
  474. $output->debug('Installing ' . $app);
  475. }
  476. $appManager = \OCP\Server::get(IAppManager::class);
  477. $config = \OCP\Server::get(IConfig::class);
  478. $appPath = $appManager->getAppPath($app);
  479. \OC_App::registerAutoloading($app, $appPath);
  480. $ms = new MigrationService($app, \OCP\Server::get(Connection::class));
  481. if ($output instanceof IOutput) {
  482. $ms->setOutput($output);
  483. }
  484. $previousVersion = $config->getAppValue($app, 'installed_version', false);
  485. $ms->migrate('latest', !$previousVersion);
  486. //run appinfo/install.php
  487. self::includeAppScript("$appPath/appinfo/install.php");
  488. $info = \OCP\Server::get(IAppManager::class)->getAppInfo($app);
  489. if (is_null($info)) {
  490. return false;
  491. }
  492. if ($output instanceof IOutput) {
  493. $output->debug('Registering tasks of ' . $app);
  494. }
  495. \OC_App::setupBackgroundJobs($info['background-jobs']);
  496. OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
  497. $config->setAppValue($app, 'installed_version', \OCP\Server::get(IAppManager::class)->getAppVersion($app));
  498. if (array_key_exists('ocsid', $info)) {
  499. $config->setAppValue($app, 'ocsid', $info['ocsid']);
  500. }
  501. //set remote/public handlers
  502. foreach ($info['remote'] as $name => $path) {
  503. $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
  504. }
  505. foreach ($info['public'] as $name => $path) {
  506. $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
  507. }
  508. OC_App::setAppTypes($info['id']);
  509. return $info['id'];
  510. }
  511. private static function includeAppScript(string $script): void {
  512. if (file_exists($script)) {
  513. include $script;
  514. }
  515. }
  516. }