base.php 37 KB

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 Björn Schießle <bjoern@schiessle.org>
  11. * @author Christoph Wurst <christoph@owncloud.com>
  12. * @author davidgumberg <davidnoizgumberg@gmail.com>
  13. * @author Florin Peter <github@florin-peter.de>
  14. * @author Georg Ehrke <georg@owncloud.com>
  15. * @author Hugo Gonzalez Labrador <hglavra@gmail.com>
  16. * @author Individual IT Services <info@individual-it.net>
  17. * @author Jakob Sack <mail@jakobsack.de>
  18. * @author Joachim Bauch <bauch@struktur.de>
  19. * @author Joachim Sokolowski <github@sokolowski.org>
  20. * @author Joas Schilling <coding@schilljs.com>
  21. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  22. * @author Lukas Reschke <lukas@statuscode.ch>
  23. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  24. * @author Morris Jobke <hey@morrisjobke.de>
  25. * @author Owen Winkler <a_github@midnightcircus.com>
  26. * @author Phil Davis <phil.davis@inf.org>
  27. * @author Ramiro Aparicio <rapariciog@gmail.com>
  28. * @author Robin Appelman <robin@icewind.nl>
  29. * @author Robin McCorkell <robin@mccorkell.me.uk>
  30. * @author Roeland Jago Douma <roeland@famdouma.nl>
  31. * @author Stefan Weil <sw@weilnetz.de>
  32. * @author Thomas Müller <thomas.mueller@tmit.eu>
  33. * @author Thomas Pulzer <t.pulzer@kniel.de>
  34. * @author Thomas Tanghus <thomas@tanghus.net>
  35. * @author Vincent Petry <pvince81@owncloud.com>
  36. * @author Volkan Gezer <volkangezer@gmail.com>
  37. *
  38. * @license AGPL-3.0
  39. *
  40. * This code is free software: you can redistribute it and/or modify
  41. * it under the terms of the GNU Affero General Public License, version 3,
  42. * as published by the Free Software Foundation.
  43. *
  44. * This program is distributed in the hope that it will be useful,
  45. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  46. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  47. * GNU Affero General Public License for more details.
  48. *
  49. * You should have received a copy of the GNU Affero General Public License, version 3,
  50. * along with this program. If not, see <http://www.gnu.org/licenses/>
  51. *
  52. */
  53. require_once 'public/Constants.php';
  54. /**
  55. * Class that is a namespace for all global OC variables
  56. * No, we can not put this class in its own file because it is used by
  57. * OC_autoload!
  58. */
  59. class OC {
  60. /**
  61. * Associative array for autoloading. classname => filename
  62. */
  63. public static $CLASSPATH = array();
  64. /**
  65. * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud)
  66. */
  67. public static $SERVERROOT = '';
  68. /**
  69. * the current request path relative to the Nextcloud root (e.g. files/index.php)
  70. */
  71. private static $SUBURI = '';
  72. /**
  73. * the Nextcloud root path for http requests (e.g. nextcloud/)
  74. */
  75. public static $WEBROOT = '';
  76. /**
  77. * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
  78. * web path in 'url'
  79. */
  80. public static $APPSROOTS = array();
  81. /**
  82. * @var string
  83. */
  84. public static $configDir;
  85. /**
  86. * requested app
  87. */
  88. public static $REQUESTEDAPP = '';
  89. /**
  90. * check if Nextcloud runs in cli mode
  91. */
  92. public static $CLI = false;
  93. /**
  94. * @var \OC\Autoloader $loader
  95. */
  96. public static $loader = null;
  97. /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
  98. public static $composerAutoloader = null;
  99. /**
  100. * @var \OC\Server
  101. */
  102. public static $server = null;
  103. /**
  104. * @var \OC\Config
  105. */
  106. private static $config = null;
  107. /**
  108. * @throws \RuntimeException when the 3rdparty directory is missing or
  109. * the app path list is empty or contains an invalid path
  110. */
  111. public static function initPaths() {
  112. if(defined('PHPUNIT_CONFIG_DIR')) {
  113. self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
  114. } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
  115. self::$configDir = OC::$SERVERROOT . '/tests/config/';
  116. } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
  117. self::$configDir = rtrim($dir, '/') . '/';
  118. } else {
  119. self::$configDir = OC::$SERVERROOT . '/config/';
  120. }
  121. self::$config = new \OC\Config(self::$configDir);
  122. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  123. /**
  124. * FIXME: The following lines are required because we can't yet instantiate
  125. * \OC::$server->getRequest() since \OC::$server does not yet exist.
  126. */
  127. $params = [
  128. 'server' => [
  129. 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
  130. 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
  131. ],
  132. ];
  133. $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
  134. $scriptName = $fakeRequest->getScriptName();
  135. if (substr($scriptName, -1) == '/') {
  136. $scriptName .= 'index.php';
  137. //make sure suburi follows the same rules as scriptName
  138. if (substr(OC::$SUBURI, -9) != 'index.php') {
  139. if (substr(OC::$SUBURI, -1) != '/') {
  140. OC::$SUBURI = OC::$SUBURI . '/';
  141. }
  142. OC::$SUBURI = OC::$SUBURI . 'index.php';
  143. }
  144. }
  145. if (OC::$CLI) {
  146. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  147. } else {
  148. if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
  149. OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
  150. if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
  151. OC::$WEBROOT = '/' . OC::$WEBROOT;
  152. }
  153. } else {
  154. // The scriptName is not ending with OC::$SUBURI
  155. // This most likely means that we are calling from CLI.
  156. // However some cron jobs still need to generate
  157. // a web URL, so we use overwritewebroot as a fallback.
  158. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  159. }
  160. // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
  161. // slash which is required by URL generation.
  162. if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
  163. substr($_SERVER['REQUEST_URI'], -1) !== '/') {
  164. header('Location: '.\OC::$WEBROOT.'/');
  165. exit();
  166. }
  167. }
  168. // search the apps folder
  169. $config_paths = self::$config->getValue('apps_paths', array());
  170. if (!empty($config_paths)) {
  171. foreach ($config_paths as $paths) {
  172. if (isset($paths['url']) && isset($paths['path'])) {
  173. $paths['url'] = rtrim($paths['url'], '/');
  174. $paths['path'] = rtrim($paths['path'], '/');
  175. OC::$APPSROOTS[] = $paths;
  176. }
  177. }
  178. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  179. OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
  180. } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
  181. OC::$APPSROOTS[] = array(
  182. 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
  183. 'url' => '/apps',
  184. 'writable' => true
  185. );
  186. }
  187. if (empty(OC::$APPSROOTS)) {
  188. throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
  189. . ' or the folder above. You can also configure the location in the config.php file.');
  190. }
  191. $paths = array();
  192. foreach (OC::$APPSROOTS as $path) {
  193. $paths[] = $path['path'];
  194. if (!is_dir($path['path'])) {
  195. throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
  196. . ' Nextcloud folder or the folder above. You can also configure the location in the'
  197. . ' config.php file.', $path['path']));
  198. }
  199. }
  200. // set the right include path
  201. set_include_path(
  202. implode(PATH_SEPARATOR, $paths)
  203. );
  204. }
  205. public static function checkConfig() {
  206. $l = \OC::$server->getL10N('lib');
  207. // Create config if it does not already exist
  208. $configFilePath = self::$configDir .'/config.php';
  209. if(!file_exists($configFilePath)) {
  210. @touch($configFilePath);
  211. }
  212. // Check if config is writable
  213. $configFileWritable = is_writable($configFilePath);
  214. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  215. || !$configFileWritable && self::checkUpgrade(false)) {
  216. $urlGenerator = \OC::$server->getURLGenerator();
  217. if (self::$CLI) {
  218. echo $l->t('Cannot write into "config" directory!')."\n";
  219. echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
  220. echo "\n";
  221. echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
  222. exit;
  223. } else {
  224. OC_Template::printErrorPage(
  225. $l->t('Cannot write into "config" directory!'),
  226. $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
  227. [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
  228. );
  229. }
  230. }
  231. }
  232. public static function checkInstalled() {
  233. if (defined('OC_CONSOLE')) {
  234. return;
  235. }
  236. // Redirect to installer if not installed
  237. if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
  238. if (OC::$CLI) {
  239. throw new Exception('Not installed');
  240. } else {
  241. $url = OC::$WEBROOT . '/index.php';
  242. header('Location: ' . $url);
  243. }
  244. exit();
  245. }
  246. }
  247. public static function checkMaintenanceMode() {
  248. // Allow ajax update script to execute without being stopped
  249. if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
  250. // send http status 503
  251. header('HTTP/1.1 503 Service Temporarily Unavailable');
  252. header('Status: 503 Service Temporarily Unavailable');
  253. header('Retry-After: 120');
  254. // render error page
  255. $template = new OC_Template('', 'update.user', 'guest');
  256. OC_Util::addScript('maintenance-check');
  257. OC_Util::addStyle('core', 'guest');
  258. $template->printPage();
  259. die();
  260. }
  261. }
  262. /**
  263. * Checks if the version requires an update and shows
  264. * @param bool $showTemplate Whether an update screen should get shown
  265. * @return bool|void
  266. */
  267. public static function checkUpgrade($showTemplate = true) {
  268. if (\OCP\Util::needUpgrade()) {
  269. if (function_exists('opcache_reset')) {
  270. opcache_reset();
  271. }
  272. $systemConfig = \OC::$server->getSystemConfig();
  273. if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
  274. self::printUpgradePage();
  275. exit();
  276. } else {
  277. return true;
  278. }
  279. }
  280. return false;
  281. }
  282. /**
  283. * Prints the upgrade page
  284. */
  285. private static function printUpgradePage() {
  286. $systemConfig = \OC::$server->getSystemConfig();
  287. $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
  288. $tooBig = false;
  289. if (!$disableWebUpdater) {
  290. $apps = \OC::$server->getAppManager();
  291. $tooBig = false;
  292. if ($apps->isInstalled('user_ldap')) {
  293. $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  294. $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
  295. ->from('ldap_user_mapping')
  296. ->execute();
  297. $row = $result->fetch();
  298. $result->closeCursor();
  299. $tooBig = ($row['user_count'] > 50);
  300. }
  301. if (!$tooBig && $apps->isInstalled('user_saml')) {
  302. $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  303. $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
  304. ->from('user_saml_users')
  305. ->execute();
  306. $row = $result->fetch();
  307. $result->closeCursor();
  308. $tooBig = ($row['user_count'] > 50);
  309. }
  310. if (!$tooBig) {
  311. // count users
  312. $stats = \OC::$server->getUserManager()->countUsers();
  313. $totalUsers = array_sum($stats);
  314. $tooBig = ($totalUsers > 50);
  315. }
  316. }
  317. $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
  318. $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
  319. if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
  320. // send http status 503
  321. header('HTTP/1.1 503 Service Temporarily Unavailable');
  322. header('Status: 503 Service Temporarily Unavailable');
  323. header('Retry-After: 120');
  324. // render error page
  325. $template = new OC_Template('', 'update.use-cli', 'guest');
  326. $template->assign('productName', 'nextcloud'); // for now
  327. $template->assign('version', OC_Util::getVersionString());
  328. $template->assign('tooBig', $tooBig);
  329. $template->printPage();
  330. die();
  331. }
  332. // check whether this is a core update or apps update
  333. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  334. $currentVersion = implode('.', \OCP\Util::getVersion());
  335. // if not a core upgrade, then it's apps upgrade
  336. $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
  337. $oldTheme = $systemConfig->getValue('theme');
  338. $systemConfig->setValue('theme', '');
  339. OC_Util::addScript('config'); // needed for web root
  340. OC_Util::addScript('update');
  341. /** @var \OC\App\AppManager $appManager */
  342. $appManager = \OC::$server->getAppManager();
  343. $tmpl = new OC_Template('', 'update.admin', 'guest');
  344. $tmpl->assign('version', OC_Util::getVersionString());
  345. $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
  346. // get third party apps
  347. $ocVersion = \OCP\Util::getVersion();
  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 %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
  358. 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);
  359. }
  360. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  361. $tmpl->assign('incompatibleAppsList', $incompatibleApps);
  362. $tmpl->assign('productName', 'Nextcloud'); // for now
  363. $tmpl->assign('oldTheme', $oldTheme);
  364. $tmpl->printPage();
  365. }
  366. public static function initSession() {
  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', array('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. \OCP\Util::logException('base', $e);
  389. //show the user a detailed error page
  390. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  391. OC_Template::printExceptionErrorPage($e);
  392. die();
  393. }
  394. $sessionLifeTime = self::getSessionLifeTime();
  395. // session timeout
  396. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  397. if (isset($_COOKIE[session_name()])) {
  398. setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
  399. }
  400. \OC::$server->getUserSession()->logout();
  401. }
  402. $session->set('LAST_ACTIVITY', time());
  403. }
  404. /**
  405. * @return string
  406. */
  407. private static function getSessionLifeTime() {
  408. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  409. }
  410. public static function loadAppClassPaths() {
  411. foreach (OC_App::getEnabledApps() as $app) {
  412. $appPath = OC_App::getAppPath($app);
  413. if ($appPath === false) {
  414. continue;
  415. }
  416. $file = $appPath . '/appinfo/classpath.php';
  417. if (file_exists($file)) {
  418. require_once $file;
  419. }
  420. }
  421. }
  422. /**
  423. * Try to set some values to the required Nextcloud default
  424. */
  425. public static function setRequiredIniValues() {
  426. @ini_set('default_charset', 'UTF-8');
  427. @ini_set('gd.jpeg_ignore_warning', 1);
  428. }
  429. /**
  430. * Send the same site cookies
  431. */
  432. private static function sendSameSiteCookies() {
  433. $cookieParams = session_get_cookie_params();
  434. $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
  435. $policies = [
  436. 'lax',
  437. 'strict',
  438. ];
  439. // Append __Host to the cookie if it meets the requirements
  440. $cookiePrefix = '';
  441. if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  442. $cookiePrefix = '__Host-';
  443. }
  444. foreach($policies as $policy) {
  445. header(
  446. sprintf(
  447. 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
  448. $cookiePrefix,
  449. $policy,
  450. $cookieParams['path'],
  451. $policy
  452. ),
  453. false
  454. );
  455. }
  456. }
  457. /**
  458. * Same Site cookie to further mitigate CSRF attacks. This cookie has to
  459. * be set in every request if cookies are sent to add a second level of
  460. * defense against CSRF.
  461. *
  462. * If the cookie is not sent this will set the cookie and reload the page.
  463. * We use an additional cookie since we want to protect logout CSRF and
  464. * also we can't directly interfere with PHP's session mechanism.
  465. */
  466. private static function performSameSiteCookieProtection() {
  467. $request = \OC::$server->getRequest();
  468. // Some user agents are notorious and don't really properly follow HTTP
  469. // specifications. For those, have an automated opt-out. Since the protection
  470. // for remote.php is applied in base.php as starting point we need to opt out
  471. // here.
  472. $incompatibleUserAgents = [
  473. // OS X Finder
  474. '/^WebDAVFS/',
  475. '/^Microsoft-WebDAV-MiniRedir/',
  476. ];
  477. if($request->isUserAgent($incompatibleUserAgents)) {
  478. return;
  479. }
  480. if(count($_COOKIE) > 0) {
  481. $requestUri = $request->getScriptName();
  482. $processingScript = explode('/', $requestUri);
  483. $processingScript = $processingScript[count($processingScript)-1];
  484. // FIXME: In a SAML scenario we don't get any strict or lax cookie
  485. // send for the ACS endpoint. Since we have some legacy code in Nextcloud
  486. // (direct PHP files) the enforcement of lax cookies is performed here
  487. // instead of the middleware.
  488. //
  489. // This means we cannot exclude some routes from the cookie validation,
  490. // which normally is not a problem but is a little bit cumbersome for
  491. // this use-case.
  492. // Once the old legacy PHP endpoints have been removed we can move
  493. // the verification into a middleware and also adds some exemptions.
  494. //
  495. // Questions about this code? Ask Lukas ;-)
  496. $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
  497. if($currentUrl === '/index.php/apps/user_saml/saml/acs' || $currentUrl === '/apps/user_saml/saml/acs') {
  498. return;
  499. }
  500. // For the "index.php" endpoint only a lax cookie is required.
  501. if($processingScript === 'index.php') {
  502. if(!$request->passesLaxCookieCheck()) {
  503. self::sendSameSiteCookies();
  504. header('Location: '.$_SERVER['REQUEST_URI']);
  505. exit();
  506. }
  507. } else {
  508. // All other endpoints require the lax and the strict cookie
  509. if(!$request->passesStrictCookieCheck()) {
  510. self::sendSameSiteCookies();
  511. // Debug mode gets access to the resources without strict cookie
  512. // due to the fact that the SabreDAV browser also lives there.
  513. if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
  514. http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
  515. exit();
  516. }
  517. }
  518. }
  519. } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
  520. self::sendSameSiteCookies();
  521. }
  522. }
  523. public static function init() {
  524. // calculate the root directories
  525. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  526. // register autoloader
  527. $loaderStart = microtime(true);
  528. require_once __DIR__ . '/autoloader.php';
  529. self::$loader = new \OC\Autoloader([
  530. OC::$SERVERROOT . '/lib/private/legacy',
  531. ]);
  532. if (defined('PHPUNIT_RUN')) {
  533. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  534. }
  535. spl_autoload_register(array(self::$loader, 'load'));
  536. $loaderEnd = microtime(true);
  537. self::$CLI = (php_sapi_name() == 'cli');
  538. // Add default composer PSR-4 autoloader
  539. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  540. try {
  541. self::initPaths();
  542. // setup 3rdparty autoloader
  543. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  544. if (!file_exists($vendorAutoLoad)) {
  545. 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".');
  546. }
  547. require_once $vendorAutoLoad;
  548. } catch (\RuntimeException $e) {
  549. if (!self::$CLI) {
  550. $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
  551. $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
  552. header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
  553. }
  554. // we can't use the template error page here, because this needs the
  555. // DI container which isn't available yet
  556. print($e->getMessage());
  557. exit();
  558. }
  559. // setup the basic server
  560. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  561. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  562. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  563. // Don't display errors and log them
  564. error_reporting(E_ALL | E_STRICT);
  565. @ini_set('display_errors', 0);
  566. @ini_set('log_errors', 1);
  567. if(!date_default_timezone_set('UTC')) {
  568. throw new \RuntimeException('Could not set timezone to UTC');
  569. };
  570. //try to configure php to enable big file uploads.
  571. //this doesn´t work always depending on the webserver and php configuration.
  572. //Let´s try to overwrite some defaults anyway
  573. //try to set the maximum execution time to 60min
  574. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  575. @set_time_limit(3600);
  576. }
  577. @ini_set('max_execution_time', 3600);
  578. @ini_set('max_input_time', 3600);
  579. //try to set the maximum filesize to 10G
  580. @ini_set('upload_max_filesize', '10G');
  581. @ini_set('post_max_size', '10G');
  582. @ini_set('file_uploads', '50');
  583. self::setRequiredIniValues();
  584. self::handleAuthHeaders();
  585. self::registerAutoloaderCache();
  586. // initialize intl fallback is necessary
  587. \Patchwork\Utf8\Bootup::initIntl();
  588. OC_Util::isSetLocaleWorking();
  589. if (!defined('PHPUNIT_RUN')) {
  590. OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
  591. $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
  592. OC\Log\ErrorHandler::register($debug);
  593. }
  594. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  595. OC_App::loadApps(array('session'));
  596. if (!self::$CLI) {
  597. self::initSession();
  598. }
  599. \OC::$server->getEventLogger()->end('init_session');
  600. self::checkConfig();
  601. self::checkInstalled();
  602. OC_Response::addSecurityHeaders();
  603. if(self::$server->getRequest()->getServerProtocol() === 'https') {
  604. ini_set('session.cookie_secure', true);
  605. }
  606. self::performSameSiteCookieProtection();
  607. if (!defined('OC_CONSOLE')) {
  608. $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
  609. if (count($errors) > 0) {
  610. if (self::$CLI) {
  611. // Convert l10n string into regular string for usage in database
  612. $staticErrors = [];
  613. foreach ($errors as $error) {
  614. echo $error['error'] . "\n";
  615. echo $error['hint'] . "\n\n";
  616. $staticErrors[] = [
  617. 'error' => (string)$error['error'],
  618. 'hint' => (string)$error['hint'],
  619. ];
  620. }
  621. try {
  622. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  623. } catch (\Exception $e) {
  624. echo('Writing to database failed');
  625. }
  626. exit(1);
  627. } else {
  628. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  629. OC_Util::addStyle('guest');
  630. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  631. exit;
  632. }
  633. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  634. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  635. }
  636. }
  637. //try to set the session lifetime
  638. $sessionLifeTime = self::getSessionLifeTime();
  639. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  640. $systemConfig = \OC::$server->getSystemConfig();
  641. // User and Groups
  642. if (!$systemConfig->getValue("installed", false)) {
  643. self::$server->getSession()->set('user_id', '');
  644. }
  645. OC_User::useBackend(new \OC\User\Database());
  646. \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
  647. // Subscribe to the hook
  648. \OCP\Util::connectHook(
  649. '\OCA\Files_Sharing\API\Server2Server',
  650. 'preLoginNameUsedAsUserName',
  651. '\OC\User\Database',
  652. 'preLoginNameUsedAsUserName'
  653. );
  654. //setup extra user backends
  655. if (!self::checkUpgrade(false)) {
  656. OC_User::setupBackends();
  657. } else {
  658. // Run upgrades in incognito mode
  659. OC_User::setIncognitoMode(true);
  660. }
  661. self::registerCacheHooks();
  662. self::registerFilesystemHooks();
  663. self::registerShareHooks();
  664. self::registerLogRotate();
  665. self::registerEncryptionWrapper();
  666. self::registerEncryptionHooks();
  667. self::registerAccountHooks();
  668. self::registerSettingsHooks();
  669. $settings = new \OC\Settings\Application();
  670. $settings->register();
  671. //make sure temporary files are cleaned up
  672. $tmpManager = \OC::$server->getTempManager();
  673. register_shutdown_function(array($tmpManager, 'clean'));
  674. $lockProvider = \OC::$server->getLockingProvider();
  675. register_shutdown_function(array($lockProvider, 'releaseAll'));
  676. // Check whether the sample configuration has been copied
  677. if($systemConfig->getValue('copied_sample_config', false)) {
  678. $l = \OC::$server->getL10N('lib');
  679. header('HTTP/1.1 503 Service Temporarily Unavailable');
  680. header('Status: 503 Service Temporarily Unavailable');
  681. OC_Template::printErrorPage(
  682. $l->t('Sample configuration detected'),
  683. $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')
  684. );
  685. return;
  686. }
  687. $request = \OC::$server->getRequest();
  688. $host = $request->getInsecureServerHost();
  689. /**
  690. * if the host passed in headers isn't trusted
  691. * FIXME: Should not be in here at all :see_no_evil:
  692. */
  693. if (!OC::$CLI
  694. // overwritehost is always trusted, workaround to not have to make
  695. // \OC\AppFramework\Http\Request::getOverwriteHost public
  696. && self::$server->getConfig()->getSystemValue('overwritehost') === ''
  697. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  698. && self::$server->getConfig()->getSystemValue('installed', false)
  699. ) {
  700. // Allow access to CSS resources
  701. $isScssRequest = false;
  702. if(strpos($request->getPathInfo(), '/css/') === 0) {
  703. $isScssRequest = true;
  704. }
  705. if (!$isScssRequest) {
  706. header('HTTP/1.1 400 Bad Request');
  707. header('Status: 400 Bad Request');
  708. \OC::$server->getLogger()->warning(
  709. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  710. [
  711. 'app' => 'core',
  712. 'remoteAddress' => $request->getRemoteAddress(),
  713. 'host' => $host,
  714. ]
  715. );
  716. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  717. $tmpl->assign('domain', $host);
  718. $tmpl->printPage();
  719. exit();
  720. }
  721. }
  722. \OC::$server->getEventLogger()->end('boot');
  723. }
  724. /**
  725. * register hooks for the cache
  726. */
  727. public static function registerCacheHooks() {
  728. //don't try to do this before we are properly setup
  729. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
  730. // NOTE: This will be replaced to use OCP
  731. $userSession = self::$server->getUserSession();
  732. $userSession->listen('\OC\User', 'postLogin', function () {
  733. try {
  734. $cache = new \OC\Cache\File();
  735. $cache->gc();
  736. } catch (\OC\ServerNotAvailableException $e) {
  737. // not a GC exception, pass it on
  738. throw $e;
  739. } catch (\OC\ForbiddenException $e) {
  740. // filesystem blocked for this request, ignore
  741. } catch (\Exception $e) {
  742. // a GC exception should not prevent users from using OC,
  743. // so log the exception
  744. \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
  745. }
  746. });
  747. }
  748. }
  749. public static function registerSettingsHooks() {
  750. $dispatcher = \OC::$server->getEventDispatcher();
  751. $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
  752. /** @var \OCP\App\ManagerEvent $event */
  753. \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
  754. });
  755. $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
  756. /** @var \OCP\App\ManagerEvent $event */
  757. $jobList = \OC::$server->getJobList();
  758. $job = 'OC\\Settings\\RemoveOrphaned';
  759. if(!($jobList->has($job, null))) {
  760. $jobList->add($job);
  761. }
  762. });
  763. }
  764. private static function registerEncryptionWrapper() {
  765. $manager = self::$server->getEncryptionManager();
  766. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  767. }
  768. private static function registerEncryptionHooks() {
  769. $enabled = self::$server->getEncryptionManager()->isEnabled();
  770. if ($enabled) {
  771. \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
  772. \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
  773. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
  774. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
  775. }
  776. }
  777. private static function registerAccountHooks() {
  778. $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
  779. \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
  780. }
  781. /**
  782. * register hooks for the cache
  783. */
  784. public static function registerLogRotate() {
  785. $systemConfig = \OC::$server->getSystemConfig();
  786. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
  787. //don't try to do this before we are properly setup
  788. //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
  789. \OC::$server->getJobList()->add('OC\Log\Rotate');
  790. }
  791. }
  792. /**
  793. * register hooks for the filesystem
  794. */
  795. public static function registerFilesystemHooks() {
  796. // Check for blacklisted files
  797. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  798. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  799. }
  800. /**
  801. * register hooks for sharing
  802. */
  803. public static function registerShareHooks() {
  804. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  805. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
  806. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
  807. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
  808. }
  809. }
  810. protected static function registerAutoloaderCache() {
  811. // The class loader takes an optional low-latency cache, which MUST be
  812. // namespaced. The instanceid is used for namespacing, but might be
  813. // unavailable at this point. Furthermore, it might not be possible to
  814. // generate an instanceid via \OC_Util::getInstanceId() because the
  815. // config file may not be writable. As such, we only register a class
  816. // loader cache if instanceid is available without trying to create one.
  817. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  818. if ($instanceId) {
  819. try {
  820. $memcacheFactory = \OC::$server->getMemCacheFactory();
  821. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  822. } catch (\Exception $ex) {
  823. }
  824. }
  825. }
  826. /**
  827. * Handle the request
  828. */
  829. public static function handleRequest() {
  830. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  831. $systemConfig = \OC::$server->getSystemConfig();
  832. // load all the classpaths from the enabled apps so they are available
  833. // in the routing files of each app
  834. OC::loadAppClassPaths();
  835. // Check if Nextcloud is installed or in maintenance (update) mode
  836. if (!$systemConfig->getValue('installed', false)) {
  837. \OC::$server->getSession()->clear();
  838. $setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
  839. \OC::$server->getL10N('lib'), \OC::$server->query(\OCP\Defaults::class), \OC::$server->getLogger(),
  840. \OC::$server->getSecureRandom());
  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();
  852. self::checkUpgrade();
  853. }
  854. // emergency app disabling
  855. if ($requestPath === '/disableapp'
  856. && $request->getMethod() === 'POST'
  857. && ((array)$request->getParam('appid')) !== ''
  858. ) {
  859. \OCP\JSON::callCheck();
  860. \OCP\JSON::checkAdminUser();
  861. $appIds = (array)$request->getParam('appid');
  862. foreach($appIds as $appId) {
  863. $appId = \OC_App::cleanAppId($appId);
  864. \OC_App::disable($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 (!self::checkUpgrade(false)
  873. && !$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(array('filesystem', 'logging'));
  880. self::handleLogin($request);
  881. }
  882. }
  883. if (!self::$CLI) {
  884. try {
  885. if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
  886. OC_App::loadApps(array('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. OC_Response::setStatus(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. header('HTTP/1.1 405 Method Not Allowed');
  905. header('Status: 405 Method Not Allowed');
  906. return;
  907. }
  908. // Someone is logged in
  909. if (\OC::$server->getUserSession()->isLoggedIn()) {
  910. OC_App::loadApps();
  911. OC_User::setupBackends();
  912. OC_Util::setupFS();
  913. // FIXME
  914. // Redirect to default application
  915. OC_Util::redirectToDefaultPage();
  916. } else {
  917. // Not handled and not logged in
  918. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  919. }
  920. }
  921. /**
  922. * Check login: apache auth, auth token, basic auth
  923. *
  924. * @param OCP\IRequest $request
  925. * @return boolean
  926. */
  927. static function handleLogin(OCP\IRequest $request) {
  928. $userSession = self::$server->getUserSession();
  929. if (OC_User::handleApacheAuth()) {
  930. return true;
  931. }
  932. if ($userSession->tryTokenLogin($request)) {
  933. return true;
  934. }
  935. if (isset($_COOKIE['nc_username'])
  936. && isset($_COOKIE['nc_token'])
  937. && isset($_COOKIE['nc_session_id'])
  938. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  939. return true;
  940. }
  941. if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  942. return true;
  943. }
  944. return false;
  945. }
  946. protected static function handleAuthHeaders() {
  947. //copy http auth headers for apache+php-fcgid work around
  948. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  949. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  950. }
  951. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  952. $vars = array(
  953. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  954. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  955. );
  956. foreach ($vars as $var) {
  957. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  958. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  959. $_SERVER['PHP_AUTH_USER'] = $name;
  960. $_SERVER['PHP_AUTH_PW'] = $password;
  961. break;
  962. }
  963. }
  964. }
  965. }
  966. OC::init();