base.php 35 KB

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