Config.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC;
  8. use OCP\HintException;
  9. /**
  10. * This class is responsible for reading and writing config.php, the very basic
  11. * configuration file of Nextcloud.
  12. */
  13. class Config {
  14. public const ENV_PREFIX = 'NC_';
  15. /** @var array Associative array ($key => $value) */
  16. protected $cache = [];
  17. /** @var array */
  18. protected $envCache = [];
  19. /** @var string */
  20. protected $configDir;
  21. /** @var string */
  22. protected $configFilePath;
  23. /** @var string */
  24. protected $configFileName;
  25. /** @var bool */
  26. protected $isReadOnly;
  27. /**
  28. * @param string $configDir Path to the config dir, needs to end with '/'
  29. * @param string $fileName (Optional) Name of the config file. Defaults to config.php
  30. */
  31. public function __construct($configDir, $fileName = 'config.php') {
  32. $this->configDir = $configDir;
  33. $this->configFilePath = $this->configDir . $fileName;
  34. $this->configFileName = $fileName;
  35. $this->readData();
  36. $this->isReadOnly = $this->getValue('config_is_read_only', false);
  37. }
  38. /**
  39. * Lists all available config keys
  40. *
  41. * Please note that it does not return the values.
  42. *
  43. * @return array an array of key names
  44. */
  45. public function getKeys() {
  46. return array_merge(array_keys($this->cache), array_keys($this->envCache));
  47. }
  48. /**
  49. * Returns a config value
  50. *
  51. * gets its value from an `NC_` prefixed environment variable
  52. * if it doesn't exist from config.php
  53. * if this doesn't exist either, it will return the given `$default`
  54. *
  55. * @param string $key key
  56. * @param mixed $default = null default value
  57. * @return mixed the value or $default
  58. */
  59. public function getValue($key, $default = null) {
  60. if (isset($this->envCache[$key])) {
  61. return $this->envCache[$key];
  62. }
  63. if (isset($this->cache[$key])) {
  64. return $this->cache[$key];
  65. }
  66. return $default;
  67. }
  68. /**
  69. * Sets and deletes values and writes the config.php
  70. *
  71. * @param array $configs Associative array with `key => value` pairs
  72. * If value is null, the config key will be deleted
  73. * @throws HintException
  74. */
  75. public function setValues(array $configs) {
  76. $needsUpdate = false;
  77. foreach ($configs as $key => $value) {
  78. if ($value !== null) {
  79. $needsUpdate |= $this->set($key, $value);
  80. } else {
  81. $needsUpdate |= $this->delete($key);
  82. }
  83. }
  84. if ($needsUpdate) {
  85. // Write changes
  86. $this->writeData();
  87. }
  88. }
  89. /**
  90. * Sets the value and writes it to config.php if required
  91. *
  92. * @param string $key key
  93. * @param mixed $value value
  94. * @throws HintException
  95. */
  96. public function setValue($key, $value) {
  97. if ($this->set($key, $value)) {
  98. // Write changes
  99. $this->writeData();
  100. }
  101. }
  102. /**
  103. * This function sets the value
  104. *
  105. * @param string $key key
  106. * @param mixed $value value
  107. * @return bool True if the file needs to be updated, false otherwise
  108. * @throws HintException
  109. */
  110. protected function set($key, $value) {
  111. if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
  112. // Add change
  113. $this->cache[$key] = $value;
  114. return true;
  115. }
  116. return false;
  117. }
  118. /**
  119. * Removes a key from the config and removes it from config.php if required
  120. *
  121. * @param string $key
  122. * @throws HintException
  123. */
  124. public function deleteKey($key) {
  125. if ($this->delete($key)) {
  126. // Write changes
  127. $this->writeData();
  128. }
  129. }
  130. /**
  131. * This function removes a key from the config
  132. *
  133. * @param string $key
  134. * @return bool True if the file needs to be updated, false otherwise
  135. * @throws HintException
  136. */
  137. protected function delete($key) {
  138. if (isset($this->cache[$key])) {
  139. // Delete key from cache
  140. unset($this->cache[$key]);
  141. return true;
  142. }
  143. return false;
  144. }
  145. /**
  146. * Loads the config file
  147. *
  148. * Reads the config file and saves it to the cache
  149. *
  150. * @throws \Exception If no lock could be acquired or the config file has not been found
  151. */
  152. private function readData() {
  153. // Default config should always get loaded
  154. $configFiles = [$this->configFilePath];
  155. // Add all files in the config dir ending with the same file name
  156. $extra = glob($this->configDir . '*.' . $this->configFileName);
  157. if (is_array($extra)) {
  158. natsort($extra);
  159. $configFiles = array_merge($configFiles, $extra);
  160. }
  161. // Include file and merge config
  162. foreach ($configFiles as $file) {
  163. unset($CONFIG);
  164. // Invalidate opcache (only if the timestamp changed)
  165. if (function_exists('opcache_invalidate')) {
  166. @opcache_invalidate($file, false);
  167. }
  168. // suppressor doesn't work here at boot time since it'll go via our onError custom error handler
  169. $filePointer = file_exists($file) ? @fopen($file, 'r') : false;
  170. if ($filePointer === false) {
  171. // e.g. wrong permissions are set
  172. if ($file === $this->configFilePath) {
  173. // opening the main config file might not be possible
  174. // (likely on a new installation)
  175. continue;
  176. }
  177. http_response_code(500);
  178. die(sprintf('FATAL: Could not open the config file %s', $file));
  179. }
  180. // Try to acquire a file lock
  181. if (!flock($filePointer, LOCK_SH)) {
  182. throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
  183. }
  184. try {
  185. include $file;
  186. } finally {
  187. // Close the file pointer and release the lock
  188. flock($filePointer, LOCK_UN);
  189. fclose($filePointer);
  190. }
  191. if (!defined('PHPUNIT_RUN') && headers_sent()) {
  192. // syntax issues in the config file like leading spaces causing PHP to send output
  193. $errorMessage = sprintf('Config file has leading content, please remove everything before "<?php" in %s', basename($file));
  194. if (!defined('OC_CONSOLE')) {
  195. print(\OCP\Util::sanitizeHTML($errorMessage));
  196. }
  197. throw new \Exception($errorMessage);
  198. }
  199. if (isset($CONFIG) && is_array($CONFIG)) {
  200. $this->cache = array_merge($this->cache, $CONFIG);
  201. }
  202. }
  203. // grab any "NC_" environment variables
  204. $envRaw = getenv();
  205. // only save environment variables prefixed with "NC_" in the cache
  206. $envPrefixLen = strlen(self::ENV_PREFIX);
  207. foreach ($envRaw as $rawEnvKey => $rawEnvValue) {
  208. if (str_starts_with($rawEnvKey, self::ENV_PREFIX)) {
  209. $realKey = substr($rawEnvKey, $envPrefixLen);
  210. $this->envCache[$realKey] = $rawEnvValue;
  211. }
  212. }
  213. }
  214. /**
  215. * Writes the config file
  216. *
  217. * Saves the config to the config file.
  218. *
  219. * @throws HintException If the config file cannot be written to
  220. * @throws \Exception If no file lock can be acquired
  221. */
  222. private function writeData() {
  223. $this->checkReadOnly();
  224. if (!is_file(\OC::$configDir . '/CAN_INSTALL') && !isset($this->cache['version'])) {
  225. throw new HintException(sprintf('Configuration was not read or initialized correctly, not overwriting %s', $this->configFilePath));
  226. }
  227. // Create a php file ...
  228. $content = "<?php\n";
  229. $content .= '$CONFIG = ';
  230. $content .= var_export($this->cache, true);
  231. $content .= ";\n";
  232. touch($this->configFilePath);
  233. $filePointer = fopen($this->configFilePath, 'r+');
  234. // Prevent others not to read the config
  235. chmod($this->configFilePath, 0640);
  236. // File does not exist, this can happen when doing a fresh install
  237. if (!is_resource($filePointer)) {
  238. throw new HintException(
  239. "Can't write into config directory!",
  240. 'This can usually be fixed by giving the webserver write access to the config directory.');
  241. }
  242. // Never write file back if disk space should be too low
  243. if (function_exists('disk_free_space')) {
  244. $df = disk_free_space($this->configDir);
  245. $size = strlen($content) + 10240;
  246. if ($df !== false && $df < (float)$size) {
  247. throw new \Exception($this->configDir . ' does not have enough space for writing the config file! Not writing it back!');
  248. }
  249. }
  250. // Try to acquire a file lock
  251. if (!flock($filePointer, LOCK_EX)) {
  252. throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
  253. }
  254. // Write the config and release the lock
  255. ftruncate($filePointer, 0);
  256. fwrite($filePointer, $content);
  257. fflush($filePointer);
  258. flock($filePointer, LOCK_UN);
  259. fclose($filePointer);
  260. if (function_exists('opcache_invalidate')) {
  261. @opcache_invalidate($this->configFilePath, true);
  262. }
  263. }
  264. /**
  265. * @throws HintException
  266. */
  267. private function checkReadOnly(): void {
  268. if ($this->isReadOnly) {
  269. throw new HintException(
  270. 'Config is set to be read-only via option "config_is_read_only".',
  271. 'Unset "config_is_read_only" to allow changes to the config file.');
  272. }
  273. }
  274. }