1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include <sync.h>
7 #include <util/system.h>
8
9 #ifdef HAVE_BOOST_PROCESS
10 #include <boost/process.hpp>
11 #endif // HAVE_BOOST_PROCESS
12
13 #include <chainparamsbase.h>
14 #include <util/strencodings.h>
15 #include <util/string.h>
16 #include <util/translation.h>
17
18
19 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
20 #include <pthread.h>
21 #include <pthread_np.h>
22 #endif
23
24 #ifndef WIN32
25 // for posix_fallocate, in configure.ac we check if it is present after this
26 #ifdef __linux__
27
28 #ifdef _POSIX_C_SOURCE
29 #undef _POSIX_C_SOURCE
30 #endif
31
32 #define _POSIX_C_SOURCE 200112L
33
34 #endif // __linux__
35
36 #include <algorithm>
37 #include <cassert>
38 #include <fcntl.h>
39 #include <sched.h>
40 #include <sys/resource.h>
41 #include <sys/stat.h>
42
43 #else
44
45 #ifdef _MSC_VER
46 #pragma warning(disable:4786)
47 #pragma warning(disable:4804)
48 #pragma warning(disable:4805)
49 #pragma warning(disable:4717)
50 #endif
51
52 #ifndef NOMINMAX
53 #define NOMINMAX
54 #endif
55 #include <codecvt>
56
57 #include <io.h> /* for _commit */
58 #include <shellapi.h>
59 #include <shlobj.h>
60 #endif
61
62 #ifdef HAVE_MALLOPT_ARENA_MAX
63 #include <malloc.h>
64 #endif
65
66 #include <boost/algorithm/string/replace.hpp>
67 #include <thread>
68 #include <typeinfo>
69 #include <univalue.h>
70
71 // Application startup time (used for uptime calculation)
72 const int64_t nStartupTime = GetTime();
73
74 const char * const BITCOIN_CONF_FILENAME = "namecoin.conf";
75 const char * const BITCOIN_SETTINGS_FILENAME = "settings.json";
76
77 ArgsManager gArgs;
78
79 /** Mutex to protect dir_locks. */
80 static Mutex cs_dir_locks;
81 /** A map that contains all the currently held directory locks. After
82 * successful locking, these will be held here until the global destructor
83 * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
84 * is called.
85 */
86 static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
87
LockDirectory(const fs::path & directory,const std::string lockfile_name,bool probe_only)88 bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
89 {
90 LOCK(cs_dir_locks);
91 fs::path pathLockFile = directory / lockfile_name;
92
93 // If a lock for this directory already exists in the map, don't try to re-lock it
94 if (dir_locks.count(pathLockFile.string())) {
95 return true;
96 }
97
98 // Create empty lock file if it doesn't exist.
99 FILE* file = fsbridge::fopen(pathLockFile, "a");
100 if (file) fclose(file);
101 auto lock = MakeUnique<fsbridge::FileLock>(pathLockFile);
102 if (!lock->TryLock()) {
103 return error("Error while attempting to lock directory %s: %s", directory.string(), lock->GetReason());
104 }
105 if (!probe_only) {
106 // Lock successful and we're not just probing, put it into the map
107 dir_locks.emplace(pathLockFile.string(), std::move(lock));
108 }
109 return true;
110 }
111
UnlockDirectory(const fs::path & directory,const std::string & lockfile_name)112 void UnlockDirectory(const fs::path& directory, const std::string& lockfile_name)
113 {
114 LOCK(cs_dir_locks);
115 dir_locks.erase((directory / lockfile_name).string());
116 }
117
ReleaseDirectoryLocks()118 void ReleaseDirectoryLocks()
119 {
120 LOCK(cs_dir_locks);
121 dir_locks.clear();
122 }
123
DirIsWritable(const fs::path & directory)124 bool DirIsWritable(const fs::path& directory)
125 {
126 fs::path tmpFile = directory / fs::unique_path();
127
128 FILE* file = fsbridge::fopen(tmpFile, "a");
129 if (!file) return false;
130
131 fclose(file);
132 remove(tmpFile);
133
134 return true;
135 }
136
CheckDiskSpace(const fs::path & dir,uint64_t additional_bytes)137 bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
138 {
139 constexpr uint64_t min_disk_space = 52428800; // 50 MiB
140
141 uint64_t free_bytes_available = fs::space(dir).available;
142 return free_bytes_available >= min_disk_space + additional_bytes;
143 }
144
GetFileSize(const char * path,std::streamsize max)145 std::streampos GetFileSize(const char* path, std::streamsize max) {
146 std::ifstream file(path, std::ios::binary);
147 file.ignore(max);
148 return file.gcount();
149 }
150
151 /**
152 * Interpret a string argument as a boolean.
153 *
154 * The definition of atoi() requires that non-numeric string values like "foo",
155 * return 0. This means that if a user unintentionally supplies a non-integer
156 * argument here, the return value is always false. This means that -foo=false
157 * does what the user probably expects, but -foo=true is well defined but does
158 * not do what they probably expected.
159 *
160 * The return value of atoi() is undefined when given input not representable as
161 * an int. On most systems this means string value between "-2147483648" and
162 * "2147483647" are well defined (this method will return true). Setting
163 * -txindex=2147483648 on most systems, however, is probably undefined.
164 *
165 * For a more extensive discussion of this topic (and a wide range of opinions
166 * on the Right Way to change this code), see PR12713.
167 */
InterpretBool(const std::string & strValue)168 static bool InterpretBool(const std::string& strValue)
169 {
170 if (strValue.empty())
171 return true;
172 return (atoi(strValue) != 0);
173 }
174
SettingName(const std::string & arg)175 static std::string SettingName(const std::string& arg)
176 {
177 return arg.size() > 0 && arg[0] == '-' ? arg.substr(1) : arg;
178 }
179
180 /**
181 * Interpret -nofoo as if the user supplied -foo=0.
182 *
183 * This method also tracks when the -no form was supplied, and if so,
184 * checks whether there was a double-negative (-nofoo=0 -> -foo=1).
185 *
186 * If there was not a double negative, it removes the "no" from the key
187 * and returns false.
188 *
189 * If there was a double negative, it removes "no" from the key, and
190 * returns true.
191 *
192 * If there was no "no", it returns the string value untouched.
193 *
194 * Where an option was negated can be later checked using the
195 * IsArgNegated() method. One use case for this is to have a way to disable
196 * options that are not normally boolean (e.g. using -nodebuglogfile to request
197 * that debug log output is not sent to any file at all).
198 */
199
InterpretOption(std::string & section,std::string & key,const std::string & value)200 static util::SettingsValue InterpretOption(std::string& section, std::string& key, const std::string& value)
201 {
202 // Split section name from key name for keys like "testnet.foo" or "regtest.bar"
203 size_t option_index = key.find('.');
204 if (option_index != std::string::npos) {
205 section = key.substr(0, option_index);
206 key.erase(0, option_index + 1);
207 }
208 if (key.substr(0, 2) == "no") {
209 key.erase(0, 2);
210 // Double negatives like -nofoo=0 are supported (but discouraged)
211 if (!InterpretBool(value)) {
212 LogPrintf("Warning: parsed potentially confusing double-negative -%s=%s\n", key, value);
213 return true;
214 }
215 return false;
216 }
217 return value;
218 }
219
220 /**
221 * Check settings value validity according to flags.
222 *
223 * TODO: Add more meaningful error checks here in the future
224 * See "here's how the flags are meant to behave" in
225 * https://github.com/bitcoin/bitcoin/pull/16097#issuecomment-514627823
226 */
CheckValid(const std::string & key,const util::SettingsValue & val,unsigned int flags,std::string & error)227 static bool CheckValid(const std::string& key, const util::SettingsValue& val, unsigned int flags, std::string& error)
228 {
229 if (val.isBool() && !(flags & ArgsManager::ALLOW_BOOL)) {
230 error = strprintf("Negating of -%s is meaningless and therefore forbidden", key);
231 return false;
232 }
233 return true;
234 }
235
236 // Define default constructor and destructor that are not inline, so code instantiating this class doesn't need to
237 // #include class definitions for all members.
238 // For example, m_settings has an internal dependency on univalue.
ArgsManager()239 ArgsManager::ArgsManager() {}
~ArgsManager()240 ArgsManager::~ArgsManager() {}
241
GetUnsuitableSectionOnlyArgs() const242 const std::set<std::string> ArgsManager::GetUnsuitableSectionOnlyArgs() const
243 {
244 std::set<std::string> unsuitables;
245
246 LOCK(cs_args);
247
248 // if there's no section selected, don't worry
249 if (m_network.empty()) return std::set<std::string> {};
250
251 // if it's okay to use the default section for this network, don't worry
252 if (m_network == CBaseChainParams::MAIN) return std::set<std::string> {};
253
254 for (const auto& arg : m_network_only_args) {
255 if (OnlyHasDefaultSectionSetting(m_settings, m_network, SettingName(arg))) {
256 unsuitables.insert(arg);
257 }
258 }
259 return unsuitables;
260 }
261
GetUnrecognizedSections() const262 const std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
263 {
264 // Section names to be recognized in the config file.
265 static const std::set<std::string> available_sections{
266 CBaseChainParams::REGTEST,
267 CBaseChainParams::SIGNET,
268 CBaseChainParams::TESTNET,
269 CBaseChainParams::MAIN
270 };
271
272 LOCK(cs_args);
273 std::list<SectionInfo> unrecognized = m_config_sections;
274 unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
275 return unrecognized;
276 }
277
SelectConfigNetwork(const std::string & network)278 void ArgsManager::SelectConfigNetwork(const std::string& network)
279 {
280 LOCK(cs_args);
281 m_network = network;
282 }
283
ParseParameters(int argc,const char * const argv[],std::string & error)284 bool ArgsManager::ParseParameters(int argc, const char* const argv[], std::string& error)
285 {
286 LOCK(cs_args);
287 m_settings.command_line_options.clear();
288
289 for (int i = 1; i < argc; i++) {
290 std::string key(argv[i]);
291
292 #ifdef MAC_OSX
293 // At the first time when a user gets the "App downloaded from the
294 // internet" warning, and clicks the Open button, macOS passes
295 // a unique process serial number (PSN) as -psn_... command-line
296 // argument, which we filter out.
297 if (key.substr(0, 5) == "-psn_") continue;
298 #endif
299
300 if (key == "-") break; //bitcoin-tx using stdin
301 std::string val;
302 size_t is_index = key.find('=');
303 if (is_index != std::string::npos) {
304 val = key.substr(is_index + 1);
305 key.erase(is_index);
306 }
307 #ifdef WIN32
308 key = ToLower(key);
309 if (key[0] == '/')
310 key[0] = '-';
311 #endif
312
313 if (key[0] != '-')
314 break;
315
316 // Transform --foo to -foo
317 if (key.length() > 1 && key[1] == '-')
318 key.erase(0, 1);
319
320 // Transform -foo to foo
321 key.erase(0, 1);
322 std::string section;
323 util::SettingsValue value = InterpretOption(section, key, val);
324 Optional<unsigned int> flags = GetArgFlags('-' + key);
325
326 // Unknown command line options and command line options with dot
327 // characters (which are returned from InterpretOption with nonempty
328 // section strings) are not valid.
329 if (!flags || !section.empty()) {
330 error = strprintf("Invalid parameter %s", argv[i]);
331 return false;
332 }
333
334 if (!CheckValid(key, value, *flags, error)) return false;
335
336 m_settings.command_line_options[key].push_back(value);
337 }
338
339 // we do not allow -includeconf from command line
340 bool success = true;
341 if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
342 for (const auto& include : util::SettingsSpan(*includes)) {
343 error += "-includeconf cannot be used from commandline; -includeconf=" + include.get_str() + "\n";
344 success = false;
345 }
346 }
347 return success;
348 }
349
GetArgFlags(const std::string & name) const350 Optional<unsigned int> ArgsManager::GetArgFlags(const std::string& name) const
351 {
352 LOCK(cs_args);
353 for (const auto& arg_map : m_available_args) {
354 const auto search = arg_map.second.find(name);
355 if (search != arg_map.second.end()) {
356 return search->second.m_flags;
357 }
358 }
359 return nullopt;
360 }
361
GetArgs(const std::string & strArg) const362 std::vector<std::string> ArgsManager::GetArgs(const std::string& strArg) const
363 {
364 std::vector<std::string> result;
365 for (const util::SettingsValue& value : GetSettingsList(strArg)) {
366 result.push_back(value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str());
367 }
368 return result;
369 }
370
IsArgSet(const std::string & strArg) const371 bool ArgsManager::IsArgSet(const std::string& strArg) const
372 {
373 return !GetSetting(strArg).isNull();
374 }
375
InitSettings(std::string & error)376 bool ArgsManager::InitSettings(std::string& error)
377 {
378 if (!GetSettingsPath()) {
379 return true; // Do nothing if settings file disabled.
380 }
381
382 std::vector<std::string> errors;
383 if (!ReadSettingsFile(&errors)) {
384 error = strprintf("Failed loading settings file:\n- %s\n", Join(errors, "\n- "));
385 return false;
386 }
387 if (!WriteSettingsFile(&errors)) {
388 error = strprintf("Failed saving settings file:\n- %s\n", Join(errors, "\n- "));
389 return false;
390 }
391 return true;
392 }
393
GetSettingsPath(fs::path * filepath,bool temp) const394 bool ArgsManager::GetSettingsPath(fs::path* filepath, bool temp) const
395 {
396 if (IsArgNegated("-settings")) {
397 return false;
398 }
399 if (filepath) {
400 std::string settings = GetArg("-settings", BITCOIN_SETTINGS_FILENAME);
401 *filepath = fs::absolute(temp ? settings + ".tmp" : settings, GetDataDir(/* net_specific= */ true));
402 }
403 return true;
404 }
405
SaveErrors(const std::vector<std::string> errors,std::vector<std::string> * error_out)406 static void SaveErrors(const std::vector<std::string> errors, std::vector<std::string>* error_out)
407 {
408 for (const auto& error : errors) {
409 if (error_out) {
410 error_out->emplace_back(error);
411 } else {
412 LogPrintf("%s\n", error);
413 }
414 }
415 }
416
ReadSettingsFile(std::vector<std::string> * errors)417 bool ArgsManager::ReadSettingsFile(std::vector<std::string>* errors)
418 {
419 fs::path path;
420 if (!GetSettingsPath(&path, /* temp= */ false)) {
421 return true; // Do nothing if settings file disabled.
422 }
423
424 LOCK(cs_args);
425 m_settings.rw_settings.clear();
426 std::vector<std::string> read_errors;
427 if (!util::ReadSettings(path, m_settings.rw_settings, read_errors)) {
428 SaveErrors(read_errors, errors);
429 return false;
430 }
431 for (const auto& setting : m_settings.rw_settings) {
432 std::string section;
433 std::string key = setting.first;
434 (void)InterpretOption(section, key, /* value */ {}); // Split setting key into section and argname
435 if (!GetArgFlags('-' + key)) {
436 LogPrintf("Ignoring unknown rw_settings value %s\n", setting.first);
437 }
438 }
439 return true;
440 }
441
WriteSettingsFile(std::vector<std::string> * errors) const442 bool ArgsManager::WriteSettingsFile(std::vector<std::string>* errors) const
443 {
444 fs::path path, path_tmp;
445 if (!GetSettingsPath(&path, /* temp= */ false) || !GetSettingsPath(&path_tmp, /* temp= */ true)) {
446 throw std::logic_error("Attempt to write settings file when dynamic settings are disabled.");
447 }
448
449 LOCK(cs_args);
450 std::vector<std::string> write_errors;
451 if (!util::WriteSettings(path_tmp, m_settings.rw_settings, write_errors)) {
452 SaveErrors(write_errors, errors);
453 return false;
454 }
455 if (!RenameOver(path_tmp, path)) {
456 SaveErrors({strprintf("Failed renaming settings file %s to %s\n", path_tmp.string(), path.string())}, errors);
457 return false;
458 }
459 return true;
460 }
461
IsArgNegated(const std::string & strArg) const462 bool ArgsManager::IsArgNegated(const std::string& strArg) const
463 {
464 return GetSetting(strArg).isFalse();
465 }
466
GetArg(const std::string & strArg,const std::string & strDefault) const467 std::string ArgsManager::GetArg(const std::string& strArg, const std::string& strDefault) const
468 {
469 const util::SettingsValue value = GetSetting(strArg);
470 return value.isNull() ? strDefault : value.isFalse() ? "0" : value.isTrue() ? "1" : value.get_str();
471 }
472
GetArg(const std::string & strArg,int64_t nDefault) const473 int64_t ArgsManager::GetArg(const std::string& strArg, int64_t nDefault) const
474 {
475 const util::SettingsValue value = GetSetting(strArg);
476 return value.isNull() ? nDefault : value.isFalse() ? 0 : value.isTrue() ? 1 : value.isNum() ? value.get_int64() : atoi64(value.get_str());
477 }
478
GetBoolArg(const std::string & strArg,bool fDefault) const479 bool ArgsManager::GetBoolArg(const std::string& strArg, bool fDefault) const
480 {
481 const util::SettingsValue value = GetSetting(strArg);
482 return value.isNull() ? fDefault : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
483 }
484
SoftSetArg(const std::string & strArg,const std::string & strValue)485 bool ArgsManager::SoftSetArg(const std::string& strArg, const std::string& strValue)
486 {
487 LOCK(cs_args);
488 if (IsArgSet(strArg)) return false;
489 ForceSetArg(strArg, strValue);
490 return true;
491 }
492
SoftSetBoolArg(const std::string & strArg,bool fValue)493 bool ArgsManager::SoftSetBoolArg(const std::string& strArg, bool fValue)
494 {
495 if (fValue)
496 return SoftSetArg(strArg, std::string("1"));
497 else
498 return SoftSetArg(strArg, std::string("0"));
499 }
500
ForceSetArg(const std::string & strArg,const std::string & strValue)501 void ArgsManager::ForceSetArg(const std::string& strArg, const std::string& strValue)
502 {
503 LOCK(cs_args);
504 m_settings.forced_settings[SettingName(strArg)] = strValue;
505 }
506
AddArg(const std::string & name,const std::string & help,unsigned int flags,const OptionsCategory & cat)507 void ArgsManager::AddArg(const std::string& name, const std::string& help, unsigned int flags, const OptionsCategory& cat)
508 {
509 // Split arg name from its help param
510 size_t eq_index = name.find('=');
511 if (eq_index == std::string::npos) {
512 eq_index = name.size();
513 }
514 std::string arg_name = name.substr(0, eq_index);
515
516 LOCK(cs_args);
517 std::map<std::string, Arg>& arg_map = m_available_args[cat];
518 auto ret = arg_map.emplace(arg_name, Arg{name.substr(eq_index, name.size() - eq_index), help, flags});
519 assert(ret.second); // Make sure an insertion actually happened
520
521 if (flags & ArgsManager::NETWORK_ONLY) {
522 m_network_only_args.emplace(arg_name);
523 }
524 }
525
AddHiddenArgs(const std::vector<std::string> & names)526 void ArgsManager::AddHiddenArgs(const std::vector<std::string>& names)
527 {
528 for (const std::string& name : names) {
529 AddArg(name, "", ArgsManager::ALLOW_ANY, OptionsCategory::HIDDEN);
530 }
531 }
532
GetHelpMessage() const533 std::string ArgsManager::GetHelpMessage() const
534 {
535 const bool show_debug = GetBoolArg("-help-debug", false);
536
537 std::string usage = "";
538 LOCK(cs_args);
539 for (const auto& arg_map : m_available_args) {
540 switch(arg_map.first) {
541 case OptionsCategory::OPTIONS:
542 usage += HelpMessageGroup("Options:");
543 break;
544 case OptionsCategory::CONNECTION:
545 usage += HelpMessageGroup("Connection options:");
546 break;
547 case OptionsCategory::ZMQ:
548 usage += HelpMessageGroup("ZeroMQ notification options:");
549 break;
550 case OptionsCategory::DEBUG_TEST:
551 usage += HelpMessageGroup("Debugging/Testing options:");
552 break;
553 case OptionsCategory::NODE_RELAY:
554 usage += HelpMessageGroup("Node relay options:");
555 break;
556 case OptionsCategory::BLOCK_CREATION:
557 usage += HelpMessageGroup("Block creation options:");
558 break;
559 case OptionsCategory::RPC:
560 usage += HelpMessageGroup("RPC server options:");
561 break;
562 case OptionsCategory::WALLET:
563 usage += HelpMessageGroup("Wallet options:");
564 break;
565 case OptionsCategory::WALLET_DEBUG_TEST:
566 if (show_debug) usage += HelpMessageGroup("Wallet debugging/testing options:");
567 break;
568 case OptionsCategory::CHAINPARAMS:
569 usage += HelpMessageGroup("Chain selection options:");
570 break;
571 case OptionsCategory::GUI:
572 usage += HelpMessageGroup("UI Options:");
573 break;
574 case OptionsCategory::COMMANDS:
575 usage += HelpMessageGroup("Commands:");
576 break;
577 case OptionsCategory::REGISTER_COMMANDS:
578 usage += HelpMessageGroup("Register Commands:");
579 break;
580 default:
581 break;
582 }
583
584 // When we get to the hidden options, stop
585 if (arg_map.first == OptionsCategory::HIDDEN) break;
586
587 for (const auto& arg : arg_map.second) {
588 if (show_debug || !(arg.second.m_flags & ArgsManager::DEBUG_ONLY)) {
589 std::string name;
590 if (arg.second.m_help_param.empty()) {
591 name = arg.first;
592 } else {
593 name = arg.first + arg.second.m_help_param;
594 }
595 usage += HelpMessageOpt(name, arg.second.m_help_text);
596 }
597 }
598 }
599 return usage;
600 }
601
HelpRequested(const ArgsManager & args)602 bool HelpRequested(const ArgsManager& args)
603 {
604 return args.IsArgSet("-?") || args.IsArgSet("-h") || args.IsArgSet("-help") || args.IsArgSet("-help-debug");
605 }
606
SetupHelpOptions(ArgsManager & args)607 void SetupHelpOptions(ArgsManager& args)
608 {
609 args.AddArg("-?", "Print this help message and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
610 args.AddHiddenArgs({"-h", "-help"});
611 }
612
613 static const int screenWidth = 79;
614 static const int optIndent = 2;
615 static const int msgIndent = 7;
616
HelpMessageGroup(const std::string & message)617 std::string HelpMessageGroup(const std::string &message) {
618 return std::string(message) + std::string("\n\n");
619 }
620
HelpMessageOpt(const std::string & option,const std::string & message)621 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
622 return std::string(optIndent,' ') + std::string(option) +
623 std::string("\n") + std::string(msgIndent,' ') +
624 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
625 std::string("\n\n");
626 }
627
FormatException(const std::exception * pex,const char * pszThread)628 static std::string FormatException(const std::exception* pex, const char* pszThread)
629 {
630 #ifdef WIN32
631 char pszModule[MAX_PATH] = "";
632 GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule));
633 #else
634 const char* pszModule = "namecoin";
635 #endif
636 if (pex)
637 return strprintf(
638 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
639 else
640 return strprintf(
641 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
642 }
643
PrintExceptionContinue(const std::exception * pex,const char * pszThread)644 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
645 {
646 std::string message = FormatException(pex, pszThread);
647 LogPrintf("\n\n************************\n%s\n", message);
648 tfm::format(std::cerr, "\n\n************************\n%s\n", message);
649 }
650
GetDefaultDataDir()651 fs::path GetDefaultDataDir()
652 {
653 // Windows: C:\Users\Username\AppData\Roaming\Namecoin
654 // macOS: ~/Library/Application Support/Namecoin
655 // Unix-like: ~/.namecoin
656 #ifdef WIN32
657 // Windows
658 return GetSpecialFolderPath(CSIDL_APPDATA) / "Namecoin";
659 #else
660 fs::path pathRet;
661 char* pszHome = getenv("HOME");
662 if (pszHome == nullptr || strlen(pszHome) == 0)
663 pathRet = fs::path("/");
664 else
665 pathRet = fs::path(pszHome);
666 #ifdef MAC_OSX
667 // macOS
668 return pathRet / "Library/Application Support/Namecoin";
669 #else
670 // Unix-like
671 return pathRet / ".namecoin";
672 #endif
673 #endif
674 }
675
676 namespace {
StripRedundantLastElementsOfPath(const fs::path & path)677 fs::path StripRedundantLastElementsOfPath(const fs::path& path)
678 {
679 auto result = path;
680 while (result.filename().string() == ".") {
681 result = result.parent_path();
682 }
683
684 assert(fs::equivalent(result, path));
685 return result;
686 }
687 } // namespace
688
689 static fs::path g_blocks_path_cache_net_specific;
690 static fs::path pathCached;
691 static fs::path pathCachedNetSpecific;
692 static RecursiveMutex csPathCached;
693
GetBlocksDir()694 const fs::path &GetBlocksDir()
695 {
696 LOCK(csPathCached);
697 fs::path &path = g_blocks_path_cache_net_specific;
698
699 // Cache the path to avoid calling fs::create_directories on every call of
700 // this function
701 if (!path.empty()) return path;
702
703 if (gArgs.IsArgSet("-blocksdir")) {
704 path = fs::system_complete(gArgs.GetArg("-blocksdir", ""));
705 if (!fs::is_directory(path)) {
706 path = "";
707 return path;
708 }
709 } else {
710 path = GetDataDir(false);
711 }
712
713 path /= BaseParams().DataDir();
714 path /= "blocks";
715 fs::create_directories(path);
716 path = StripRedundantLastElementsOfPath(path);
717 return path;
718 }
719
GetDataDir(bool fNetSpecific)720 const fs::path &GetDataDir(bool fNetSpecific)
721 {
722 LOCK(csPathCached);
723 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
724
725 // Cache the path to avoid calling fs::create_directories on every call of
726 // this function
727 if (!path.empty()) return path;
728
729 std::string datadir = gArgs.GetArg("-datadir", "");
730 if (!datadir.empty()) {
731 path = fs::system_complete(datadir);
732 if (!fs::is_directory(path)) {
733 path = "";
734 return path;
735 }
736 } else {
737 path = GetDefaultDataDir();
738 }
739 if (fNetSpecific)
740 path /= BaseParams().DataDir();
741
742 if (fs::create_directories(path)) {
743 // This is the first run, create wallets subdirectory too
744 fs::create_directories(path / "wallets");
745 }
746
747 path = StripRedundantLastElementsOfPath(path);
748 return path;
749 }
750
CheckDataDirOption()751 bool CheckDataDirOption()
752 {
753 std::string datadir = gArgs.GetArg("-datadir", "");
754 return datadir.empty() || fs::is_directory(fs::system_complete(datadir));
755 }
756
ClearDatadirCache()757 void ClearDatadirCache()
758 {
759 LOCK(csPathCached);
760
761 pathCached = fs::path();
762 pathCachedNetSpecific = fs::path();
763 g_blocks_path_cache_net_specific = fs::path();
764 }
765
GetConfigFile(const std::string & confPath)766 fs::path GetConfigFile(const std::string& confPath)
767 {
768 return AbsPathForConfigVal(fs::path(confPath), false);
769 }
770
GetConfigOptions(std::istream & stream,const std::string & filepath,std::string & error,std::vector<std::pair<std::string,std::string>> & options,std::list<SectionInfo> & sections)771 static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
772 {
773 std::string str, prefix;
774 std::string::size_type pos;
775 int linenr = 1;
776 while (std::getline(stream, str)) {
777 bool used_hash = false;
778 if ((pos = str.find('#')) != std::string::npos) {
779 str = str.substr(0, pos);
780 used_hash = true;
781 }
782 const static std::string pattern = " \t\r\n";
783 str = TrimString(str, pattern);
784 if (!str.empty()) {
785 if (*str.begin() == '[' && *str.rbegin() == ']') {
786 const std::string section = str.substr(1, str.size() - 2);
787 sections.emplace_back(SectionInfo{section, filepath, linenr});
788 prefix = section + '.';
789 } else if (*str.begin() == '-') {
790 error = strprintf("parse error on line %i: %s, options in configuration file must be specified without leading -", linenr, str);
791 return false;
792 } else if ((pos = str.find('=')) != std::string::npos) {
793 std::string name = prefix + TrimString(str.substr(0, pos), pattern);
794 std::string value = TrimString(str.substr(pos + 1), pattern);
795 if (used_hash && name.find("rpcpassword") != std::string::npos) {
796 error = strprintf("parse error on line %i, using # in rpcpassword can be ambiguous and should be avoided", linenr);
797 return false;
798 }
799 options.emplace_back(name, value);
800 if ((pos = name.rfind('.')) != std::string::npos && prefix.length() <= pos) {
801 sections.emplace_back(SectionInfo{name.substr(0, pos), filepath, linenr});
802 }
803 } else {
804 error = strprintf("parse error on line %i: %s", linenr, str);
805 if (str.size() >= 2 && str.substr(0, 2) == "no") {
806 error += strprintf(", if you intended to specify a negated option, use %s=1 instead", str);
807 }
808 return false;
809 }
810 }
811 ++linenr;
812 }
813 return true;
814 }
815
ReadConfigStream(std::istream & stream,const std::string & filepath,std::string & error,bool ignore_invalid_keys)816 bool ArgsManager::ReadConfigStream(std::istream& stream, const std::string& filepath, std::string& error, bool ignore_invalid_keys)
817 {
818 LOCK(cs_args);
819 std::vector<std::pair<std::string, std::string>> options;
820 if (!GetConfigOptions(stream, filepath, error, options, m_config_sections)) {
821 return false;
822 }
823 for (const std::pair<std::string, std::string>& option : options) {
824 std::string section;
825 std::string key = option.first;
826 util::SettingsValue value = InterpretOption(section, key, option.second);
827 Optional<unsigned int> flags = GetArgFlags('-' + key);
828 if (flags) {
829 if (!CheckValid(key, value, *flags, error)) {
830 return false;
831 }
832 m_settings.ro_config[section][key].push_back(value);
833 } else {
834 if (ignore_invalid_keys) {
835 LogPrintf("Ignoring unknown configuration value %s\n", option.first);
836 } else {
837 error = strprintf("Invalid configuration value %s", option.first);
838 return false;
839 }
840 }
841 }
842 return true;
843 }
844
ReadConfigFiles(std::string & error,bool ignore_invalid_keys)845 bool ArgsManager::ReadConfigFiles(std::string& error, bool ignore_invalid_keys)
846 {
847 {
848 LOCK(cs_args);
849 m_settings.ro_config.clear();
850 m_config_sections.clear();
851 }
852
853 const std::string confPath = GetArg("-conf", BITCOIN_CONF_FILENAME);
854 fsbridge::ifstream stream(GetConfigFile(confPath));
855
856 // ok to not have a config file
857 if (stream.good()) {
858 if (!ReadConfigStream(stream, confPath, error, ignore_invalid_keys)) {
859 return false;
860 }
861 // `-includeconf` cannot be included in the command line arguments except
862 // as `-noincludeconf` (which indicates that no included conf file should be used).
863 bool use_conf_file{true};
864 {
865 LOCK(cs_args);
866 if (auto* includes = util::FindKey(m_settings.command_line_options, "includeconf")) {
867 // ParseParameters() fails if a non-negated -includeconf is passed on the command-line
868 assert(util::SettingsSpan(*includes).last_negated());
869 use_conf_file = false;
870 }
871 }
872 if (use_conf_file) {
873 std::string chain_id = GetChainName();
874 std::vector<std::string> conf_file_names;
875
876 auto add_includes = [&](const std::string& network, size_t skip = 0) {
877 size_t num_values = 0;
878 LOCK(cs_args);
879 if (auto* section = util::FindKey(m_settings.ro_config, network)) {
880 if (auto* values = util::FindKey(*section, "includeconf")) {
881 for (size_t i = std::max(skip, util::SettingsSpan(*values).negated()); i < values->size(); ++i) {
882 conf_file_names.push_back((*values)[i].get_str());
883 }
884 num_values = values->size();
885 }
886 }
887 return num_values;
888 };
889
890 // We haven't set m_network yet (that happens in SelectParams()), so manually check
891 // for network.includeconf args.
892 const size_t chain_includes = add_includes(chain_id);
893 const size_t default_includes = add_includes({});
894
895 for (const std::string& conf_file_name : conf_file_names) {
896 fsbridge::ifstream conf_file_stream(GetConfigFile(conf_file_name));
897 if (conf_file_stream.good()) {
898 if (!ReadConfigStream(conf_file_stream, conf_file_name, error, ignore_invalid_keys)) {
899 return false;
900 }
901 LogPrintf("Included configuration file %s\n", conf_file_name);
902 } else {
903 error = "Failed to include configuration file " + conf_file_name;
904 return false;
905 }
906 }
907
908 // Warn about recursive -includeconf
909 conf_file_names.clear();
910 add_includes(chain_id, /* skip= */ chain_includes);
911 add_includes({}, /* skip= */ default_includes);
912 std::string chain_id_final = GetChainName();
913 if (chain_id_final != chain_id) {
914 // Also warn about recursive includeconf for the chain that was specified in one of the includeconfs
915 add_includes(chain_id_final);
916 }
917 for (const std::string& conf_file_name : conf_file_names) {
918 tfm::format(std::cerr, "warning: -includeconf cannot be used from included files; ignoring -includeconf=%s\n", conf_file_name);
919 }
920 }
921 }
922
923 // If datadir is changed in .conf file:
924 ClearDatadirCache();
925 if (!CheckDataDirOption()) {
926 error = strprintf("specified data directory \"%s\" does not exist.", GetArg("-datadir", ""));
927 return false;
928 }
929 return true;
930 }
931
GetChainName() const932 std::string ArgsManager::GetChainName() const
933 {
934 auto get_net = [&](const std::string& arg) {
935 LOCK(cs_args);
936 util::SettingsValue value = util::GetSetting(m_settings, /* section= */ "", SettingName(arg),
937 /* ignore_default_section_config= */ false,
938 /* get_chain_name= */ true);
939 return value.isNull() ? false : value.isBool() ? value.get_bool() : InterpretBool(value.get_str());
940 };
941
942 const bool fRegTest = get_net("-regtest");
943 const bool fSigNet = get_net("-signet");
944 const bool fTestNet = get_net("-testnet");
945 const bool is_chain_arg_set = IsArgSet("-chain");
946
947 if ((int)is_chain_arg_set + (int)fRegTest + (int)fSigNet + (int)fTestNet > 1) {
948 throw std::runtime_error("Invalid combination of -regtest, -signet, -testnet and -chain. Can use at most one.");
949 }
950 if (fRegTest)
951 return CBaseChainParams::REGTEST;
952 if (fSigNet) {
953 return CBaseChainParams::SIGNET;
954 }
955 if (fTestNet)
956 return CBaseChainParams::TESTNET;
957
958 return GetArg("-chain", CBaseChainParams::MAIN);
959 }
960
UseDefaultSection(const std::string & arg) const961 bool ArgsManager::UseDefaultSection(const std::string& arg) const
962 {
963 return m_network == CBaseChainParams::MAIN || m_network_only_args.count(arg) == 0;
964 }
965
GetSetting(const std::string & arg) const966 util::SettingsValue ArgsManager::GetSetting(const std::string& arg) const
967 {
968 LOCK(cs_args);
969 return util::GetSetting(
970 m_settings, m_network, SettingName(arg), !UseDefaultSection(arg), /* get_chain_name= */ false);
971 }
972
GetSettingsList(const std::string & arg) const973 std::vector<util::SettingsValue> ArgsManager::GetSettingsList(const std::string& arg) const
974 {
975 LOCK(cs_args);
976 return util::GetSettingsList(m_settings, m_network, SettingName(arg), !UseDefaultSection(arg));
977 }
978
logArgsPrefix(const std::string & prefix,const std::string & section,const std::map<std::string,std::vector<util::SettingsValue>> & args) const979 void ArgsManager::logArgsPrefix(
980 const std::string& prefix,
981 const std::string& section,
982 const std::map<std::string, std::vector<util::SettingsValue>>& args) const
983 {
984 std::string section_str = section.empty() ? "" : "[" + section + "] ";
985 for (const auto& arg : args) {
986 for (const auto& value : arg.second) {
987 Optional<unsigned int> flags = GetArgFlags('-' + arg.first);
988 if (flags) {
989 std::string value_str = (*flags & SENSITIVE) ? "****" : value.write();
990 LogPrintf("%s %s%s=%s\n", prefix, section_str, arg.first, value_str);
991 }
992 }
993 }
994 }
995
LogArgs() const996 void ArgsManager::LogArgs() const
997 {
998 LOCK(cs_args);
999 for (const auto& section : m_settings.ro_config) {
1000 logArgsPrefix("Config file arg:", section.first, section.second);
1001 }
1002 for (const auto& setting : m_settings.rw_settings) {
1003 LogPrintf("Setting file arg: %s = %s\n", setting.first, setting.second.write());
1004 }
1005 logArgsPrefix("Command-line arg:", "", m_settings.command_line_options);
1006 }
1007
RenameOver(fs::path src,fs::path dest)1008 bool RenameOver(fs::path src, fs::path dest)
1009 {
1010 #ifdef WIN32
1011 return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
1012 MOVEFILE_REPLACE_EXISTING) != 0;
1013 #else
1014 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1015 return (rc == 0);
1016 #endif /* WIN32 */
1017 }
1018
1019 /**
1020 * Ignores exceptions thrown by Boost's create_directories if the requested directory exists.
1021 * Specifically handles case where path p exists, but it wasn't possible for the user to
1022 * write to the parent directory.
1023 */
TryCreateDirectories(const fs::path & p)1024 bool TryCreateDirectories(const fs::path& p)
1025 {
1026 try
1027 {
1028 return fs::create_directories(p);
1029 } catch (const fs::filesystem_error&) {
1030 if (!fs::exists(p) || !fs::is_directory(p))
1031 throw;
1032 }
1033
1034 // create_directories didn't create the directory, it had to have existed already
1035 return false;
1036 }
1037
FileCommit(FILE * file)1038 bool FileCommit(FILE *file)
1039 {
1040 if (fflush(file) != 0) { // harmless if redundantly called
1041 LogPrintf("%s: fflush failed: %d\n", __func__, errno);
1042 return false;
1043 }
1044 #ifdef WIN32
1045 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1046 if (FlushFileBuffers(hFile) == 0) {
1047 LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__, GetLastError());
1048 return false;
1049 }
1050 #else
1051 #if HAVE_FDATASYNC
1052 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
1053 LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
1054 return false;
1055 }
1056 #elif defined(MAC_OSX) && defined(F_FULLFSYNC)
1057 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
1058 LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
1059 return false;
1060 }
1061 #else
1062 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
1063 LogPrintf("%s: fsync failed: %d\n", __func__, errno);
1064 return false;
1065 }
1066 #endif
1067 #endif
1068 return true;
1069 }
1070
TruncateFile(FILE * file,unsigned int length)1071 bool TruncateFile(FILE *file, unsigned int length) {
1072 #if defined(WIN32)
1073 return _chsize(_fileno(file), length) == 0;
1074 #else
1075 return ftruncate(fileno(file), length) == 0;
1076 #endif
1077 }
1078
1079 /**
1080 * this function tries to raise the file descriptor limit to the requested number.
1081 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
1082 */
RaiseFileDescriptorLimit(int nMinFD)1083 int RaiseFileDescriptorLimit(int nMinFD) {
1084 #if defined(WIN32)
1085 return 2048;
1086 #else
1087 struct rlimit limitFD;
1088 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
1089 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
1090 limitFD.rlim_cur = nMinFD;
1091 if (limitFD.rlim_cur > limitFD.rlim_max)
1092 limitFD.rlim_cur = limitFD.rlim_max;
1093 setrlimit(RLIMIT_NOFILE, &limitFD);
1094 getrlimit(RLIMIT_NOFILE, &limitFD);
1095 }
1096 return limitFD.rlim_cur;
1097 }
1098 return nMinFD; // getrlimit failed, assume it's fine
1099 #endif
1100 }
1101
1102 /**
1103 * this function tries to make a particular range of a file allocated (corresponding to disk space)
1104 * it is advisory, and the range specified in the arguments will never contain live data
1105 */
AllocateFileRange(FILE * file,unsigned int offset,unsigned int length)1106 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
1107 #if defined(WIN32)
1108 // Windows-specific version
1109 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
1110 LARGE_INTEGER nFileSize;
1111 int64_t nEndPos = (int64_t)offset + length;
1112 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
1113 nFileSize.u.HighPart = nEndPos >> 32;
1114 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
1115 SetEndOfFile(hFile);
1116 #elif defined(MAC_OSX)
1117 // OSX specific version
1118 // NOTE: Contrary to other OS versions, the OSX version assumes that
1119 // NOTE: offset is the size of the file.
1120 fstore_t fst;
1121 fst.fst_flags = F_ALLOCATECONTIG;
1122 fst.fst_posmode = F_PEOFPOSMODE;
1123 fst.fst_offset = 0;
1124 fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
1125 fst.fst_bytesalloc = 0;
1126 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
1127 fst.fst_flags = F_ALLOCATEALL;
1128 fcntl(fileno(file), F_PREALLOCATE, &fst);
1129 }
1130 ftruncate(fileno(file), static_cast<off_t>(offset) + length);
1131 #else
1132 #if defined(HAVE_POSIX_FALLOCATE)
1133 // Version using posix_fallocate
1134 off_t nEndPos = (off_t)offset + length;
1135 if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
1136 #endif
1137 // Fallback version
1138 // TODO: just write one byte per block
1139 static const char buf[65536] = {};
1140 if (fseek(file, offset, SEEK_SET)) {
1141 return;
1142 }
1143 while (length > 0) {
1144 unsigned int now = 65536;
1145 if (length < now)
1146 now = length;
1147 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
1148 length -= now;
1149 }
1150 #endif
1151 }
1152
1153 #ifdef WIN32
GetSpecialFolderPath(int nFolder,bool fCreate)1154 fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
1155 {
1156 WCHAR pszPath[MAX_PATH] = L"";
1157
1158 if(SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate))
1159 {
1160 return fs::path(pszPath);
1161 }
1162
1163 LogPrintf("SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
1164 return fs::path("");
1165 }
1166 #endif
1167
1168 #ifndef WIN32
ShellEscape(const std::string & arg)1169 std::string ShellEscape(const std::string& arg)
1170 {
1171 std::string escaped = arg;
1172 boost::replace_all(escaped, "'", "'\"'\"'");
1173 return "'" + escaped + "'";
1174 }
1175 #endif
1176
1177 #if HAVE_SYSTEM
runCommand(const std::string & strCommand)1178 void runCommand(const std::string& strCommand)
1179 {
1180 if (strCommand.empty()) return;
1181 #ifndef WIN32
1182 int nErr = ::system(strCommand.c_str());
1183 #else
1184 int nErr = ::_wsystem(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().from_bytes(strCommand).c_str());
1185 #endif
1186 if (nErr)
1187 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
1188 }
1189 #endif
1190
1191 #ifdef HAVE_BOOST_PROCESS
RunCommandParseJSON(const std::string & str_command,const std::string & str_std_in)1192 UniValue RunCommandParseJSON(const std::string& str_command, const std::string& str_std_in)
1193 {
1194 namespace bp = boost::process;
1195
1196 UniValue result_json;
1197 bp::opstream stdin_stream;
1198 bp::ipstream stdout_stream;
1199 bp::ipstream stderr_stream;
1200
1201 if (str_command.empty()) return UniValue::VNULL;
1202
1203 bp::child c(
1204 str_command,
1205 bp::std_out > stdout_stream,
1206 bp::std_err > stderr_stream,
1207 bp::std_in < stdin_stream
1208 );
1209 if (!str_std_in.empty()) {
1210 stdin_stream << str_std_in << std::endl;
1211 }
1212 stdin_stream.pipe().close();
1213
1214 std::string result;
1215 std::string error;
1216 std::getline(stdout_stream, result);
1217 std::getline(stderr_stream, error);
1218
1219 c.wait();
1220 const int n_error = c.exit_code();
1221 if (n_error) throw std::runtime_error(strprintf("RunCommandParseJSON error: process(%s) returned %d: %s\n", str_command, n_error, error));
1222 if (!result_json.read(result)) throw std::runtime_error("Unable to parse JSON: " + result);
1223
1224 return result_json;
1225 }
1226 #endif // HAVE_BOOST_PROCESS
1227
SetupEnvironment()1228 void SetupEnvironment()
1229 {
1230 #ifdef HAVE_MALLOPT_ARENA_MAX
1231 // glibc-specific: On 32-bit systems set the number of arenas to 1.
1232 // By default, since glibc 2.10, the C library will create up to two heap
1233 // arenas per core. This is known to cause excessive virtual address space
1234 // usage in our usage. Work around it by setting the maximum number of
1235 // arenas to 1.
1236 if (sizeof(void*) == 4) {
1237 mallopt(M_ARENA_MAX, 1);
1238 }
1239 #endif
1240 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
1241 // may be invalid, in which case the "C.UTF-8" locale is used as fallback.
1242 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
1243 try {
1244 std::locale(""); // Raises a runtime error if current locale is invalid
1245 } catch (const std::runtime_error&) {
1246 setenv("LC_ALL", "C.UTF-8", 1);
1247 }
1248 #elif defined(WIN32)
1249 // Set the default input/output charset is utf-8
1250 SetConsoleCP(CP_UTF8);
1251 SetConsoleOutputCP(CP_UTF8);
1252 #endif
1253 // The path locale is lazy initialized and to avoid deinitialization errors
1254 // in multithreading environments, it is set explicitly by the main thread.
1255 // A dummy locale is used to extract the internal default locale, used by
1256 // fs::path, which is then used to explicitly imbue the path.
1257 std::locale loc = fs::path::imbue(std::locale::classic());
1258 #ifndef WIN32
1259 fs::path::imbue(loc);
1260 #else
1261 fs::path::imbue(std::locale(loc, new std::codecvt_utf8_utf16<wchar_t>()));
1262 #endif
1263 }
1264
SetupNetworking()1265 bool SetupNetworking()
1266 {
1267 #ifdef WIN32
1268 // Initialize Windows Sockets
1269 WSADATA wsadata;
1270 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1271 if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
1272 return false;
1273 #endif
1274 return true;
1275 }
1276
GetNumCores()1277 int GetNumCores()
1278 {
1279 return std::thread::hardware_concurrency();
1280 }
1281
CopyrightHolders(const std::string & strPrefix)1282 std::string CopyrightHolders(const std::string& strPrefix)
1283 {
1284 const auto copyright_devs = strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION);
1285 std::string strCopyrightHolders = strPrefix + copyright_devs;
1286 return strCopyrightHolders;
1287 }
1288
1289 // Obtain the application startup time (used for uptime calculation)
GetStartupTime()1290 int64_t GetStartupTime()
1291 {
1292 return nStartupTime;
1293 }
1294
AbsPathForConfigVal(const fs::path & path,bool net_specific)1295 fs::path AbsPathForConfigVal(const fs::path& path, bool net_specific)
1296 {
1297 if (path.is_absolute()) {
1298 return path;
1299 }
1300 return fs::absolute(path, GetDataDir(net_specific));
1301 }
1302
ScheduleBatchPriority()1303 void ScheduleBatchPriority()
1304 {
1305 #ifdef SCHED_BATCH
1306 const static sched_param param{};
1307 const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, ¶m);
1308 if (rc != 0) {
1309 LogPrintf("Failed to pthread_setschedparam: %s\n", strerror(rc));
1310 }
1311 #endif
1312 }
1313
1314 namespace util {
1315 #ifdef WIN32
WinCmdLineArgs()1316 WinCmdLineArgs::WinCmdLineArgs()
1317 {
1318 wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
1319 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> utf8_cvt;
1320 argv = new char*[argc];
1321 args.resize(argc);
1322 for (int i = 0; i < argc; i++) {
1323 args[i] = utf8_cvt.to_bytes(wargv[i]);
1324 argv[i] = &*args[i].begin();
1325 }
1326 LocalFree(wargv);
1327 }
1328
~WinCmdLineArgs()1329 WinCmdLineArgs::~WinCmdLineArgs()
1330 {
1331 delete[] argv;
1332 }
1333
get()1334 std::pair<int, char**> WinCmdLineArgs::get()
1335 {
1336 return std::make_pair(argc, argv);
1337 }
1338 #endif
1339 } // namespace util
1340