You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.php 42KB

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