You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1082 lines
37 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
15 years ago
15 years ago
15 years ago
15 years ago
15 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
12 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
  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. $template->printPage();
  259. die();
  260. }
  261. }
  262. public static function checkSingleUserMode($lockIfNoUserLoggedIn = false) {
  263. if (!\OC::$server->getSystemConfig()->getValue('singleuser', false)) {
  264. return;
  265. }
  266. $user = OC_User::getUserSession()->getUser();
  267. if ($user) {
  268. $group = \OC::$server->getGroupManager()->get('admin');
  269. if ($group->inGroup($user)) {
  270. return;
  271. }
  272. } else {
  273. if(!$lockIfNoUserLoggedIn) {
  274. return;
  275. }
  276. }
  277. // send http status 503
  278. header('HTTP/1.1 503 Service Temporarily Unavailable');
  279. header('Status: 503 Service Temporarily Unavailable');
  280. header('Retry-After: 120');
  281. // render error page
  282. $template = new OC_Template('', 'singleuser.user', 'guest');
  283. $template->printPage();
  284. die();
  285. }
  286. /**
  287. * Checks if the version requires an update and shows
  288. * @param bool $showTemplate Whether an update screen should get shown
  289. * @return bool|void
  290. */
  291. public static function checkUpgrade($showTemplate = true) {
  292. if (\OCP\Util::needUpgrade()) {
  293. $systemConfig = \OC::$server->getSystemConfig();
  294. if ($showTemplate && !$systemConfig->getValue('maintenance', false)) {
  295. self::printUpgradePage();
  296. exit();
  297. } else {
  298. return true;
  299. }
  300. }
  301. return false;
  302. }
  303. /**
  304. * Prints the upgrade page
  305. */
  306. private static function printUpgradePage() {
  307. $systemConfig = \OC::$server->getSystemConfig();
  308. $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
  309. $tooBig = false;
  310. if (!$disableWebUpdater) {
  311. $apps = \OC::$server->getAppManager();
  312. $tooBig = $apps->isInstalled('user_ldap') || $apps->isInstalled('user_shibboleth');
  313. if (!$tooBig) {
  314. // count users
  315. $stats = \OC::$server->getUserManager()->countUsers();
  316. $totalUsers = array_sum($stats);
  317. $tooBig = ($totalUsers > 50);
  318. }
  319. }
  320. if ($disableWebUpdater || $tooBig) {
  321. // send http status 503
  322. header('HTTP/1.1 503 Service Temporarily Unavailable');
  323. header('Status: 503 Service Temporarily Unavailable');
  324. header('Retry-After: 120');
  325. // render error page
  326. $template = new OC_Template('', 'update.use-cli', 'guest');
  327. $template->assign('productName', 'nextcloud'); // for now
  328. $template->assign('version', OC_Util::getVersionString());
  329. $template->assign('tooBig', $tooBig);
  330. $template->printPage();
  331. die();
  332. }
  333. // check whether this is a core update or apps update
  334. $installedVersion = $systemConfig->getValue('version', '0.0.0');
  335. $currentVersion = implode('.', \OCP\Util::getVersion());
  336. // if not a core upgrade, then it's apps upgrade
  337. $isAppsOnlyUpgrade = (version_compare($currentVersion, $installedVersion, '='));
  338. $oldTheme = $systemConfig->getValue('theme');
  339. $systemConfig->setValue('theme', '');
  340. \OCP\Util::addScript('config'); // needed for web root
  341. \OCP\Util::addScript('update');
  342. \OCP\Util::addStyle('update');
  343. /** @var \OCP\App\IAppManager $appManager */
  344. $appManager = \OC::$server->getAppManager();
  345. $tmpl = new OC_Template('', 'update.admin', 'guest');
  346. $tmpl->assign('version', OC_Util::getVersionString());
  347. $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
  348. // get third party apps
  349. $ocVersion = \OCP\Util::getVersion();
  350. $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
  351. foreach ($incompatibleApps as $appInfo) {
  352. if ($appManager->isShipped($appInfo['id'])) {
  353. $l = \OC::$server->getL10N('core');
  354. $hint = $l->t('The files of the app "%$1s" (%$2s) were not replaced correctly.', [$appInfo['name'], $appInfo['id']]);
  355. throw new \OC\HintException('The files of the app "' . $appInfo['name'] . '" (' . $appInfo['id'] . ') were not replaced correctly.', $hint);
  356. }
  357. }
  358. $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
  359. $tmpl->assign('incompatibleAppsList', $incompatibleApps);
  360. $tmpl->assign('productName', 'Nextcloud'); // for now
  361. $tmpl->assign('oldTheme', $oldTheme);
  362. $tmpl->printPage();
  363. }
  364. public static function initSession() {
  365. // prevents javascript from accessing php session cookies
  366. ini_set('session.cookie_httponly', true);
  367. // set the cookie path to the Nextcloud directory
  368. $cookie_path = OC::$WEBROOT ? : '/';
  369. ini_set('session.cookie_path', $cookie_path);
  370. // Let the session name be changed in the initSession Hook
  371. $sessionName = OC_Util::getInstanceId();
  372. try {
  373. // Allow session apps to create a custom session object
  374. $useCustomSession = false;
  375. $session = self::$server->getSession();
  376. OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
  377. if (!$useCustomSession) {
  378. // set the session name to the instance id - which is unique
  379. $session = new \OC\Session\Internal($sessionName);
  380. }
  381. $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
  382. $session = $cryptoWrapper->wrapSession($session);
  383. self::$server->setSession($session);
  384. // if session can't be started break with http 500 error
  385. } catch (Exception $e) {
  386. \OCP\Util::logException('base', $e);
  387. //show the user a detailed error page
  388. OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
  389. OC_Template::printExceptionErrorPage($e);
  390. die();
  391. }
  392. $sessionLifeTime = self::getSessionLifeTime();
  393. // session timeout
  394. if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
  395. if (isset($_COOKIE[session_name()])) {
  396. setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
  397. }
  398. \OC::$server->getUserSession()->logout();
  399. }
  400. $session->set('LAST_ACTIVITY', time());
  401. }
  402. /**
  403. * @return string
  404. */
  405. private static function getSessionLifeTime() {
  406. return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
  407. }
  408. public static function loadAppClassPaths() {
  409. foreach (OC_App::getEnabledApps() as $app) {
  410. $appPath = OC_App::getAppPath($app);
  411. if ($appPath === false) {
  412. continue;
  413. }
  414. $file = $appPath . '/appinfo/classpath.php';
  415. if (file_exists($file)) {
  416. require_once $file;
  417. }
  418. }
  419. }
  420. /**
  421. * Try to set some values to the required Nextcloud default
  422. */
  423. public static function setRequiredIniValues() {
  424. @ini_set('default_charset', 'UTF-8');
  425. @ini_set('gd.jpeg_ignore_warning', 1);
  426. }
  427. /**
  428. * Send the same site cookies
  429. */
  430. private static function sendSameSiteCookies() {
  431. $cookieParams = session_get_cookie_params();
  432. $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
  433. $policies = [
  434. 'lax',
  435. 'strict',
  436. ];
  437. foreach($policies as $policy) {
  438. header(
  439. sprintf(
  440. 'Set-Cookie: nc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
  441. $policy,
  442. $cookieParams['path'],
  443. $policy
  444. ),
  445. false
  446. );
  447. }
  448. }
  449. /**
  450. * Same Site cookie to further mitigate CSRF attacks. This cookie has to
  451. * be set in every request if cookies are sent to add a second level of
  452. * defense against CSRF.
  453. *
  454. * If the cookie is not sent this will set the cookie and reload the page.
  455. * We use an additional cookie since we want to protect logout CSRF and
  456. * also we can't directly interfere with PHP's session mechanism.
  457. */
  458. private static function performSameSiteCookieProtection() {
  459. $request = \OC::$server->getRequest();
  460. // Some user agents are notorious and don't really properly follow HTTP
  461. // specifications. For those, have an automated opt-out. Since the protection
  462. // for remote.php is applied in base.php as starting point we need to opt out
  463. // here.
  464. $incompatibleUserAgents = [
  465. // OS X Finder
  466. '/^WebDAVFS/',
  467. ];
  468. if($request->isUserAgent($incompatibleUserAgents)) {
  469. return;
  470. }
  471. // Chrome on Android has a bug that it doesn't sent cookies with the
  472. // same-site attribute for the download manager. To work around that
  473. // all same-site cookies get deleted and recreated directly. Awesome!
  474. // FIXME: Remove once Chrome 54 is deployed to end-users
  475. // @see https://github.com/nextcloud/server/pull/1454
  476. if($request->isUserAgent([\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME])) {
  477. return;
  478. }
  479. if(count($_COOKIE) > 0) {
  480. $requestUri = $request->getScriptName();
  481. $processingScript = explode('/', $requestUri);
  482. $processingScript = $processingScript[count($processingScript)-1];
  483. // FIXME: In a SAML scenario we don't get any strict or lax cookie
  484. // send for the ACS endpoint. Since we have some legacy code in Nextcloud
  485. // (direct PHP files) the enforcement of lax cookies is performed here
  486. // instead of the middleware.
  487. //
  488. // This means we cannot exclude some routes from the cookie validation,
  489. // which normally is not a problem but is a little bit cumbersome for
  490. // this use-case.
  491. // Once the old legacy PHP endpoints have been removed we can move
  492. // the verification into a middleware and also adds some exemptions.
  493. //
  494. // Questions about this code? Ask Lukas ;-)
  495. $currentUrl = substr(explode('?',$request->getRequestUri(), 2)[0], strlen(\OC::$WEBROOT));
  496. if($currentUrl === '/index.php/apps/user_saml/saml/acs') {
  497. return;
  498. }
  499. // For the "index.php" endpoint only a lax cookie is required.
  500. if($processingScript === 'index.php') {
  501. if(!$request->passesLaxCookieCheck()) {
  502. self::sendSameSiteCookies();
  503. header('Location: '.$_SERVER['REQUEST_URI']);
  504. exit();
  505. }
  506. } else {
  507. // All other endpoints require the lax and the strict cookie
  508. if(!$request->passesStrictCookieCheck()) {
  509. self::sendSameSiteCookies();
  510. // Debug mode gets access to the resources without strict cookie
  511. // due to the fact that the SabreDAV browser also lives there.
  512. if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
  513. http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
  514. exit();
  515. }
  516. }
  517. }
  518. } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
  519. self::sendSameSiteCookies();
  520. }
  521. }
  522. public static function init() {
  523. // calculate the root directories
  524. OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
  525. // register autoloader
  526. $loaderStart = microtime(true);
  527. require_once __DIR__ . '/autoloader.php';
  528. self::$loader = new \OC\Autoloader([
  529. OC::$SERVERROOT . '/lib/private/legacy',
  530. ]);
  531. if (defined('PHPUNIT_RUN')) {
  532. self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
  533. }
  534. spl_autoload_register(array(self::$loader, 'load'));
  535. $loaderEnd = microtime(true);
  536. self::$CLI = (php_sapi_name() == 'cli');
  537. // Add default composer PSR-4 autoloader
  538. self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
  539. try {
  540. self::initPaths();
  541. // setup 3rdparty autoloader
  542. $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
  543. if (!file_exists($vendorAutoLoad)) {
  544. 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".');
  545. }
  546. require_once $vendorAutoLoad;
  547. } catch (\RuntimeException $e) {
  548. if (!self::$CLI) {
  549. $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
  550. $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
  551. header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
  552. }
  553. // we can't use the template error page here, because this needs the
  554. // DI container which isn't available yet
  555. print($e->getMessage());
  556. exit();
  557. }
  558. // setup the basic server
  559. self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
  560. \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
  561. \OC::$server->getEventLogger()->start('boot', 'Initialize');
  562. // Don't display errors and log them
  563. error_reporting(E_ALL | E_STRICT);
  564. @ini_set('display_errors', 0);
  565. @ini_set('log_errors', 1);
  566. if(!date_default_timezone_set('UTC')) {
  567. throw new \RuntimeException('Could not set timezone to UTC');
  568. };
  569. //try to configure php to enable big file uploads.
  570. //this doesn´t work always depending on the webserver and php configuration.
  571. //Let´s try to overwrite some defaults anyway
  572. //try to set the maximum execution time to 60min
  573. @set_time_limit(3600);
  574. @ini_set('max_execution_time', 3600);
  575. @ini_set('max_input_time', 3600);
  576. //try to set the maximum filesize to 10G
  577. @ini_set('upload_max_filesize', '10G');
  578. @ini_set('post_max_size', '10G');
  579. @ini_set('file_uploads', '50');
  580. self::setRequiredIniValues();
  581. self::handleAuthHeaders();
  582. self::registerAutoloaderCache();
  583. // initialize intl fallback is necessary
  584. \Patchwork\Utf8\Bootup::initIntl();
  585. OC_Util::isSetLocaleWorking();
  586. if (!defined('PHPUNIT_RUN')) {
  587. OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
  588. $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
  589. OC\Log\ErrorHandler::register($debug);
  590. }
  591. // register the stream wrappers
  592. stream_wrapper_register('fakedir', 'OC\Files\Stream\Dir');
  593. stream_wrapper_register('static', 'OC\Files\Stream\StaticStream');
  594. stream_wrapper_register('close', 'OC\Files\Stream\Close');
  595. stream_wrapper_register('quota', 'OC\Files\Stream\Quota');
  596. \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
  597. OC_App::loadApps(array('session'));
  598. if (!self::$CLI) {
  599. self::initSession();
  600. }
  601. \OC::$server->getEventLogger()->end('init_session');
  602. self::checkConfig();
  603. self::checkInstalled();
  604. OC_Response::addSecurityHeaders();
  605. if(self::$server->getRequest()->getServerProtocol() === 'https') {
  606. ini_set('session.cookie_secure', true);
  607. }
  608. self::performSameSiteCookieProtection();
  609. if (!defined('OC_CONSOLE')) {
  610. $errors = OC_Util::checkServer(\OC::$server->getConfig());
  611. if (count($errors) > 0) {
  612. if (self::$CLI) {
  613. // Convert l10n string into regular string for usage in database
  614. $staticErrors = [];
  615. foreach ($errors as $error) {
  616. echo $error['error'] . "\n";
  617. echo $error['hint'] . "\n\n";
  618. $staticErrors[] = [
  619. 'error' => (string)$error['error'],
  620. 'hint' => (string)$error['hint'],
  621. ];
  622. }
  623. try {
  624. \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
  625. } catch (\Exception $e) {
  626. echo('Writing to database failed');
  627. }
  628. exit(1);
  629. } else {
  630. OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
  631. OC_Template::printGuestPage('', 'error', array('errors' => $errors));
  632. exit;
  633. }
  634. } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
  635. \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
  636. }
  637. }
  638. //try to set the session lifetime
  639. $sessionLifeTime = self::getSessionLifeTime();
  640. @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
  641. $systemConfig = \OC::$server->getSystemConfig();
  642. // User and Groups
  643. if (!$systemConfig->getValue("installed", false)) {
  644. self::$server->getSession()->set('user_id', '');
  645. }
  646. OC_User::useBackend(new \OC\User\Database());
  647. OC_Group::useBackend(new \OC\Group\Database());
  648. // Subscribe to the hook
  649. \OCP\Util::connectHook(
  650. '\OCA\Files_Sharing\API\Server2Server',
  651. 'preLoginNameUsedAsUserName',
  652. '\OC\User\Database',
  653. 'preLoginNameUsedAsUserName'
  654. );
  655. //setup extra user backends
  656. if (!self::checkUpgrade(false)) {
  657. OC_User::setupBackends();
  658. } else {
  659. // Run upgrades in incognito mode
  660. OC_User::setIncognitoMode(true);
  661. }
  662. self::registerCacheHooks();
  663. self::registerFilesystemHooks();
  664. if ($systemConfig->getValue('enable_previews', true)) {
  665. self::registerPreviewHooks();
  666. }
  667. self::registerShareHooks();
  668. self::registerLogRotate();
  669. self::registerEncryptionWrapper();
  670. self::registerEncryptionHooks();
  671. self::registerSettingsHooks();
  672. //make sure temporary files are cleaned up
  673. $tmpManager = \OC::$server->getTempManager();
  674. register_shutdown_function(array($tmpManager, 'clean'));
  675. $lockProvider = \OC::$server->getLockingProvider();
  676. register_shutdown_function(array($lockProvider, 'releaseAll'));
  677. // Check whether the sample configuration has been copied
  678. if($systemConfig->getValue('copied_sample_config', false)) {
  679. $l = \OC::$server->getL10N('lib');
  680. header('HTTP/1.1 503 Service Temporarily Unavailable');
  681. header('Status: 503 Service Temporarily Unavailable');
  682. OC_Template::printErrorPage(
  683. $l->t('Sample configuration detected'),
  684. $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
  685. );
  686. return;
  687. }
  688. $request = \OC::$server->getRequest();
  689. $host = $request->getInsecureServerHost();
  690. /**
  691. * if the host passed in headers isn't trusted
  692. * FIXME: Should not be in here at all :see_no_evil:
  693. */
  694. if (!OC::$CLI
  695. // overwritehost is always trusted, workaround to not have to make
  696. // \OC\AppFramework\Http\Request::getOverwriteHost public
  697. && self::$server->getConfig()->getSystemValue('overwritehost') === ''
  698. && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
  699. && self::$server->getConfig()->getSystemValue('installed', false)
  700. ) {
  701. header('HTTP/1.1 400 Bad Request');
  702. header('Status: 400 Bad Request');
  703. \OC::$server->getLogger()->warning(
  704. 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
  705. [
  706. 'app' => 'core',
  707. 'remoteAddress' => $request->getRemoteAddress(),
  708. 'host' => $host,
  709. ]
  710. );
  711. $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
  712. $tmpl->assign('domain', $host);
  713. $tmpl->printPage();
  714. exit();
  715. }
  716. \OC::$server->getEventLogger()->end('boot');
  717. }
  718. /**
  719. * register hooks for the cache
  720. */
  721. public static function registerCacheHooks() {
  722. //don't try to do this before we are properly setup
  723. if (\OC::$server->getSystemConfig()->getValue('installed', false) && !self::checkUpgrade(false)) {
  724. // NOTE: This will be replaced to use OCP
  725. $userSession = self::$server->getUserSession();
  726. $userSession->listen('\OC\User', 'postLogin', function () {
  727. try {
  728. $cache = new \OC\Cache\File();
  729. $cache->gc();
  730. } catch (\OC\ServerNotAvailableException $e) {
  731. // not a GC exception, pass it on
  732. throw $e;
  733. } catch (\Exception $e) {
  734. // a GC exception should not prevent users from using OC,
  735. // so log the exception
  736. \OC::$server->getLogger()->warning('Exception when running cache gc: ' . $e->getMessage(), array('app' => 'core'));
  737. }
  738. });
  739. }
  740. }
  741. public static function registerSettingsHooks() {
  742. $dispatcher = \OC::$server->getEventDispatcher();
  743. $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_DISABLE, function($event) {
  744. /** @var \OCP\App\ManagerEvent $event */
  745. \OC::$server->getSettingsManager()->onAppDisabled($event->getAppID());
  746. });
  747. $dispatcher->addListener(OCP\App\ManagerEvent::EVENT_APP_UPDATE, function($event) {
  748. /** @var \OCP\App\ManagerEvent $event */
  749. $jobList = \OC::$server->getJobList();
  750. $job = 'OC\\Settings\\RemoveOrphaned';
  751. if(!($jobList->has($job, null))) {
  752. $jobList->add($job);
  753. }
  754. });
  755. }
  756. private static function registerEncryptionWrapper() {
  757. $manager = self::$server->getEncryptionManager();
  758. \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
  759. }
  760. private static function registerEncryptionHooks() {
  761. $enabled = self::$server->getEncryptionManager()->isEnabled();
  762. if ($enabled) {
  763. \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OC\Encryption\HookManager', 'postShared');
  764. \OCP\Util::connectHook('OCP\Share', 'post_unshare', 'OC\Encryption\HookManager', 'postUnshared');
  765. \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OC\Encryption\HookManager', 'postRename');
  766. \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', 'OC\Encryption\HookManager', 'postRestore');
  767. }
  768. }
  769. /**
  770. * register hooks for the cache
  771. */
  772. public static function registerLogRotate() {
  773. $systemConfig = \OC::$server->getSystemConfig();
  774. if ($systemConfig->getValue('installed', false) && $systemConfig->getValue('log_rotate_size', false) && !self::checkUpgrade(false)) {
  775. //don't try to do this before we are properly setup
  776. //use custom logfile path if defined, otherwise use default of nextcloud.log in data directory
  777. \OCP\BackgroundJob::registerJob('OC\Log\Rotate', $systemConfig->getValue('logfile', $systemConfig->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/nextcloud.log'));
  778. }
  779. }
  780. /**
  781. * register hooks for the filesystem
  782. */
  783. public static function registerFilesystemHooks() {
  784. // Check for blacklisted files
  785. OC_Hook::connect('OC_Filesystem', 'write', 'OC\Files\Filesystem', 'isBlacklisted');
  786. OC_Hook::connect('OC_Filesystem', 'rename', 'OC\Files\Filesystem', 'isBlacklisted');
  787. }
  788. /**
  789. * register hooks for previews
  790. */
  791. public static function registerPreviewHooks() {
  792. OC_Hook::connect('OC_Filesystem', 'post_write', 'OC\Preview', 'post_write');
  793. OC_Hook::connect('OC_Filesystem', 'delete', 'OC\Preview', 'prepare_delete_files');
  794. OC_Hook::connect('\OCP\Versions', 'preDelete', 'OC\Preview', 'prepare_delete');
  795. OC_Hook::connect('\OCP\Trashbin', 'preDelete', 'OC\Preview', 'prepare_delete');
  796. OC_Hook::connect('OC_Filesystem', 'post_delete', 'OC\Preview', 'post_delete_files');
  797. OC_Hook::connect('\OCP\Versions', 'delete', 'OC\Preview', 'post_delete_versions');
  798. OC_Hook::connect('\OCP\Trashbin', 'delete', 'OC\Preview', 'post_delete');
  799. OC_Hook::connect('\OCP\Versions', 'rollback', 'OC\Preview', 'post_delete_versions');
  800. }
  801. /**
  802. * register hooks for sharing
  803. */
  804. public static function registerShareHooks() {
  805. if (\OC::$server->getSystemConfig()->getValue('installed')) {
  806. OC_Hook::connect('OC_User', 'post_deleteUser', 'OC\Share20\Hooks', 'post_deleteUser');
  807. OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OC\Share20\Hooks', 'post_removeFromGroup');
  808. OC_Hook::connect('OC_User', 'post_deleteGroup', 'OC\Share20\Hooks', 'post_deleteGroup');
  809. }
  810. }
  811. protected static function registerAutoloaderCache() {
  812. // The class loader takes an optional low-latency cache, which MUST be
  813. // namespaced. The instanceid is used for namespacing, but might be
  814. // unavailable at this point. Furthermore, it might not be possible to
  815. // generate an instanceid via \OC_Util::getInstanceId() because the
  816. // config file may not be writable. As such, we only register a class
  817. // loader cache if instanceid is available without trying to create one.
  818. $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
  819. if ($instanceId) {
  820. try {
  821. $memcacheFactory = \OC::$server->getMemCacheFactory();
  822. self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
  823. } catch (\Exception $ex) {
  824. }
  825. }
  826. }
  827. /**
  828. * Handle the request
  829. */
  830. public static function handleRequest() {
  831. \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
  832. $systemConfig = \OC::$server->getSystemConfig();
  833. // load all the classpaths from the enabled apps so they are available
  834. // in the routing files of each app
  835. OC::loadAppClassPaths();
  836. // Check if Nextcloud is installed or in maintenance (update) mode
  837. if (!$systemConfig->getValue('installed', false)) {
  838. \OC::$server->getSession()->clear();
  839. $setupHelper = new OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
  840. \OC::$server->getL10N('lib'), \OC::$server->getThemingDefaults(), \OC::$server->getLogger(),
  841. \OC::$server->getSecureRandom());
  842. $controller = new OC\Core\Controller\SetupController($setupHelper);
  843. $controller->run($_POST);
  844. exit();
  845. }
  846. $request = \OC::$server->getRequest();
  847. $requestPath = $request->getRawPathInfo();
  848. if ($requestPath === '/heartbeat') {
  849. return;
  850. }
  851. if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
  852. self::checkMaintenanceMode();
  853. self::checkUpgrade();
  854. }
  855. // emergency app disabling
  856. if ($requestPath === '/disableapp'
  857. && $request->getMethod() === 'POST'
  858. && ((string)$request->getParam('appid')) !== ''
  859. ) {
  860. \OCP\JSON::callCheck();
  861. \OCP\JSON::checkAdminUser();
  862. $appId = (string)$request->getParam('appid');
  863. $appId = \OC_App::cleanAppId($appId);
  864. \OC_App::disable($appId);
  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 (!self::checkUpgrade(false)
  872. && !$systemConfig->getValue('maintenance', false)) {
  873. // For logged-in users: Load everything
  874. if(OC_User::isLoggedIn()) {
  875. OC_App::loadApps();
  876. } else {
  877. // For guests: Load only filesystem and logging
  878. OC_App::loadApps(array('filesystem', 'logging'));
  879. self::handleLogin($request);
  880. }
  881. }
  882. if (!self::$CLI) {
  883. try {
  884. if (!$systemConfig->getValue('maintenance', false) && !self::checkUpgrade(false)) {
  885. OC_App::loadApps(array('filesystem', 'logging'));
  886. OC_App::loadApps();
  887. }
  888. self::checkSingleUserMode();
  889. OC_Util::setupFS();
  890. OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
  891. return;
  892. } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
  893. //header('HTTP/1.0 404 Not Found');
  894. } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
  895. OC_Response::setStatus(405);
  896. return;
  897. }
  898. }
  899. // Handle WebDAV
  900. if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
  901. // not allowed any more to prevent people
  902. // mounting this root directly.
  903. // Users need to mount remote.php/webdav instead.
  904. header('HTTP/1.1 405 Method Not Allowed');
  905. header('Status: 405 Method Not Allowed');
  906. return;
  907. }
  908. // Someone is logged in
  909. if (OC_User::isLoggedIn()) {
  910. OC_App::loadApps();
  911. OC_User::setupBackends();
  912. OC_Util::setupFS();
  913. // FIXME
  914. // Redirect to default application
  915. OC_Util::redirectToDefaultPage();
  916. } else {
  917. // Not handled and not logged in
  918. header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
  919. }
  920. }
  921. /**
  922. * Check login: apache auth, auth token, basic auth
  923. *
  924. * @param OCP\IRequest $request
  925. * @return boolean
  926. */
  927. static function handleLogin(OCP\IRequest $request) {
  928. $userSession = self::$server->getUserSession();
  929. if (OC_User::handleApacheAuth()) {
  930. return true;
  931. }
  932. if ($userSession->tryTokenLogin($request)) {
  933. return true;
  934. }
  935. if (isset($_COOKIE['nc_username'])
  936. && isset($_COOKIE['nc_token'])
  937. && isset($_COOKIE['nc_session_id'])
  938. && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
  939. return true;
  940. }
  941. if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
  942. return true;
  943. }
  944. return false;
  945. }
  946. protected static function handleAuthHeaders() {
  947. //copy http auth headers for apache+php-fcgid work around
  948. if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
  949. $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
  950. }
  951. // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
  952. $vars = array(
  953. 'HTTP_AUTHORIZATION', // apache+php-cgi work around
  954. 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
  955. );
  956. foreach ($vars as $var) {
  957. if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
  958. list($name, $password) = explode(':', base64_decode($matches[1]), 2);
  959. $_SERVER['PHP_AUTH_USER'] = $name;
  960. $_SERVER['PHP_AUTH_PW'] = $password;
  961. break;
  962. }
  963. }
  964. }
  965. }
  966. OC::init();