Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Installer.php 19KB

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