base.php 41 KB

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