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"
22 // for posix_fallocate
25 #ifdef _POSIX_C_SOURCE
26 #undef _POSIX_C_SOURCE
29 #define _POSIX_C_SOURCE 200112L
35 #include <sys/resource.h>
41 #pragma warning(disable:4786)
42 #pragma warning(disable:4804)
43 #pragma warning(disable:4805)
44 #pragma warning(disable:4717)
50 #define _WIN32_WINNT 0x0501
55 #define _WIN32_IE 0x0501
57 #define WIN32_LEAN_AND_MEAN 1
62 #include <io.h> /* for _commit */
66 #ifdef HAVE_SYS_PRCTL_H
67 #include <sys/prctl.h>
70 #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
71 #include <boost/algorithm/string/join.hpp>
72 #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
73 #include <boost/filesystem.hpp>
74 #include <boost/filesystem/fstream.hpp>
75 #include <boost/foreach.hpp>
76 #include <boost/program_options/detail/config_file.hpp>
77 #include <boost/program_options/parsers.hpp>
78 #include <boost/thread.hpp>
79 #include <openssl/crypto.h>
80 #include <openssl/rand.h>
82 // Work around clang compilation problem in Boost 1.46:
83 // /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
84 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
85 // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
88 namespace program_options {
89 std::string to_internal(const std::string&);
96 map<string, string> mapArgs;
97 map<string, vector<string> > mapMultiArgs;
99 bool fPrintToConsole = false;
100 bool fPrintToDebugLog = true;
101 bool fDaemon = false;
102 bool fServer = false;
103 string strMiscWarning;
104 bool fLogTimestamps = false;
105 bool fLogIPs = false;
106 volatile bool fReopenDebugLog = false;
108 /** Init OpenSSL library multithreading support */
109 static CCriticalSection** ppmutexOpenSSL;
110 void locking_callback(int mode, int i, const char* file, int line)
112 if (mode & CRYPTO_LOCK) {
113 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
115 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
125 // Init OpenSSL library multithreading support
126 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
127 for (int i = 0; i < CRYPTO_num_locks(); i++)
128 ppmutexOpenSSL[i] = new CCriticalSection();
129 CRYPTO_set_locking_callback(locking_callback);
132 // Seed OpenSSL PRNG with current contents of the screen
136 // Seed OpenSSL PRNG with performance counter
141 // Securely erase the memory used by the PRNG
143 // Shutdown OpenSSL library multithreading support
144 CRYPTO_set_locking_callback(NULL);
145 for (int i = 0; i < CRYPTO_num_locks(); i++)
146 delete ppmutexOpenSSL[i];
147 OPENSSL_free(ppmutexOpenSSL);
153 * LogPrintf() has been broken a couple of times now
154 * by well-meaning people adding mutexes in the most straightforward way.
155 * It breaks because it may be called by global destructors during shutdown.
156 * Since the order of destruction of static/global objects is undefined,
157 * defining a mutex as a global object doesn't work (the mutex gets
158 * destroyed, and then some later destructor calls OutputDebugStringF,
159 * maybe indirectly, and you get a core dump at shutdown trying to lock
163 static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
165 * We use boost::call_once() to make sure these are initialized
166 * in a thread-safe manner the first time called:
168 static FILE* fileout = NULL;
169 static boost::mutex* mutexDebugLog = NULL;
171 static void DebugPrintInit()
173 assert(fileout == NULL);
174 assert(mutexDebugLog == NULL);
176 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
177 fileout = fopen(pathDebug.string().c_str(), "a");
178 if (fileout) setbuf(fileout, NULL); // unbuffered
180 mutexDebugLog = new boost::mutex();
183 bool LogAcceptCategory(const char* category)
185 if (category != NULL)
190 // Give each thread quick access to -debug settings.
191 // This helps prevent issues debugging global destructors,
192 // where mapMultiArgs might be deleted before another
193 // global destructor calls LogPrint()
194 static boost::thread_specific_ptr<set<string> > ptrCategory;
195 if (ptrCategory.get() == NULL)
197 const vector<string>& categories = mapMultiArgs["-debug"];
198 ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
199 // thread_specific_ptr automatically deletes the set when the thread ends.
201 const set<string>& setCategories = *ptrCategory.get();
203 // if not debugging everything and not debugging specific category, LogPrint does nothing.
204 if (setCategories.count(string("")) == 0 &&
205 setCategories.count(string(category)) == 0)
211 int LogPrintStr(const std::string &str)
213 int ret = 0; // Returns total number of characters written
217 ret = fwrite(str.data(), 1, str.size(), stdout);
220 else if (fPrintToDebugLog && AreBaseParamsConfigured())
222 static bool fStartedNewLine = true;
223 boost::call_once(&DebugPrintInit, debugPrintInitFlag);
228 boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
230 // reopen the log file, if requested
231 if (fReopenDebugLog) {
232 fReopenDebugLog = false;
233 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
234 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
235 setbuf(fileout, NULL); // unbuffered
238 // Debug print useful for profiling
239 if (fLogTimestamps && fStartedNewLine)
240 ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
241 if (!str.empty() && str[str.size()-1] == '\n')
242 fStartedNewLine = true;
244 fStartedNewLine = false;
246 ret = fwrite(str.data(), 1, str.size(), fileout);
252 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
254 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
255 if (name.find("-no") == 0)
257 std::string positive("-");
258 positive.append(name.begin()+3, name.end());
259 if (mapSettingsRet.count(positive) == 0)
261 bool value = !GetBoolArg(name, false);
262 mapSettingsRet[positive] = (value ? "1" : "0");
267 void ParseParameters(int argc, const char* const argv[])
270 mapMultiArgs.clear();
272 for (int i = 1; i < argc; i++)
274 std::string str(argv[i]);
275 std::string strValue;
276 size_t is_index = str.find('=');
277 if (is_index != std::string::npos)
279 strValue = str.substr(is_index+1);
280 str = str.substr(0, is_index);
283 boost::to_lower(str);
284 if (boost::algorithm::starts_with(str, "/"))
285 str = "-" + str.substr(1);
291 // Interpret --foo as -foo.
292 // If both --foo and -foo are set, the last takes effect.
293 if (str.length() > 1 && str[1] == '-')
296 mapArgs[str] = strValue;
297 mapMultiArgs[str].push_back(strValue);
301 BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
303 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
304 InterpretNegativeSetting(entry.first, mapArgs);
308 std::string GetArg(const std::string& strArg, const std::string& strDefault)
310 if (mapArgs.count(strArg))
311 return mapArgs[strArg];
315 int64_t GetArg(const std::string& strArg, int64_t nDefault)
317 if (mapArgs.count(strArg))
318 return atoi64(mapArgs[strArg]);
322 bool GetBoolArg(const std::string& strArg, bool fDefault)
324 if (mapArgs.count(strArg))
326 if (mapArgs[strArg].empty())
328 return (atoi(mapArgs[strArg]) != 0);
333 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
335 if (mapArgs.count(strArg))
337 mapArgs[strArg] = strValue;
341 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
344 return SoftSetArg(strArg, std::string("1"));
346 return SoftSetArg(strArg, std::string("0"));
349 static std::string FormatException(const std::exception* pex, const char* pszThread)
352 char pszModule[MAX_PATH] = "";
353 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
355 const char* pszModule = "bitcoin";
359 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
362 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
365 void PrintExceptionContinue(const std::exception* pex, const char* pszThread)
367 std::string message = FormatException(pex, pszThread);
368 LogPrintf("\n\n************************\n%s\n", message);
369 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
370 strMiscWarning = message;
373 boost::filesystem::path GetDefaultDataDir()
375 namespace fs = boost::filesystem;
376 // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
377 // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
378 // Mac: ~/Library/Application Support/Bitcoin
382 return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
385 char* pszHome = getenv("HOME");
386 if (pszHome == NULL || strlen(pszHome) == 0)
387 pathRet = fs::path("/");
389 pathRet = fs::path(pszHome);
392 pathRet /= "Library/Application Support";
393 TryCreateDirectory(pathRet);
394 return pathRet / "Bitcoin";
397 return pathRet / ".bitcoin";
402 static boost::filesystem::path pathCached;
403 static boost::filesystem::path pathCachedNetSpecific;
404 static CCriticalSection csPathCached;
406 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
408 namespace fs = boost::filesystem;
412 fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached;
414 // This can be called during exceptions by LogPrintf(), so we cache the
415 // value so we don't have to do memory allocations after that.
419 if (mapArgs.count("-datadir")) {
420 path = fs::system_complete(mapArgs["-datadir"]);
421 if (!fs::is_directory(path)) {
426 path = GetDefaultDataDir();
429 path /= BaseParams().DataDir();
431 fs::create_directories(path);
436 void ClearDatadirCache()
438 pathCached = boost::filesystem::path();
439 pathCachedNetSpecific = boost::filesystem::path();
442 boost::filesystem::path GetConfigFile()
444 boost::filesystem::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
445 if (!pathConfigFile.is_complete())
446 pathConfigFile = GetDataDir(false) / pathConfigFile;
448 return pathConfigFile;
451 void ReadConfigFile(map<string, string>& mapSettingsRet,
452 map<string, vector<string> >& mapMultiSettingsRet)
454 boost::filesystem::ifstream streamConfig(GetConfigFile());
455 if (!streamConfig.good())
456 return; // No bitcoin.conf file is OK
458 set<string> setOptions;
459 setOptions.insert("*");
461 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
463 // Don't overwrite existing settings so command line settings override bitcoin.conf
464 string strKey = string("-") + it->string_key;
465 if (mapSettingsRet.count(strKey) == 0)
467 mapSettingsRet[strKey] = it->value[0];
468 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
469 InterpretNegativeSetting(strKey, mapSettingsRet);
471 mapMultiSettingsRet[strKey].push_back(it->value[0]);
473 // If datadir is changed in .conf file:
478 boost::filesystem::path GetPidFile()
480 boost::filesystem::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
481 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
485 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
487 FILE* file = fopen(path.string().c_str(), "w");
490 fprintf(file, "%d\n", pid);
496 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
499 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
500 MOVEFILE_REPLACE_EXISTING) != 0;
502 int rc = std::rename(src.string().c_str(), dest.string().c_str());
508 * Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
509 * Specifically handles case where path p exists, but it wasn't possible for the user to
510 * write to the parent directory.
512 bool TryCreateDirectory(const boost::filesystem::path& p)
516 return boost::filesystem::create_directory(p);
517 } catch (const boost::filesystem::filesystem_error&) {
518 if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
522 // create_directory didn't create the directory, it had to have existed already
526 void FileCommit(FILE *fileout)
528 fflush(fileout); // harmless if redundantly called
530 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout));
531 FlushFileBuffers(hFile);
533 #if defined(__linux__) || defined(__NetBSD__)
534 fdatasync(fileno(fileout));
535 #elif defined(__APPLE__) && defined(F_FULLFSYNC)
536 fcntl(fileno(fileout), F_FULLFSYNC, 0);
538 fsync(fileno(fileout));
543 bool TruncateFile(FILE *file, unsigned int length) {
545 return _chsize(_fileno(file), length) == 0;
547 return ftruncate(fileno(file), length) == 0;
552 * this function tries to raise the file descriptor limit to the requested number.
553 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
555 int RaiseFileDescriptorLimit(int nMinFD) {
559 struct rlimit limitFD;
560 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
561 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
562 limitFD.rlim_cur = nMinFD;
563 if (limitFD.rlim_cur > limitFD.rlim_max)
564 limitFD.rlim_cur = limitFD.rlim_max;
565 setrlimit(RLIMIT_NOFILE, &limitFD);
566 getrlimit(RLIMIT_NOFILE, &limitFD);
568 return limitFD.rlim_cur;
570 return nMinFD; // getrlimit failed, assume it's fine
575 * this function tries to make a particular range of a file allocated (corresponding to disk space)
576 * it is advisory, and the range specified in the arguments will never contain live data
578 void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
580 // Windows-specific version
581 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
582 LARGE_INTEGER nFileSize;
583 int64_t nEndPos = (int64_t)offset + length;
584 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
585 nFileSize.u.HighPart = nEndPos >> 32;
586 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
588 #elif defined(MAC_OSX)
589 // OSX specific version
591 fst.fst_flags = F_ALLOCATECONTIG;
592 fst.fst_posmode = F_PEOFPOSMODE;
594 fst.fst_length = (off_t)offset + length;
595 fst.fst_bytesalloc = 0;
596 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
597 fst.fst_flags = F_ALLOCATEALL;
598 fcntl(fileno(file), F_PREALLOCATE, &fst);
600 ftruncate(fileno(file), fst.fst_length);
601 #elif defined(__linux__)
602 // Version using posix_fallocate
603 off_t nEndPos = (off_t)offset + length;
604 posix_fallocate(fileno(file), 0, nEndPos);
607 // TODO: just write one byte per block
608 static const char buf[65536] = {};
609 fseek(file, offset, SEEK_SET);
611 unsigned int now = 65536;
614 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
620 void ShrinkDebugFile()
622 // Scroll debug.log if it's getting too big
623 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
624 FILE* file = fopen(pathLog.string().c_str(), "r");
625 if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
627 // Restart the file with some of the end
628 std::vector <char> vch(200000,0);
629 fseek(file, -((long)vch.size()), SEEK_END);
630 int nBytes = fread(begin_ptr(vch), 1, vch.size(), file);
633 file = fopen(pathLog.string().c_str(), "w");
636 fwrite(begin_ptr(vch), 1, nBytes, file);
640 else if (file != NULL)
645 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
647 namespace fs = boost::filesystem;
649 char pszPath[MAX_PATH] = "";
651 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
653 return fs::path(pszPath);
656 LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
661 boost::filesystem::path GetTempPath() {
662 #if BOOST_FILESYSTEM_VERSION == 3
663 return boost::filesystem::temp_directory_path();
665 // TODO: remove when we don't support filesystem v2 anymore
666 boost::filesystem::path path;
668 char pszPath[MAX_PATH] = "";
670 if (GetTempPathA(MAX_PATH, pszPath))
671 path = boost::filesystem::path(pszPath);
673 path = boost::filesystem::path("/tmp");
675 if (path.empty() || !boost::filesystem::is_directory(path)) {
676 LogPrintf("GetTempPath(): failed to find temp path\n");
677 return boost::filesystem::path("");
683 void runCommand(std::string strCommand)
685 int nErr = ::system(strCommand.c_str());
687 LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
690 void RenameThread(const char* name)
692 #if defined(PR_SET_NAME)
693 // Only the first 15 characters are used (16 - NUL terminator)
694 ::prctl(PR_SET_NAME, name, 0, 0, 0);
695 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
696 // TODO: This is currently disabled because it needs to be verified to work
697 // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
699 pthread_set_name_np(pthread_self(), name);
701 #elif defined(MAC_OSX)
702 pthread_setname_np(name);
704 // Prevent warnings for unused parameters...
709 void SetupEnvironment()
714 #if BOOST_FILESYSTEM_VERSION == 3
715 boost::filesystem::path::codecvt(); // Raises runtime error if current locale is invalid
716 #else // boost filesystem v2
717 std::locale(); // Raises runtime error if current locale is invalid
719 } catch (const std::runtime_error&) {
720 setenv("LC_ALL", "C", 1); // Force C locale
725 void SetThreadPriority(int nPriority)
728 SetThreadPriority(GetCurrentThread(), nPriority);
731 setpriority(PRIO_THREAD, 0, nPriority);
733 setpriority(PRIO_PROCESS, 0, nPriority);
734 #endif // PRIO_THREAD