Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "ConfigDB.h"
21 :
22 : #include "lib/alignment.h"
23 : #include "lib/allocators/shared_ptr.h"
24 : #include "lib/debug.h"
25 : #include "lib/file/vfs/vfs.h"
26 : #include "lib/file/vfs/vfs_path.h"
27 : #include "lib/path.h"
28 : #include "lib/secure_crt.h"
29 : #include "lib/status.h"
30 : #include "ps/CLogger.h"
31 : #include "ps/CStr.h"
32 : #include "ps/Filesystem.h"
33 : #include "ps/Profiler2.h"
34 :
35 : #include <algorithm>
36 : #include <cstddef>
37 : #include <mutex>
38 : #include <unordered_set>
39 : #include <version>
40 :
41 : #if defined(__cpp_lib_to_chars)
42 : #include <charconv>
43 : #else
44 : #include <sstream>
45 : #endif
46 :
47 : namespace
48 : {
49 :
50 72 : void TriggerAllHooks(const std::multimap<CStr, std::function<void()>>& hooks, const CStr& name)
51 : {
52 72 : std::for_each(hooks.lower_bound(name), hooks.upper_bound(name), [](const std::pair<CStr, std::function<void()>>& hook) { hook.second(); });
53 72 : }
54 :
55 : // These entries will not be printed to logfiles, so that logfiles can be shared without leaking personal or sensitive data
56 : const std::unordered_set<std::string> g_UnloggedEntries = {
57 : "lobby.password",
58 : "lobby.buddies", // The buddy list of older versions, now stored in the server roster and removed on migration.
59 : "userreport.id" // authentication token for GDPR personal data requests
60 : };
61 :
62 : #define CHECK_NS(rval)\
63 : do {\
64 : if (ns < 0 || ns >= CFG_LAST)\
65 : {\
66 : debug_warn(L"CConfigDB: Invalid ns value");\
67 : return rval;\
68 : }\
69 : } while (false)
70 :
71 59 : template<typename T> void Get(const CStr& value, T& ret)
72 : {
73 : #if defined(__cpp_lib_to_chars)
74 59 : std::from_chars(value.data(), value.data() + value.size(), ret);
75 : #else
76 : // TODO: switch to std::from_chars after minimal libcxx supports it.
77 : std::stringstream ss(value);
78 : ss >> ret;
79 : #endif
80 59 : }
81 :
82 0 : template<> void Get<>(const CStr& value, bool& ret)
83 : {
84 0 : ret = value == "true";
85 0 : }
86 :
87 48 : template<> void Get<>(const CStr& value, std::string& ret)
88 : {
89 48 : ret = value;
90 48 : }
91 :
92 87 : std::string EscapeString(const CStr& str)
93 : {
94 87 : std::string ret;
95 469 : for (size_t i = 0; i < str.length(); ++i)
96 : {
97 382 : if (str[i] == '\\')
98 0 : ret += "\\\\";
99 382 : else if (str[i] == '"')
100 0 : ret += "\\\"";
101 : else
102 764 : ret += str[i];
103 : }
104 87 : return ret;
105 0 : }
106 :
107 : } // anonymous namespace
108 :
109 : #define GETVAL(type)\
110 : void CConfigDB::GetValue(EConfigNamespace ns, const std::string_view name, type& value)\
111 : {\
112 : CHECK_NS(;);\
113 : std::lock_guard<std::recursive_mutex> s(m_Mutex);\
114 : TConfigMap::iterator it = m_Map[CFG_COMMAND].find(name);\
115 : if (it != m_Map[CFG_COMMAND].end())\
116 : {\
117 : if (!it->second.empty())\
118 : ::Get(it->second[0], value);\
119 : return;\
120 : }\
121 : for (int search_ns = ns; search_ns >= 0; --search_ns)\
122 : {\
123 : it = m_Map[search_ns].find(name);\
124 : if (it != m_Map[search_ns].end())\
125 : {\
126 : if (!it->second.empty())\
127 : ::Get(it->second[0], value);\
128 : return;\
129 : }\
130 : }\
131 : }
132 420 : GETVAL(bool)
133 569 : GETVAL(int)
134 0 : GETVAL(std::uint32_t)
135 236 : GETVAL(float)
136 0 : GETVAL(double)
137 230 : GETVAL(std::string)
138 : #undef GETVAL
139 :
140 : std::unique_ptr<CConfigDB> g_ConfigDBPtr;
141 :
142 12 : void CConfigDB::Initialise()
143 : {
144 24 : g_ConfigDBPtr = std::make_unique<CConfigDB>();
145 12 : }
146 :
147 12 : void CConfigDB::Shutdown()
148 : {
149 12 : PROFILE2("CConfigDB::Shutdown");
150 12 : g_ConfigDBPtr.reset();
151 12 : }
152 :
153 31 : bool CConfigDB::IsInitialised()
154 : {
155 31 : return !!g_ConfigDBPtr;
156 : }
157 :
158 268 : CConfigDB* CConfigDB::Instance()
159 : {
160 268 : return g_ConfigDBPtr.get();
161 : }
162 :
163 58 : CConfigDB::CConfigDB()
164 : {
165 29 : m_HasChanges.fill(false);
166 29 : }
167 :
168 29 : CConfigDB::~CConfigDB()
169 : {
170 29 : }
171 :
172 0 : bool CConfigDB::HasChanges(EConfigNamespace ns) const
173 : {
174 0 : CHECK_NS(false);
175 :
176 0 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
177 0 : return m_HasChanges[ns];
178 : }
179 :
180 0 : void CConfigDB::SetChanges(EConfigNamespace ns, bool value)
181 : {
182 0 : CHECK_NS(;);
183 :
184 0 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
185 0 : m_HasChanges[ns] = value;
186 : }
187 :
188 0 : void CConfigDB::GetValues(EConfigNamespace ns, const CStr& name, CConfigValueSet& values) const
189 : {
190 0 : CHECK_NS(;);
191 :
192 0 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
193 0 : TConfigMap::const_iterator it = m_Map[CFG_COMMAND].find(name);
194 0 : if (it != m_Map[CFG_COMMAND].end())
195 : {
196 0 : values = it->second;
197 0 : return;
198 : }
199 :
200 0 : for (int search_ns = ns; search_ns >= 0; --search_ns)
201 : {
202 0 : it = m_Map[search_ns].find(name);
203 0 : if (it != m_Map[search_ns].end())
204 : {
205 0 : values = it->second;
206 : return;
207 : }
208 : }
209 : }
210 :
211 0 : EConfigNamespace CConfigDB::GetValueNamespace(EConfigNamespace ns, const CStr& name) const
212 : {
213 0 : CHECK_NS(CFG_LAST);
214 :
215 0 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
216 0 : TConfigMap::const_iterator it = m_Map[CFG_COMMAND].find(name);
217 0 : if (it != m_Map[CFG_COMMAND].end())
218 : return CFG_COMMAND;
219 :
220 0 : for (int search_ns = ns; search_ns >= 0; --search_ns)
221 : {
222 0 : it = m_Map[search_ns].find(name);
223 0 : if (it != m_Map[search_ns].end())
224 0 : return (EConfigNamespace)search_ns;
225 : }
226 :
227 : return CFG_LAST;
228 : }
229 :
230 21 : std::map<CStr, CConfigValueSet> CConfigDB::GetValuesWithPrefix(EConfigNamespace ns, const CStr& prefix) const
231 : {
232 21 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
233 21 : std::map<CStr, CConfigValueSet> ret;
234 :
235 21 : CHECK_NS(ret);
236 :
237 : // Loop upwards so that values in later namespaces can override
238 : // values in earlier namespaces
239 147 : for (int search_ns = 0; search_ns <= ns; ++search_ns)
240 223 : for (const std::pair<const CStr, CConfigValueSet>& p : m_Map[search_ns])
241 97 : if (p.first.starts_with(prefix))
242 17 : ret[p.first] = p.second;
243 :
244 21 : for (const std::pair<const CStr, CConfigValueSet>& p : m_Map[CFG_COMMAND])
245 0 : if (p.first.starts_with(prefix))
246 0 : ret[p.first] = p.second;
247 :
248 : return ret;
249 21 : }
250 :
251 72 : void CConfigDB::SetValueString(EConfigNamespace ns, const CStr& name, const CStr& value)
252 : {
253 72 : CHECK_NS(;);
254 :
255 144 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
256 72 : TConfigMap::iterator it = m_Map[ns].find(name);
257 72 : if (it == m_Map[ns].end())
258 90 : it = m_Map[ns].insert(m_Map[ns].begin(), make_pair(name, CConfigValueSet(1)));
259 :
260 72 : if (!it->second.empty())
261 72 : it->second[0] = value;
262 : else
263 0 : it->second.emplace_back(value);
264 :
265 72 : TriggerAllHooks(m_Hooks, name);
266 : }
267 :
268 0 : void CConfigDB::SetValueBool(EConfigNamespace ns, const CStr& name, const bool value)
269 : {
270 0 : CStr valueString = value ? "true" : "false";
271 0 : SetValueString(ns, name, valueString);
272 0 : }
273 :
274 4 : void CConfigDB::SetValueList(EConfigNamespace ns, const CStr& name, std::vector<CStr> values)
275 : {
276 4 : CHECK_NS(;);
277 :
278 8 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
279 4 : TConfigMap::iterator it = m_Map[ns].find(name);
280 4 : if (it == m_Map[ns].end())
281 8 : it = m_Map[ns].insert(m_Map[ns].begin(), make_pair(name, CConfigValueSet(1)));
282 :
283 4 : it->second = values;
284 : }
285 :
286 0 : bool CConfigDB::RemoveValue(EConfigNamespace ns, const CStr& name)
287 : {
288 0 : CHECK_NS(false);
289 :
290 0 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
291 0 : TConfigMap::iterator it = m_Map[ns].find(name);
292 0 : if (it == m_Map[ns].end())
293 : return false;
294 0 : m_Map[ns].erase(it);
295 :
296 0 : TriggerAllHooks(m_Hooks, name);
297 : return true;
298 : }
299 :
300 8 : void CConfigDB::SetConfigFile(EConfigNamespace ns, const VfsPath& path)
301 : {
302 8 : CHECK_NS(;);
303 :
304 16 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
305 16 : m_ConfigFile[ns] = path;
306 : }
307 :
308 41 : bool CConfigDB::Reload(EConfigNamespace ns)
309 : {
310 41 : CHECK_NS(false);
311 :
312 82 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
313 :
314 41 : std::unique_ptr<std::uint8_t[], AlignedDeleter> buffer;
315 41 : size_t buflen;
316 41 : {
317 : // Handle missing files quietly
318 41 : if (g_VFS->GetFileInfo(m_ConfigFile[ns], NULL) < 0)
319 : {
320 9 : LOGMESSAGE("Cannot find config file \"{}\" - ignoring", m_ConfigFile[ns].string8());
321 3 : return false;
322 : }
323 :
324 114 : LOGMESSAGE("Loading config file \"{}\"", m_ConfigFile[ns].string8());
325 38 : Status ret = g_VFS->LoadFile(m_ConfigFile[ns], buffer, buflen);
326 38 : if (ret != INFO::OK)
327 : {
328 0 : LOGERROR("CConfigDB::Reload(): vfs_load for \"{}\" failed: return was {}",
329 : m_ConfigFile[ns].string8(), static_cast<long long>(ret));
330 0 : return false;
331 : }
332 : }
333 :
334 79 : TConfigMap newMap;
335 38 : if (ns == CFG_MOD)
336 4 : newMap.swap(m_Map[CFG_MOD]);
337 :
338 38 : char *filebuf = (char*)buffer.get();
339 38 : char *filebufend = filebuf+buflen;
340 :
341 38 : bool quoted = false;
342 76 : CStr header;
343 38 : CStr name;
344 38 : CStr value;
345 38 : int line = 1;
346 38 : std::vector<CStr> values;
347 516 : for (char* pos = filebuf; pos < filebufend; ++pos)
348 : {
349 478 : switch (*pos)
350 : {
351 : case '\n':
352 : case ';':
353 : break; // We finished parsing this line
354 :
355 45 : case ' ':
356 45 : case '\r':
357 45 : case '\t':
358 45 : continue; // ignore
359 :
360 3 : case '[':
361 3 : header.clear();
362 21 : for (++pos; pos < filebufend && *pos != '\n' && *pos != ']'; ++pos)
363 18 : header.push_back(*pos);
364 :
365 3 : if (pos == filebufend || *pos == '\n')
366 : {
367 0 : LOGERROR("Config header with missing close tag encountered on line {} in '{}'",
368 : line, m_ConfigFile[ns].string8());
369 0 : header.clear();
370 0 : ++line;
371 0 : continue;
372 0 : }
373 :
374 6 : LOGMESSAGE("Found config header '{}'", header);
375 3 : header.push_back('.');
376 3 : while (++pos < filebufend && *pos != '\n' && *pos != ';')
377 0 : if (*pos != ' ' && *pos != '\r')
378 : {
379 0 : LOGERROR("Config settings on the same line as a header on line {} in '{}'",
380 : line, m_ConfigFile[ns].string8());
381 0 : break;
382 : }
383 3 : while (pos < filebufend && *pos != '\n')
384 0 : ++pos;
385 3 : ++line;
386 3 : continue;
387 :
388 45 : case '=':
389 : // Parse parameters (comma separated, possibly quoted)
390 138 : for (++pos; pos < filebufend && *pos != '\n' && *pos != ';'; ++pos)
391 : {
392 93 : switch (*pos)
393 : {
394 32 : case '"':
395 32 : quoted = true;
396 : // parse until not quoted anymore
397 207 : for (++pos; pos < filebufend && *pos != '\n' && *pos != '"'; ++pos)
398 : {
399 175 : if (*pos == '\\' && ++pos == filebufend)
400 : {
401 0 : LOGERROR("Escape character at end of input (line {} in '{}')",
402 : line, m_ConfigFile[ns].string8());
403 0 : break;
404 : }
405 :
406 175 : value.push_back(*pos);
407 : }
408 32 : if (pos < filebufend && *pos == '"')
409 : quoted = false;
410 : else
411 0 : --pos; // We should terminate the outer loop too
412 : break;
413 :
414 : case ' ':
415 : case '\r':
416 : case '\t':
417 : break; // ignore
418 :
419 0 : case ',':
420 0 : if (!value.empty())
421 0 : values.push_back(value);
422 93 : value.clear();
423 : break;
424 :
425 16 : default:
426 16 : value.push_back(*pos);
427 : break;
428 : }
429 : }
430 45 : if (quoted) // We ignore the invalid parameter
431 : {
432 0 : LOGERROR("Unmatched quote while parsing config file '{}' on line {}",
433 : m_ConfigFile[ns].string8(), line);
434 : }
435 45 : else if (!value.empty())
436 44 : values.push_back(value);
437 45 : value.clear();
438 45 : quoted = false;
439 45 : break; // We are either at the end of the line, or we still have a comment to parse
440 :
441 383 : default:
442 383 : name.push_back(*pos);
443 383 : continue;
444 431 : }
445 :
446 : // Consume the rest of the line
447 47 : while (pos < filebufend && *pos != '\n')
448 0 : ++pos;
449 : // Store the setting
450 47 : if (!name.empty())
451 : {
452 90 : CStr key(header + name);
453 45 : newMap[key] = values;
454 45 : if (g_UnloggedEntries.find(key) != g_UnloggedEntries.end())
455 0 : LOGMESSAGE("Loaded config string \"{}\"", key);
456 45 : else if (values.empty())
457 3 : LOGMESSAGE("Loaded config string \"{}\" = (empty)", key);
458 : else
459 : {
460 44 : std::string vals;
461 44 : for (size_t i = 0; i + 1 < newMap[key].size(); ++i)
462 0 : vals += "\"" + EscapeString(newMap[key][i]) + "\", ";
463 176 : vals += "\"" + EscapeString(newMap[key][values.size()-1]) + "\"";
464 132 : LOGMESSAGE("Loaded config string \"{}\" = {}", key, vals);
465 44 : }
466 45 : }
467 :
468 47 : name.clear();
469 47 : values.clear();
470 47 : ++line;
471 : }
472 :
473 38 : if (!name.empty())
474 0 : LOGERROR("Config file does not have a new line after the last config setting '{}'", name);
475 :
476 38 : m_Map[ns].swap(newMap);
477 38 : m_HasChanges[ns] = false;
478 :
479 38 : return true;
480 : }
481 :
482 33 : bool CConfigDB::WriteFile(EConfigNamespace ns) const
483 : {
484 33 : CHECK_NS(false);
485 :
486 66 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
487 33 : return WriteFile(ns, m_ConfigFile[ns]);
488 : }
489 :
490 36 : bool CConfigDB::WriteFile(EConfigNamespace ns, const VfsPath& path) const
491 : {
492 36 : CHECK_NS(false);
493 :
494 72 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
495 36 : std::shared_ptr<std::uint8_t> buf;
496 :
497 36 : const size_t buffersize = 1*MiB;
498 36 : AllocateAligned(buf, buffersize, maxSectorSize);
499 36 : size_t len = 0;
500 36 : char* pos = (char*)buf.get();
501 :
502 77 : for (const std::pair<const CStr, CConfigValueSet>& p : m_Map[ns])
503 : {
504 41 : size_t i;
505 41 : pos += sprintf_s(pos, buffersize - len, "%s = ", p.first.c_str());
506 44 : for (i = 0; i + 1 < p.second.size(); ++i)
507 3 : pos += sprintf_s(pos, buffersize - len, "\"%s\", ", EscapeString(p.second[i]).c_str());
508 41 : if (!p.second.empty())
509 40 : pos += sprintf_s(pos, buffersize - len, "\"%s\"\n", EscapeString(p.second[i]).c_str());
510 : else
511 1 : pos += sprintf_s(pos, buffersize - len, "\"\"\n");
512 :
513 41 : len = pos - (char*)buf.get();
514 : }
515 :
516 36 : Status ret = g_VFS->CreateFile(path, {buf.get(), len});
517 36 : if (ret < 0)
518 : {
519 0 : LOGERROR("CConfigDB::WriteFile(): CreateFile \"{}\" failed (error: {})", path.string8(),
520 : static_cast<int>(ret));
521 0 : return false;
522 : }
523 :
524 : return true;
525 : }
526 :
527 0 : bool CConfigDB::WriteValueToFile(EConfigNamespace ns, const CStr& name, const CStr& value)
528 : {
529 0 : CHECK_NS(false);
530 :
531 0 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
532 0 : return WriteValueToFile(ns, name, value, m_ConfigFile[ns]);
533 : }
534 :
535 0 : bool CConfigDB::WriteValueToFile(EConfigNamespace ns, const CStr& name, const CStr& value, const VfsPath& path)
536 : {
537 0 : CHECK_NS(false);
538 :
539 0 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
540 :
541 0 : TConfigMap newMap;
542 0 : m_Map[ns].swap(newMap);
543 0 : Reload(ns);
544 :
545 0 : SetValueString(ns, name, value);
546 0 : bool ret = WriteFile(ns, path);
547 0 : m_Map[ns].swap(newMap);
548 0 : return ret;
549 : }
550 :
551 12 : CConfigDBHook CConfigDB::RegisterHookAndCall(const CStr& name, std::function<void()> hook)
552 : {
553 12 : hook();
554 12 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
555 12 : return CConfigDBHook(*this, m_Hooks.emplace(name, hook));
556 12 : }
557 :
558 24 : void CConfigDB::UnregisterHook(CConfigDBHook&& hook)
559 : {
560 24 : if (hook.m_Ptr != m_Hooks.end())
561 : {
562 12 : std::lock_guard<std::recursive_mutex> s(m_Mutex);
563 12 : m_Hooks.erase(hook.m_Ptr);
564 12 : hook.m_Ptr = m_Hooks.end();
565 12 : }
566 24 : }
567 :
568 0 : void CConfigDB::UnregisterHook(std::unique_ptr<CConfigDBHook> hook)
569 : {
570 0 : UnregisterHook(std::move(*hook.get()));
571 0 : }
572 :
573 : #undef CHECK_NS
|