Installer.php 17 KB

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