1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "allocators.h"
13 #include <boost/program_options/detail/config_file.hpp>
14 #include <boost/program_options/parsers.hpp>
15 #include <boost/filesystem.hpp>
16 #include <boost/filesystem/fstream.hpp>
17 #include <boost/date_time/posix_time/posix_time.hpp>
18 #include <boost/thread.hpp>
19 #include <openssl/crypto.h>
20 #include <openssl/rand.h>
23 #include <io.h> /* for _commit */
25 #elif defined(__linux__)
26 #include <sys/prctl.h>
29 #if !defined(WIN32) && !defined(ANDROID)
35 namespace bt = boost::posix_time;
37 map<string, string> mapArgs;
38 map<string, vector<string> > mapMultiArgs;
40 bool fDebugNet = false;
41 bool fPrintToConsole = false;
42 bool fPrintToDebugger = false;
43 bool fRequestShutdown = false;
44 bool fShutdown = false;
47 bool fCommandLine = false;
48 string strMiscWarning;
49 bool fTestNet = false;
50 bool fNoListen = false;
51 bool fLogTimestamps = false;
52 bool fReopenDebugLog = false;
54 // Extended DecodeDumpTime implementation, see this page for details:
55 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
56 const std::locale formats[] = {
57 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
58 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
59 std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
60 std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
61 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
64 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
66 std::time_t pt_to_time_t(const bt::ptime& pt)
68 bt::ptime timet_start(boost::gregorian::date(1970,1,1));
69 bt::time_duration diff = pt - timet_start;
70 return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
73 // Init OpenSSL library multithreading support
74 static CCriticalSection** ppmutexOpenSSL;
75 void locking_callback(int mode, int i, const char* file, int line)
77 if (mode & CRYPTO_LOCK) {
78 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
80 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
84 LockedPageManager LockedPageManager::instance;
92 // Init OpenSSL library multithreading support
93 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
94 for (int i = 0; i < CRYPTO_num_locks(); i++)
95 ppmutexOpenSSL[i] = new CCriticalSection();
96 CRYPTO_set_locking_callback(locking_callback);
99 // Seed random number generator with screen scrape and other hardware sources
103 // Seed random number generator with performance counter
108 // Shutdown OpenSSL library multithreading support
109 CRYPTO_set_locking_callback(NULL);
110 for (int i = 0; i < CRYPTO_num_locks(); i++)
111 delete ppmutexOpenSSL[i];
112 OPENSSL_free(ppmutexOpenSSL);
118 static FILE* fileout = NULL;
120 inline int OutputDebugStringF(const char* pszFormat, ...)
127 va_start(arg_ptr, pszFormat);
128 ret = vprintf(pszFormat, arg_ptr);
131 else if (!fPrintToDebugger)
133 // print to debug.log
137 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
138 fileout = fopen(pathDebug.string().c_str(), "a");
139 if (fileout) setbuf(fileout, NULL); // unbuffered
143 static bool fStartedNewLine = true;
145 // This routine may be called by global destructors during shutdown.
146 // Since the order of destruction of static/global objects is undefined,
147 // allocate mutexDebugLog on the heap the first time this routine
148 // is called to avoid crashes during shutdown.
149 static std::mutex* mutexDebugLog = nullptr;
150 if (mutexDebugLog == nullptr) mutexDebugLog = new std::mutex();
151 std::scoped_lock scoped_lock(*mutexDebugLog);
153 // reopen the log file, if requested
154 if (fReopenDebugLog) {
155 fReopenDebugLog = false;
156 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
157 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
158 setbuf(fileout, NULL); // unbuffered
161 // Debug print useful for profiling
162 if (fLogTimestamps && fStartedNewLine)
163 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
164 if (pszFormat[strlen(pszFormat) - 1] == '\n')
165 fStartedNewLine = true;
167 fStartedNewLine = false;
170 va_start(arg_ptr, pszFormat);
171 ret = vfprintf(fileout, pszFormat, arg_ptr);
177 if (fPrintToDebugger)
179 static CCriticalSection cs_OutputDebugStringF;
181 // accumulate and output a line at a time
183 LOCK(cs_OutputDebugStringF);
184 static std::string buffer;
187 va_start(arg_ptr, pszFormat);
188 buffer += vstrprintf(pszFormat, arg_ptr);
191 size_t line_start = 0, line_end;
192 while((line_end = buffer.find('\n', line_start)) != -1)
194 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
195 line_start = line_end + 1;
197 buffer.erase(0, line_start);
204 string vstrprintf(const char *format, va_list ap)
208 int limit = sizeof(buffer);
214 va_copy(arg_ptr, ap);
216 va_list arg_ptr = ap;
219 ret = _vsnprintf(p, limit, format, arg_ptr);
221 ret = vsnprintf(p, limit, format, arg_ptr);
224 if (ret >= 0 && ret < limit)
229 p = new(nothrow) char[limit];
231 throw std::bad_alloc();
233 string str(p, p+ret);
239 string real_strprintf(const char *format, int dummy, ...)
242 va_start(arg_ptr, dummy);
243 string str = vstrprintf(format, arg_ptr);
248 string real_strprintf(const std::string &format, int dummy, ...)
251 va_start(arg_ptr, dummy);
252 string str = vstrprintf(format.c_str(), arg_ptr);
257 bool error(const char *format, ...)
260 va_start(arg_ptr, format);
261 std::string str = vstrprintf(format, arg_ptr);
263 printf("ERROR: %s\n", str.c_str());
268 void ParseString(const string& str, char c, vector<string>& v)
272 string::size_type i1 = 0;
273 string::size_type i2;
276 i2 = str.find(c, i1);
279 v.push_back(str.substr(i1));
282 v.push_back(str.substr(i1, i2-i1));
288 string FormatMoney(int64_t n, bool fPlus)
290 // Note: not using straight sprintf here because we do NOT want
291 // localized number formatting.
292 int64_t n_abs = (n > 0 ? n : -n);
293 int64_t quotient = n_abs/COIN;
294 int64_t remainder = n_abs%COIN;
295 string str = strprintf("%" PRId64 ".%06" PRId64, quotient, remainder);
297 // Right-trim excess zeros before the decimal point:
299 for (size_t i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
302 str.erase(str.size()-nTrim, nTrim);
305 str.insert(0u, 1, '-');
306 else if (fPlus && n > 0)
307 str.insert(0u, 1, '+');
312 bool ParseMoney(const string& str, int64_t& nRet)
314 return ParseMoney(str.c_str(), nRet);
317 bool ParseMoney(const char* pszIn, int64_t& nRet)
321 const char* p = pszIn;
329 int64_t nMult = CENT*10;
330 while (isdigit(*p) && (nMult > 0))
332 nUnits += nMult * (*p++ - '0');
341 strWhole.insert(strWhole.end(), *p);
346 if (strWhole.size() > 10) // guard against 63 bit overflow
348 if (nUnits < 0 || nUnits > COIN)
350 int64_t nWhole = atoi64(strWhole);
351 int64_t nValue = nWhole*COIN + nUnits;
358 static const signed char phexdigit[256] =
359 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
360 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
361 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
362 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
363 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
364 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
365 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
366 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
367 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
368 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
369 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
370 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
371 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
372 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
373 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
374 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
376 bool IsHex(const string& str)
378 for (unsigned char c : str)
380 if (phexdigit[c] < 0)
383 return (str.size() > 0) && (str.size()%2 == 0);
386 vector<unsigned char> ParseHex(const char* psz)
388 // convert hex dump to vector
389 vector<unsigned char> vch;
392 while (isspace(*psz))
394 signed char c = phexdigit[(unsigned char)*psz++];
395 if (c == (signed char)-1)
397 unsigned char n = (c << 4);
398 c = phexdigit[(unsigned char)*psz++];
399 if (c == (signed char)-1)
407 vector<unsigned char> ParseHex(const string& str)
409 return ParseHex(str.c_str());
412 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
414 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
415 if (name.find("-no") == 0)
417 std::string positive("-");
418 positive.append(name.begin()+3, name.end());
419 if (mapSettingsRet.count(positive) == 0)
421 bool value = !GetBoolArg(name);
422 mapSettingsRet[positive] = (value ? "1" : "0");
427 void ParseParameters(int argc, const char* const argv[])
430 mapMultiArgs.clear();
431 for (int i = 1; i < argc; i++)
433 std::string str(argv[i]);
434 std::string strValue;
435 size_t is_index = str.find('=');
436 if (is_index != std::string::npos)
438 strValue = str.substr(is_index+1);
439 str = str.substr(0, is_index);
442 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
443 if (str.compare(0,1, "/") == 0)
444 str = "-" + str.substr(1);
449 mapArgs[str] = strValue;
450 mapMultiArgs[str].push_back(strValue);
454 for (const auto& entry : mapArgs)
456 string name = entry.first;
458 // interpret --foo as -foo (as long as both are not set)
459 if (name.find("--") == 0)
461 std::string singleDash(name.begin()+1, name.end());
462 if (mapArgs.count(singleDash) == 0)
463 mapArgs[singleDash] = entry.second;
467 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
468 InterpretNegativeSetting(name, mapArgs);
472 std::string GetArg(const std::string& strArg, const std::string& strDefault)
474 if (mapArgs.count(strArg))
475 return mapArgs[strArg];
479 int64_t GetArg(const std::string& strArg, int64_t nDefault)
481 if (mapArgs.count(strArg))
482 return atoi64(mapArgs[strArg]);
486 int32_t GetArgInt(const std::string& strArg, int32_t nDefault)
488 if (mapArgs.count(strArg))
489 return strtol(mapArgs[strArg]);
493 uint32_t GetArgUInt(const std::string& strArg, uint32_t nDefault)
495 if (mapArgs.count(strArg))
496 return strtoul(mapArgs[strArg]);
500 bool GetBoolArg(const std::string& strArg, bool fDefault)
502 if (mapArgs.count(strArg))
504 if (mapArgs[strArg].empty())
506 return (atoi(mapArgs[strArg]) != 0);
511 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
513 if (mapArgs.count(strArg) || mapMultiArgs.count(strArg))
515 mapArgs[strArg] = strValue;
516 mapMultiArgs[strArg].push_back(strValue);
521 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
524 return SoftSetArg(strArg, std::string("1"));
526 return SoftSetArg(strArg, std::string("0"));
530 string EncodeBase64(const unsigned char* pch, size_t len)
532 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
535 strRet.reserve((len+2)/3*4);
538 const unsigned char *pchEnd = pch+len;
545 case 0: // we have no bits
546 strRet += pbase64[enc >> 2];
547 left = (enc & 3) << 4;
551 case 1: // we have two bits
552 strRet += pbase64[left | (enc >> 4)];
553 left = (enc & 15) << 2;
557 case 2: // we have four bits
558 strRet += pbase64[left | (enc >> 6)];
559 strRet += pbase64[enc & 63];
567 strRet += pbase64[left];
576 string EncodeBase64(const string& str)
578 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
581 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
583 static const int decode64_table[256] =
585 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
586 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
587 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
588 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
589 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
590 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
591 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
592 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
593 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
594 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
595 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
596 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
597 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
603 vector<unsigned char> vchRet;
604 vchRet.reserve(strlen(p)*3/4);
611 int dec = decode64_table[(unsigned char)*p];
612 if (dec == -1) break;
616 case 0: // we have no bits and get 6
621 case 1: // we have 6 bits and keep 4
622 vchRet.push_back((left<<2) | (dec>>4));
627 case 2: // we have 4 bits and get 6, we keep 2
628 vchRet.push_back((left<<4) | (dec>>2));
633 case 3: // we have 2 bits and get 6
634 vchRet.push_back((left<<6) | dec);
643 case 0: // 4n base64 characters processed: ok
646 case 1: // 4n+1 base64 character processed: impossible
650 case 2: // 4n+2 base64 characters processed: require '=='
651 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
655 case 3: // 4n+3 base64 characters processed: require '='
656 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
664 string DecodeBase64(const string& str)
666 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
667 return string((const char*)&vchRet[0], vchRet.size());
670 string EncodeBase32(const unsigned char* pch, size_t len)
672 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
675 strRet.reserve((len+4)/5*8);
678 const unsigned char *pchEnd = pch+len;
685 case 0: // we have no bits
686 strRet += pbase32[enc >> 3];
687 left = (enc & 7) << 2;
691 case 1: // we have three bits
692 strRet += pbase32[left | (enc >> 6)];
693 strRet += pbase32[(enc >> 1) & 31];
694 left = (enc & 1) << 4;
698 case 2: // we have one bit
699 strRet += pbase32[left | (enc >> 4)];
700 left = (enc & 15) << 1;
704 case 3: // we have four bits
705 strRet += pbase32[left | (enc >> 7)];
706 strRet += pbase32[(enc >> 2) & 31];
707 left = (enc & 3) << 3;
711 case 4: // we have two bits
712 strRet += pbase32[left | (enc >> 5)];
713 strRet += pbase32[enc & 31];
718 static const int nPadding[5] = {0, 6, 4, 3, 1};
721 strRet += pbase32[left];
722 for (int n=0; n<nPadding[mode]; n++)
729 string EncodeBase32(const string& str)
731 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
734 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
736 static const int decode32_table[256] =
738 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
739 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
740 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
741 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
742 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
743 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
744 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
745 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
746 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
747 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
748 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
749 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
750 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
756 vector<unsigned char> vchRet;
757 vchRet.reserve((strlen(p))*5/8);
764 int dec = decode32_table[(unsigned char)*p];
765 if (dec == -1) break;
769 case 0: // we have no bits and get 5
774 case 1: // we have 5 bits and keep 2
775 vchRet.push_back((left<<3) | (dec>>2));
780 case 2: // we have 2 bits and keep 7
781 left = left << 5 | dec;
785 case 3: // we have 7 bits and keep 4
786 vchRet.push_back((left<<1) | (dec>>4));
791 case 4: // we have 4 bits, and keep 1
792 vchRet.push_back((left<<4) | (dec>>1));
797 case 5: // we have 1 bit, and keep 6
798 left = left << 5 | dec;
802 case 6: // we have 6 bits, and keep 3
803 vchRet.push_back((left<<2) | (dec>>3));
808 case 7: // we have 3 bits, and keep 0
809 vchRet.push_back((left<<5) | dec);
818 case 0: // 8n base32 characters processed: ok
821 case 1: // 8n+1 base32 characters processed: impossible
827 case 2: // 8n+2 base32 characters processed: require '======'
828 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
832 case 4: // 8n+4 base32 characters processed: require '===='
833 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
837 case 5: // 8n+5 base32 characters processed: require '==='
838 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
842 case 7: // 8n+7 base32 characters processed: require '='
843 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
851 string DecodeBase32(const string& str)
853 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
854 return string((const char*)&vchRet[0], vchRet.size());
858 int64_t DecodeDumpTime(const std::string& s)
862 for(size_t i=0; i<formats_n; ++i)
864 std::istringstream is(s);
865 is.imbue(formats[i]);
867 if(pt != bt::ptime()) break;
870 return pt_to_time_t(pt);
873 std::string EncodeDumpTime(int64_t nTime) {
874 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
877 std::string EncodeDumpString(const std::string &str) {
878 std::stringstream ret;
879 for (unsigned char c : str) {
880 if (c <= 32 || c >= 128 || c == '%') {
881 ret << '%' << HexStr(&c, &c + 1);
889 std::string DecodeDumpString(const std::string &str) {
890 std::stringstream ret;
891 for (unsigned int pos = 0; pos < str.length(); pos++) {
892 unsigned char c = str[pos];
893 if (c == '%' && pos+2 < str.length()) {
894 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
895 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
903 bool WildcardMatch(const char* psz, const char* mask)
910 return (*psz == '\0');
912 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
927 bool WildcardMatch(const string& str, const string& mask)
929 return WildcardMatch(str.c_str(), mask.c_str());
939 static std::string FormatException(std::exception* pex, const char* pszThread)
942 char pszModule[MAX_PATH] = "";
943 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
945 const char* pszModule = "novacoin";
949 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
952 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
955 void LogException(std::exception* pex, const char* pszThread)
957 std::string message = FormatException(pex, pszThread);
958 printf("\n%s", message.c_str());
961 void PrintException(std::exception* pex, const char* pszThread)
963 std::string message = FormatException(pex, pszThread);
964 printf("\n\n************************\n%s\n", message.c_str());
965 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
966 strMiscWarning = message;
970 void LogStackTrace() {
971 printf("\n\n******* exception encountered *******\n");
974 #if !defined(WIN32) && !defined(ANDROID)
977 size = backtrace(pszBuffer, 32);
978 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
983 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
985 std::string message = FormatException(pex, pszThread);
986 printf("\n\n************************\n%s\n", message.c_str());
987 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
988 strMiscWarning = message;
991 boost::filesystem::path GetDefaultDataDir()
993 namespace fs = boost::filesystem;
994 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
995 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
996 // Mac: ~/Library/Application Support/NovaCoin
1000 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1003 char* pszHome = getenv("HOME");
1004 if (pszHome == NULL || strlen(pszHome) == 0)
1005 pathRet = fs::path("/");
1007 pathRet = fs::path(pszHome);
1010 pathRet /= "Library/Application Support";
1011 fs::create_directory(pathRet);
1012 return pathRet / "NovaCoin";
1015 return pathRet / ".novacoin";
1020 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1022 namespace fs = boost::filesystem;
1024 static fs::path pathCached[2];
1025 static CCriticalSection csPathCached;
1026 static bool cachedPath[2] = {false, false};
1028 fs::path &path = pathCached[fNetSpecific];
1030 // This can be called during exceptions by printf, so we cache the
1031 // value so we don't have to do memory allocations after that.
1032 if (cachedPath[fNetSpecific])
1037 if (mapArgs.count("-datadir")) {
1038 path = fs::system_complete(mapArgs["-datadir"]);
1039 if (!fs::is_directory(path)) {
1044 path = GetDefaultDataDir();
1046 if (fNetSpecific && GetBoolArg("-testnet", false))
1049 fs::create_directory(path);
1051 cachedPath[fNetSpecific]=true;
1055 string randomStrGen(int length) {
1056 static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
1058 result.resize(length);
1059 for (int32_t i = 0; i < length; i++)
1060 result[i] = charset[rand() % charset.length()];
1067 srand(static_cast<unsigned int>(time(NULL)));
1070 #if BOOST_FILESYSTEM_VERSION >= 3
1071 pConf.open(GetConfigFile().generic_string().c_str());
1073 pConf.open(GetConfigFile().string().c_str());
1075 pConf << "rpcuser=user\nrpcpassword="
1078 + "\n#(0=off, 1=on) daemon - run in the background as a daemon and accept commands"
1080 + "\n#(0=off, 1=on) server - accept command line and JSON-RPC commands"
1082 + "\nrpcallowip=127.0.0.1";
1086 boost::filesystem::path GetConfigFile()
1088 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1089 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1090 return pathConfigFile;
1093 void ReadConfigFile(map<string, string>& mapSettingsRet,
1094 map<string, vector<string> >& mapMultiSettingsRet)
1096 boost::filesystem::ifstream streamConfig(GetConfigFile());
1097 if (!streamConfig.good())
1100 new(&streamConfig) boost::filesystem::ifstream(GetConfigFile());
1101 if(!streamConfig.good())
1105 set<string> setOptions;
1106 setOptions.insert("*");
1108 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1110 // Don't overwrite existing settings so command line settings override bitcoin.conf
1111 string strKey = string("-") + it->string_key;
1112 if (mapSettingsRet.count(strKey) == 0)
1114 mapSettingsRet[strKey] = it->value[0];
1115 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1116 InterpretNegativeSetting(strKey, mapSettingsRet);
1118 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1122 boost::filesystem::path GetPidFile()
1124 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1125 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1130 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1132 FILE* file = fopen(path.string().c_str(), "w");
1135 fprintf(file, "%d\n", pid);
1141 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1144 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1145 MOVEFILE_REPLACE_EXISTING) != 0;
1147 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1152 void FileCommit(FILE *fileout)
1154 fflush(fileout); // harmless if redundantly called
1156 _commit(_fileno(fileout));
1158 fsync(fileno(fileout));
1162 int GetFilesize(FILE* file)
1164 int nSavePos = ftell(file);
1166 if (fseek(file, 0, SEEK_END) == 0)
1167 nFilesize = ftell(file);
1168 fseek(file, nSavePos, SEEK_SET);
1172 void ShrinkDebugFile()
1174 // Scroll debug.log if it's getting too big
1175 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1176 FILE* file = fopen(pathLog.string().c_str(), "r");
1177 if (file && GetFilesize(file) > 10 * 1000000)
1179 // Restart the file with some of the end
1181 vector<char>* vBuf = new vector <char>(200000, 0);
1182 fseek(file, -((long)(vBuf->size())), SEEK_END);
1183 size_t nBytes = fread(&vBuf->operator[](0), 1, vBuf->size(), file);
1185 file = fopen(pathLog.string().c_str(), "w");
1188 fwrite(&vBuf->operator[](0), 1, nBytes, file);
1193 catch (const bad_alloc& e) {
1194 // Bad things happen - no free memory in heap at program startup
1196 printf("Warning: %s in %s:%d\n ShrinkDebugFile failed - debug.log expands further", e.what(), __FILE__, __LINE__);
1207 int64_t now = time(NULL);
1212 string FormatVersion(int nVersion)
1214 if (nVersion%100 == 0)
1215 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1217 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1220 string FormatFullVersion()
1222 return CLIENT_BUILD;
1225 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1226 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1228 std::ostringstream ss;
1230 ss << name << ":" << FormatVersion(nClientVersion);
1231 if (!comments.empty())
1234 for (const auto& st : comments)
1237 if (st == comments.back()) break;
1247 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1249 namespace fs = boost::filesystem;
1251 char pszPath[MAX_PATH] = "";
1253 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1255 return fs::path(pszPath);
1258 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1259 return fs::path("");
1263 void runCommand(std::string strCommand)
1265 int nErr = ::system(strCommand.c_str());
1267 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1270 void RenameThread(const char* name)
1272 #if defined(PR_SET_NAME)
1273 // Only the first 15 characters are used (16 - NUL terminator)
1274 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1275 #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
1276 pthread_set_name_np(pthread_self(), name);
1277 #elif defined(__APPLE__)
1278 pthread_setname_np(name);
1280 // Prevent warnings for unused parameters...
1285 bool NewThread(void(*pfn)(void*), void* parg)
1289 boost::thread(pfn, parg); // thread detaches when out of scope
1290 } catch(boost::thread_resource_error &e) {
1291 printf("Error creating thread: %s\n", e.what());
1297 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
1299 // std::locale takes ownership of the pointer
1300 std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
1301 std::stringstream ss;
1303 ss << boost::posix_time::from_time_t(nTime);