Config.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. $filePointer = @fopen($file, 'r');
  169. if ($filePointer === false) {
  170. // e.g. wrong permissions are set
  171. if ($file === $this->configFilePath) {
  172. // opening the main config file might not be possible
  173. // (likely on a new installation)
  174. continue;
  175. }
  176. http_response_code(500);
  177. die(sprintf('FATAL: Could not open the config file %s', $file));
  178. }
  179. // Try to acquire a file lock
  180. if (!flock($filePointer, LOCK_SH)) {
  181. throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
  182. }
  183. try {
  184. include $file;
  185. } finally {
  186. // Close the file pointer and release the lock
  187. flock($filePointer, LOCK_UN);
  188. fclose($filePointer);
  189. }
  190. if (!defined('PHPUNIT_RUN') && headers_sent()) {
  191. // syntax issues in the config file like leading spaces causing PHP to send output
  192. $errorMessage = sprintf('Config file has leading content, please remove everything before "<?php" in %s', basename($file));
  193. if (!defined('OC_CONSOLE')) {
  194. print(\OCP\Util::sanitizeHTML($errorMessage));
  195. }
  196. throw new \Exception($errorMessage);
  197. }
  198. if (isset($CONFIG) && is_array($CONFIG)) {
  199. $this->cache = array_merge($this->cache, $CONFIG);
  200. }
  201. }
  202. // grab any "NC_" environment variables
  203. $envRaw = getenv();
  204. // only save environment variables prefixed with "NC_" in the cache
  205. $envPrefixLen = strlen(self::ENV_PREFIX);
  206. foreach ($envRaw as $rawEnvKey => $rawEnvValue) {
  207. if (str_starts_with($rawEnvKey, self::ENV_PREFIX)) {
  208. $realKey = substr($rawEnvKey, $envPrefixLen);
  209. $this->envCache[$realKey] = $rawEnvValue;
  210. }
  211. }
  212. }
  213. /**
  214. * Writes the config file
  215. *
  216. * Saves the config to the config file.
  217. *
  218. * @throws HintException If the config file cannot be written to
  219. * @throws \Exception If no file lock can be acquired
  220. */
  221. private function writeData() {
  222. $this->checkReadOnly();
  223. if (!is_file(\OC::$configDir.'/CAN_INSTALL') && !isset($this->cache['version'])) {
  224. throw new HintException(sprintf('Configuration was not read or initialized correctly, not overwriting %s', $this->configFilePath));
  225. }
  226. // Create a php file ...
  227. $content = "<?php\n";
  228. $content .= '$CONFIG = ';
  229. $content .= var_export($this->cache, true);
  230. $content .= ";\n";
  231. touch($this->configFilePath);
  232. $filePointer = fopen($this->configFilePath, 'r+');
  233. // Prevent others not to read the config
  234. chmod($this->configFilePath, 0640);
  235. // File does not exist, this can happen when doing a fresh install
  236. if (!is_resource($filePointer)) {
  237. throw new HintException(
  238. "Can't write into config directory!",
  239. 'This can usually be fixed by giving the webserver write access to the config directory.');
  240. }
  241. // Never write file back if disk space should be too low
  242. if (function_exists('disk_free_space')) {
  243. $df = disk_free_space($this->configDir);
  244. $size = strlen($content) + 10240;
  245. if ($df !== false && $df < (float)$size) {
  246. throw new \Exception($this->configDir . ' does not have enough space for writing the config file! Not writing it back!');
  247. }
  248. }
  249. // Try to acquire a file lock
  250. if (!flock($filePointer, LOCK_EX)) {
  251. throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
  252. }
  253. // Write the config and release the lock
  254. ftruncate($filePointer, 0);
  255. fwrite($filePointer, $content);
  256. fflush($filePointer);
  257. flock($filePointer, LOCK_UN);
  258. fclose($filePointer);
  259. if (function_exists('opcache_invalidate')) {
  260. @opcache_invalidate($this->configFilePath, true);
  261. }
  262. }
  263. /**
  264. * @throws HintException
  265. */
  266. private function checkReadOnly(): void {
  267. if ($this->isReadOnly) {
  268. throw new HintException(
  269. 'Config is set to be read-only via option "config_is_read_only".',
  270. 'Unset "config_is_read_only" to allow changes to the config file.');
  271. }
  272. }
  273. }