base.php 39 KB

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