base.php 41 KB

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