base.php 37 KB

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