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.

1092 lines
36 KiB

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