base.php 36 KB

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