Config.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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_keys($this->cache);
  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. $envKey = self::ENV_PREFIX . $key;
  61. if (isset($this->envCache[$envKey])) {
  62. return $this->envCache[$envKey];
  63. }
  64. if (isset($this->cache[$key])) {
  65. return $this->cache[$key];
  66. }
  67. return $default;
  68. }
  69. /**
  70. * Sets and deletes values and writes the config.php
  71. *
  72. * @param array $configs Associative array with `key => value` pairs
  73. * If value is null, the config key will be deleted
  74. * @throws HintException
  75. */
  76. public function setValues(array $configs) {
  77. $needsUpdate = false;
  78. foreach ($configs as $key => $value) {
  79. if ($value !== null) {
  80. $needsUpdate |= $this->set($key, $value);
  81. } else {
  82. $needsUpdate |= $this->delete($key);
  83. }
  84. }
  85. if ($needsUpdate) {
  86. // Write changes
  87. $this->writeData();
  88. }
  89. }
  90. /**
  91. * Sets the value and writes it to config.php if required
  92. *
  93. * @param string $key key
  94. * @param mixed $value value
  95. * @throws HintException
  96. */
  97. public function setValue($key, $value) {
  98. if ($this->set($key, $value)) {
  99. // Write changes
  100. $this->writeData();
  101. }
  102. }
  103. /**
  104. * This function sets the value
  105. *
  106. * @param string $key key
  107. * @param mixed $value value
  108. * @return bool True if the file needs to be updated, false otherwise
  109. * @throws HintException
  110. */
  111. protected function set($key, $value) {
  112. if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
  113. // Add change
  114. $this->cache[$key] = $value;
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Removes a key from the config and removes it from config.php if required
  121. *
  122. * @param string $key
  123. * @throws HintException
  124. */
  125. public function deleteKey($key) {
  126. if ($this->delete($key)) {
  127. // Write changes
  128. $this->writeData();
  129. }
  130. }
  131. /**
  132. * This function removes a key from the config
  133. *
  134. * @param string $key
  135. * @return bool True if the file needs to be updated, false otherwise
  136. * @throws HintException
  137. */
  138. protected function delete($key) {
  139. if (isset($this->cache[$key])) {
  140. // Delete key from cache
  141. unset($this->cache[$key]);
  142. return true;
  143. }
  144. return false;
  145. }
  146. /**
  147. * Loads the config file
  148. *
  149. * Reads the config file and saves it to the cache
  150. *
  151. * @throws \Exception If no lock could be acquired or the config file has not been found
  152. */
  153. private function readData() {
  154. // Default config should always get loaded
  155. $configFiles = [$this->configFilePath];
  156. // Add all files in the config dir ending with the same file name
  157. $extra = glob($this->configDir.'*.'.$this->configFileName);
  158. if (is_array($extra)) {
  159. natsort($extra);
  160. $configFiles = array_merge($configFiles, $extra);
  161. }
  162. // Include file and merge config
  163. foreach ($configFiles as $file) {
  164. unset($CONFIG);
  165. // Invalidate opcache (only if the timestamp changed)
  166. if (function_exists('opcache_invalidate')) {
  167. opcache_invalidate($file, false);
  168. }
  169. $filePointer = @fopen($file, 'r');
  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. $this->envCache = getenv();
  204. }
  205. /**
  206. * Writes the config file
  207. *
  208. * Saves the config to the config file.
  209. *
  210. * @throws HintException If the config file cannot be written to
  211. * @throws \Exception If no file lock can be acquired
  212. */
  213. private function writeData() {
  214. $this->checkReadOnly();
  215. if (!is_file(\OC::$configDir.'/CAN_INSTALL') && !isset($this->cache['version'])) {
  216. throw new HintException(sprintf('Configuration was not read or initialized correctly, not overwriting %s', $this->configFilePath));
  217. }
  218. // Create a php file ...
  219. $content = "<?php\n";
  220. $content .= '$CONFIG = ';
  221. $content .= var_export($this->cache, true);
  222. $content .= ";\n";
  223. touch($this->configFilePath);
  224. $filePointer = fopen($this->configFilePath, 'r+');
  225. // Prevent others not to read the config
  226. chmod($this->configFilePath, 0640);
  227. // File does not exist, this can happen when doing a fresh install
  228. if (!is_resource($filePointer)) {
  229. throw new HintException(
  230. "Can't write into config directory!",
  231. 'This can usually be fixed by giving the webserver write access to the config directory.');
  232. }
  233. // Never write file back if disk space should be too low
  234. if (function_exists('disk_free_space')) {
  235. $df = disk_free_space($this->configDir);
  236. $size = strlen($content) + 10240;
  237. if ($df !== false && $df < (float)$size) {
  238. throw new \Exception($this->configDir . " does not have enough space for writing the config file! Not writing it back!");
  239. }
  240. }
  241. // Try to acquire a file lock
  242. if (!flock($filePointer, LOCK_EX)) {
  243. throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
  244. }
  245. // Write the config and release the lock
  246. ftruncate($filePointer, 0);
  247. fwrite($filePointer, $content);
  248. fflush($filePointer);
  249. flock($filePointer, LOCK_UN);
  250. fclose($filePointer);
  251. if (function_exists('opcache_invalidate')) {
  252. @opcache_invalidate($this->configFilePath, true);
  253. }
  254. }
  255. /**
  256. * @throws HintException
  257. */
  258. private function checkReadOnly(): void {
  259. if ($this->isReadOnly) {
  260. throw new HintException(
  261. 'Config is set to be read-only via option "config_is_read_only".',
  262. 'Unset "config_is_read_only" to allow changes to the config file.');
  263. }
  264. }
  265. }