base.php 36 KB

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