Installer.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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 Bart Visscher <bartv@thisnet.nl>
  8. * @author Brice Maron <brice@bmaron.net>
  9. * @author Christian Weiske <cweiske@cweiske.de>
  10. * @author Christopher Schäpers <kondou@ts.unde.re>
  11. * @author Frank Karlitschek <frank@karlitschek.de>
  12. * @author Georg Ehrke <georg@owncloud.com>
  13. * @author Jakob Sack <mail@jakobsack.de>
  14. * @author Joas Schilling <coding@schilljs.com>
  15. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  16. * @author Kamil Domanski <kdomanski@kdemail.net>
  17. * @author Lukas Reschke <lukas@statuscode.ch>
  18. * @author michag86 <micha_g@arcor.de>
  19. * @author Morris Jobke <hey@morrisjobke.de>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author root <root@oc.(none)>
  23. * @author Thomas Müller <thomas.mueller@tmit.eu>
  24. * @author Thomas Tanghus <thomas@tanghus.net>
  25. *
  26. * @license AGPL-3.0
  27. *
  28. * This code is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU Affero General Public License, version 3,
  30. * as published by the Free Software Foundation.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU Affero General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU Affero General Public License, version 3,
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>
  39. *
  40. */
  41. namespace OC;
  42. use Doctrine\DBAL\Exception\TableExistsException;
  43. use OC\App\AppManager;
  44. use OC\App\AppStore\Bundles\Bundle;
  45. use OC\App\AppStore\Fetcher\AppFetcher;
  46. use OC\App\CodeChecker\CodeChecker;
  47. use OC\App\CodeChecker\EmptyCheck;
  48. use OC\App\CodeChecker\PrivateCheck;
  49. use OC\Archive\TAR;
  50. use OC_App;
  51. use OC_DB;
  52. use OC_Helper;
  53. use OCP\App\IAppManager;
  54. use OCP\Http\Client\IClientService;
  55. use OCP\IConfig;
  56. use OCP\ILogger;
  57. use OCP\ITempManager;
  58. use phpseclib\File\X509;
  59. /**
  60. * This class provides the functionality needed to install, update and remove apps
  61. */
  62. class Installer {
  63. /** @var AppFetcher */
  64. private $appFetcher;
  65. /** @var IClientService */
  66. private $clientService;
  67. /** @var ITempManager */
  68. private $tempManager;
  69. /** @var ILogger */
  70. private $logger;
  71. /** @var IConfig */
  72. private $config;
  73. /**
  74. * @param AppFetcher $appFetcher
  75. * @param IClientService $clientService
  76. * @param ITempManager $tempManager
  77. * @param ILogger $logger
  78. * @param IConfig $config
  79. */
  80. public function __construct(AppFetcher $appFetcher,
  81. IClientService $clientService,
  82. ITempManager $tempManager,
  83. ILogger $logger,
  84. IConfig $config) {
  85. $this->appFetcher = $appFetcher;
  86. $this->clientService = $clientService;
  87. $this->tempManager = $tempManager;
  88. $this->logger = $logger;
  89. $this->config = $config;
  90. }
  91. /**
  92. * Installs an app that is located in one of the app folders already
  93. *
  94. * @param string $appId App to install
  95. * @throws \Exception
  96. * @return string app ID
  97. */
  98. public function installApp($appId) {
  99. $app = \OC_App::findAppInDirectories($appId);
  100. if($app === false) {
  101. throw new \Exception('App not found in any app directory');
  102. }
  103. $basedir = $app['path'].'/'.$appId;
  104. $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
  105. $l = \OC::$server->getL10N('core');
  106. if(!is_array($info)) {
  107. throw new \Exception(
  108. $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
  109. [$info['name']]
  110. )
  111. );
  112. }
  113. $version = \OCP\Util::getVersion();
  114. if (!\OC_App::isAppCompatible($version, $info)) {
  115. throw new \Exception(
  116. // TODO $l
  117. $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
  118. [$info['name']]
  119. )
  120. );
  121. }
  122. // check for required dependencies
  123. \OC_App::checkAppDependencies($this->config, $l, $info);
  124. //install the database
  125. if(is_file($basedir.'/appinfo/database.xml')) {
  126. if (\OC::$server->getAppConfig()->getValue($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. }
  132. \OC_App::registerAutoloading($appId, $basedir);
  133. \OC_App::setupBackgroundJobs($info['background-jobs']);
  134. if(isset($info['settings']) && is_array($info['settings'])) {
  135. \OC::$server->getSettingsManager()->setupSettings($info['settings']);
  136. }
  137. //run appinfo/install.php
  138. if((!isset($data['noinstall']) or $data['noinstall']==false)) {
  139. self::includeAppScript($basedir . '/appinfo/install.php');
  140. }
  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. * @brief checks whether or not an app is installed
  158. * @param string $app app
  159. * @returns bool
  160. *
  161. * Checks whether or not an app is installed, i.e. registered in apps table.
  162. */
  163. public static function isInstalled( $app ) {
  164. return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
  165. }
  166. /**
  167. * Updates the specified app from the appstore
  168. *
  169. * @param string $appId
  170. * @return bool
  171. */
  172. public function updateAppstoreApp($appId) {
  173. if(self::isUpdateAvailable($appId, $this->appFetcher)) {
  174. try {
  175. $this->downloadApp($appId);
  176. } catch (\Exception $e) {
  177. $this->logger->error($e->getMessage(), ['app' => 'core']);
  178. return false;
  179. }
  180. return OC_App::updateApp($appId);
  181. }
  182. return false;
  183. }
  184. /**
  185. * Downloads an app and puts it into the app directory
  186. *
  187. * @param string $appId
  188. *
  189. * @throws \Exception If the installation was not successful
  190. */
  191. public function downloadApp($appId) {
  192. $appId = strtolower($appId);
  193. $apps = $this->appFetcher->get();
  194. foreach($apps as $app) {
  195. if($app['id'] === $appId) {
  196. // Load the certificate
  197. $certificate = new X509();
  198. $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
  199. $loadedCertificate = $certificate->loadX509($app['certificate']);
  200. // Verify if the certificate has been revoked
  201. $crl = new X509();
  202. $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
  203. $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
  204. if($crl->validateSignature() !== true) {
  205. throw new \Exception('Could not validate CRL signature');
  206. }
  207. $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
  208. $revoked = $crl->getRevoked($csn);
  209. if ($revoked !== false) {
  210. throw new \Exception(
  211. sprintf(
  212. 'Certificate "%s" has been revoked',
  213. $csn
  214. )
  215. );
  216. }
  217. // Verify if the certificate has been issued by the Nextcloud Code Authority CA
  218. if($certificate->validateSignature() !== true) {
  219. throw new \Exception(
  220. sprintf(
  221. 'App with id %s has a certificate not issued by a trusted Code Signing Authority',
  222. $appId
  223. )
  224. );
  225. }
  226. // Verify if the certificate is issued for the requested app id
  227. $certInfo = openssl_x509_parse($app['certificate']);
  228. if(!isset($certInfo['subject']['CN'])) {
  229. throw new \Exception(
  230. sprintf(
  231. 'App with id %s has a cert with no CN',
  232. $appId
  233. )
  234. );
  235. }
  236. if($certInfo['subject']['CN'] !== $appId) {
  237. throw new \Exception(
  238. sprintf(
  239. 'App with id %s has a cert issued to %s',
  240. $appId,
  241. $certInfo['subject']['CN']
  242. )
  243. );
  244. }
  245. // Download the release
  246. $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
  247. $client = $this->clientService->newClient();
  248. $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
  249. // Check if the signature actually matches the downloaded content
  250. $certificate = openssl_get_publickey($app['certificate']);
  251. $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
  252. openssl_free_key($certificate);
  253. if($verified === true) {
  254. // Seems to match, let's proceed
  255. $extractDir = $this->tempManager->getTemporaryFolder();
  256. $archive = new TAR($tempFile);
  257. if($archive) {
  258. $archive->extract($extractDir);
  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. * @param AppFetcher $appFetcher
  339. * @return string|false false or the version number of the update
  340. */
  341. public static function isUpdateAvailable($appId,
  342. AppFetcher $appFetcher) {
  343. static $isInstanceReadyForUpdates = null;
  344. if ($isInstanceReadyForUpdates === null) {
  345. $installPath = OC_App::getInstallPath();
  346. if ($installPath === false || $installPath === null) {
  347. $isInstanceReadyForUpdates = false;
  348. } else {
  349. $isInstanceReadyForUpdates = true;
  350. }
  351. }
  352. if ($isInstanceReadyForUpdates === false) {
  353. return false;
  354. }
  355. $apps = $appFetcher->get();
  356. foreach($apps as $app) {
  357. if($app['id'] === $appId) {
  358. $currentVersion = OC_App::getAppVersion($appId);
  359. $newestVersion = $app['releases'][0]['version'];
  360. if (version_compare($newestVersion, $currentVersion, '>')) {
  361. return $newestVersion;
  362. } else {
  363. return false;
  364. }
  365. }
  366. }
  367. return false;
  368. }
  369. /**
  370. * Check if app is already downloaded
  371. * @param string $name name of the application to remove
  372. * @return boolean
  373. *
  374. * The function will check if the app is already downloaded in the apps repository
  375. */
  376. public function isDownloaded($name) {
  377. foreach(\OC::$APPSROOTS as $dir) {
  378. $dirToTest = $dir['path'];
  379. $dirToTest .= '/';
  380. $dirToTest .= $name;
  381. $dirToTest .= '/';
  382. if (is_dir($dirToTest)) {
  383. return true;
  384. }
  385. }
  386. return false;
  387. }
  388. /**
  389. * Removes an app
  390. * @param string $appId ID of the application to remove
  391. * @return boolean
  392. *
  393. *
  394. * This function works as follows
  395. * -# call uninstall repair steps
  396. * -# removing the files
  397. *
  398. * The function will not delete preferences, tables and the configuration,
  399. * this has to be done by the function oc_app_uninstall().
  400. */
  401. public function removeApp($appId) {
  402. if($this->isDownloaded( $appId )) {
  403. $appDir = OC_App::getInstallPath() . '/' . $appId;
  404. OC_Helper::rmdirr($appDir);
  405. return true;
  406. }else{
  407. \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
  408. return false;
  409. }
  410. }
  411. /**
  412. * Installs the app within the bundle and marks the bundle as installed
  413. *
  414. * @param Bundle $bundle
  415. * @throws \Exception If app could not get installed
  416. */
  417. public function installAppBundle(Bundle $bundle) {
  418. $appIds = $bundle->getAppIdentifiers();
  419. foreach($appIds as $appId) {
  420. if(!$this->isDownloaded($appId)) {
  421. $this->downloadApp($appId);
  422. }
  423. $this->installApp($appId);
  424. $app = new OC_App();
  425. $app->enable($appId);
  426. }
  427. $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
  428. $bundles[] = $bundle->getIdentifier();
  429. $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
  430. }
  431. /**
  432. * Installs shipped apps
  433. *
  434. * This function installs all apps found in the 'apps' directory that should be enabled by default;
  435. * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
  436. * working ownCloud at the end instead of an aborted update.
  437. * @return array Array of error messages (appid => Exception)
  438. */
  439. public static function installShippedApps($softErrors = false) {
  440. $errors = [];
  441. foreach(\OC::$APPSROOTS as $app_dir) {
  442. if($dir = opendir( $app_dir['path'] )) {
  443. while( false !== ( $filename = readdir( $dir ))) {
  444. if( substr( $filename, 0, 1 ) != '.' and is_dir($app_dir['path']."/$filename") ) {
  445. if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
  446. if(!Installer::isInstalled($filename)) {
  447. $info=OC_App::getAppInfo($filename);
  448. $enabled = isset($info['default_enable']);
  449. if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
  450. && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
  451. if ($softErrors) {
  452. try {
  453. Installer::installShippedApp($filename);
  454. } catch (HintException $e) {
  455. if ($e->getPrevious() instanceof TableExistsException) {
  456. $errors[$filename] = $e;
  457. continue;
  458. }
  459. throw $e;
  460. }
  461. } else {
  462. Installer::installShippedApp($filename);
  463. }
  464. \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
  465. }
  466. }
  467. }
  468. }
  469. }
  470. closedir( $dir );
  471. }
  472. }
  473. return $errors;
  474. }
  475. /**
  476. * install an app already placed in the app folder
  477. * @param string $app id of the app to install
  478. * @return integer
  479. */
  480. public static function installShippedApp($app) {
  481. //install the database
  482. $appPath = OC_App::getAppPath($app);
  483. if(is_file("$appPath/appinfo/database.xml")) {
  484. try {
  485. OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
  486. } catch (TableExistsException $e) {
  487. throw new HintException(
  488. 'Failed to enable app ' . $app,
  489. 'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer">support channels</a>.',
  490. 0, $e
  491. );
  492. }
  493. }
  494. //run appinfo/install.php
  495. \OC_App::registerAutoloading($app, $appPath);
  496. self::includeAppScript("$appPath/appinfo/install.php");
  497. $info = OC_App::getAppInfo($app);
  498. if (is_null($info)) {
  499. return false;
  500. }
  501. \OC_App::setupBackgroundJobs($info['background-jobs']);
  502. OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
  503. $config = \OC::$server->getConfig();
  504. $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
  505. if (array_key_exists('ocsid', $info)) {
  506. $config->setAppValue($app, 'ocsid', $info['ocsid']);
  507. }
  508. //set remote/public handlers
  509. foreach($info['remote'] as $name=>$path) {
  510. $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
  511. }
  512. foreach($info['public'] as $name=>$path) {
  513. $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
  514. }
  515. OC_App::setAppTypes($info['id']);
  516. if(isset($info['settings']) && is_array($info['settings'])) {
  517. // requires that autoloading was registered for the app,
  518. // as happens before running the install.php some lines above
  519. \OC::$server->getSettingsManager()->setupSettings($info['settings']);
  520. }
  521. return $info['id'];
  522. }
  523. /**
  524. * check the code of an app with some static code checks
  525. * @param string $folder the folder of the app to check
  526. * @return boolean true for app is o.k. and false for app is not o.k.
  527. */
  528. public static function checkCode($folder) {
  529. // is the code checker enabled?
  530. if(!\OC::$server->getConfig()->getSystemValue('appcodechecker', false)) {
  531. return true;
  532. }
  533. $codeChecker = new CodeChecker(new PrivateCheck(new EmptyCheck()));
  534. $errors = $codeChecker->analyseFolder(basename($folder), $folder);
  535. return empty($errors);
  536. }
  537. /**
  538. * @param string $script
  539. */
  540. private static function includeAppScript($script) {
  541. if ( file_exists($script) ){
  542. include $script;
  543. }
  544. }
  545. }