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

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