Config.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Adam Williamson <awilliam@redhat.com>
  6. * @author Aldo "xoen" Giambelluca <xoen@xoen.org>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Brice Maron <brice@bmaron.net>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Frank Karlitschek <frank@karlitschek.de>
  12. * @author Jakob Sack <mail@jakobsack.de>
  13. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  14. * @author Joas Schilling <coding@schilljs.com>
  15. * @author John Molakvoæ <skjnldsv@protonmail.com>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Philipp Schaffrath <github@philipp.schaffrath.email>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Robin McCorkell <robin@mccorkell.me.uk>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. *
  24. * @license AGPL-3.0
  25. *
  26. * This code is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License, version 3,
  28. * as published by the Free Software Foundation.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License, version 3,
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>
  37. *
  38. */
  39. namespace OC;
  40. use OCP\HintException;
  41. /**
  42. * This class is responsible for reading and writing config.php, the very basic
  43. * configuration file of Nextcloud.
  44. */
  45. class Config {
  46. public const ENV_PREFIX = 'NC_';
  47. /** @var array Associative array ($key => $value) */
  48. protected $cache = [];
  49. /** @var array */
  50. protected $envCache = [];
  51. /** @var string */
  52. protected $configDir;
  53. /** @var string */
  54. protected $configFilePath;
  55. /** @var string */
  56. protected $configFileName;
  57. /** @var bool */
  58. protected $isReadOnly;
  59. /**
  60. * @param string $configDir Path to the config dir, needs to end with '/'
  61. * @param string $fileName (Optional) Name of the config file. Defaults to config.php
  62. */
  63. public function __construct($configDir, $fileName = 'config.php') {
  64. $this->configDir = $configDir;
  65. $this->configFilePath = $this->configDir.$fileName;
  66. $this->configFileName = $fileName;
  67. $this->readData();
  68. $this->isReadOnly = $this->getValue('config_is_read_only', false);
  69. }
  70. /**
  71. * Lists all available config keys
  72. *
  73. * Please note that it does not return the values.
  74. *
  75. * @return array an array of key names
  76. */
  77. public function getKeys() {
  78. return array_merge(array_keys($this->cache), array_keys($this->envCache));
  79. }
  80. /**
  81. * Returns a config value
  82. *
  83. * gets its value from an `NC_` prefixed environment variable
  84. * if it doesn't exist from config.php
  85. * if this doesn't exist either, it will return the given `$default`
  86. *
  87. * @param string $key key
  88. * @param mixed $default = null default value
  89. * @return mixed the value or $default
  90. */
  91. public function getValue($key, $default = null) {
  92. if (isset($this->envCache[$key])) {
  93. return $this->envCache[$key];
  94. }
  95. if (isset($this->cache[$key])) {
  96. return $this->cache[$key];
  97. }
  98. return $default;
  99. }
  100. /**
  101. * Sets and deletes values and writes the config.php
  102. *
  103. * @param array $configs Associative array with `key => value` pairs
  104. * If value is null, the config key will be deleted
  105. * @throws HintException
  106. */
  107. public function setValues(array $configs) {
  108. $needsUpdate = false;
  109. foreach ($configs as $key => $value) {
  110. if ($value !== null) {
  111. $needsUpdate |= $this->set($key, $value);
  112. } else {
  113. $needsUpdate |= $this->delete($key);
  114. }
  115. }
  116. if ($needsUpdate) {
  117. // Write changes
  118. $this->writeData();
  119. }
  120. }
  121. /**
  122. * Sets the value and writes it to config.php if required
  123. *
  124. * @param string $key key
  125. * @param mixed $value value
  126. * @throws HintException
  127. */
  128. public function setValue($key, $value) {
  129. if ($this->set($key, $value)) {
  130. // Write changes
  131. $this->writeData();
  132. }
  133. }
  134. /**
  135. * This function sets the value
  136. *
  137. * @param string $key key
  138. * @param mixed $value value
  139. * @return bool True if the file needs to be updated, false otherwise
  140. * @throws HintException
  141. */
  142. protected function set($key, $value) {
  143. if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
  144. // Add change
  145. $this->cache[$key] = $value;
  146. return true;
  147. }
  148. return false;
  149. }
  150. /**
  151. * Removes a key from the config and removes it from config.php if required
  152. *
  153. * @param string $key
  154. * @throws HintException
  155. */
  156. public function deleteKey($key) {
  157. if ($this->delete($key)) {
  158. // Write changes
  159. $this->writeData();
  160. }
  161. }
  162. /**
  163. * This function removes a key from the config
  164. *
  165. * @param string $key
  166. * @return bool True if the file needs to be updated, false otherwise
  167. * @throws HintException
  168. */
  169. protected function delete($key) {
  170. if (isset($this->cache[$key])) {
  171. // Delete key from cache
  172. unset($this->cache[$key]);
  173. return true;
  174. }
  175. return false;
  176. }
  177. /**
  178. * Loads the config file
  179. *
  180. * Reads the config file and saves it to the cache
  181. *
  182. * @throws \Exception If no lock could be acquired or the config file has not been found
  183. */
  184. private function readData() {
  185. // Default config should always get loaded
  186. $configFiles = [$this->configFilePath];
  187. // Add all files in the config dir ending with the same file name
  188. $extra = glob($this->configDir.'*.'.$this->configFileName);
  189. if (is_array($extra)) {
  190. natsort($extra);
  191. $configFiles = array_merge($configFiles, $extra);
  192. }
  193. // Include file and merge config
  194. foreach ($configFiles as $file) {
  195. unset($CONFIG);
  196. // Invalidate opcache (only if the timestamp changed)
  197. if (function_exists('opcache_invalidate')) {
  198. @opcache_invalidate($file, false);
  199. }
  200. // suppressor doesn't work here at boot time since it'll go via our onError custom error handler
  201. $filePointer = file_exists($file) ? @fopen($file, 'r') : false;
  202. if ($filePointer === false) {
  203. // e.g. wrong permissions are set
  204. if ($file === $this->configFilePath) {
  205. // opening the main config file might not be possible
  206. // (likely on a new installation)
  207. continue;
  208. }
  209. http_response_code(500);
  210. die(sprintf('FATAL: Could not open the config file %s', $file));
  211. }
  212. // Try to acquire a file lock
  213. if (!flock($filePointer, LOCK_SH)) {
  214. throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
  215. }
  216. try {
  217. include $file;
  218. } finally {
  219. // Close the file pointer and release the lock
  220. flock($filePointer, LOCK_UN);
  221. fclose($filePointer);
  222. }
  223. if (!defined('PHPUNIT_RUN') && headers_sent()) {
  224. // syntax issues in the config file like leading spaces causing PHP to send output
  225. $errorMessage = sprintf('Config file has leading content, please remove everything before "<?php" in %s', basename($file));
  226. if (!defined('OC_CONSOLE')) {
  227. print(\OCP\Util::sanitizeHTML($errorMessage));
  228. }
  229. throw new \Exception($errorMessage);
  230. }
  231. if (isset($CONFIG) && is_array($CONFIG)) {
  232. $this->cache = array_merge($this->cache, $CONFIG);
  233. }
  234. }
  235. // grab any "NC_" environment variables
  236. $envRaw = getenv();
  237. // only save environment variables prefixed with "NC_" in the cache
  238. $envPrefixLen = strlen(self::ENV_PREFIX);
  239. foreach ($envRaw as $rawEnvKey => $rawEnvValue) {
  240. if (str_starts_with($rawEnvKey, self::ENV_PREFIX)) {
  241. $realKey = substr($rawEnvKey, $envPrefixLen);
  242. $this->envCache[$realKey] = $rawEnvValue;
  243. }
  244. }
  245. }
  246. /**
  247. * Writes the config file
  248. *
  249. * Saves the config to the config file.
  250. *
  251. * @throws HintException If the config file cannot be written to
  252. * @throws \Exception If no file lock can be acquired
  253. */
  254. private function writeData() {
  255. $this->checkReadOnly();
  256. if (!is_file(\OC::$configDir.'/CAN_INSTALL') && !isset($this->cache['version'])) {
  257. throw new HintException(sprintf('Configuration was not read or initialized correctly, not overwriting %s', $this->configFilePath));
  258. }
  259. // Create a php file ...
  260. $content = "<?php\n";
  261. $content .= '$CONFIG = ';
  262. $content .= var_export($this->cache, true);
  263. $content .= ";\n";
  264. touch($this->configFilePath);
  265. $filePointer = fopen($this->configFilePath, 'r+');
  266. // Prevent others not to read the config
  267. chmod($this->configFilePath, 0640);
  268. // File does not exist, this can happen when doing a fresh install
  269. if (!is_resource($filePointer)) {
  270. throw new HintException(
  271. "Can't write into config directory!",
  272. 'This can usually be fixed by giving the webserver write access to the config directory.');
  273. }
  274. // Never write file back if disk space should be too low
  275. if (function_exists('disk_free_space')) {
  276. $df = disk_free_space($this->configDir);
  277. $size = strlen($content) + 10240;
  278. if ($df !== false && $df < (float)$size) {
  279. throw new \Exception($this->configDir . " does not have enough space for writing the config file! Not writing it back!");
  280. }
  281. }
  282. // Try to acquire a file lock
  283. if (!flock($filePointer, LOCK_EX)) {
  284. throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
  285. }
  286. // Write the config and release the lock
  287. ftruncate($filePointer, 0);
  288. fwrite($filePointer, $content);
  289. fflush($filePointer);
  290. flock($filePointer, LOCK_UN);
  291. fclose($filePointer);
  292. if (function_exists('opcache_invalidate')) {
  293. @opcache_invalidate($this->configFilePath, true);
  294. }
  295. }
  296. /**
  297. * @throws HintException
  298. */
  299. private function checkReadOnly(): void {
  300. if ($this->isReadOnly) {
  301. throw new HintException(
  302. 'Config is set to be read-only via option "config_is_read_only".',
  303. 'Unset "config_is_read_only" to allow changes to the config file.');
  304. }
  305. }
  306. }