base.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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 Daniel Kesselberg <mail@danielkesselberg.de>
  15. * @author davidgumberg <davidnoizgumberg@gmail.com>
  16. * @author Eric Masseran <rico.masseran@gmail.com>
  17. * @author Florin Peter <github@florin-peter.de>
  18. * @author Greta Doci <gretadoci@gmail.com>
  19. * @author Jakob Sack <mail@jakobsack.de>
  20. * @author jaltek <jaltek@mailbox.org>
  21. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  22. * @author Joachim Sokolowski <github@sokolowski.org>
  23. * @author Joas Schilling <coding@schilljs.com>
  24. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  25. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  26. * @author Jose Quinteiro <github@quinteiro.org>
  27. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  28. * @author Julius Härtl <jus@bitgrid.net>
  29. * @author Ko- <k.stoffelen@cs.ru.nl>
  30. * @author Lukas Reschke <lukas@statuscode.ch>
  31. * @author MartB <mart.b@outlook.de>
  32. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  33. * @author Morris Jobke <hey@morrisjobke.de>
  34. * @author Owen Winkler <a_github@midnightcircus.com>
  35. * @author Phil Davis <phil.davis@inf.org>
  36. * @author Ramiro Aparicio <rapariciog@gmail.com>
  37. * @author Robin Appelman <robin@icewind.nl>
  38. * @author Robin McCorkell <robin@mccorkell.me.uk>
  39. * @author Roeland Jago Douma <roeland@famdouma.nl>
  40. * @author Sebastian Wessalowski <sebastian@wessalowski.org>
  41. * @author Stefan Weil <sw@weilnetz.de>
  42. * @author Thomas Müller <thomas.mueller@tmit.eu>
  43. * @author Thomas Tanghus <thomas@tanghus.net>
  44. * @author Tobia De Koninck <tobia@ledfan.be>
  45. * @author Vincent Petry <pvince81@owncloud.com>
  46. * @author Volkan Gezer <volkangezer@gmail.com>
  47. *
  48. * @license AGPL-3.0
  49. *
  50. * This code is free software: you can redistribute it and/or modify
  51. * it under the terms of the GNU Affero General Public License, version 3,
  52. * as published by the Free Software Foundation.
  53. *
  54. * This program is distributed in the hope that it will be useful,
  55. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  56. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  57. * GNU Affero General Public License for more details.
  58. *
  59. * You should have received a copy of the GNU Affero General Public License, version 3,
  60. * along with this program. If not, see <http://www.gnu.org/licenses/>
  61. *
  62. */
  63. use OCP\ILogger;
  64. use OCP\Share;
  65. use OC\Encryption\HookManager;
  66. use OC\Files\Filesystem;
  67. use OC\Share20\Hooks;
  68. require_once 'public/Constants.php';
  69. /**
  70. * Class that is a namespace for all global OC variables
  71. * No, we can not put this class in its own file because it is used by
  72. * OC_autoload!
  73. */
  74. class OC {
  75. /**
  76. * Associative array for autoloading. classname => filename
  77. */
  78. public static $CLASSPATH = [];
  79. /**
  80. * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud)
  81. */
  82. public static $SERVERROOT = '';
  83. /**
  84. * the current request path relative to the Nextcloud root (e.g. files/index.php)
  85. */
  86. private static $SUBURI = '';
  87. /**
  88. * the Nextcloud root path for http requests (e.g. nextcloud/)
  89. */
  90. public static $WEBROOT = '';
  91. /**
  92. * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
  93. * web path in 'url'
  94. */
  95. public static $APPSROOTS = [];
  96. /**
  97. * @var string
  98. */
  99. public static $configDir;
  100. /**
  101. * requested app
  102. */
  103. public static $REQUESTEDAPP = '';
  104. /**
  105. * check if Nextcloud runs in cli mode
  106. */
  107. public static $CLI = false;
  108. /**
  109. * @var \OC\Autoloader $loader
  110. */
  111. public static $loader = null;
  112. /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
  113. public static $composerAutoloader = null;
  114. /**
  115. * @var \OC\Server
  116. */
  117. public static $server = null;
  118. /**
  119. * @var \OC\Config
  120. */
  121. private static $config = null;
  122. /**
  123. * @throws \RuntimeException when the 3rdparty directory is missing or
  124. * the app path list is empty or contains an invalid path
  125. */
  126. public static function initPaths() {
  127. if (defined('PHPUNIT_CONFIG_DIR')) {
  128. self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
  129. } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
  130. self::$configDir = OC::$SERVERROOT . '/tests/config/';
  131. } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
  132. self::$configDir = rtrim($dir, '/') . '/';
  133. } else {
  134. self::$configDir = OC::$SERVERROOT . '/config/';
  135. }
  136. self::$config = new \OC\Config(self::$configDir);
  137. OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
  138. /**
  139. * FIXME: The following lines are required because we can't yet instantiate
  140. * \OC::$server->getRequest() since \OC::$server does not yet exist.
  141. */
  142. $params = [
  143. 'server' => [
  144. 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
  145. 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
  146. ],
  147. ];
  148. $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
  149. $scriptName = $fakeRequest->getScriptName();
  150. if (substr($scriptName, -1) == '/') {
  151. $scriptName .= 'index.php';
  152. //make sure suburi follows the same rules as scriptName
  153. if (substr(OC::$SUBURI, -9) != 'index.php') {
  154. if (substr(OC::$SUBURI, -1) != '/') {
  155. OC::$SUBURI = OC::$SUBURI . '/';
  156. }
  157. OC::$SUBURI = OC::$SUBURI . 'index.php';
  158. }
  159. }
  160. if (OC::$CLI) {
  161. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  162. } else {
  163. if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
  164. OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
  165. if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
  166. OC::$WEBROOT = '/' . OC::$WEBROOT;
  167. }
  168. } else {
  169. // The scriptName is not ending with OC::$SUBURI
  170. // This most likely means that we are calling from CLI.
  171. // However some cron jobs still need to generate
  172. // a web URL, so we use overwritewebroot as a fallback.
  173. OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
  174. }
  175. // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
  176. // slash which is required by URL generation.
  177. if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
  178. substr($_SERVER['REQUEST_URI'], -1) !== '/') {
  179. header('Location: '.\OC::$WEBROOT.'/');
  180. exit();
  181. }
  182. }
  183. // search the apps folder
  184. $config_paths = self::$config->getValue('apps_paths', []);
  185. if (!empty($config_paths)) {
  186. foreach ($config_paths as $paths) {
  187. if (isset($paths['url']) && isset($paths['path'])) {
  188. $paths['url'] = rtrim($paths['url'], '/');
  189. $paths['path'] = rtrim($paths['path'], '/');
  190. OC::$APPSROOTS[] = $paths;
  191. }
  192. }
  193. } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
  194. OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
  195. } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
  196. OC::$APPSROOTS[] = [
  197. 'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
  198. 'url' => '/apps',
  199. 'writable' => true
  200. ];
  201. }
  202. if (empty(OC::$APPSROOTS)) {
  203. throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
  204. . ' or the folder above. You can also configure the location in the config.php file.');
  205. }
  206. $paths = [];
  207. foreach (OC::$APPSROOTS as $path) {
  208. $paths[] = $path['path'];
  209. if (!is_dir($path['path'])) {
  210. throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
  211. . ' Nextcloud folder or the folder above. You can also configure the location in the'
  212. . ' config.php file.', $path['path']));
  213. }
  214. }
  215. // set the right include path
  216. set_include_path(
  217. implode(PATH_SEPARATOR, $paths)
  218. );
  219. }
  220. public static function checkConfig() {
  221. $l = \OC::$server->getL10N('lib');
  222. // Create config if it does not already exist
  223. $configFilePath = self::$configDir .'/config.php';
  224. if (!file_exists($configFilePath)) {
  225. @touch($configFilePath);
  226. }
  227. // Check if config is writable
  228. $configFileWritable = is_writable($configFilePath);
  229. if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
  230. || !$configFileWritable && \OCP\Util::needUpgrade()) {
  231. $urlGenerator = \OC::$server->getURLGenerator();
  232. if (self::$CLI) {
  233. echo $l->t('Cannot write into "config" directory!')."\n";
  234. echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
  235. echo "\n";
  236. 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";
  237. echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n";
  238. exit;
  239. } else {
  240. OC_Template::printErrorPage(
  241. $l->t('Cannot write into "config" directory!'),
  242. $l->t('This can usually be fixed by giving the webserver write access to the config directory.') . '. '
  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', ['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([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. self::$server->boot();
  531. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  532. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  533. // Override php.ini and log everything if we're troubleshooting
  534. if (self::$config->getValue('loglevel') === ILogger::DEBUG) {
  535. error_reporting(E_ALL);
  536. }
  537. // Don't display errors and log them
  538. @ini_set('display_errors', '0');
  539. @ini_set('log_errors', '1');
  540. if (!date_default_timezone_set('UTC')) {
  541. throw new \RuntimeException('Could not set timezone to UTC');
  542. }
  543. //try to configure php to enable big file uploads.
  544. //this doesn´t work always depending on the webserver and php configuration.
  545. //Let´s try to overwrite some defaults anyway
  546. //try to set the maximum execution time to 60min
  547. if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
  548. @set_time_limit(3600);
  549. }
  550. @ini_set('max_execution_time', '3600');
  551. @ini_set('max_input_time', '3600');
  552. //try to set the maximum filesize to 10G
  553. @ini_set('upload_max_filesize', '10G');
  554. @ini_set('post_max_size', '10G');
  555. @ini_set('file_uploads', '50');
  556. self::setRequiredIniValues();
  557. self::handleAuthHeaders();
  558. self::registerAutoloaderCache();
  559. // initialize intl fallback is necessary
  560. \Patchwork\Utf8\Bootup::initIntl();
  561. OC_Util::isSetLocaleWorking();
  562. if (!defined('PHPUNIT_RUN')) {
  563. OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
  564. $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
  565. OC\Log\ErrorHandler::register($debug);
  566. }
  567. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  568. OC_App::loadApps(['session']);
  569. if (!self::$CLI) {
  570. self::initSession();
  571. }
  572. \OC::$server->getEventLogger()->end('init_session');
  573. self::checkConfig();
  574. self::checkInstalled();
  575. OC_Response::addSecurityHeaders();
  576. self::performSameSiteCookieProtection();
  577. if (!defined('OC_CONSOLE')) {
  578. $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
  579. if (count($errors) > 0) {
  580. if (!self::$CLI) {
  581. http_response_code(503);
  582. OC_Util::addStyle('guest');
  583. try {
  584. OC_Template::printGuestPage('', 'error', ['errors' => $errors]);
  585. exit;
  586. } catch (\Exception $e) {
  587. // In case any error happens when showing the error page, we simply fall back to posting the text.
  588. // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it.
  589. }
  590. }
  591. // Convert l10n string into regular string for usage in database
  592. $staticErrors = [];
  593. foreach ($errors as $error) {
  594. echo $error['error'] . "\n";
  595. echo $error['hint'] . "\n\n";
  596. $staticErrors[] = [
  597. 'error' => (string)$error['error'],
  598. 'hint' => (string)$error['hint'],
  599. ];
  600. }
  601. try {
  602. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  603. } catch (\Exception $e) {
  604. echo('Writing to database failed');
  605. }
  606. exit(1);
  607. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  608. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  609. }
  610. }
  611. //try to set the session lifetime
  612. $sessionLifeTime = self::getSessionLifeTime();
  613. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  614. $systemConfig = \OC::$server->getSystemConfig();
  615. // User and Groups
  616. if (!$systemConfig->getValue("installed", false)) {
  617. self::$server->getSession()->set('user_id', '');
  618. }
  619. OC_User::useBackend(new \OC\User\Database());
  620. \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
  621. // Subscribe to the hook
  622. \OCP\Util::connectHook(
  623. '\OCA\Files_Sharing\API\Server2Server',
  624. 'preLoginNameUsedAsUserName',
  625. '\OC\User\Database',
  626. 'preLoginNameUsedAsUserName'
  627. );
  628. //setup extra user backends
  629. if (!\OCP\Util::needUpgrade()) {
  630. OC_User::setupBackends();
  631. } else {
  632. // Run upgrades in incognito mode
  633. OC_User::setIncognitoMode(true);
  634. }
  635. self::registerCleanupHooks();
  636. self::registerFilesystemHooks();
  637. self::registerShareHooks();
  638. self::registerEncryptionWrapper();
  639. self::registerEncryptionHooks();
  640. self::registerAccountHooks();
  641. self::registerResourceCollectionHooks();
  642. self::registerAppRestrictionsHooks();
  643. // Make sure that the application class is not loaded before the database is setup
  644. if ($systemConfig->getValue("installed", false)) {
  645. OC_App::loadApp('settings');
  646. $settings = \OC::$server->query(\OCA\Settings\AppInfo\Application::class);
  647. $settings->register();
  648. }
  649. //make sure temporary files are cleaned up
  650. $tmpManager = \OC::$server->getTempManager();
  651. register_shutdown_function([$tmpManager, 'clean']);
  652. $lockProvider = \OC::$server->getLockingProvider();
  653. register_shutdown_function([$lockProvider, 'releaseAll']);
  654. // Check whether the sample configuration has been copied
  655. if ($systemConfig->getValue('copied_sample_config', false)) {
  656. $l = \OC::$server->getL10N('lib');
  657. OC_Template::printErrorPage(
  658. $l->t('Sample configuration detected'),
  659. $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'),
  660. 503
  661. );
  662. return;
  663. }
  664. $request = \OC::$server->getRequest();
  665. $host = $request->getInsecureServerHost();
  666. /**
  667. * if the host passed in headers isn't trusted
  668. * FIXME: Should not be in here at all :see_no_evil:
  669. */
  670. if (!OC::$CLI
  671. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  672. && self::$server->getConfig()->getSystemValue('installed', false)
  673. ) {
  674. // Allow access to CSS resources
  675. $isScssRequest = false;
  676. if (strpos($request->getPathInfo(), '/css/') === 0) {
  677. $isScssRequest = true;
  678. }
  679. if (substr($request->getRequestUri(), -11) === '/status.php') {
  680. http_response_code(400);
  681. header('Content-Type: application/json');
  682. echo '{"error": "Trusted domain error.", "code": 15}';
  683. exit();
  684. }
  685. if (!$isScssRequest) {
  686. http_response_code(400);
  687. \OC::$server->getLogger()->info(
  688. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  689. [
  690. 'app' => 'core',
  691. 'remoteAddress' => $request->getRemoteAddress(),
  692. 'host' => $host,
  693. ]
  694. );
  695. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  696. $tmpl->assign('docUrl', \OC::$server->getURLGenerator()->linkToDocs('admin-trusted-domains'));
  697. $tmpl->printPage();
  698. exit();
  699. }
  700. }
  701. \OC::$server->getEventLogger()->end('boot');
  702. }
  703. /**
  704. * register hooks for the cleanup of cache and bruteforce protection
  705. */
  706. public static function registerCleanupHooks() {
  707. //don't try to do this before we are properly setup
  708. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
  709. // NOTE: This will be replaced to use OCP
  710. $userSession = self::$server->getUserSession();
  711. $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
  712. if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) {
  713. // reset brute force delay for this IP address and username
  714. $uid = \OC::$server->getUserSession()->getUser()->getUID();
  715. $request = \OC::$server->getRequest();
  716. $throttler = \OC::$server->getBruteForceThrottler();
  717. $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
  718. }
  719. try {
  720. $cache = new \OC\Cache\File();
  721. $cache->gc();
  722. } catch (\OC\ServerNotAvailableException $e) {
  723. // not a GC exception, pass it on
  724. throw $e;
  725. } catch (\OC\ForbiddenException $e) {
  726. // filesystem blocked for this request, ignore
  727. } catch (\Exception $e) {
  728. // a GC exception should not prevent users from using OC,
  729. // so log the exception
  730. \OC::$server->getLogger()->logException($e, [
  731. 'message' => 'Exception when running cache gc.',
  732. 'level' => ILogger::WARN,
  733. 'app' => 'core',
  734. ]);
  735. }
  736. });
  737. }
  738. }
  739. private static function registerEncryptionWrapper() {
  740. $manager = self::$server->getEncryptionManager();
  741. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  742. }
  743. private static function registerEncryptionHooks() {
  744. $enabled = self::$server->getEncryptionManager()->isEnabled();
  745. if ($enabled) {
  746. \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
  747. \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
  748. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
  749. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
  750. }
  751. }
  752. private static function registerAccountHooks() {
  753. $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
  754. \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
  755. }
  756. private static function registerAppRestrictionsHooks() {
  757. $groupManager = self::$server->query(\OCP\IGroupManager::class);
  758. $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) {
  759. $appManager = self::$server->getAppManager();
  760. $apps = $appManager->getEnabledAppsForGroup($group);
  761. foreach ($apps as $appId) {
  762. $restrictions = $appManager->getAppRestriction($appId);
  763. if (empty($restrictions)) {
  764. continue;
  765. }
  766. $key = array_search($group->getGID(), $restrictions);
  767. unset($restrictions[$key]);
  768. $restrictions = array_values($restrictions);
  769. if (empty($restrictions)) {
  770. $appManager->disableApp($appId);
  771. } else {
  772. $appManager->enableAppForGroups($appId, $restrictions);
  773. }
  774. }
  775. });
  776. }
  777. private static function registerResourceCollectionHooks() {
  778. \OC\Collaboration\Resources\Listener::register(\OC::$server->getEventDispatcher());
  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', Filesystem::class, 'isBlacklisted');
  786. OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
  787. }
  788. /**
  789. * register hooks for sharing
  790. */
  791. public static function registerShareHooks() {
  792. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  793. OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
  794. OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
  795. OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
  796. }
  797. }
  798. protected static function registerAutoloaderCache() {
  799. // The class loader takes an optional low-latency cache, which MUST be
  800. // namespaced. The instanceid is used for namespacing, but might be
  801. // unavailable at this point. Furthermore, it might not be possible to
  802. // generate an instanceid via \OC_Util::getInstanceId() because the
  803. // config file may not be writable. As such, we only register a class
  804. // loader cache if instanceid is available without trying to create one.
  805. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  806. if ($instanceId) {
  807. try {
  808. $memcacheFactory = \OC::$server->getMemCacheFactory();
  809. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  810. } catch (\Exception $ex) {
  811. }
  812. }
  813. }
  814. /**
  815. * Handle the request
  816. */
  817. public static function handleRequest() {
  818. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  819. $systemConfig = \OC::$server->getSystemConfig();
  820. // Check if Nextcloud is installed or in maintenance (update) mode
  821. if (!$systemConfig->getValue('installed', false)) {
  822. \OC::$server->getSession()->clear();
  823. $setupHelper = new OC\Setup(
  824. $systemConfig,
  825. \OC::$server->getIniWrapper(),
  826. \OC::$server->getL10N('lib'),
  827. \OC::$server->query(\OCP\Defaults::class),
  828. \OC::$server->getLogger(),
  829. \OC::$server->getSecureRandom(),
  830. \OC::$server->query(\OC\Installer::class)
  831. );
  832. $controller = new OC\Core\Controller\SetupController($setupHelper);
  833. $controller->run($_POST);
  834. exit();
  835. }
  836. $request = \OC::$server->getRequest();
  837. $requestPath = $request->getRawPathInfo();
  838. if ($requestPath === '/heartbeat') {
  839. return;
  840. }
  841. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  842. self::checkMaintenanceMode();
  843. if (\OCP\Util::needUpgrade()) {
  844. if (function_exists('opcache_reset')) {
  845. opcache_reset();
  846. }
  847. if (!((bool) $systemConfig->getValue('maintenance', false))) {
  848. self::printUpgradePage($systemConfig);
  849. exit();
  850. }
  851. }
  852. }
  853. // emergency app disabling
  854. if ($requestPath === '/disableapp'
  855. && $request->getMethod() === 'POST'
  856. && ((array)$request->getParam('appid')) !== ''
  857. ) {
  858. \OC_JSON::callCheck();
  859. \OC_JSON::checkAdminUser();
  860. $appIds = (array)$request->getParam('appid');
  861. foreach ($appIds as $appId) {
  862. $appId = \OC_App::cleanAppId($appId);
  863. \OC::$server->getAppManager()->disableApp($appId);
  864. }
  865. \OC_JSON::success();
  866. exit();
  867. }
  868. // Always load authentication apps
  869. OC_App::loadApps(['authentication']);
  870. // Load minimum set of apps
  871. if (!\OCP\Util::needUpgrade()
  872. && !((bool) $systemConfig->getValue('maintenance', false))) {
  873. // For logged-in users: Load everything
  874. if (\OC::$server->getUserSession()->isLoggedIn()) {
  875. OC_App::loadApps();
  876. } else {
  877. // For guests: Load only filesystem and logging
  878. OC_App::loadApps(['filesystem', 'logging']);
  879. self::handleLogin($request);
  880. }
  881. }
  882. if (!self::$CLI) {
  883. try {
  884. if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) {
  885. OC_App::loadApps(['filesystem', 'logging']);
  886. OC_App::loadApps();
  887. }
  888. OC_Util::setupFS();
  889. OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
  890. return;
  891. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  892. //header('HTTP/1.0 404 Not Found');
  893. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  894. http_response_code(405);
  895. return;
  896. }
  897. }
  898. // Handle WebDAV
  899. if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
  900. // not allowed any more to prevent people
  901. // mounting this root directly.
  902. // Users need to mount remote.php/webdav instead.
  903. http_response_code(405);
  904. return;
  905. }
  906. // Someone is logged in
  907. if (\OC::$server->getUserSession()->isLoggedIn()) {
  908. OC_App::loadApps();
  909. OC_User::setupBackends();
  910. OC_Util::setupFS();
  911. // FIXME
  912. // Redirect to default application
  913. OC_Util::redirectToDefaultPage();
  914. } else {
  915. // Not handled and not logged in
  916. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  917. }
  918. }
  919. /**
  920. * Check login: apache auth, auth token, basic auth
  921. *
  922. * @param OCP\IRequest $request
  923. * @return boolean
  924. */
  925. public static function handleLogin(OCP\IRequest $request) {
  926. $userSession = self::$server->getUserSession();
  927. if (OC_User::handleApacheAuth()) {
  928. return true;
  929. }
  930. if ($userSession->tryTokenLogin($request)) {
  931. return true;
  932. }
  933. if (isset($_COOKIE['nc_username'])
  934. && isset($_COOKIE['nc_token'])
  935. && isset($_COOKIE['nc_session_id'])
  936. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  937. return true;
  938. }
  939. if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  940. return true;
  941. }
  942. return false;
  943. }
  944. protected static function handleAuthHeaders() {
  945. //copy http auth headers for apache+php-fcgid work around
  946. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  947. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  948. }
  949. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  950. $vars = [
  951. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  952. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  953. ];
  954. foreach ($vars as $var) {
  955. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  956. $credentials = explode(':', base64_decode($matches[1]), 2);
  957. if (count($credentials) === 2) {
  958. $_SERVER['PHP_AUTH_USER'] = $credentials[0];
  959. $_SERVER['PHP_AUTH_PW'] = $credentials[1];
  960. break;
  961. }
  962. }
  963. }
  964. }
  965. }
  966. OC::init();