1
0

Installer.php 19 KB

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