base.php 36 KB

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