base.php 36 KB

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