base.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Adam Williamson <awilliam@redhat.com>
  6. * @author Andreas Fischer <bantu@owncloud.com>
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bart Visscher <bartv@thisnet.nl>
  9. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  10. * @author Bjoern Schiessle <bjoern@schiessle.org>
  11. * @author Björn Schießle <bjoern@schiessle.org>
  12. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  13. * @author Damjan Georgievski <gdamjan@gmail.com>
  14. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  15. * @author davidgumberg <davidnoizgumberg@gmail.com>
  16. * @author Eric Masseran <rico.masseran@gmail.com>
  17. * @author Florin Peter <github@florin-peter.de>
  18. * @author Greta Doci <gretadoci@gmail.com>
  19. * @author J0WI <J0WI@users.noreply.github.com>
  20. * @author Jakob Sack <mail@jakobsack.de>
  21. * @author jaltek <jaltek@mailbox.org>
  22. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  23. * @author Joachim Sokolowski <github@sokolowski.org>
  24. * @author Joas Schilling <coding@schilljs.com>
  25. * @author John Molakvoæ <skjnldsv@protonmail.com>
  26. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  27. * @author Jose Quinteiro <github@quinteiro.org>
  28. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  29. * @author Julius Härtl <jus@bitgrid.net>
  30. * @author Ko- <k.stoffelen@cs.ru.nl>
  31. * @author Lukas Reschke <lukas@statuscode.ch>
  32. * @author MartB <mart.b@outlook.de>
  33. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  34. * @author Morris Jobke <hey@morrisjobke.de>
  35. * @author Owen Winkler <a_github@midnightcircus.com>
  36. * @author Phil Davis <phil.davis@inf.org>
  37. * @author Ramiro Aparicio <rapariciog@gmail.com>
  38. * @author Robin Appelman <robin@icewind.nl>
  39. * @author Robin McCorkell <robin@mccorkell.me.uk>
  40. * @author Roeland Jago Douma <roeland@famdouma.nl>
  41. * @author Sebastian Wessalowski <sebastian@wessalowski.org>
  42. * @author Stefan Weil <sw@weilnetz.de>
  43. * @author Thomas Müller <thomas.mueller@tmit.eu>
  44. * @author Thomas Tanghus <thomas@tanghus.net>
  45. * @author Tobia De Koninck <tobia@ledfan.be>
  46. * @author Vincent Petry <vincent@nextcloud.com>
  47. * @author Volkan Gezer <volkangezer@gmail.com>
  48. *
  49. * @license AGPL-3.0
  50. *
  51. * This code is free software: you can redistribute it and/or modify
  52. * it under the terms of the GNU Affero General Public License, version 3,
  53. * as published by the Free Software Foundation.
  54. *
  55. * This program is distributed in the hope that it will be useful,
  56. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  57. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  58. * GNU Affero General Public License for more details.
  59. *
  60. * You should have received a copy of the GNU Affero General Public License, version 3,
  61. * along with this program. If not, see <http://www.gnu.org/licenses/>
  62. *
  63. */
  64. use OC\EventDispatcher\SymfonyAdapter;
  65. use OCP\EventDispatcher\IEventDispatcher;
  66. use OCP\Group\Events\UserRemovedEvent;
  67. use OCP\ILogger;
  68. use OCP\Server;
  69. use OCP\Share;
  70. use OC\Encryption\HookManager;
  71. use OC\Files\Filesystem;
  72. use OC\Share20\Hooks;
  73. use OCP\User\Events\UserChangedEvent;
  74. require_once 'public/Constants.php';
  75. /**
  76. * Class that is a namespace for all global OC variables
  77. * No, we can not put this class in its own file because it is used by
  78. * OC_autoload!
  79. */
  80. class OC {
  81. /**
  82. * Associative array for autoloading. classname => filename
  83. */
  84. public static $CLASSPATH = [];
  85. /**
  86. * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud)
  87. */
  88. public static $SERVERROOT = '';
  89. /**
  90. * the current request path relative to the Nextcloud root (e.g. files/index.php)
  91. */
  92. private static $SUBURI = '';
  93. /**
  94. * the Nextcloud root path for http requests (e.g. nextcloud/)
  95. */
  96. public static $WEBROOT = '';
  97. /**
  98. * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
  99. * web path in 'url'
  100. */
  101. public static $APPSROOTS = [];
  102. /**
  103. * @var string
  104. */
  105. public static $configDir;
  106. /**
  107. * requested app
  108. */
  109. public static $REQUESTEDAPP = '';
  110. /**
  111. * check if Nextcloud runs in cli mode
  112. */
  113. public static $CLI = false;
  114. /**
  115. * @var \OC\Autoloader $loader
  116. */
  117. public static $loader = null;
  118. /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
  119. public static $composerAutoloader = null;
  120. /**
  121. * @var \OC\Server
  122. */
  123. public static $server = null;
  124. /**
  125. * @var \OC\Config
  126. */
  127. private static $config = null;
  128. /**
  129. * @throws \RuntimeException when the 3rdparty directory is missing or
  130. * the app path list is empty or contains an invalid path
  131. */
  132. public static function initPaths() {
  133. if (defined('PHPUNIT_CONFIG_DIR')) {
  134. self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
  135. } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
  136. self::$configDir = OC::$SERVERROOT . '/tests/config/';
  137. } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
  138. self::$configDir = rtrim($dir, '/') . '/';
  139. } else {
  140. self::$configDir = OC::$SERVERROOT . '/config/';
  141. }
  142. self::$config = new \OC\Config(self::$configDir);
  143. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  144. /**
  145. * FIXME: The following lines are required because we can't yet instantiate
  146. * \OC::$server->getRequest() since \OC::$server does not yet exist.
  147. */
  148. $params = [
  149. 'server' => [
  150. 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
  151. 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
  152. ],
  153. ];
  154. $fakeRequest = new \OC\AppFramework\Http\Request(
  155. $params,
  156. new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()),
  157. new \OC\AllConfig(new \OC\SystemConfig(self::$config))
  158. );
  159. $scriptName = $fakeRequest->getScriptName();
  160. if (substr($scriptName, -1) == '/') {
  161. $scriptName .= 'index.php';
  162. //make sure suburi follows the same rules as scriptName
  163. if (substr(OC::$SUBURI, -9) != 'index.php') {
  164. if (substr(OC::$SUBURI, -1) != '/') {
  165. OC::$SUBURI = OC::$SUBURI . '/';
  166. }
  167. OC::$SUBURI = OC::$SUBURI . 'index.php';
  168. }
  169. }
  170. if (OC::$CLI) {
  171. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  172. } else {
  173. if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
  174. OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
  175. if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
  176. OC::$WEBROOT = '/' . OC::$WEBROOT;
  177. }
  178. } else {
  179. // The scriptName is not ending with OC::$SUBURI
  180. // This most likely means that we are calling from CLI.
  181. // However some cron jobs still need to generate
  182. // a web URL, so we use overwritewebroot as a fallback.
  183. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  184. }
  185. // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
  186. // slash which is required by URL generation.
  187. if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
  188. substr($_SERVER['REQUEST_URI'], -1) !== '/') {
  189. header('Location: '.\OC::$WEBROOT.'/');
  190. exit();
  191. }
  192. }
  193. // search the apps folder
  194. $config_paths = self::$config->getValue('apps_paths', []);
  195. if (!empty($config_paths)) {
  196. foreach ($config_paths as $paths) {
  197. if (isset($paths['url']) && isset($paths['path'])) {
  198. $paths['url'] = rtrim($paths['url'], '/');
  199. $paths['path'] = rtrim($paths['path'], '/');
  200. OC::$APPSROOTS[] = $paths;
  201. }
  202. }
  203. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  204. OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
  205. }
  206. if (empty(OC::$APPSROOTS)) {
  207. throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
  208. . '. You can also configure the location in the config.php file.');
  209. }
  210. $paths = [];
  211. foreach (OC::$APPSROOTS as $path) {
  212. $paths[] = $path['path'];
  213. if (!is_dir($path['path'])) {
  214. throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
  215. . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path']));
  216. }
  217. }
  218. // set the right include path
  219. set_include_path(
  220. implode(PATH_SEPARATOR, $paths)
  221. );
  222. }
  223. public static function checkConfig() {
  224. $l = \OC::$server->getL10N('lib');
  225. // Create config if it does not already exist
  226. $configFilePath = self::$configDir .'/config.php';
  227. if (!file_exists($configFilePath)) {
  228. @touch($configFilePath);
  229. }
  230. // Check if config is writable
  231. $configFileWritable = is_writable($configFilePath);
  232. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  233. || !$configFileWritable && \OCP\Util::needUpgrade()) {
  234. $urlGenerator = \OC::$server->getURLGenerator();
  235. if (self::$CLI) {
  236. echo $l->t('Cannot write into "config" directory!')."\n";
  237. echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n";
  238. echo "\n";
  239. echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n";
  240. echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
  241. exit;
  242. } else {
  243. OC_Template::printErrorPage(
  244. $l->t('Cannot write into "config" directory!'),
  245. $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' '
  246. . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' '
  247. . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]),
  248. 503
  249. );
  250. }
  251. }
  252. }
  253. public static function checkInstalled(\OC\SystemConfig $systemConfig) {
  254. if (defined('OC_CONSOLE')) {
  255. return;
  256. }
  257. // Redirect to installer if not installed
  258. if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
  259. if (OC::$CLI) {
  260. throw new Exception('Not installed');
  261. } else {
  262. $url = OC::$WEBROOT . '/index.php';
  263. header('Location: ' . $url);
  264. }
  265. exit();
  266. }
  267. }
  268. public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig) {
  269. // Allow ajax update script to execute without being stopped
  270. if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') {
  271. // send http status 503
  272. http_response_code(503);
  273. header('Retry-After: 120');
  274. // render error page
  275. $template = new OC_Template('', 'update.user', 'guest');
  276. \OCP\Util::addScript('core', 'maintenance');
  277. \OCP\Util::addStyle('core', 'guest');
  278. $template->printPage();
  279. die();
  280. }
  281. }
  282. /**
  283. * Prints the upgrade page
  284. *
  285. * @param \OC\SystemConfig $systemConfig
  286. */
  287. private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
  288. $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
  289. $tooBig = false;
  290. if (!$disableWebUpdater) {
  291. $apps = \OC::$server->getAppManager();
  292. if ($apps->isInstalled('user_ldap')) {
  293. $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  294. $result = $qb->select($qb->func()->count('*', 'user_count'))
  295. ->from('ldap_user_mapping')
  296. ->execute();
  297. $row = $result->fetch();
  298. $result->closeCursor();
  299. $tooBig = ($row['user_count'] > 50);
  300. }
  301. if (!$tooBig && $apps->isInstalled('user_saml')) {
  302. $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  303. $result = $qb->select($qb->func()->count('*', 'user_count'))
  304. ->from('user_saml_users')
  305. ->execute();
  306. $row = $result->fetch();
  307. $result->closeCursor();
  308. $tooBig = ($row['user_count'] > 50);
  309. }
  310. if (!$tooBig) {
  311. // count users
  312. $stats = \OC::$server->getUserManager()->countUsers();
  313. $totalUsers = array_sum($stats);
  314. $tooBig = ($totalUsers > 50);
  315. }
  316. }
  317. $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
  318. $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
  319. if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
  320. // send http status 503
  321. http_response_code(503);
  322. header('Retry-After: 120');
  323. // render error page
  324. $template = new OC_Template('', 'update.use-cli', 'guest');
  325. $template->assign('productName', 'nextcloud'); // for now
  326. $template->assign('version', OC_Util::getVersionString());
  327. $template->assign('tooBig', $tooBig);
  328. $template->printPage();
  329. die();
  330. }
  331. // check whether this is a core update or apps update
  332. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  333. $currentVersion = implode('.', \OCP\Util::getVersion());
  334. // if not a core upgrade, then it's apps upgrade
  335. $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
  336. $oldTheme = $systemConfig->getValue('theme');
  337. $systemConfig->setValue('theme', '');
  338. \OCP\Util::addScript('core', 'common');
  339. \OCP\Util::addScript('core', 'main');
  340. \OCP\Util::addTranslations('core');
  341. \OCP\Util::addScript('core', 'update');
  342. /** @var \OC\App\AppManager $appManager */
  343. $appManager = \OC::$server->getAppManager();
  344. $tmpl = new OC_Template('', 'update.admin', 'guest');
  345. $tmpl->assign('version', OC_Util::getVersionString());
  346. $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
  347. // get third party apps
  348. $ocVersion = \OCP\Util::getVersion();
  349. $ocVersion = implode('.', $ocVersion);
  350. $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
  351. $incompatibleShippedApps = [];
  352. foreach ($incompatibleApps as $appInfo) {
  353. if ($appManager->isShipped($appInfo['id'])) {
  354. $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
  355. }
  356. }
  357. if (!empty($incompatibleShippedApps)) {
  358. $l = \OC::$server->getL10N('core');
  359. $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
  360. throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
  361. }
  362. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  363. $tmpl->assign('incompatibleAppsList', $incompatibleApps);
  364. try {
  365. $defaults = new \OC_Defaults();
  366. $tmpl->assign('productName', $defaults->getName());
  367. } catch (Throwable $error) {
  368. $tmpl->assign('productName', 'Nextcloud');
  369. }
  370. $tmpl->assign('oldTheme', $oldTheme);
  371. $tmpl->printPage();
  372. }
  373. public static function initSession() {
  374. if (self::$server->getRequest()->getServerProtocol() === 'https') {
  375. ini_set('session.cookie_secure', 'true');
  376. }
  377. // prevents javascript from accessing php session cookies
  378. ini_set('session.cookie_httponly', 'true');
  379. // set the cookie path to the Nextcloud directory
  380. $cookie_path = OC::$WEBROOT ? : '/';
  381. ini_set('session.cookie_path', $cookie_path);
  382. // Let the session name be changed in the initSession Hook
  383. $sessionName = OC_Util::getInstanceId();
  384. try {
  385. // set the session name to the instance id - which is unique
  386. $session = new \OC\Session\Internal($sessionName);
  387. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  388. $session = $cryptoWrapper->wrapSession($session);
  389. self::$server->setSession($session);
  390. // if session can't be started break with http 500 error
  391. } catch (Exception $e) {
  392. \OC::$server->getLogger()->logException($e, ['app' => 'base']);
  393. //show the user a detailed error page
  394. OC_Template::printExceptionErrorPage($e, 500);
  395. die();
  396. }
  397. $sessionLifeTime = self::getSessionLifeTime();
  398. // session timeout
  399. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  400. if (isset($_COOKIE[session_name()])) {
  401. setcookie(session_name(), '', -1, self::$WEBROOT ? : '/');
  402. }
  403. \OC::$server->getUserSession()->logout();
  404. }
  405. $session->set('LAST_ACTIVITY', time());
  406. }
  407. /**
  408. * @return string
  409. */
  410. private static function getSessionLifeTime() {
  411. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  412. }
  413. /**
  414. * Try to set some values to the required Nextcloud default
  415. */
  416. public static function setRequiredIniValues() {
  417. @ini_set('default_charset', 'UTF-8');
  418. @ini_set('gd.jpeg_ignore_warning', '1');
  419. }
  420. /**
  421. * Send the same site cookies
  422. */
  423. private static function sendSameSiteCookies() {
  424. $cookieParams = session_get_cookie_params();
  425. $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
  426. $policies = [
  427. 'lax',
  428. 'strict',
  429. ];
  430. // Append __Host to the cookie if it meets the requirements
  431. $cookiePrefix = '';
  432. if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  433. $cookiePrefix = '__Host-';
  434. }
  435. foreach ($policies as $policy) {
  436. header(
  437. sprintf(
  438. 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
  439. $cookiePrefix,
  440. $policy,
  441. $cookieParams['path'],
  442. $policy
  443. ),
  444. false
  445. );
  446. }
  447. }
  448. /**
  449. * Same Site cookie to further mitigate CSRF attacks. This cookie has to
  450. * be set in every request if cookies are sent to add a second level of
  451. * defense against CSRF.
  452. *
  453. * If the cookie is not sent this will set the cookie and reload the page.
  454. * We use an additional cookie since we want to protect logout CSRF and
  455. * also we can't directly interfere with PHP's session mechanism.
  456. */
  457. private static function performSameSiteCookieProtection(\OCP\IConfig $config) {
  458. $request = \OC::$server->getRequest();
  459. // Some user agents are notorious and don't really properly follow HTTP
  460. // specifications. For those, have an automated opt-out. Since the protection
  461. // for remote.php is applied in base.php as starting point we need to opt out
  462. // here.
  463. $incompatibleUserAgents = $config->getSystemValue('csrf.optout');
  464. // Fallback, if csrf.optout is unset
  465. if (!is_array($incompatibleUserAgents)) {
  466. $incompatibleUserAgents = [
  467. // OS X Finder
  468. '/^WebDAVFS/',
  469. // Windows webdav drive
  470. '/^Microsoft-WebDAV-MiniRedir/',
  471. ];
  472. }
  473. if ($request->isUserAgent($incompatibleUserAgents)) {
  474. return;
  475. }
  476. if (count($_COOKIE) > 0) {
  477. $requestUri = $request->getScriptName();
  478. $processingScript = explode('/', $requestUri);
  479. $processingScript = $processingScript[count($processingScript) - 1];
  480. // index.php routes are handled in the middleware
  481. if ($processingScript === 'index.php') {
  482. return;
  483. }
  484. // All other endpoints require the lax and the strict cookie
  485. if (!$request->passesStrictCookieCheck()) {
  486. self::sendSameSiteCookies();
  487. // Debug mode gets access to the resources without strict cookie
  488. // due to the fact that the SabreDAV browser also lives there.
  489. if (!$config->getSystemValue('debug', false)) {
  490. http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
  491. exit();
  492. }
  493. }
  494. } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
  495. self::sendSameSiteCookies();
  496. }
  497. }
  498. public static function init() {
  499. // calculate the root directories
  500. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  501. // register autoloader
  502. $loaderStart = microtime(true);
  503. require_once __DIR__ . '/autoloader.php';
  504. self::$loader = new \OC\Autoloader([
  505. OC::$SERVERROOT . '/lib/private/legacy',
  506. ]);
  507. if (defined('PHPUNIT_RUN')) {
  508. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  509. }
  510. spl_autoload_register([self::$loader, 'load']);
  511. $loaderEnd = microtime(true);
  512. self::$CLI = (php_sapi_name() == 'cli');
  513. // Add default composer PSR-4 autoloader
  514. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  515. try {
  516. self::initPaths();
  517. // setup 3rdparty autoloader
  518. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  519. if (!file_exists($vendorAutoLoad)) {
  520. throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
  521. }
  522. require_once $vendorAutoLoad;
  523. } catch (\RuntimeException $e) {
  524. if (!self::$CLI) {
  525. http_response_code(503);
  526. }
  527. // we can't use the template error page here, because this needs the
  528. // DI container which isn't available yet
  529. print($e->getMessage());
  530. exit();
  531. }
  532. // setup the basic server
  533. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  534. self::$server->boot();
  535. $eventLogger = \OC::$server->getEventLogger();
  536. $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  537. $eventLogger->start('boot', 'Initialize');
  538. // Override php.ini and log everything if we're troubleshooting
  539. if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
  540. error_reporting(E_ALL);
  541. }
  542. // Don't display errors and log them
  543. @ini_set('display_errors', '0');
  544. @ini_set('log_errors', '1');
  545. if (!date_default_timezone_set('UTC')) {
  546. throw new \RuntimeException('Could not set timezone to UTC');
  547. }
  548. //try to configure php to enable big file uploads.
  549. //this doesn´t work always depending on the webserver and php configuration.
  550. //Let´s try to overwrite some defaults if they are smaller than 1 hour
  551. if (intval(@ini_get('max_execution_time') ?? 0) < 3600) {
  552. @ini_set('max_execution_time', strval(3600));
  553. }
  554. if (intval(@ini_get('max_input_time') ?? 0) < 3600) {
  555. @ini_set('max_input_time', strval(3600));
  556. }
  557. //try to set the maximum execution time to the largest time limit we have
  558. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  559. @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
  560. }
  561. self::setRequiredIniValues();
  562. self::handleAuthHeaders();
  563. $systemConfig = \OC::$server->get(\OC\SystemConfig::class);
  564. self::registerAutoloaderCache($systemConfig);
  565. // initialize intl fallback if necessary
  566. OC_Util::isSetLocaleWorking();
  567. $config = \OC::$server->get(\OCP\IConfig::class);
  568. if (!defined('PHPUNIT_RUN')) {
  569. OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
  570. $debug = $config->getSystemValue('debug', false);
  571. OC\Log\ErrorHandler::register($debug);
  572. }
  573. /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
  574. $bootstrapCoordinator = \OC::$server->query(\OC\AppFramework\Bootstrap\Coordinator::class);
  575. $bootstrapCoordinator->runInitialRegistration();
  576. $eventLogger->start('init_session', 'Initialize session');
  577. OC_App::loadApps(['session']);
  578. if (!self::$CLI) {
  579. self::initSession();
  580. }
  581. $eventLogger->end('init_session');
  582. self::checkConfig();
  583. self::checkInstalled($systemConfig);
  584. OC_Response::addSecurityHeaders();
  585. self::performSameSiteCookieProtection($config);
  586. if (!defined('OC_CONSOLE')) {
  587. $errors = OC_Util::checkServer($systemConfig);
  588. if (count($errors) > 0) {
  589. if (!self::$CLI) {
  590. http_response_code(503);
  591. OC_Util::addStyle('guest');
  592. try {
  593. OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
  594. exit;
  595. } catch (\Exception $e) {
  596. // In case any error happens when showing the error page, we simply fall back to posting the text.
  597. // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
  598. }
  599. }
  600. // Convert l10n string into regular string for usage in database
  601. $staticErrors = [];
  602. foreach ($errors as $error) {
  603. echo $error['error'] . "\n";
  604. echo $error['hint'] . "\n\n";
  605. $staticErrors[] = [
  606. 'error' => (string)$error['error'],
  607. 'hint' => (string)$error['hint'],
  608. ];
  609. }
  610. try {
  611. $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  612. } catch (\Exception $e) {
  613. echo('Writing to database failed');
  614. }
  615. exit(1);
  616. } elseif (self::$CLI && $config->getSystemValue('installed', false)) {
  617. $config->deleteAppValue('core', 'cronErrors');
  618. }
  619. }
  620. //try to set the session lifetime
  621. $sessionLifeTime = self::getSessionLifeTime();
  622. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  623. // User and Groups
  624. if (!$systemConfig->getValue("installed", false)) {
  625. self::$server->getSession()->set('user_id', '');
  626. }
  627. OC_User::useBackend(new \OC\User\Database());
  628. \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
  629. // Subscribe to the hook
  630. \OCP\Util::connectHook(
  631. '\OCA\Files_Sharing\API\Server2Server',
  632. 'preLoginNameUsedAsUserName',
  633. '\OC\User\Database',
  634. 'preLoginNameUsedAsUserName'
  635. );
  636. //setup extra user backends
  637. if (!\OCP\Util::needUpgrade()) {
  638. OC_User::setupBackends();
  639. } else {
  640. // Run upgrades in incognito mode
  641. OC_User::setIncognitoMode(true);
  642. }
  643. self::registerCleanupHooks($systemConfig);
  644. self::registerFilesystemHooks();
  645. self::registerShareHooks($systemConfig);
  646. self::registerEncryptionWrapperAndHooks();
  647. self::registerAccountHooks();
  648. self::registerResourceCollectionHooks();
  649. self::registerAppRestrictionsHooks();
  650. // Make sure that the application class is not loaded before the database is setup
  651. if ($systemConfig->getValue("installed", false)) {
  652. OC_App::loadApp('settings');
  653. /* Build core application to make sure that listeners are registered */
  654. self::$server->get(\OC\Core\Application::class);
  655. }
  656. //make sure temporary files are cleaned up
  657. $tmpManager = \OC::$server->getTempManager();
  658. register_shutdown_function([$tmpManager, 'clean']);
  659. $lockProvider = \OC::$server->getLockingProvider();
  660. register_shutdown_function([$lockProvider, 'releaseAll']);
  661. // Check whether the sample configuration has been copied
  662. if ($systemConfig->getValue('copied_sample_config', false)) {
  663. $l = \OC::$server->getL10N('lib');
  664. OC_Template::printErrorPage(
  665. $l->t('Sample configuration detected'),
  666. $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'),
  667. 503
  668. );
  669. return;
  670. }
  671. $request = \OC::$server->getRequest();
  672. $host = $request->getInsecureServerHost();
  673. /**
  674. * if the host passed in headers isn't trusted
  675. * FIXME: Should not be in here at all :see_no_evil:
  676. */
  677. if (!OC::$CLI
  678. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  679. && $config->getSystemValue('installed', false)
  680. ) {
  681. // Allow access to CSS resources
  682. $isScssRequest = false;
  683. if (strpos($request->getPathInfo(), '/css/') === 0) {
  684. $isScssRequest = true;
  685. }
  686. if (substr($request->getRequestUri(), -11) === '/status.php') {
  687. http_response_code(400);
  688. header('Content-Type: application/json');
  689. echo '{"error": "Trusted domain error.", "code": 15}';
  690. exit();
  691. }
  692. if (!$isScssRequest) {
  693. http_response_code(400);
  694. \OC::$server->getLogger()->warning(
  695. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  696. [
  697. 'app' => 'core',
  698. 'remoteAddress' => $request->getRemoteAddress(),
  699. 'host' => $host,
  700. ]
  701. );
  702. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  703. $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
  704. $tmpl->printPage();
  705. exit();
  706. }
  707. }
  708. $eventLogger->end('boot');
  709. $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
  710. $eventLogger->start('runtime', 'Runtime');
  711. $eventLogger->start('request', 'Full request after boot');
  712. register_shutdown_function(function () use ($eventLogger) {
  713. $eventLogger->end('request');
  714. });
  715. }
  716. /**
  717. * register hooks for the cleanup of cache and bruteforce protection
  718. */
  719. public static function registerCleanupHooks(\OC\SystemConfig $systemConfig) {
  720. //don't try to do this before we are properly setup
  721. if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
  722. // NOTE: This will be replaced to use OCP
  723. $userSession = self::$server->getUserSession();
  724. $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
  725. if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
  726. // reset brute force delay for this IP address and username
  727. $uid = \OC::$server->getUserSession()->getUser()->getUID();
  728. $request = \OC::$server->getRequest();
  729. $throttler = \OC::$server->getBruteForceThrottler();
  730. $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
  731. }
  732. try {
  733. $cache = new \OC\Cache\File();
  734. $cache->gc();
  735. } catch (\OC\ServerNotAvailableException $e) {
  736. // not a GC exception, pass it on
  737. throw $e;
  738. } catch (\OC\ForbiddenException $e) {
  739. // filesystem blocked for this request, ignore
  740. } catch (\Exception $e) {
  741. // a GC exception should not prevent users from using OC,
  742. // so log the exception
  743. \OC::$server->getLogger()->logException($e, [
  744. 'message' => 'Exception when running cache gc.',
  745. 'level' => ILogger::WARN,
  746. 'app' => 'core',
  747. ]);
  748. }
  749. });
  750. }
  751. }
  752. private static function registerEncryptionWrapperAndHooks() {
  753. $manager = self::$server->getEncryptionManager();
  754. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  755. $enabled = $manager->isEnabled();
  756. if ($enabled) {
  757. \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
  758. \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
  759. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
  760. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
  761. }
  762. }
  763. private static function registerAccountHooks() {
  764. /** @var IEventDispatcher $dispatcher */
  765. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  766. $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
  767. }
  768. private static function registerAppRestrictionsHooks() {
  769. /** @var \OC\Group\Manager $groupManager */
  770. $groupManager = self::$server->query(\OCP\IGroupManager::class);
  771. $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
  772. $appManager = self::$server->getAppManager();
  773. $apps = $appManager->getEnabledAppsForGroup($group);
  774. foreach ($apps as $appId) {
  775. $restrictions = $appManager->getAppRestriction($appId);
  776. if (empty($restrictions)) {
  777. continue;
  778. }
  779. $key = array_search($group->getGID(), $restrictions);
  780. unset($restrictions[$key]);
  781. $restrictions = array_values($restrictions);
  782. if (empty($restrictions)) {
  783. $appManager->disableApp($appId);
  784. } else {
  785. $appManager->enableAppForGroups($appId, $restrictions);
  786. }
  787. }
  788. });
  789. }
  790. private static function registerResourceCollectionHooks() {
  791. \OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class));
  792. }
  793. /**
  794. * register hooks for the filesystem
  795. */
  796. public static function registerFilesystemHooks() {
  797. // Check for blacklisted files
  798. OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
  799. OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
  800. }
  801. /**
  802. * register hooks for sharing
  803. */
  804. public static function registerShareHooks(\OC\SystemConfig $systemConfig) {
  805. if ($systemConfig->getValue('installed')) {
  806. OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
  807. OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
  808. /** @var IEventDispatcher $dispatcher */
  809. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  810. $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
  811. }
  812. }
  813. protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig) {
  814. // The class loader takes an optional low-latency cache, which MUST be
  815. // namespaced. The instanceid is used for namespacing, but might be
  816. // unavailable at this point. Furthermore, it might not be possible to
  817. // generate an instanceid via \OC_Util::getInstanceId() because the
  818. // config file may not be writable. As such, we only register a class
  819. // loader cache if instanceid is available without trying to create one.
  820. $instanceId = $systemConfig->getValue('instanceid', null);
  821. if ($instanceId) {
  822. try {
  823. $memcacheFactory = \OC::$server->getMemCacheFactory();
  824. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  825. } catch (\Exception $ex) {
  826. }
  827. }
  828. }
  829. /**
  830. * Handle the request
  831. */
  832. public static function handleRequest() {
  833. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  834. $systemConfig = \OC::$server->getSystemConfig();
  835. // Check if Nextcloud is installed or in maintenance (update) mode
  836. if (!$systemConfig->getValue('installed', false)) {
  837. \OC::$server->getSession()->clear();
  838. $setupHelper = new OC\Setup(
  839. $systemConfig,
  840. \OC::$server->get(\bantu\IniGetWrapper\IniGetWrapper::class),
  841. \OC::$server->getL10N('lib'),
  842. \OC::$server->query(\OCP\Defaults::class),
  843. \OC::$server->get(\Psr\Log\LoggerInterface::class),
  844. \OC::$server->getSecureRandom(),
  845. \OC::$server->query(\OC\Installer::class)
  846. );
  847. $controller = new OC\Core\Controller\SetupController($setupHelper);
  848. $controller->run($_POST);
  849. exit();
  850. }
  851. $request = \OC::$server->getRequest();
  852. $requestPath = $request->getRawPathInfo();
  853. if ($requestPath === '/heartbeat') {
  854. return;
  855. }
  856. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  857. self::checkMaintenanceMode($systemConfig);
  858. if (\OCP\Util::needUpgrade()) {
  859. if (function_exists('opcache_reset')) {
  860. opcache_reset();
  861. }
  862. if (!((bool) $systemConfig->getValue('maintenance', false))) {
  863. self::printUpgradePage($systemConfig);
  864. exit();
  865. }
  866. }
  867. }
  868. // emergency app disabling
  869. if ($requestPath === '/disableapp'
  870. && $request->getMethod() === 'POST'
  871. && ((array)$request->getParam('appid')) !== ''
  872. ) {
  873. \OC_JSON::callCheck();
  874. \OC_JSON::checkAdminUser();
  875. $appIds = (array)$request->getParam('appid');
  876. foreach ($appIds as $appId) {
  877. $appId = \OC_App::cleanAppId($appId);
  878. \OC::$server->getAppManager()->disableApp($appId);
  879. }
  880. \OC_JSON::success();
  881. exit();
  882. }
  883. // Always load authentication apps
  884. OC_App::loadApps(['authentication']);
  885. // Load minimum set of apps
  886. if (!\OCP\Util::needUpgrade()
  887. && !((bool) $systemConfig->getValue('maintenance', false))) {
  888. // For logged-in users: Load everything
  889. if (\OC::$server->getUserSession()->isLoggedIn()) {
  890. OC_App::loadApps();
  891. } else {
  892. // For guests: Load only filesystem and logging
  893. OC_App::loadApps(['filesystem', 'logging']);
  894. // Don't try to login when a client is trying to get a OAuth token.
  895. // OAuth needs to support basic auth too, so the login is not valid
  896. // inside Nextcloud and the Login exception would ruin it.
  897. if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
  898. self::handleLogin($request);
  899. }
  900. }
  901. }
  902. if (!self::$CLI) {
  903. try {
  904. if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
  905. OC_App::loadApps(['filesystem', 'logging']);
  906. OC_App::loadApps();
  907. }
  908. OC::$server->get(\OC\Route\Router::class)->match($request->getRawPathInfo());
  909. return;
  910. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  911. //header('HTTP/1.0 404 Not Found');
  912. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  913. http_response_code(405);
  914. return;
  915. }
  916. }
  917. // Handle WebDAV
  918. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
  919. // not allowed any more to prevent people
  920. // mounting this root directly.
  921. // Users need to mount remote.php/webdav instead.
  922. http_response_code(405);
  923. return;
  924. }
  925. // Handle requests for JSON or XML
  926. $acceptHeader = $request->getHeader('Accept');
  927. if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
  928. http_response_code(404);
  929. return;
  930. }
  931. // Someone is logged in
  932. if (\OC::$server->getUserSession()->isLoggedIn()) {
  933. OC_App::loadApps();
  934. OC_User::setupBackends();
  935. OC_Util::setupFS();
  936. header('Location: ' . \OC::$server->getURLGenerator()->linkToDefaultPageUrl());
  937. } else {
  938. // Not handled and not logged in
  939. header('Location: ' . \OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  940. }
  941. }
  942. /**
  943. * Check login: apache auth, auth token, basic auth
  944. *
  945. * @param OCP\IRequest $request
  946. * @return boolean
  947. */
  948. public static function handleLogin(OCP\IRequest $request) {
  949. $userSession = self::$server->getUserSession();
  950. if (OC_User::handleApacheAuth()) {
  951. return true;
  952. }
  953. if ($userSession->tryTokenLogin($request)) {
  954. return true;
  955. }
  956. if (isset($_COOKIE['nc_username'])
  957. && isset($_COOKIE['nc_token'])
  958. && isset($_COOKIE['nc_session_id'])
  959. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  960. return true;
  961. }
  962. if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  963. return true;
  964. }
  965. return false;
  966. }
  967. protected static function handleAuthHeaders() {
  968. //copy http auth headers for apache+php-fcgid work around
  969. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  970. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  971. }
  972. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  973. $vars = [
  974. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  975. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  976. ];
  977. foreach ($vars as $var) {
  978. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  979. $credentials = explode(':', base64_decode($matches[1]), 2);
  980. if (count($credentials) === 2) {
  981. $_SERVER['PHP_AUTH_USER'] = $credentials[0];
  982. $_SERVER['PHP_AUTH_PW'] = $credentials[1];
  983. break;
  984. }
  985. }
  986. }
  987. }
  988. }
  989. OC::init();