base.php 37 KB

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