base.php 35 KB

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