You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.php 37KB

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