Installer.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. $version = implode('.', \OCP\Util::getVersion());
  107. if (!\OC_App::isAppCompatible($version, $info)) {
  108. throw new \Exception(
  109. // TODO $l
  110. $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
  111. [$info['name']]
  112. )
  113. );
  114. }
  115. // check for required dependencies
  116. \OC_App::checkAppDependencies($this->config, $l, $info);
  117. \OC_App::registerAutoloading($appId, $basedir);
  118. //install the database
  119. if(is_file($basedir.'/appinfo/database.xml')) {
  120. if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
  121. OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
  122. } else {
  123. OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
  124. }
  125. } else {
  126. $ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
  127. $ms->migrate();
  128. }
  129. \OC_App::setupBackgroundJobs($info['background-jobs']);
  130. //run appinfo/install.php
  131. if(!isset($data['noinstall']) or $data['noinstall']==false) {
  132. self::includeAppScript($basedir . '/appinfo/install.php');
  133. }
  134. $appData = OC_App::getAppInfo($appId);
  135. OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
  136. //set the installed version
  137. \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
  138. \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
  139. //set remote/public handlers
  140. foreach($info['remote'] as $name=>$path) {
  141. \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
  142. }
  143. foreach($info['public'] as $name=>$path) {
  144. \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
  145. }
  146. OC_App::setAppTypes($info['id']);
  147. return $info['id'];
  148. }
  149. /**
  150. * @brief checks whether or not an app is installed
  151. * @param string $app app
  152. * @returns bool
  153. *
  154. * Checks whether or not an app is installed, i.e. registered in apps table.
  155. */
  156. public static function isInstalled( $app ) {
  157. return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
  158. }
  159. /**
  160. * Updates the specified app from the appstore
  161. *
  162. * @param string $appId
  163. * @return bool
  164. */
  165. public function updateAppstoreApp($appId) {
  166. if($this->isUpdateAvailable($appId)) {
  167. try {
  168. $this->downloadApp($appId);
  169. } catch (\Exception $e) {
  170. $this->logger->logException($e, [
  171. 'level' => \OCP\Util::ERROR,
  172. 'app' => 'core',
  173. ]);
  174. return false;
  175. }
  176. return OC_App::updateApp($appId);
  177. }
  178. return false;
  179. }
  180. /**
  181. * Downloads an app and puts it into the app directory
  182. *
  183. * @param string $appId
  184. *
  185. * @throws \Exception If the installation was not successful
  186. */
  187. public function downloadApp($appId) {
  188. $appId = strtolower($appId);
  189. $apps = $this->appFetcher->get();
  190. foreach($apps as $app) {
  191. if($app['id'] === $appId) {
  192. // Load the certificate
  193. $certificate = new X509();
  194. $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
  195. $loadedCertificate = $certificate->loadX509($app['certificate']);
  196. // Verify if the certificate has been revoked
  197. $crl = new X509();
  198. $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
  199. $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
  200. if($crl->validateSignature() !== true) {
  201. throw new \Exception('Could not validate CRL signature');
  202. }
  203. $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
  204. $revoked = $crl->getRevoked($csn);
  205. if ($revoked !== false) {
  206. throw new \Exception(
  207. sprintf(
  208. 'Certificate "%s" has been revoked',
  209. $csn
  210. )
  211. );
  212. }
  213. // Verify if the certificate has been issued by the Nextcloud Code Authority CA
  214. if($certificate->validateSignature() !== true) {
  215. throw new \Exception(
  216. sprintf(
  217. 'App with id %s has a certificate not issued by a trusted Code Signing Authority',
  218. $appId
  219. )
  220. );
  221. }
  222. // Verify if the certificate is issued for the requested app id
  223. $certInfo = openssl_x509_parse($app['certificate']);
  224. if(!isset($certInfo['subject']['CN'])) {
  225. throw new \Exception(
  226. sprintf(
  227. 'App with id %s has a cert with no CN',
  228. $appId
  229. )
  230. );
  231. }
  232. if($certInfo['subject']['CN'] !== $appId) {
  233. throw new \Exception(
  234. sprintf(
  235. 'App with id %s has a cert issued to %s',
  236. $appId,
  237. $certInfo['subject']['CN']
  238. )
  239. );
  240. }
  241. // Download the release
  242. $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
  243. $client = $this->clientService->newClient();
  244. $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
  245. // Check if the signature actually matches the downloaded content
  246. $certificate = openssl_get_publickey($app['certificate']);
  247. $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
  248. openssl_free_key($certificate);
  249. if($verified === true) {
  250. // Seems to match, let's proceed
  251. $extractDir = $this->tempManager->getTemporaryFolder();
  252. $archive = new TAR($tempFile);
  253. if($archive) {
  254. if (!$archive->extract($extractDir)) {
  255. throw new \Exception(
  256. sprintf(
  257. 'Could not extract app %s',
  258. $appId
  259. )
  260. );
  261. }
  262. $allFiles = scandir($extractDir);
  263. $folders = array_diff($allFiles, ['.', '..']);
  264. $folders = array_values($folders);
  265. if(count($folders) > 1) {
  266. throw new \Exception(
  267. sprintf(
  268. 'Extracted app %s has more than 1 folder',
  269. $appId
  270. )
  271. );
  272. }
  273. // Check if appinfo/info.xml has the same app ID as well
  274. $loadEntities = libxml_disable_entity_loader(false);
  275. $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
  276. libxml_disable_entity_loader($loadEntities);
  277. if((string)$xml->id !== $appId) {
  278. throw new \Exception(
  279. sprintf(
  280. 'App for id %s has a wrong app ID in info.xml: %s',
  281. $appId,
  282. (string)$xml->id
  283. )
  284. );
  285. }
  286. // Check if the version is lower than before
  287. $currentVersion = OC_App::getAppVersion($appId);
  288. $newVersion = (string)$xml->version;
  289. if(version_compare($currentVersion, $newVersion) === 1) {
  290. throw new \Exception(
  291. sprintf(
  292. 'App for id %s has version %s and tried to update to lower version %s',
  293. $appId,
  294. $currentVersion,
  295. $newVersion
  296. )
  297. );
  298. }
  299. $baseDir = OC_App::getInstallPath() . '/' . $appId;
  300. // Remove old app with the ID if existent
  301. OC_Helper::rmdirr($baseDir);
  302. // Move to app folder
  303. if(@mkdir($baseDir)) {
  304. $extractDir .= '/' . $folders[0];
  305. OC_Helper::copyr($extractDir, $baseDir);
  306. }
  307. OC_Helper::copyr($extractDir, $baseDir);
  308. OC_Helper::rmdirr($extractDir);
  309. return;
  310. } else {
  311. throw new \Exception(
  312. sprintf(
  313. 'Could not extract app with ID %s to %s',
  314. $appId,
  315. $extractDir
  316. )
  317. );
  318. }
  319. } else {
  320. // Signature does not match
  321. throw new \Exception(
  322. sprintf(
  323. 'App with id %s has invalid signature',
  324. $appId
  325. )
  326. );
  327. }
  328. }
  329. }
  330. throw new \Exception(
  331. sprintf(
  332. 'Could not download app %s',
  333. $appId
  334. )
  335. );
  336. }
  337. /**
  338. * Check if an update for the app is available
  339. *
  340. * @param string $appId
  341. * @return string|false false or the version number of the update
  342. */
  343. public function isUpdateAvailable($appId) {
  344. if ($this->isInstanceReadyForUpdates === null) {
  345. $installPath = OC_App::getInstallPath();
  346. if ($installPath === false || $installPath === null) {
  347. $this->isInstanceReadyForUpdates = false;
  348. } else {
  349. $this->isInstanceReadyForUpdates = true;
  350. }
  351. }
  352. if ($this->isInstanceReadyForUpdates === false) {
  353. return false;
  354. }
  355. if ($this->isInstalledFromGit($appId) === true) {
  356. return false;
  357. }
  358. if ($this->apps === null) {
  359. $this->apps = $this->appFetcher->get();
  360. }
  361. foreach($this->apps as $app) {
  362. if($app['id'] === $appId) {
  363. $currentVersion = OC_App::getAppVersion($appId);
  364. $newestVersion = $app['releases'][0]['version'];
  365. if (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.', \OCP\Util::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. $errors = [];
  464. foreach(\OC::$APPSROOTS as $app_dir) {
  465. if($dir = opendir( $app_dir['path'] )) {
  466. while( false !== ( $filename = readdir( $dir ))) {
  467. if( $filename[0] !== '.' and is_dir($app_dir['path']."/$filename") ) {
  468. if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
  469. if(!Installer::isInstalled($filename)) {
  470. $info=OC_App::getAppInfo($filename);
  471. $enabled = isset($info['default_enable']);
  472. if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
  473. && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
  474. if ($softErrors) {
  475. try {
  476. Installer::installShippedApp($filename);
  477. } catch (HintException $e) {
  478. if ($e->getPrevious() instanceof TableExistsException) {
  479. $errors[$filename] = $e;
  480. continue;
  481. }
  482. throw $e;
  483. }
  484. } else {
  485. Installer::installShippedApp($filename);
  486. }
  487. \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
  488. }
  489. }
  490. }
  491. }
  492. }
  493. closedir( $dir );
  494. }
  495. }
  496. return $errors;
  497. }
  498. /**
  499. * install an app already placed in the app folder
  500. * @param string $app id of the app to install
  501. * @return integer
  502. */
  503. public static function installShippedApp($app) {
  504. //install the database
  505. $appPath = OC_App::getAppPath($app);
  506. \OC_App::registerAutoloading($app, $appPath);
  507. if(is_file("$appPath/appinfo/database.xml")) {
  508. try {
  509. OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
  510. } catch (TableExistsException $e) {
  511. throw new HintException(
  512. 'Failed to enable app ' . $app,
  513. 'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
  514. 0, $e
  515. );
  516. }
  517. } else {
  518. $ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
  519. $ms->migrate();
  520. }
  521. //run appinfo/install.php
  522. self::includeAppScript("$appPath/appinfo/install.php");
  523. $info = OC_App::getAppInfo($app);
  524. if (is_null($info)) {
  525. return false;
  526. }
  527. \OC_App::setupBackgroundJobs($info['background-jobs']);
  528. OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
  529. $config = \OC::$server->getConfig();
  530. $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
  531. if (array_key_exists('ocsid', $info)) {
  532. $config->setAppValue($app, 'ocsid', $info['ocsid']);
  533. }
  534. //set remote/public handlers
  535. foreach($info['remote'] as $name=>$path) {
  536. $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
  537. }
  538. foreach($info['public'] as $name=>$path) {
  539. $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
  540. }
  541. OC_App::setAppTypes($info['id']);
  542. return $info['id'];
  543. }
  544. /**
  545. * @param string $script
  546. */
  547. private static function includeAppScript($script) {
  548. if ( file_exists($script) ){
  549. include $script;
  550. }
  551. }
  552. }