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

base.php 36KB

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