1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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.
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
12 #include "chainparamsbase.h"
14 #include "serialize.h"
16 #include "utilstrencodings.h"
21 #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
23 #include <pthread_np.h>
27 // for posix_fallocate
30 #ifdef _POSIX_C_SOURCE
31 #undef _POSIX_C_SOURCE
34 #define _POSIX_C_SOURCE 200112L
40 #include <sys/resource.h>
46 #pragma warning(disable:4786)
47 #pragma warning(disable:4804)
48 #pragma warning(disable:4805)
49 #pragma warning(disable:4717)
55 #define _WIN32_WINNT 0x0501
60 #define _WIN32_IE 0x0501
62 #define WIN32_LEAN_AND_MEAN 1
67 #include <io.h> /* for _commit */
71 #ifdef HAVE_SYS_PRCTL_H
72 #include <sys/prctl.h>
75 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
76 #include <boost/algorithm/string/join.hpp>
77 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
78 #include <boost/filesystem.hpp>
79 #include <boost/filesystem/fstream.hpp>
80 #include <boost/foreach.hpp>
81 #include <boost/program_options/detail/config_file.hpp>
82 #include <boost/program_options/parsers.hpp>
83 #include <boost/thread.hpp>
84 #include <openssl/crypto.h>
85 #include <openssl/rand.h>
86 #include <openssl/conf.h>
88 // Work around clang compilation problem in Boost 1.46:
89 // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
90 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
91 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
94 namespace program_options {
95 std::string to_internal(const std::string&);
102 map<string, string> mapArgs;
103 map<string, vector<string> > mapMultiArgs;
105 bool fPrintToConsole = false;
106 bool fPrintToDebugLog = true;
107 bool fDaemon = false;
108 bool fServer = false;
109 string strMiscWarning;
110 bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS;
111 bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS;
112 bool fLogIPs = DEFAULT_LOGIPS;
113 std::atomic<bool> fReopenDebugLog(false);
114 CTranslationInterface translationInterface;
116 /** Init OpenSSL library multithreading support */
117 static CCriticalSection** ppmutexOpenSSL;
118 void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS
120 if (mode & CRYPTO_LOCK) {
121 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
123 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
133 // Init OpenSSL library multithreading support
134 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
135 for (int i = 0; i < CRYPTO_num_locks(); i++)
136 ppmutexOpenSSL[i] = new CCriticalSection();
137 CRYPTO_set_locking_callback(locking_callback);
139 // OpenSSL can optionally load a config file which lists optional loadable modules and engines.
140 // We don't use them so we don't require the config. However some of our libs may call functions
141 // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing
142 // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be
143 // that the config appears to have been loaded and there are no modules/engines available.
147 // Seed OpenSSL PRNG with current contents of the screen
151 // Seed OpenSSL PRNG with performance counter
156 // Securely erase the memory used by the PRNG
158 // Shutdown OpenSSL library multithreading support
159 CRYPTO_set_locking_callback(NULL);
160 for (int i = 0; i < CRYPTO_num_locks(); i++)
161 delete ppmutexOpenSSL[i];
162 OPENSSL_free(ppmutexOpenSSL);
168 * LogPrintf() has been broken a couple of times now
169 * by well-meaning people adding mutexes in the most straightforward way.
170 * It breaks because it may be called by global destructors during shutdown.
171 * Since the order of destruction of static/global objects is undefined,
172 * defining a mutex as a global object doesn't work (the mutex gets
173 * destroyed, and then some later destructor calls OutputDebugStringF,
174 * maybe indirectly, and you get a core dump at shutdown trying to lock
178 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
180 * We use boost::call_once() to make sure these are initialized
181 * in a thread-safe manner the first time called:
183 static FILE* fileout = NULL;
184 static boost::mutex* mutexDebugLog = NULL;
186 static void DebugPrintInit()
188 assert(fileout == NULL);
189 assert(mutexDebugLog == NULL);
191 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
192 fileout = fopen(pathDebug.string().c_str(), "a");
193 if (fileout) setbuf(fileout, NULL); // unbuffered
195 mutexDebugLog = new boost::mutex();
198 bool LogAcceptCategory(const char* category)
200 if (category != NULL)
205 // Give each thread quick access to -debug settings.
206 // This helps prevent issues debugging global destructors,
207 // where mapMultiArgs might be deleted before another
208 // global destructor calls LogPrint()
209 static boost::thread_specific_ptr<set<string> > ptrCategory;
210 if (ptrCategory.get() == NULL)
212 const vector<string>& categories = mapMultiArgs["-debug"];
213 ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
214 // thread_specific_ptr automatically deletes the set when the thread ends.
216 const set<string>& setCategories = *ptrCategory.get();
218 // if not debugging everything and not debugging specific category, LogPrint does nothing.
219 if (setCategories.count(string("")) == 0 &&
220 setCategories.count(string(category)) == 0)
226 int LogPrintStr(const std::string &str)
228 int ret = 0; // Returns total number of characters written
232 ret = fwrite(str.data(), 1, str.size(), stdout);
235 else if (fPrintToDebugLog && AreBaseParamsConfigured())
237 static bool fStartedNewLine = true;
238 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
243 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
245 // reopen the log file, if requested
246 if (fReopenDebugLog) {
247 fReopenDebugLog = false;
248 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
249 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
250 setbuf(fileout, NULL); // unbuffered
253 // Debug print useful for profiling
254 if (fLogTimestamps && fStartedNewLine)
255 ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
256 if (!str.empty() && str[str.size()-1] == '\n')
257 fStartedNewLine = true;
259 fStartedNewLine = false;
261 ret = fwrite(str.data(), 1, str.size(), fileout);
267 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
269 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
270 if (name.find("-no") == 0)
272 std::string positive("-");
273 positive.append(name.begin()+3, name.end());
274 if (mapSettingsRet.count(positive) == 0)
276 bool value = !GetBoolArg(name, false);
277 mapSettingsRet[positive] = (value ? "1" : "0");
282 void ParseParameters(int argc, const char* const argv[])
285 mapMultiArgs.clear();
287 for (int i = 1; i < argc; i++)
289 std::string str(argv[i]);
290 std::string strValue;
291 size_t is_index = str.find('=');
292 if (is_index != std::string::npos)
294 strValue = str.substr(is_index+1);
295 str = str.substr(0, is_index);
298 boost::to_lower(str);
299 if (boost::algorithm::starts_with(str, "/"))
300 str = "-" + str.substr(1);
306 // Interpret --foo as -foo.
307 // If both --foo and -foo are set, the last takes effect.
308 if (str.length() > 1 && str[1] == '-')
311 mapArgs[str] = strValue;
312 mapMultiArgs[str].push_back(strValue);
316 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
318 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
319 InterpretNegativeSetting(entry.first, mapArgs);
323 std::string GetArg(const std::string& strArg, const std::string& strDefault)
325 if (mapArgs.count(strArg))
326 return mapArgs[strArg];
330 int64_t GetArg(const std::string& strArg, int64_t nDefault)
332 if (mapArgs.count(strArg))
333 return atoi64(mapArgs[strArg]);
337 bool GetBoolArg(const std::string& strArg, bool fDefault)
339 if (mapArgs.count(strArg))
341 if (mapArgs[strArg].empty())
343 return (atoi(mapArgs[strArg]) != 0);
348 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
350 if (mapArgs.count(strArg))
352 mapArgs[strArg] = strValue;
356 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
359 return SoftSetArg(strArg, std::string("1"));
361 return SoftSetArg(strArg, std::string("0"));
364 static const int screenWidth = 79;
365 static const int optIndent = 2;
366 static const int msgIndent = 7;
368 std::string HelpMessageGroup(const std::string &message) {
369 return std::string(message) + std::string("\n\n");
372 std::string HelpMessageOpt(const std::string &option, const std::string &message) {
373 return std::string(optIndent,' ') + std::string(option) +
374 std::string("\n") + std::string(msgIndent,' ') +
375 FormatParagraph(message, screenWidth - msgIndent, msgIndent) +
379 static std::string FormatException(const std::exception* pex, const char* pszThread)
382 char pszModule[MAX_PATH] = "";
383 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
385 const char* pszModule = "Komodo";
389 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
392 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
395 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
397 std::string message = FormatException(pex, pszThread);
398 LogPrintf("\n\n************************\n%s\n", message);
399 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
400 strMiscWarning = message;
403 char ASSETCHAINS_SYMBOL[16];
405 boost::filesystem::path GetDefaultDataDir()
407 namespace fs = boost::filesystem;
408 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Zcash
409 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Zcash
410 // Mac: ~/Library/Application Support/Zcash
414 if ( ASSETCHAINS_SYMBOL[0] == 0 )
415 return GetSpecialFolderPath(CSIDL_APPDATA) / "Komodo";
416 else return GetSpecialFolderPath(CSIDL_APPDATA) / "Komodo" / ASSETCHAINS_SYMBOL;
419 char* pszHome = getenv("HOME");
420 if (pszHome == NULL || strlen(pszHome) == 0)
421 pathRet = fs::path("/");
423 pathRet = fs::path(pszHome);
426 pathRet /= "Library/Application Support";
427 TryCreateDirectory(pathRet);
428 if ( ASSETCHAINS_SYMBOL[0] == 0 )
429 return pathRet / "Komodo";
433 TryCreateDirectory(pathRet);
434 return pathRet / ASSETCHAINS_SYMBOL;
438 if ( ASSETCHAINS_SYMBOL[0] == 0 )
439 return pathRet / ".komodo";
440 else return pathRet / ".komodo" / ASSETCHAINS_SYMBOL;
445 static boost::filesystem::path pathCached;
446 static boost::filesystem::path pathCachedNetSpecific;
447 static boost::filesystem::path zc_paramsPathCached;
448 static CCriticalSection csPathCached;
450 static boost::filesystem::path ZC_GetBaseParamsDir()
452 // Copied from GetDefaultDataDir and adapter for zcash params.
454 namespace fs = boost::filesystem;
455 // Windows < Vista: C:\Documents and Settings\Username\Application Data\ZcashParams
456 // Windows >= Vista: C:\Users\Username\AppData\Roaming\ZcashParams
457 // Mac: ~/Library/Application Support/ZcashParams
458 // Unix: ~/.zcash-params
461 return GetSpecialFolderPath(CSIDL_APPDATA) / "ZcashParams";
464 char* pszHome = getenv("HOME");
465 if (pszHome == NULL || strlen(pszHome) == 0)
466 pathRet = fs::path("/");
468 pathRet = fs::path(pszHome);
471 pathRet /= "Library/Application Support";
472 TryCreateDirectory(pathRet);
473 return pathRet / "ZcashParams";
476 return pathRet / ".zcash-params";
481 const boost::filesystem::path &ZC_GetParamsDir()
483 namespace fs = boost::filesystem;
485 LOCK(csPathCached); // Reuse the same lock as upstream.
487 fs::path &path = zc_paramsPathCached;
489 // This can be called during exceptions by LogPrintf(), so we cache the
490 // value so we don't have to do memory allocations after that.
494 path = ZC_GetBaseParamsDir();
499 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
501 namespace fs = boost::filesystem;
505 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
507 // This can be called during exceptions by LogPrintf(), so we cache the
508 // value so we don't have to do memory allocations after that.
512 if (mapArgs.count("-datadir")) {
513 path = fs::system_complete(mapArgs["-datadir"]);
514 if (!fs::is_directory(path)) {
519 path = GetDefaultDataDir();
522 path /= BaseParams().DataDir();
524 fs::create_directories(path);
529 void ClearDatadirCache()
531 pathCached = boost::filesystem::path();
532 pathCachedNetSpecific = boost::filesystem::path();
535 boost::filesystem::path GetConfigFile()
537 boost::filesystem::path pathConfigFile(GetArg("-conf", "komodo.conf"));
538 if (!pathConfigFile.is_complete())
539 pathConfigFile = GetDataDir(false) / pathConfigFile;
541 return pathConfigFile;
544 void ReadConfigFile(map<string, string>& mapSettingsRet,
545 map<string, vector<string> >& mapMultiSettingsRet)
547 boost::filesystem::ifstream streamConfig(GetConfigFile());
548 if (!streamConfig.good())
549 return; // No komodo.conf file is OK
551 set<string> setOptions;
552 setOptions.insert("*");
554 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
556 // Don't overwrite existing settings so command line settings override komodo.conf
557 string strKey = string("-") + it->string_key;
558 if (mapSettingsRet.count(strKey) == 0)
560 mapSettingsRet[strKey] = it->value[0];
561 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
562 InterpretNegativeSetting(strKey, mapSettingsRet);
564 mapMultiSettingsRet[strKey].push_back(it->value[0]);
566 // If datadir is changed in .conf file:
571 boost::filesystem::path GetPidFile()
573 boost::filesystem::path pathPidFile(GetArg("-pid", "komodod.pid"));
574 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
578 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
580 FILE* file = fopen(path.string().c_str(), "w");
583 fprintf(file, "%d\n", pid);
589 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
592 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
593 MOVEFILE_REPLACE_EXISTING) != 0;
595 int rc = std::rename(src.string().c_str(), dest.string().c_str());
601 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
602 * Specifically handles case where path p exists, but it wasn't possible for the user to
603 * write to the parent directory.
605 bool TryCreateDirectory(const boost::filesystem::path& p)
609 return boost::filesystem::create_directory(p);
610 } catch (const boost::filesystem::filesystem_error&) {
611 if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
615 // create_directory didn't create the directory, it had to have existed already
619 void FileCommit(FILE *fileout)
621 fflush(fileout); // harmless if redundantly called
623 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout));
624 FlushFileBuffers(hFile);
626 #if defined(__linux__) || defined(__NetBSD__)
627 fdatasync(fileno(fileout));
628 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
629 fcntl(fileno(fileout), F_FULLFSYNC, 0);
631 fsync(fileno(fileout));
636 bool TruncateFile(FILE *file, unsigned int length) {
638 return _chsize(_fileno(file), length) == 0;
640 return ftruncate(fileno(file), length) == 0;
645 * this function tries to raise the file descriptor limit to the requested number.
646 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
648 int RaiseFileDescriptorLimit(int nMinFD) {
652 struct rlimit limitFD;
653 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
654 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
655 limitFD.rlim_cur = nMinFD;
656 if (limitFD.rlim_cur > limitFD.rlim_max)
657 limitFD.rlim_cur = limitFD.rlim_max;
658 setrlimit(RLIMIT_NOFILE, &limitFD);
659 getrlimit(RLIMIT_NOFILE, &limitFD);
661 return limitFD.rlim_cur;
663 return nMinFD; // getrlimit failed, assume it's fine
668 * this function tries to make a particular range of a file allocated (corresponding to disk space)
669 * it is advisory, and the range specified in the arguments will never contain live data
671 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
673 // Windows-specific version
674 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
675 LARGE_INTEGER nFileSize;
676 int64_t nEndPos = (int64_t)offset + length;
677 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
678 nFileSize.u.HighPart = nEndPos >> 32;
679 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
681 #elif defined(MAC_OSX)
682 // OSX specific version
684 fst.fst_flags = F_ALLOCATECONTIG;
685 fst.fst_posmode = F_PEOFPOSMODE;
687 fst.fst_length = (off_t)offset + length;
688 fst.fst_bytesalloc = 0;
689 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
690 fst.fst_flags = F_ALLOCATEALL;
691 fcntl(fileno(file), F_PREALLOCATE, &fst);
693 ftruncate(fileno(file), fst.fst_length);
694 #elif defined(__linux__)
695 // Version using posix_fallocate
696 off_t nEndPos = (off_t)offset + length;
697 posix_fallocate(fileno(file), 0, nEndPos);
700 // TODO: just write one byte per block
701 static const char buf[65536] = {};
702 fseek(file, offset, SEEK_SET);
704 unsigned int now = 65536;
707 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
713 void ShrinkDebugFile()
715 // Scroll debug.log if it's getting too big
716 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
717 FILE* file = fopen(pathLog.string().c_str(), "r");
718 if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
720 // Restart the file with some of the end
721 std::vector <char> vch(200000,0);
722 fseek(file, -((long)vch.size()), SEEK_END);
723 int nBytes = fread(begin_ptr(vch), 1, vch.size(), file);
726 file = fopen(pathLog.string().c_str(), "w");
729 fwrite(begin_ptr(vch), 1, nBytes, file);
733 else if (file != NULL)
738 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
740 namespace fs = boost::filesystem;
742 char pszPath[MAX_PATH] = "";
744 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
746 return fs::path(pszPath);
749 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
754 boost::filesystem::path GetTempPath() {
755 #if BOOST_FILESYSTEM_VERSION == 3
756 return boost::filesystem::temp_directory_path();
758 // TODO: remove when we don't support filesystem v2 anymore
759 boost::filesystem::path path;
761 char pszPath[MAX_PATH] = "";
763 if (GetTempPathA(MAX_PATH, pszPath))
764 path = boost::filesystem::path(pszPath);
766 path = boost::filesystem::path("/tmp");
768 if (path.empty() || !boost::filesystem::is_directory(path)) {
769 LogPrintf("GetTempPath(): failed to find temp path\n");
770 return boost::filesystem::path("");
776 void runCommand(std::string strCommand)
778 int nErr = ::system(strCommand.c_str());
780 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
783 void RenameThread(const char* name)
785 #if defined(PR_SET_NAME)
786 // Only the first 15 characters are used (16 - NUL terminator)
787 ::prctl(PR_SET_NAME, name, 0, 0, 0);
788 #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__))
789 pthread_set_name_np(pthread_self(), name);
791 #elif defined(MAC_OSX)
792 pthread_setname_np(name);
794 // Prevent warnings for unused parameters...
799 void SetupEnvironment()
801 // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale
802 // may be invalid, in which case the "C" locale is used as fallback.
803 #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
805 std::locale(""); // Raises a runtime error if current locale is invalid
806 } catch (const std::runtime_error&) {
807 setenv("LC_ALL", "C", 1);
810 // The path locale is lazy initialized and to avoid deinitialization errors
811 // in multithreading environments, it is set explicitly by the main thread.
812 // A dummy locale is used to extract the internal default locale, used by
813 // boost::filesystem::path, which is then used to explicitly imbue the path.
814 std::locale loc = boost::filesystem::path::imbue(std::locale::classic());
815 boost::filesystem::path::imbue(loc);
818 void SetThreadPriority(int nPriority)
821 SetThreadPriority(GetCurrentThread(), nPriority);
824 setpriority(PRIO_THREAD, 0, nPriority);
826 setpriority(PRIO_PROCESS, 0, nPriority);
827 #endif // PRIO_THREAD