1
0

base.php 42 KB

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