base.php 41 KB

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