base.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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 instantiiate
  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($_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. OC::$SERVERROOT . '/lib/private' . PATH_SEPARATOR .
  203. self::$configDir . PATH_SEPARATOR .
  204. OC::$SERVERROOT . '/3rdparty' . PATH_SEPARATOR .
  205. implode(PATH_SEPARATOR, $paths) . PATH_SEPARATOR .
  206. get_include_path() . PATH_SEPARATOR .
  207. OC::$SERVERROOT
  208. );
  209. }
  210. public static function checkConfig() {
  211. $l = \OC::$server->getL10N('lib');
  212. // Create config if it does not already exist
  213. $configFilePath = self::$configDir .'/config.php';
  214. if(!file_exists($configFilePath)) {
  215. @touch($configFilePath);
  216. }
  217. // Check if config is writable
  218. $configFileWritable = is_writable($configFilePath);
  219. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  220. || !$configFileWritable && self::checkUpgrade(false)) {
  221. $urlGenerator = \OC::$server->getURLGenerator();
  222. if (self::$CLI) {
  223. echo $l->t('Cannot write into "config" directory!')."\n";
  224. echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
  225. echo "\n";
  226. echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
  227. exit;
  228. } else {
  229. OC_Template::printErrorPage(
  230. $l->t('Cannot write into "config" directory!'),
  231. $l->t('This can usually be fixed by '
  232. . '%sgiving the webserver write access to the config directory%s.',
  233. array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
  234. );
  235. }
  236. }
  237. }
  238. public static function checkInstalled() {
  239. if (defined('OC_CONSOLE')) {
  240. return;
  241. }
  242. // Redirect to installer if not installed
  243. if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI != '/index.php') {
  244. if (OC::$CLI) {
  245. throw new Exception('Not installed');
  246. } else {
  247. $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
  248. header('Location: ' . $url);
  249. }
  250. exit();
  251. }
  252. }
  253. public static function checkMaintenanceMode() {
  254. // Allow ajax update script to execute without being stopped
  255. if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
  256. // send http status 503
  257. header('HTTP/1.1 503 Service Temporarily Unavailable');
  258. header('Status: 503 Service Temporarily Unavailable');
  259. header('Retry-After: 120');
  260. // render error page
  261. $template = new OC_Template('', 'update.user', 'guest');
  262. OC_Util::addScript('maintenance-check');
  263. $template->printPage();
  264. die();
  265. }
  266. }
  267. public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
  268. if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) {
  269. return;
  270. }
  271. $user = OC_User::getUserSession()->getUser();
  272. if ($user) {
  273. $group = \OC::$server->getGroupManager()->get('admin');
  274. if ($group->inGroup($user)) {
  275. return;
  276. }
  277. } else {
  278. if(!$lockIfNoUserLoggedIn) {
  279. return;
  280. }
  281. }
  282. // send http status 503
  283. header('HTTP/1.1 503 Service Temporarily Unavailable');
  284. header('Status: 503 Service Temporarily Unavailable');
  285. header('Retry-After: 120');
  286. // render error page
  287. $template = new OC_Template('', 'singleuser.user', 'guest');
  288. $template->printPage();
  289. die();
  290. }
  291. /**
  292. * Checks if the version requires an update and shows
  293. * @param bool $showTemplate Whether an update screen should get shown
  294. * @return bool|void
  295. */
  296. public static function checkUpgrade($showTemplate = true) {
  297. if (\OCP\Util::needUpgrade()) {
  298. $systemConfig = \OC::$server->getSystemConfig();
  299. if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
  300. self::printUpgradePage();
  301. exit();
  302. } else {
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. /**
  309. * Prints the upgrade page
  310. */
  311. private static function printUpgradePage() {
  312. $systemConfig = \OC::$server->getSystemConfig();
  313. $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
  314. $tooBig = false;
  315. if (!$disableWebUpdater) {
  316. $apps = \OC::$server->getAppManager();
  317. $tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth');
  318. if (!$tooBig) {
  319. // count users
  320. $stats = \OC::$server->getUserManager()->countUsers();
  321. $totalUsers = array_sum($stats);
  322. $tooBig = ($totalUsers > 50);
  323. }
  324. }
  325. if ($disableWebUpdater || $tooBig) {
  326. // send http status 503
  327. header('HTTP/1.1 503 Service Temporarily Unavailable');
  328. header('Status: 503 Service Temporarily Unavailable');
  329. header('Retry-After: 120');
  330. // render error page
  331. $template = new OC_Template('', 'update.use-cli', 'guest');
  332. $template->assign('productName', 'nextcloud'); // for now
  333. $template->assign('version', OC_Util::getVersionString());
  334. $template->assign('tooBig', $tooBig);
  335. $template->printPage();
  336. die();
  337. }
  338. // check whether this is a core update or apps update
  339. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  340. $currentVersion = implode('.', \OCP\Util::getVersion());
  341. // if not a core upgrade, then it's apps upgrade
  342. $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
  343. $oldTheme = $systemConfig->getValue('theme');
  344. $systemConfig->setValue('theme', '');
  345. \OCP\Util::addScript('config'); // needed for web root
  346. \OCP\Util::addScript('update');
  347. \OCP\Util::addStyle('update');
  348. $appManager = \OC::$server->getAppManager();
  349. $tmpl = new OC_Template('', 'update.admin', 'guest');
  350. $tmpl->assign('version', OC_Util::getVersionString());
  351. $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
  352. // get third party apps
  353. $ocVersion = \OCP\Util::getVersion();
  354. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  355. $tmpl->assign('incompatibleAppsList', $appManager->getIncompatibleApps($ocVersion));
  356. $tmpl->assign('productName', 'Nextcloud'); // for now
  357. $tmpl->assign('oldTheme', $oldTheme);
  358. $tmpl->printPage();
  359. }
  360. public static function initSession() {
  361. // prevents javascript from accessing php session cookies
  362. ini_set('session.cookie_httponly', true);
  363. // set the cookie path to the Nextcloud directory
  364. $cookie_path = OC::$WEBROOT ? : '/';
  365. ini_set('session.cookie_path', $cookie_path);
  366. // Let the session name be changed in the initSession Hook
  367. $sessionName = OC_Util::getInstanceId();
  368. try {
  369. // Allow session apps to create a custom session object
  370. $useCustomSession = false;
  371. $session = self::$server->getSession();
  372. OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
  373. if (!$useCustomSession) {
  374. // set the session name to the instance id - which is unique
  375. $session = new \OC\Session\Internal($sessionName);
  376. }
  377. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  378. $session = $cryptoWrapper->wrapSession($session);
  379. self::$server->setSession($session);
  380. // if session can't be started break with http 500 error
  381. } catch (Exception $e) {
  382. \OCP\Util::logException('base', $e);
  383. //show the user a detailed error page
  384. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  385. OC_Template::printExceptionErrorPage($e);
  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(), null, -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. public static function loadAppClassPaths() {
  405. foreach (OC_App::getEnabledApps() as $app) {
  406. $appPath = OC_App::getAppPath($app);
  407. if ($appPath === false) {
  408. continue;
  409. }
  410. $file = $appPath . '/appinfo/classpath.php';
  411. if (file_exists($file)) {
  412. require_once $file;
  413. }
  414. }
  415. }
  416. /**
  417. * Try to set some values to the required Nextcloud default
  418. */
  419. public static function setRequiredIniValues() {
  420. @ini_set('default_charset', 'UTF-8');
  421. @ini_set('gd.jpeg_ignore_warning', 1);
  422. }
  423. /**
  424. * Send the same site cookies
  425. */
  426. private static function sendSameSiteCookies() {
  427. $cookieParams = session_get_cookie_params();
  428. $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
  429. $policies = [
  430. 'lax',
  431. 'strict',
  432. ];
  433. foreach($policies as $policy) {
  434. header(
  435. sprintf(
  436. 'Set-Cookie: nc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
  437. $policy,
  438. $cookieParams['path'],
  439. $policy
  440. ),
  441. false
  442. );
  443. }
  444. }
  445. /**
  446. * Same Site cookie to further mitigate CSRF attacks. This cookie has to
  447. * be set in every request if cookies are sent to add a second level of
  448. * defense against CSRF.
  449. *
  450. * If the cookie is not sent this will set the cookie and reload the page.
  451. * We use an additional cookie since we want to protect logout CSRF and
  452. * also we can't directly interfere with PHP's session mechanism.
  453. */
  454. private static function performSameSiteCookieProtection() {
  455. if(count($_COOKIE) > 0) {
  456. $request = \OC::$server->getRequest();
  457. $requestUri = $request->getScriptName();
  458. $processingScript = explode('/', $requestUri);
  459. $processingScript = $processingScript[count($processingScript)-1];
  460. // FIXME: In a SAML scenario we don't get any strict or lax cookie
  461. // send for the ACS endpoint. Since we have some legacy code in Nextcloud
  462. // (direct PHP files) the enforcement of lax cookies is performed here
  463. // instead of the middleware.
  464. //
  465. // This means we cannot exclude some routes from the cookie validation,
  466. // which normally is not a problem but is a little bit cumbersome for
  467. // this use-case.
  468. // Once the old legacy PHP endpoints have been removed we can move
  469. // the verification into a middleware and also adds some exemptions.
  470. //
  471. // Questions about this code? Ask Lukas ;-)
  472. $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
  473. if($currentUrl === '/index.php/apps/user_saml/saml/acs') {
  474. return;
  475. }
  476. // For the "index.php" endpoint only a lax cookie is required.
  477. if($processingScript === 'index.php') {
  478. if(!$request->passesLaxCookieCheck()) {
  479. self::sendSameSiteCookies();
  480. header('Location: '.$_SERVER['REQUEST_URI']);
  481. exit();
  482. }
  483. } else {
  484. // All other endpoints require the lax and the strict cookie
  485. if(!$request->passesStrictCookieCheck()) {
  486. self::sendSameSiteCookies();
  487. // Debug mode gets access to the resources without strict cookie
  488. // due to the fact that the SabreDAV browser also lives there.
  489. if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
  490. http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
  491. exit();
  492. }
  493. }
  494. }
  495. } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
  496. self::sendSameSiteCookies();
  497. }
  498. }
  499. public static function init() {
  500. // calculate the root directories
  501. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  502. // register autoloader
  503. $loaderStart = microtime(true);
  504. require_once __DIR__ . '/autoloader.php';
  505. self::$loader = new \OC\Autoloader([
  506. OC::$SERVERROOT . '/lib/private/legacy',
  507. ]);
  508. if (defined('PHPUNIT_RUN')) {
  509. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  510. }
  511. spl_autoload_register(array(self::$loader, 'load'));
  512. $loaderEnd = microtime(true);
  513. self::$CLI = (php_sapi_name() == 'cli');
  514. // Add default composer PSR-4 autoloader
  515. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  516. try {
  517. self::initPaths();
  518. // setup 3rdparty autoloader
  519. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  520. if (!file_exists($vendorAutoLoad)) {
  521. 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".');
  522. }
  523. require_once $vendorAutoLoad;
  524. } catch (\RuntimeException $e) {
  525. if (!self::$CLI) {
  526. $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
  527. $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
  528. header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
  529. }
  530. // we can't use the template error page here, because this needs the
  531. // DI container which isn't available yet
  532. print($e->getMessage());
  533. exit();
  534. }
  535. // setup the basic server
  536. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  537. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  538. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  539. // Don't display errors and log them
  540. error_reporting(E_ALL | E_STRICT);
  541. @ini_set('display_errors', 0);
  542. @ini_set('log_errors', 1);
  543. date_default_timezone_set('UTC');
  544. //try to configure php to enable big file uploads.
  545. //this doesn´t work always depending on the webserver and php configuration.
  546. //Let´s try to overwrite some defaults anyway
  547. //try to set the maximum execution time to 60min
  548. @set_time_limit(3600);
  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. // register the stream wrappers
  567. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  568. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  569. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  570. stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
  571. stream_wrapper_register('oc', 'OC\Files\Stream\OC');
  572. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  573. OC_App::loadApps(array('session'));
  574. if (!self::$CLI) {
  575. self::initSession();
  576. }
  577. \OC::$server->getEventLogger()->end('init_session');
  578. self::checkConfig();
  579. self::checkInstalled();
  580. OC_Response::addSecurityHeaders();
  581. if(self::$server->getRequest()->getServerProtocol() === 'https') {
  582. ini_set('session.cookie_secure', true);
  583. }
  584. self::performSameSiteCookieProtection();
  585. if (!defined('OC_CONSOLE')) {
  586. $errors = OC_Util::checkServer(\OC::$server->getConfig());
  587. if (count($errors) > 0) {
  588. if (self::$CLI) {
  589. // Convert l10n string into regular string for usage in database
  590. $staticErrors = [];
  591. foreach ($errors as $error) {
  592. echo $error['error'] . "\n";
  593. echo $error['hint'] . "\n\n";
  594. $staticErrors[] = [
  595. 'error' => (string)$error['error'],
  596. 'hint' => (string)$error['hint'],
  597. ];
  598. }
  599. try {
  600. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  601. } catch (\Exception $e) {
  602. echo('Writing to database failed');
  603. }
  604. exit(1);
  605. } else {
  606. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  607. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  608. exit;
  609. }
  610. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  611. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  612. }
  613. }
  614. //try to set the session lifetime
  615. $sessionLifeTime = self::getSessionLifeTime();
  616. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  617. $systemConfig = \OC::$server->getSystemConfig();
  618. // User and Groups
  619. if (!$systemConfig->getValue("installed", false)) {
  620. self::$server->getSession()->set('user_id', '');
  621. }
  622. OC_User::useBackend(new \OC\User\Database());
  623. OC_Group::useBackend(new \OC\Group\Database());
  624. // Subscribe to the hook
  625. \OCP\Util::connectHook(
  626. '\OCA\Files_Sharing\API\Server2Server',
  627. 'preLoginNameUsedAsUserName',
  628. '\OC\User\Database',
  629. 'preLoginNameUsedAsUserName'
  630. );
  631. //setup extra user backends
  632. if (!self::checkUpgrade(false)) {
  633. OC_User::setupBackends();
  634. } else {
  635. // Run upgrades in incognito mode
  636. OC_User::setIncognitoMode(true);
  637. }
  638. self::registerCacheHooks();
  639. self::registerFilesystemHooks();
  640. if ($systemConfig->getValue('enable_previews', true)) {
  641. self::registerPreviewHooks();
  642. }
  643. self::registerShareHooks();
  644. self::registerLogRotate();
  645. self::registerEncryptionWrapper();
  646. self::registerEncryptionHooks();
  647. self::registerSettingsHooks();
  648. //make sure temporary files are cleaned up
  649. $tmpManager = \OC::$server->getTempManager();
  650. register_shutdown_function(array($tmpManager, 'clean'));
  651. $lockProvider = \OC::$server->getLockingProvider();
  652. register_shutdown_function(array($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. header('HTTP/1.1 503 Service Temporarily Unavailable');
  657. header('Status: 503 Service Temporarily Unavailable');
  658. OC_Template::printErrorPage(
  659. $l->t('Sample configuration detected'),
  660. $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')
  661. );
  662. return;
  663. }
  664. $request = \OC::$server->getRequest();
  665. $host = $request->getInsecureServerHost();
  666. /**
  667. * if the host passed in headers isn't trusted
  668. * FIXME: Should not be in here at all :see_no_evil:
  669. */
  670. if (!OC::$CLI
  671. // overwritehost is always trusted, workaround to not have to make
  672. // \OC\AppFramework\Http\Request::getOverwriteHost public
  673. && self::$server->getConfig()->getSystemValue('overwritehost') === ''
  674. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  675. && self::$server->getConfig()->getSystemValue('installed', false)
  676. ) {
  677. header('HTTP/1.1 400 Bad Request');
  678. header('Status: 400 Bad Request');
  679. \OC::$server->getLogger()->warning(
  680. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  681. [
  682. 'app' => 'core',
  683. 'remoteAddress' => $request->getRemoteAddress(),
  684. 'host' => $host,
  685. ]
  686. );
  687. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  688. $tmpl->assign('domain', $host);
  689. $tmpl->printPage();
  690. exit();
  691. }
  692. \OC::$server->getEventLogger()->end('boot');
  693. }
  694. /**
  695. * register hooks for the cache
  696. */
  697. public static function registerCacheHooks() {
  698. //don't try to do this before we are properly setup
  699. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
  700. // NOTE: This will be replaced to use OCP
  701. $userSession = self::$server->getUserSession();
  702. $userSession->listen('\OC\User', 'postLogin', function () {
  703. try {
  704. $cache = new \OC\Cache\File();
  705. $cache->gc();
  706. } catch (\OC\ServerNotAvailableException $e) {
  707. // not a GC exception, pass it on
  708. throw $e;
  709. } catch (\Exception $e) {
  710. // a GC exception should not prevent users from using OC,
  711. // so log the exception
  712. \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
  713. }
  714. });
  715. }
  716. }
  717. public static function registerSettingsHooks() {
  718. $dispatcher = \OC::$server->getEventDispatcher();
  719. $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
  720. /** @var \OCP\App\ManagerEvent $event */
  721. \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
  722. });
  723. $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
  724. /** @var \OCP\App\ManagerEvent $event */
  725. $jobList = \OC::$server->getJobList();
  726. $job = 'OC\\Settings\\RemoveOrphaned';
  727. if(!($jobList->has($job, null))) {
  728. $jobList->add($job);
  729. }
  730. });
  731. }
  732. private static function registerEncryptionWrapper() {
  733. $manager = self::$server->getEncryptionManager();
  734. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  735. }
  736. private static function registerEncryptionHooks() {
  737. $enabled = self::$server->getEncryptionManager()->isEnabled();
  738. if ($enabled) {
  739. \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
  740. \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
  741. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
  742. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
  743. }
  744. }
  745. /**
  746. * register hooks for the cache
  747. */
  748. public static function registerLogRotate() {
  749. $systemConfig = \OC::$server->getSystemConfig();
  750. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
  751. //don't try to do this before we are properly setup
  752. //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
  753. \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/nextcloud.log'));
  754. }
  755. }
  756. /**
  757. * register hooks for the filesystem
  758. */
  759. public static function registerFilesystemHooks() {
  760. // Check for blacklisted files
  761. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  762. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  763. }
  764. /**
  765. * register hooks for previews
  766. */
  767. public static function registerPreviewHooks() {
  768. OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
  769. OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
  770. OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
  771. OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
  772. OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
  773. OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
  774. OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
  775. OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
  776. }
  777. /**
  778. * register hooks for sharing
  779. */
  780. public static function registerShareHooks() {
  781. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  782. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
  783. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
  784. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
  785. }
  786. }
  787. protected static function registerAutoloaderCache() {
  788. // The class loader takes an optional low-latency cache, which MUST be
  789. // namespaced. The instanceid is used for namespacing, but might be
  790. // unavailable at this point. Furthermore, it might not be possible to
  791. // generate an instanceid via \OC_Util::getInstanceId() because the
  792. // config file may not be writable. As such, we only register a class
  793. // loader cache if instanceid is available without trying to create one.
  794. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  795. if ($instanceId) {
  796. try {
  797. $memcacheFactory = \OC::$server->getMemCacheFactory();
  798. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  799. } catch (\Exception $ex) {
  800. }
  801. }
  802. }
  803. /**
  804. * Handle the request
  805. */
  806. public static function handleRequest() {
  807. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  808. $systemConfig = \OC::$server->getSystemConfig();
  809. // load all the classpaths from the enabled apps so they are available
  810. // in the routing files of each app
  811. OC::loadAppClassPaths();
  812. // Check if Nextcloud is installed or in maintenance (update) mode
  813. if (!$systemConfig->getValue('installed', false)) {
  814. \OC::$server->getSession()->clear();
  815. $setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
  816. \OC::$server->getL10N('lib'), \OC::$server->getThemingDefaults(), \OC::$server->getLogger(),
  817. \OC::$server->getSecureRandom());
  818. $controller = new OC\Core\Controller\SetupController($setupHelper);
  819. $controller->run($_POST);
  820. exit();
  821. }
  822. $request = \OC::$server->getRequest();
  823. $requestPath = $request->getRawPathInfo();
  824. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  825. self::checkMaintenanceMode();
  826. self::checkUpgrade();
  827. }
  828. // emergency app disabling
  829. if ($requestPath === '/disableapp'
  830. && $request->getMethod() === 'POST'
  831. && ((string)$request->getParam('appid')) !== ''
  832. ) {
  833. \OCP\JSON::callCheck();
  834. \OCP\JSON::checkAdminUser();
  835. $appId = (string)$request->getParam('appid');
  836. $appId = \OC_App::cleanAppId($appId);
  837. \OC_App::disable($appId);
  838. \OC_JSON::success();
  839. exit();
  840. }
  841. // Always load authentication apps
  842. OC_App::loadApps(['authentication']);
  843. // Load minimum set of apps
  844. if (!self::checkUpgrade(false)
  845. && !$systemConfig->getValue('maintenance', false)) {
  846. // For logged-in users: Load everything
  847. if(OC_User::isLoggedIn()) {
  848. OC_App::loadApps();
  849. } else {
  850. // For guests: Load only filesystem and logging
  851. OC_App::loadApps(array('filesystem', 'logging'));
  852. self::handleLogin($request);
  853. }
  854. }
  855. if (!self::$CLI) {
  856. try {
  857. if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
  858. OC_App::loadApps(array('filesystem', 'logging'));
  859. OC_App::loadApps();
  860. }
  861. self::checkSingleUserMode();
  862. OC_Util::setupFS();
  863. OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
  864. return;
  865. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  866. //header('HTTP/1.0 404 Not Found');
  867. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  868. OC_Response::setStatus(405);
  869. return;
  870. }
  871. }
  872. // Handle WebDAV
  873. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  874. // not allowed any more to prevent people
  875. // mounting this root directly.
  876. // Users need to mount remote.php/webdav instead.
  877. header('HTTP/1.1 405 Method Not Allowed');
  878. header('Status: 405 Method Not Allowed');
  879. return;
  880. }
  881. // Someone is logged in
  882. if (OC_User::isLoggedIn()) {
  883. OC_App::loadApps();
  884. OC_User::setupBackends();
  885. OC_Util::setupFS();
  886. // FIXME
  887. // Redirect to default application
  888. OC_Util::redirectToDefaultPage();
  889. } else {
  890. // Not handled and not logged in
  891. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  892. }
  893. }
  894. /**
  895. * Check login: apache auth, auth token, basic auth
  896. *
  897. * @param OCP\IRequest $request
  898. * @return boolean
  899. */
  900. static function handleLogin(OCP\IRequest $request) {
  901. $userSession = self::$server->getUserSession();
  902. if (OC_User::handleApacheAuth()) {
  903. return true;
  904. }
  905. if ($userSession->tryTokenLogin($request)) {
  906. return true;
  907. }
  908. if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  909. return true;
  910. }
  911. return false;
  912. }
  913. protected static function handleAuthHeaders() {
  914. //copy http auth headers for apache+php-fcgid work around
  915. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  916. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  917. }
  918. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  919. $vars = array(
  920. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  921. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  922. );
  923. foreach ($vars as $var) {
  924. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  925. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  926. $_SERVER['PHP_AUTH_USER'] = $name;
  927. $_SERVER['PHP_AUTH_PW'] = $password;
  928. break;
  929. }
  930. }
  931. }
  932. }
  933. OC::init();