base.php 37 KB

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