You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Installer.php 18KB

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