1
0

base.php 41 KB

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