base.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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. // and cron.php does not need any authentication at all
  512. if ($processingScript === 'index.php'
  513. || $processingScript === 'cron.php') {
  514. return;
  515. }
  516. // All other endpoints require the lax and the strict cookie
  517. if (!$request->passesStrictCookieCheck()) {
  518. logger('core')->warning('Request does not pass strict cookie check');
  519. self::sendSameSiteCookies();
  520. // Debug mode gets access to the resources without strict cookie
  521. // due to the fact that the SabreDAV browser also lives there.
  522. if (!$config->getSystemValueBool('debug', false)) {
  523. http_response_code(\OCP\AppFramework\Http::STATUS_PRECONDITION_FAILED);
  524. header('Content-Type: application/json');
  525. echo json_encode(['error' => 'Strict Cookie has not been found in request']);
  526. exit();
  527. }
  528. }
  529. } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
  530. self::sendSameSiteCookies();
  531. }
  532. }
  533. public static function init(): void {
  534. // prevent any XML processing from loading external entities
  535. libxml_set_external_entity_loader(static function () {
  536. return null;
  537. });
  538. // calculate the root directories
  539. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  540. // register autoloader
  541. $loaderStart = microtime(true);
  542. require_once __DIR__ . '/autoloader.php';
  543. self::$loader = new \OC\Autoloader([
  544. OC::$SERVERROOT . '/lib/private/legacy',
  545. ]);
  546. if (defined('PHPUNIT_RUN')) {
  547. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  548. }
  549. spl_autoload_register([self::$loader, 'load']);
  550. $loaderEnd = microtime(true);
  551. self::$CLI = (php_sapi_name() == 'cli');
  552. // Add default composer PSR-4 autoloader, ensure apcu to be disabled
  553. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  554. self::$composerAutoloader->setApcuPrefix(null);
  555. try {
  556. self::initPaths();
  557. // setup 3rdparty autoloader
  558. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  559. if (!file_exists($vendorAutoLoad)) {
  560. 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".');
  561. }
  562. require_once $vendorAutoLoad;
  563. } catch (\RuntimeException $e) {
  564. if (!self::$CLI) {
  565. http_response_code(503);
  566. }
  567. // we can't use the template error page here, because this needs the
  568. // DI container which isn't available yet
  569. print($e->getMessage());
  570. exit();
  571. }
  572. // setup the basic server
  573. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  574. self::$server->boot();
  575. $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class);
  576. $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  577. $eventLogger->start('boot', 'Initialize');
  578. // Override php.ini and log everything if we're troubleshooting
  579. if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
  580. error_reporting(E_ALL);
  581. }
  582. // Don't display errors and log them
  583. @ini_set('display_errors', '0');
  584. @ini_set('log_errors', '1');
  585. if (!date_default_timezone_set('UTC')) {
  586. throw new \RuntimeException('Could not set timezone to UTC');
  587. }
  588. //try to configure php to enable big file uploads.
  589. //this doesn´t work always depending on the webserver and php configuration.
  590. //Let´s try to overwrite some defaults if they are smaller than 1 hour
  591. if (intval(@ini_get('max_execution_time') ?: 0) < 3600) {
  592. @ini_set('max_execution_time', strval(3600));
  593. }
  594. if (intval(@ini_get('max_input_time') ?: 0) < 3600) {
  595. @ini_set('max_input_time', strval(3600));
  596. }
  597. //try to set the maximum execution time to the largest time limit we have
  598. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  599. @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time'))));
  600. }
  601. self::setRequiredIniValues();
  602. self::handleAuthHeaders();
  603. $systemConfig = Server::get(\OC\SystemConfig::class);
  604. self::registerAutoloaderCache($systemConfig);
  605. // initialize intl fallback if necessary
  606. OC_Util::isSetLocaleWorking();
  607. $config = Server::get(\OCP\IConfig::class);
  608. if (!defined('PHPUNIT_RUN')) {
  609. $errorHandler = new OC\Log\ErrorHandler(
  610. \OCP\Server::get(\Psr\Log\LoggerInterface::class),
  611. );
  612. $exceptionHandler = [$errorHandler, 'onException'];
  613. if ($config->getSystemValueBool('debug', false)) {
  614. set_error_handler([$errorHandler, 'onAll'], E_ALL);
  615. if (\OC::$CLI) {
  616. $exceptionHandler = ['OC_Template', 'printExceptionErrorPage'];
  617. }
  618. } else {
  619. set_error_handler([$errorHandler, 'onError']);
  620. }
  621. register_shutdown_function([$errorHandler, 'onShutdown']);
  622. set_exception_handler($exceptionHandler);
  623. }
  624. /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */
  625. $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
  626. $bootstrapCoordinator->runInitialRegistration();
  627. $eventLogger->start('init_session', 'Initialize session');
  628. OC_App::loadApps(['session']);
  629. if (!self::$CLI) {
  630. self::initSession();
  631. }
  632. $eventLogger->end('init_session');
  633. self::checkConfig();
  634. self::checkInstalled($systemConfig);
  635. OC_Response::addSecurityHeaders();
  636. self::performSameSiteCookieProtection($config);
  637. if (!defined('OC_CONSOLE')) {
  638. $errors = OC_Util::checkServer($systemConfig);
  639. if (count($errors) > 0) {
  640. if (!self::$CLI) {
  641. http_response_code(503);
  642. OC_Util::addStyle('guest');
  643. try {
  644. OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
  645. exit;
  646. } catch (\Exception $e) {
  647. // In case any error happens when showing the error page, we simply fall back to posting the text.
  648. // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
  649. }
  650. }
  651. // Convert l10n string into regular string for usage in database
  652. $staticErrors = [];
  653. foreach ($errors as $error) {
  654. echo $error['error'] . "\n";
  655. echo $error['hint'] . "\n\n";
  656. $staticErrors[] = [
  657. 'error' => (string)$error['error'],
  658. 'hint' => (string)$error['hint'],
  659. ];
  660. }
  661. try {
  662. $config->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  663. } catch (\Exception $e) {
  664. echo('Writing to database failed');
  665. }
  666. exit(1);
  667. } elseif (self::$CLI && $config->getSystemValueBool('installed', false)) {
  668. $config->deleteAppValue('core', 'cronErrors');
  669. }
  670. }
  671. // User and Groups
  672. if (!$systemConfig->getValue("installed", false)) {
  673. self::$server->getSession()->set('user_id', '');
  674. }
  675. OC_User::useBackend(new \OC\User\Database());
  676. Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database());
  677. // Subscribe to the hook
  678. \OCP\Util::connectHook(
  679. '\OCA\Files_Sharing\API\Server2Server',
  680. 'preLoginNameUsedAsUserName',
  681. '\OC\User\Database',
  682. 'preLoginNameUsedAsUserName'
  683. );
  684. //setup extra user backends
  685. if (!\OCP\Util::needUpgrade()) {
  686. OC_User::setupBackends();
  687. } else {
  688. // Run upgrades in incognito mode
  689. OC_User::setIncognitoMode(true);
  690. }
  691. self::registerCleanupHooks($systemConfig);
  692. self::registerShareHooks($systemConfig);
  693. self::registerEncryptionWrapperAndHooks();
  694. self::registerAccountHooks();
  695. self::registerResourceCollectionHooks();
  696. self::registerFileReferenceEventListener();
  697. self::registerRenderReferenceEventListener();
  698. self::registerAppRestrictionsHooks();
  699. // Make sure that the application class is not loaded before the database is setup
  700. if ($systemConfig->getValue("installed", false)) {
  701. OC_App::loadApp('settings');
  702. /* Build core application to make sure that listeners are registered */
  703. Server::get(\OC\Core\Application::class);
  704. }
  705. //make sure temporary files are cleaned up
  706. $tmpManager = Server::get(\OCP\ITempManager::class);
  707. register_shutdown_function([$tmpManager, 'clean']);
  708. $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class);
  709. register_shutdown_function([$lockProvider, 'releaseAll']);
  710. // Check whether the sample configuration has been copied
  711. if ($systemConfig->getValue('copied_sample_config', false)) {
  712. $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
  713. OC_Template::printErrorPage(
  714. $l->t('Sample configuration detected'),
  715. $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'),
  716. 503
  717. );
  718. return;
  719. }
  720. $request = Server::get(IRequest::class);
  721. $host = $request->getInsecureServerHost();
  722. /**
  723. * if the host passed in headers isn't trusted
  724. * FIXME: Should not be in here at all :see_no_evil:
  725. */
  726. if (!OC::$CLI
  727. && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host)
  728. && $config->getSystemValueBool('installed', false)
  729. ) {
  730. // Allow access to CSS resources
  731. $isScssRequest = false;
  732. if (strpos($request->getPathInfo() ?: '', '/css/') === 0) {
  733. $isScssRequest = true;
  734. }
  735. if (substr($request->getRequestUri(), -11) === '/status.php') {
  736. http_response_code(400);
  737. header('Content-Type: application/json');
  738. echo '{"error": "Trusted domain error.", "code": 15}';
  739. exit();
  740. }
  741. if (!$isScssRequest) {
  742. http_response_code(400);
  743. Server::get(LoggerInterface::class)->info(
  744. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  745. [
  746. 'app' => 'core',
  747. 'remoteAddress' => $request->getRemoteAddress(),
  748. 'host' => $host,
  749. ]
  750. );
  751. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  752. $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains'));
  753. $tmpl->printPage();
  754. exit();
  755. }
  756. }
  757. $eventLogger->end('boot');
  758. $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true));
  759. $eventLogger->start('runtime', 'Runtime');
  760. $eventLogger->start('request', 'Full request after boot');
  761. register_shutdown_function(function () use ($eventLogger) {
  762. $eventLogger->end('request');
  763. });
  764. }
  765. /**
  766. * register hooks for the cleanup of cache and bruteforce protection
  767. */
  768. public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void {
  769. //don't try to do this before we are properly setup
  770. if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
  771. // NOTE: This will be replaced to use OCP
  772. $userSession = Server::get(\OC\User\Session::class);
  773. $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
  774. if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
  775. // reset brute force delay for this IP address and username
  776. $uid = $userSession->getUser()->getUID();
  777. $request = Server::get(IRequest::class);
  778. $throttler = Server::get(IThrottler::class);
  779. $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
  780. }
  781. try {
  782. $cache = new \OC\Cache\File();
  783. $cache->gc();
  784. } catch (\OC\ServerNotAvailableException $e) {
  785. // not a GC exception, pass it on
  786. throw $e;
  787. } catch (\OC\ForbiddenException $e) {
  788. // filesystem blocked for this request, ignore
  789. } catch (\Exception $e) {
  790. // a GC exception should not prevent users from using OC,
  791. // so log the exception
  792. Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [
  793. 'app' => 'core',
  794. 'exception' => $e,
  795. ]);
  796. }
  797. });
  798. }
  799. }
  800. private static function registerEncryptionWrapperAndHooks(): void {
  801. $manager = Server::get(\OCP\Encryption\IManager::class);
  802. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  803. $enabled = $manager->isEnabled();
  804. if ($enabled) {
  805. \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
  806. \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
  807. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
  808. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
  809. }
  810. }
  811. private static function registerAccountHooks(): void {
  812. /** @var IEventDispatcher $dispatcher */
  813. $dispatcher = Server::get(IEventDispatcher::class);
  814. $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class);
  815. }
  816. private static function registerAppRestrictionsHooks(): void {
  817. /** @var \OC\Group\Manager $groupManager */
  818. $groupManager = Server::get(\OCP\IGroupManager::class);
  819. $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
  820. $appManager = Server::get(\OCP\App\IAppManager::class);
  821. $apps = $appManager->getEnabledAppsForGroup($group);
  822. foreach ($apps as $appId) {
  823. $restrictions = $appManager->getAppRestriction($appId);
  824. if (empty($restrictions)) {
  825. continue;
  826. }
  827. $key = array_search($group->getGID(), $restrictions);
  828. unset($restrictions[$key]);
  829. $restrictions = array_values($restrictions);
  830. if (empty($restrictions)) {
  831. $appManager->disableApp($appId);
  832. } else {
  833. $appManager->enableAppForGroups($appId, $restrictions);
  834. }
  835. }
  836. });
  837. }
  838. private static function registerResourceCollectionHooks(): void {
  839. \OC\Collaboration\Resources\Listener::register(Server::get(IEventDispatcher::class));
  840. }
  841. private static function registerFileReferenceEventListener(): void {
  842. \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class));
  843. }
  844. private static function registerRenderReferenceEventListener() {
  845. \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class));
  846. }
  847. /**
  848. * register hooks for sharing
  849. */
  850. public static function registerShareHooks(\OC\SystemConfig $systemConfig): void {
  851. if ($systemConfig->getValue('installed')) {
  852. OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
  853. OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
  854. /** @var IEventDispatcher $dispatcher */
  855. $dispatcher = Server::get(IEventDispatcher::class);
  856. $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class);
  857. }
  858. }
  859. protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void {
  860. // The class loader takes an optional low-latency cache, which MUST be
  861. // namespaced. The instanceid is used for namespacing, but might be
  862. // unavailable at this point. Furthermore, it might not be possible to
  863. // generate an instanceid via \OC_Util::getInstanceId() because the
  864. // config file may not be writable. As such, we only register a class
  865. // loader cache if instanceid is available without trying to create one.
  866. $instanceId = $systemConfig->getValue('instanceid', null);
  867. if ($instanceId) {
  868. try {
  869. $memcacheFactory = Server::get(\OCP\ICacheFactory::class);
  870. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  871. } catch (\Exception $ex) {
  872. }
  873. }
  874. }
  875. /**
  876. * Handle the request
  877. */
  878. public static function handleRequest(): void {
  879. Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request');
  880. $systemConfig = Server::get(\OC\SystemConfig::class);
  881. // Check if Nextcloud is installed or in maintenance (update) mode
  882. if (!$systemConfig->getValue('installed', false)) {
  883. \OC::$server->getSession()->clear();
  884. $controller = Server::get(\OC\Core\Controller\SetupController::class);
  885. $controller->run($_POST);
  886. exit();
  887. }
  888. $request = Server::get(IRequest::class);
  889. $requestPath = $request->getRawPathInfo();
  890. if ($requestPath === '/heartbeat') {
  891. return;
  892. }
  893. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  894. self::checkMaintenanceMode($systemConfig);
  895. if (\OCP\Util::needUpgrade()) {
  896. if (function_exists('opcache_reset')) {
  897. opcache_reset();
  898. }
  899. if (!((bool) $systemConfig->getValue('maintenance', false))) {
  900. self::printUpgradePage($systemConfig);
  901. exit();
  902. }
  903. }
  904. }
  905. // Always load authentication apps
  906. OC_App::loadApps(['authentication']);
  907. OC_App::loadApps(['extended_authentication']);
  908. // Load minimum set of apps
  909. if (!\OCP\Util::needUpgrade()
  910. && !((bool) $systemConfig->getValue('maintenance', false))) {
  911. // For logged-in users: Load everything
  912. if (Server::get(IUserSession::class)->isLoggedIn()) {
  913. OC_App::loadApps();
  914. } else {
  915. // For guests: Load only filesystem and logging
  916. OC_App::loadApps(['filesystem', 'logging']);
  917. // Don't try to login when a client is trying to get a OAuth token.
  918. // OAuth needs to support basic auth too, so the login is not valid
  919. // inside Nextcloud and the Login exception would ruin it.
  920. if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') {
  921. self::handleLogin($request);
  922. }
  923. }
  924. }
  925. if (!self::$CLI) {
  926. try {
  927. if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
  928. OC_App::loadApps(['filesystem', 'logging']);
  929. OC_App::loadApps();
  930. }
  931. Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo());
  932. return;
  933. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  934. //header('HTTP/1.0 404 Not Found');
  935. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  936. http_response_code(405);
  937. return;
  938. }
  939. }
  940. // Handle WebDAV
  941. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
  942. // not allowed any more to prevent people
  943. // mounting this root directly.
  944. // Users need to mount remote.php/webdav instead.
  945. http_response_code(405);
  946. return;
  947. }
  948. // Handle requests for JSON or XML
  949. $acceptHeader = $request->getHeader('Accept');
  950. if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) {
  951. http_response_code(404);
  952. return;
  953. }
  954. // Handle resources that can't be found
  955. // This prevents browsers from redirecting to the default page and then
  956. // attempting to parse HTML as CSS and similar.
  957. $destinationHeader = $request->getHeader('Sec-Fetch-Dest');
  958. if (in_array($destinationHeader, ['font', 'script', 'style'])) {
  959. http_response_code(404);
  960. return;
  961. }
  962. // Redirect to the default app or login only as an entry point
  963. if ($requestPath === '') {
  964. // Someone is logged in
  965. if (Server::get(IUserSession::class)->isLoggedIn()) {
  966. header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl());
  967. } else {
  968. // Not handled and not logged in
  969. header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm'));
  970. }
  971. return;
  972. }
  973. try {
  974. Server::get(\OC\Route\Router::class)->match('/error/404');
  975. } catch (\Exception $e) {
  976. if (!$e instanceof MethodNotAllowedException) {
  977. logger('core')->emergency($e->getMessage(), ['exception' => $e]);
  978. }
  979. $l = Server::get(\OCP\L10N\IFactory::class)->get('lib');
  980. OC_Template::printErrorPage(
  981. '404',
  982. $l->t('The page could not be found on the server.'),
  983. 404
  984. );
  985. }
  986. }
  987. /**
  988. * Check login: apache auth, auth token, basic auth
  989. */
  990. public static function handleLogin(OCP\IRequest $request): bool {
  991. if ($request->getHeader('X-Nextcloud-Federation')) {
  992. return false;
  993. }
  994. $userSession = Server::get(\OC\User\Session::class);
  995. if (OC_User::handleApacheAuth()) {
  996. return true;
  997. }
  998. if (self::tryAppAPILogin($request)) {
  999. return true;
  1000. }
  1001. if ($userSession->tryTokenLogin($request)) {
  1002. return true;
  1003. }
  1004. if (isset($_COOKIE['nc_username'])
  1005. && isset($_COOKIE['nc_token'])
  1006. && isset($_COOKIE['nc_session_id'])
  1007. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  1008. return true;
  1009. }
  1010. if ($userSession->tryBasicAuthLogin($request, Server::get(IThrottler::class))) {
  1011. return true;
  1012. }
  1013. return false;
  1014. }
  1015. protected static function handleAuthHeaders(): void {
  1016. //copy http auth headers for apache+php-fcgid work around
  1017. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  1018. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  1019. }
  1020. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  1021. $vars = [
  1022. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  1023. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  1024. ];
  1025. foreach ($vars as $var) {
  1026. if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  1027. $credentials = explode(':', base64_decode($matches[1]), 2);
  1028. if (count($credentials) === 2) {
  1029. $_SERVER['PHP_AUTH_USER'] = $credentials[0];
  1030. $_SERVER['PHP_AUTH_PW'] = $credentials[1];
  1031. break;
  1032. }
  1033. }
  1034. }
  1035. }
  1036. protected static function tryAppAPILogin(OCP\IRequest $request): bool {
  1037. $appManager = Server::get(OCP\App\IAppManager::class);
  1038. if (!$request->getHeader('AUTHORIZATION-APP-API')) {
  1039. return false;
  1040. }
  1041. if (!$appManager->isInstalled('app_api')) {
  1042. return false;
  1043. }
  1044. try {
  1045. $appAPIService = Server::get(OCA\AppAPI\Service\AppAPIService::class);
  1046. return $appAPIService->validateExAppRequestToNC($request);
  1047. } catch (\Psr\Container\NotFoundExceptionInterface|\Psr\Container\ContainerExceptionInterface $e) {
  1048. return false;
  1049. }
  1050. }
  1051. }
  1052. OC::init();