1
0

Installer.php 18 KB

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