base.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  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. 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 '
  227. . '%sgiving the webserver write access to the config directory%s.',
  228. array('<a href="' . $urlGenerator->linkToDocs('admin-dir_permissions') . '" target="_blank" rel="noreferrer">', '</a>'))
  229. );
  230. }
  231. }
  232. }
  233. public static function checkInstalled() {
  234. if (defined('OC_CONSOLE')) {
  235. return;
  236. }
  237. // Redirect to installer if not installed
  238. if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
  239. if (OC::$CLI) {
  240. throw new Exception('Not installed');
  241. } else {
  242. $url = OC::$WEBROOT . '/index.php';
  243. header('Location: ' . $url);
  244. }
  245. exit();
  246. }
  247. }
  248. public static function checkMaintenanceMode() {
  249. // Allow ajax update script to execute without being stopped
  250. if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
  251. // send http status 503
  252. header('HTTP/1.1 503 Service Temporarily Unavailable');
  253. header('Status: 503 Service Temporarily Unavailable');
  254. header('Retry-After: 120');
  255. // render error page
  256. $template = new OC_Template('', 'update.user', 'guest');
  257. OC_Util::addScript('maintenance-check');
  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. $systemConfig = \OC::$server->getSystemConfig();
  270. if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
  271. self::printUpgradePage();
  272. exit();
  273. } else {
  274. return true;
  275. }
  276. }
  277. return false;
  278. }
  279. /**
  280. * Prints the upgrade page
  281. */
  282. private static function printUpgradePage() {
  283. $systemConfig = \OC::$server->getSystemConfig();
  284. $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
  285. $tooBig = false;
  286. if (!$disableWebUpdater) {
  287. $apps = \OC::$server->getAppManager();
  288. $tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth');
  289. if (!$tooBig) {
  290. // count users
  291. $stats = \OC::$server->getUserManager()->countUsers();
  292. $totalUsers = array_sum($stats);
  293. $tooBig = ($totalUsers > 50);
  294. }
  295. }
  296. if ($disableWebUpdater || $tooBig) {
  297. // send http status 503
  298. header('HTTP/1.1 503 Service Temporarily Unavailable');
  299. header('Status: 503 Service Temporarily Unavailable');
  300. header('Retry-After: 120');
  301. // render error page
  302. $template = new OC_Template('', 'update.use-cli', 'guest');
  303. $template->assign('productName', 'nextcloud'); // for now
  304. $template->assign('version', OC_Util::getVersionString());
  305. $template->assign('tooBig', $tooBig);
  306. $template->printPage();
  307. die();
  308. }
  309. // check whether this is a core update or apps update
  310. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  311. $currentVersion = implode('.', \OCP\Util::getVersion());
  312. // if not a core upgrade, then it's apps upgrade
  313. $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
  314. $oldTheme = $systemConfig->getValue('theme');
  315. $systemConfig->setValue('theme', '');
  316. OC_Util::addScript('config'); // needed for web root
  317. OC_Util::addScript('update');
  318. /** @var \OC\App\AppManager $appManager */
  319. $appManager = \OC::$server->getAppManager();
  320. $tmpl = new OC_Template('', 'update.admin', 'guest');
  321. $tmpl->assign('version', OC_Util::getVersionString());
  322. $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
  323. // get third party apps
  324. $ocVersion = \OCP\Util::getVersion();
  325. $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
  326. $incompatibleShippedApps = [];
  327. foreach ($incompatibleApps as $appInfo) {
  328. if ($appManager->isShipped($appInfo['id'])) {
  329. $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
  330. }
  331. }
  332. if (!empty($incompatibleShippedApps)) {
  333. $l = \OC::$server->getL10N('core');
  334. $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)]);
  335. 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);
  336. }
  337. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  338. $tmpl->assign('incompatibleAppsList', $incompatibleApps);
  339. $tmpl->assign('productName', 'Nextcloud'); // for now
  340. $tmpl->assign('oldTheme', $oldTheme);
  341. $tmpl->printPage();
  342. }
  343. public static function initSession() {
  344. // prevents javascript from accessing php session cookies
  345. ini_set('session.cookie_httponly', true);
  346. // set the cookie path to the Nextcloud directory
  347. $cookie_path = OC::$WEBROOT ? : '/';
  348. ini_set('session.cookie_path', $cookie_path);
  349. // Let the session name be changed in the initSession Hook
  350. $sessionName = OC_Util::getInstanceId();
  351. try {
  352. // Allow session apps to create a custom session object
  353. $useCustomSession = false;
  354. $session = self::$server->getSession();
  355. OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
  356. if (!$useCustomSession) {
  357. // set the session name to the instance id - which is unique
  358. $session = new \OC\Session\Internal($sessionName);
  359. }
  360. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  361. $session = $cryptoWrapper->wrapSession($session);
  362. self::$server->setSession($session);
  363. // if session can't be started break with http 500 error
  364. } catch (Exception $e) {
  365. \OCP\Util::logException('base', $e);
  366. //show the user a detailed error page
  367. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  368. OC_Template::printExceptionErrorPage($e);
  369. die();
  370. }
  371. $sessionLifeTime = self::getSessionLifeTime();
  372. // session timeout
  373. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  374. if (isset($_COOKIE[session_name()])) {
  375. setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
  376. }
  377. \OC::$server->getUserSession()->logout();
  378. }
  379. $session->set('LAST_ACTIVITY', time());
  380. }
  381. /**
  382. * @return string
  383. */
  384. private static function getSessionLifeTime() {
  385. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  386. }
  387. public static function loadAppClassPaths() {
  388. foreach (OC_App::getEnabledApps() as $app) {
  389. $appPath = OC_App::getAppPath($app);
  390. if ($appPath === false) {
  391. continue;
  392. }
  393. $file = $appPath . '/appinfo/classpath.php';
  394. if (file_exists($file)) {
  395. require_once $file;
  396. }
  397. }
  398. }
  399. /**
  400. * Try to set some values to the required Nextcloud default
  401. */
  402. public static function setRequiredIniValues() {
  403. @ini_set('default_charset', 'UTF-8');
  404. @ini_set('gd.jpeg_ignore_warning', 1);
  405. }
  406. /**
  407. * Send the same site cookies
  408. */
  409. private static function sendSameSiteCookies() {
  410. $cookieParams = session_get_cookie_params();
  411. $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
  412. $policies = [
  413. 'lax',
  414. 'strict',
  415. ];
  416. // Append __Host to the cookie if it meets the requirements
  417. $cookiePrefix = '';
  418. if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  419. $cookiePrefix = '__Host-';
  420. }
  421. foreach($policies as $policy) {
  422. header(
  423. sprintf(
  424. 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
  425. $cookiePrefix,
  426. $policy,
  427. $cookieParams['path'],
  428. $policy
  429. ),
  430. false
  431. );
  432. }
  433. }
  434. /**
  435. * Same Site cookie to further mitigate CSRF attacks. This cookie has to
  436. * be set in every request if cookies are sent to add a second level of
  437. * defense against CSRF.
  438. *
  439. * If the cookie is not sent this will set the cookie and reload the page.
  440. * We use an additional cookie since we want to protect logout CSRF and
  441. * also we can't directly interfere with PHP's session mechanism.
  442. */
  443. private static function performSameSiteCookieProtection() {
  444. $request = \OC::$server->getRequest();
  445. // Some user agents are notorious and don't really properly follow HTTP
  446. // specifications. For those, have an automated opt-out. Since the protection
  447. // for remote.php is applied in base.php as starting point we need to opt out
  448. // here.
  449. $incompatibleUserAgents = [
  450. // OS X Finder
  451. '/^WebDAVFS/',
  452. ];
  453. if($request->isUserAgent($incompatibleUserAgents)) {
  454. return;
  455. }
  456. if(count($_COOKIE) > 0) {
  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' || $currentUrl === '/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. if(!date_default_timezone_set('UTC')) {
  544. throw new \RuntimeException('Could not set timezone to UTC');
  545. };
  546. //try to configure php to enable big file uploads.
  547. //this doesn´t work always depending on the webserver and php configuration.
  548. //Let´s try to overwrite some defaults anyway
  549. //try to set the maximum execution time to 60min
  550. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  551. @set_time_limit(3600);
  552. }
  553. @ini_set('max_execution_time', 3600);
  554. @ini_set('max_input_time', 3600);
  555. //try to set the maximum filesize to 10G
  556. @ini_set('upload_max_filesize', '10G');
  557. @ini_set('post_max_size', '10G');
  558. @ini_set('file_uploads', '50');
  559. self::setRequiredIniValues();
  560. self::handleAuthHeaders();
  561. self::registerAutoloaderCache();
  562. // initialize intl fallback is necessary
  563. \Patchwork\Utf8\Bootup::initIntl();
  564. OC_Util::isSetLocaleWorking();
  565. if (!defined('PHPUNIT_RUN')) {
  566. OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
  567. $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
  568. OC\Log\ErrorHandler::register($debug);
  569. }
  570. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  571. OC_App::loadApps(array('session'));
  572. if (!self::$CLI) {
  573. self::initSession();
  574. }
  575. \OC::$server->getEventLogger()->end('init_session');
  576. self::checkConfig();
  577. self::checkInstalled();
  578. OC_Response::addSecurityHeaders();
  579. if(self::$server->getRequest()->getServerProtocol() === 'https') {
  580. ini_set('session.cookie_secure', true);
  581. }
  582. self::performSameSiteCookieProtection();
  583. if (!defined('OC_CONSOLE')) {
  584. $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
  585. if (count($errors) > 0) {
  586. if (self::$CLI) {
  587. // Convert l10n string into regular string for usage in database
  588. $staticErrors = [];
  589. foreach ($errors as $error) {
  590. echo $error['error'] . "\n";
  591. echo $error['hint'] . "\n\n";
  592. $staticErrors[] = [
  593. 'error' => (string)$error['error'],
  594. 'hint' => (string)$error['hint'],
  595. ];
  596. }
  597. try {
  598. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  599. } catch (\Exception $e) {
  600. echo('Writing to database failed');
  601. }
  602. exit(1);
  603. } else {
  604. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  605. OC_Util::addStyle('guest');
  606. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  607. exit;
  608. }
  609. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  610. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  611. }
  612. }
  613. //try to set the session lifetime
  614. $sessionLifeTime = self::getSessionLifeTime();
  615. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  616. $systemConfig = \OC::$server->getSystemConfig();
  617. // User and Groups
  618. if (!$systemConfig->getValue("installed", false)) {
  619. self::$server->getSession()->set('user_id', '');
  620. }
  621. OC_User::useBackend(new \OC\User\Database());
  622. \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
  623. // Subscribe to the hook
  624. \OCP\Util::connectHook(
  625. '\OCA\Files_Sharing\API\Server2Server',
  626. 'preLoginNameUsedAsUserName',
  627. '\OC\User\Database',
  628. 'preLoginNameUsedAsUserName'
  629. );
  630. //setup extra user backends
  631. if (!self::checkUpgrade(false)) {
  632. OC_User::setupBackends();
  633. } else {
  634. // Run upgrades in incognito mode
  635. OC_User::setIncognitoMode(true);
  636. }
  637. self::registerCacheHooks();
  638. self::registerFilesystemHooks();
  639. self::registerShareHooks();
  640. self::registerLogRotate();
  641. self::registerEncryptionWrapper();
  642. self::registerEncryptionHooks();
  643. self::registerAccountHooks();
  644. self::registerSettingsHooks();
  645. //make sure temporary files are cleaned up
  646. $tmpManager = \OC::$server->getTempManager();
  647. register_shutdown_function(array($tmpManager, 'clean'));
  648. $lockProvider = \OC::$server->getLockingProvider();
  649. register_shutdown_function(array($lockProvider, 'releaseAll'));
  650. // Check whether the sample configuration has been copied
  651. if($systemConfig->getValue('copied_sample_config', false)) {
  652. $l = \OC::$server->getL10N('lib');
  653. header('HTTP/1.1 503 Service Temporarily Unavailable');
  654. header('Status: 503 Service Temporarily Unavailable');
  655. OC_Template::printErrorPage(
  656. $l->t('Sample configuration detected'),
  657. $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')
  658. );
  659. return;
  660. }
  661. $request = \OC::$server->getRequest();
  662. $host = $request->getInsecureServerHost();
  663. /**
  664. * if the host passed in headers isn't trusted
  665. * FIXME: Should not be in here at all :see_no_evil:
  666. */
  667. if (!OC::$CLI
  668. // overwritehost is always trusted, workaround to not have to make
  669. // \OC\AppFramework\Http\Request::getOverwriteHost public
  670. && self::$server->getConfig()->getSystemValue('overwritehost') === ''
  671. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  672. && self::$server->getConfig()->getSystemValue('installed', false)
  673. ) {
  674. // Allow access to CSS resources
  675. $isScssRequest = false;
  676. if(strpos($request->getPathInfo(), '/css/') === 0) {
  677. $isScssRequest = true;
  678. }
  679. if (!$isScssRequest) {
  680. header('HTTP/1.1 400 Bad Request');
  681. header('Status: 400 Bad Request');
  682. \OC::$server->getLogger()->warning(
  683. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  684. [
  685. 'app' => 'core',
  686. 'remoteAddress' => $request->getRemoteAddress(),
  687. 'host' => $host,
  688. ]
  689. );
  690. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  691. $tmpl->assign('domain', $host);
  692. $tmpl->printPage();
  693. exit();
  694. }
  695. }
  696. \OC::$server->getEventLogger()->end('boot');
  697. }
  698. /**
  699. * register hooks for the cache
  700. */
  701. public static function registerCacheHooks() {
  702. //don't try to do this before we are properly setup
  703. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
  704. // NOTE: This will be replaced to use OCP
  705. $userSession = self::$server->getUserSession();
  706. $userSession->listen('\OC\User', 'postLogin', function () {
  707. try {
  708. $cache = new \OC\Cache\File();
  709. $cache->gc();
  710. } catch (\OC\ServerNotAvailableException $e) {
  711. // not a GC exception, pass it on
  712. throw $e;
  713. } catch (\Exception $e) {
  714. // a GC exception should not prevent users from using OC,
  715. // so log the exception
  716. \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
  717. }
  718. });
  719. }
  720. }
  721. public static function registerSettingsHooks() {
  722. $dispatcher = \OC::$server->getEventDispatcher();
  723. $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
  724. /** @var \OCP\App\ManagerEvent $event */
  725. \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
  726. });
  727. $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
  728. /** @var \OCP\App\ManagerEvent $event */
  729. $jobList = \OC::$server->getJobList();
  730. $job = 'OC\\Settings\\RemoveOrphaned';
  731. if(!($jobList->has($job, null))) {
  732. $jobList->add($job);
  733. }
  734. });
  735. }
  736. private static function registerEncryptionWrapper() {
  737. $manager = self::$server->getEncryptionManager();
  738. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  739. }
  740. private static function registerEncryptionHooks() {
  741. $enabled = self::$server->getEncryptionManager()->isEnabled();
  742. if ($enabled) {
  743. \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
  744. \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
  745. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
  746. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
  747. }
  748. }
  749. private static function registerAccountHooks() {
  750. $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
  751. \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
  752. }
  753. /**
  754. * register hooks for the cache
  755. */
  756. public static function registerLogRotate() {
  757. $systemConfig = \OC::$server->getSystemConfig();
  758. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
  759. //don't try to do this before we are properly setup
  760. //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
  761. \OC::$server->getJobList()->add('OC\Log\Rotate');
  762. }
  763. }
  764. /**
  765. * register hooks for the filesystem
  766. */
  767. public static function registerFilesystemHooks() {
  768. // Check for blacklisted files
  769. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  770. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  771. }
  772. /**
  773. * register hooks for sharing
  774. */
  775. public static function registerShareHooks() {
  776. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  777. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
  778. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
  779. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
  780. }
  781. }
  782. protected static function registerAutoloaderCache() {
  783. // The class loader takes an optional low-latency cache, which MUST be
  784. // namespaced. The instanceid is used for namespacing, but might be
  785. // unavailable at this point. Furthermore, it might not be possible to
  786. // generate an instanceid via \OC_Util::getInstanceId() because the
  787. // config file may not be writable. As such, we only register a class
  788. // loader cache if instanceid is available without trying to create one.
  789. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  790. if ($instanceId) {
  791. try {
  792. $memcacheFactory = \OC::$server->getMemCacheFactory();
  793. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  794. } catch (\Exception $ex) {
  795. }
  796. }
  797. }
  798. /**
  799. * Handle the request
  800. */
  801. public static function handleRequest() {
  802. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  803. $systemConfig = \OC::$server->getSystemConfig();
  804. // load all the classpaths from the enabled apps so they are available
  805. // in the routing files of each app
  806. OC::loadAppClassPaths();
  807. // Check if Nextcloud is installed or in maintenance (update) mode
  808. if (!$systemConfig->getValue('installed', false)) {
  809. \OC::$server->getSession()->clear();
  810. $setupHelper = new OC\Setup(\OC::$server->getSystemConfig(), \OC::$server->getIniWrapper(),
  811. \OC::$server->getL10N('lib'), \OC::$server->getThemingDefaults(), \OC::$server->getLogger(),
  812. \OC::$server->getSecureRandom());
  813. $controller = new OC\Core\Controller\SetupController($setupHelper);
  814. $controller->run($_POST);
  815. exit();
  816. }
  817. $request = \OC::$server->getRequest();
  818. $requestPath = $request->getRawPathInfo();
  819. if ($requestPath === '/heartbeat') {
  820. return;
  821. }
  822. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  823. self::checkMaintenanceMode();
  824. self::checkUpgrade();
  825. }
  826. // emergency app disabling
  827. if ($requestPath === '/disableapp'
  828. && $request->getMethod() === 'POST'
  829. && ((string)$request->getParam('appid')) !== ''
  830. ) {
  831. \OCP\JSON::callCheck();
  832. \OCP\JSON::checkAdminUser();
  833. $appId = (string)$request->getParam('appid');
  834. $appId = \OC_App::cleanAppId($appId);
  835. \OC_App::disable($appId);
  836. \OC_JSON::success();
  837. exit();
  838. }
  839. // Always load authentication apps
  840. OC_App::loadApps(['authentication']);
  841. // Load minimum set of apps
  842. if (!self::checkUpgrade(false)
  843. && !$systemConfig->getValue('maintenance', false)) {
  844. // For logged-in users: Load everything
  845. if(\OC::$server->getUserSession()->isLoggedIn()) {
  846. OC_App::loadApps();
  847. } else {
  848. // For guests: Load only filesystem and logging
  849. OC_App::loadApps(array('filesystem', 'logging'));
  850. self::handleLogin($request);
  851. }
  852. }
  853. if (!self::$CLI) {
  854. try {
  855. if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
  856. OC_App::loadApps(array('filesystem', 'logging'));
  857. OC_App::loadApps();
  858. }
  859. OC_Util::setupFS();
  860. OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
  861. return;
  862. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  863. //header('HTTP/1.0 404 Not Found');
  864. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  865. OC_Response::setStatus(405);
  866. return;
  867. }
  868. }
  869. // Handle WebDAV
  870. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  871. // not allowed any more to prevent people
  872. // mounting this root directly.
  873. // Users need to mount remote.php/webdav instead.
  874. header('HTTP/1.1 405 Method Not Allowed');
  875. header('Status: 405 Method Not Allowed');
  876. return;
  877. }
  878. // Someone is logged in
  879. if (\OC::$server->getUserSession()->isLoggedIn()) {
  880. OC_App::loadApps();
  881. OC_User::setupBackends();
  882. OC_Util::setupFS();
  883. // FIXME
  884. // Redirect to default application
  885. OC_Util::redirectToDefaultPage();
  886. } else {
  887. // Not handled and not logged in
  888. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  889. }
  890. }
  891. /**
  892. * Check login: apache auth, auth token, basic auth
  893. *
  894. * @param OCP\IRequest $request
  895. * @return boolean
  896. */
  897. static function handleLogin(OCP\IRequest $request) {
  898. $userSession = self::$server->getUserSession();
  899. if (OC_User::handleApacheAuth()) {
  900. return true;
  901. }
  902. if ($userSession->tryTokenLogin($request)) {
  903. return true;
  904. }
  905. if (isset($_COOKIE['nc_username'])
  906. && isset($_COOKIE['nc_token'])
  907. && isset($_COOKIE['nc_session_id'])
  908. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  909. return true;
  910. }
  911. if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  912. return true;
  913. }
  914. return false;
  915. }
  916. protected static function handleAuthHeaders() {
  917. //copy http auth headers for apache+php-fcgid work around
  918. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  919. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  920. }
  921. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  922. $vars = array(
  923. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  924. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  925. );
  926. foreach ($vars as $var) {
  927. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  928. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  929. $_SERVER['PHP_AUTH_USER'] = $name;
  930. $_SERVER['PHP_AUTH_PW'] = $password;
  931. break;
  932. }
  933. }
  934. }
  935. }
  936. OC::init();