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/filesystem.hpp>
15 #include <boost/filesystem/fstream.hpp>
16 #include <boost/date_time/posix_time/posix_time.hpp>
17 #include <boost/thread.hpp>
20 #include <io.h> /* for _commit */
22 #include <openssl/rand.h> // RAND_screen
23 #elif defined(__linux__)
24 #include <sys/prctl.h>
27 #if !defined(WIN32) && !defined(ANDROID)
33 namespace bt = boost::posix_time;
35 map<string, string> mapArgs;
36 map<string, vector<string> > mapMultiArgs;
38 bool fDebugNet = false;
39 bool fPrintToConsole = false;
40 bool fPrintToDebugger = false;
41 bool fRequestShutdown = false;
42 bool fShutdown = false;
45 bool fCommandLine = false;
46 string strMiscWarning;
47 bool fTestNet = false;
48 bool fNoListen = false;
49 bool fLogTimestamps = false;
50 bool fReopenDebugLog = false;
52 // Extended DecodeDumpTime implementation, see this page for details:
53 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
54 const std::locale formats[] = {
55 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
56 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
57 std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
58 std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
59 std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
62 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
64 std::time_t pt_to_time_t(const bt::ptime& pt)
66 bt::ptime timet_start(boost::gregorian::date(1970,1,1));
67 bt::time_duration diff = pt - timet_start;
68 return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
71 // Init OpenSSL library multithreading support
72 static CCriticalSection** ppmutexOpenSSL;
73 void locking_callback(int mode, int i, const char* file, int line)
75 if (mode & CRYPTO_LOCK) {
76 ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
78 LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
82 LockedPageManager LockedPageManager::instance;
90 // Init OpenSSL library multithreading support
91 ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
92 for (int i = 0; i < CRYPTO_num_locks(); i++)
93 ppmutexOpenSSL[i] = new CCriticalSection();
94 CRYPTO_set_locking_callback(locking_callback);
97 // Seed random number generator with screen scrape and other hardware sources
101 // Seed random number generator with performance counter
106 // Shutdown OpenSSL library multithreading support
107 CRYPTO_set_locking_callback(NULL);
108 for (int i = 0; i < CRYPTO_num_locks(); i++)
109 delete ppmutexOpenSSL[i];
110 OPENSSL_free(ppmutexOpenSSL);
116 static FILE* fileout = NULL;
118 inline int OutputDebugStringF(const char* pszFormat, ...)
125 va_start(arg_ptr, pszFormat);
126 ret = vprintf(pszFormat, arg_ptr);
129 else if (!fPrintToDebugger)
131 // print to debug.log
135 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
136 fileout = fopen(pathDebug.string().c_str(), "a");
137 if (fileout) setbuf(fileout, NULL); // unbuffered
141 static bool fStartedNewLine = true;
143 // This routine may be called by global destructors during shutdown.
144 // Since the order of destruction of static/global objects is undefined,
145 // allocate mutexDebugLog on the heap the first time this routine
146 // is called to avoid crashes during shutdown.
147 static std::mutex* mutexDebugLog = nullptr;
148 if (mutexDebugLog == nullptr) mutexDebugLog = new std::mutex();
149 std::scoped_lock scoped_lock(*mutexDebugLog);
151 // reopen the log file, if requested
152 if (fReopenDebugLog) {
153 fReopenDebugLog = false;
154 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
155 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
156 setbuf(fileout, NULL); // unbuffered
159 // Debug print useful for profiling
160 if (fLogTimestamps && fStartedNewLine)
161 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
162 if (pszFormat[strlen(pszFormat) - 1] == '\n')
163 fStartedNewLine = true;
165 fStartedNewLine = false;
168 va_start(arg_ptr, pszFormat);
169 ret = vfprintf(fileout, pszFormat, arg_ptr);
175 if (fPrintToDebugger)
177 static CCriticalSection cs_OutputDebugStringF;
179 // accumulate and output a line at a time
181 LOCK(cs_OutputDebugStringF);
182 static std::string buffer;
185 va_start(arg_ptr, pszFormat);
186 buffer += vstrprintf(pszFormat, arg_ptr);
189 size_t line_start = 0, line_end;
190 while((line_end = buffer.find('\n', line_start)) != -1)
192 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
193 line_start = line_end + 1;
195 buffer.erase(0, line_start);
202 string vstrprintf(const char *format, va_list ap)
206 int limit = sizeof(buffer);
212 va_copy(arg_ptr, ap);
214 va_list arg_ptr = ap;
217 ret = _vsnprintf(p, limit, format, arg_ptr);
219 ret = vsnprintf(p, limit, format, arg_ptr);
222 if (ret >= 0 && ret < limit)
227 p = new(nothrow) char[limit];
229 throw std::bad_alloc();
231 string str(p, p+ret);
237 string real_strprintf(const char *format, int dummy, ...)
240 va_start(arg_ptr, dummy);
241 string str = vstrprintf(format, arg_ptr);
246 string real_strprintf(const std::string &format, int dummy, ...)
249 va_start(arg_ptr, dummy);
250 string str = vstrprintf(format.c_str(), arg_ptr);
255 bool error(const char *format, ...)
258 va_start(arg_ptr, format);
259 std::string str = vstrprintf(format, arg_ptr);
261 printf("ERROR: %s\n", str.c_str());
266 void ParseString(const string& str, char c, vector<string>& v)
270 string::size_type i1 = 0;
271 string::size_type i2;
274 i2 = str.find(c, i1);
277 v.push_back(str.substr(i1));
280 v.push_back(str.substr(i1, i2-i1));
286 string FormatMoney(int64_t n, bool fPlus)
288 // Note: not using straight sprintf here because we do NOT want
289 // localized number formatting.
290 int64_t n_abs = (n > 0 ? n : -n);
291 int64_t quotient = n_abs/COIN;
292 int64_t remainder = n_abs%COIN;
293 string str = strprintf("%" PRId64 ".%06" PRId64, quotient, remainder);
295 // Right-trim excess zeros before the decimal point:
297 for (size_t i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
300 str.erase(str.size()-nTrim, nTrim);
303 str.insert(0u, 1, '-');
304 else if (fPlus && n > 0)
305 str.insert(0u, 1, '+');
310 bool ParseMoney(const string& str, int64_t& nRet)
312 return ParseMoney(str.c_str(), nRet);
315 bool ParseMoney(const char* pszIn, int64_t& nRet)
319 const char* p = pszIn;
327 int64_t nMult = CENT*10;
328 while (isdigit(*p) && (nMult > 0))
330 nUnits += nMult * (*p++ - '0');
339 strWhole.insert(strWhole.end(), *p);
344 if (strWhole.size() > 10) // guard against 63 bit overflow
346 if (nUnits < 0 || nUnits > COIN)
348 int64_t nWhole = atoi64(strWhole);
349 int64_t nValue = nWhole*COIN + nUnits;
356 static const signed char phexdigit[256] =
357 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
358 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
359 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
360 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
361 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
362 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-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,-1,-1,-1,-1,-1,-1,-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, };
374 bool IsHex(const string& str)
376 for (unsigned char c : str)
378 if (phexdigit[c] < 0)
381 return (str.size() > 0) && (str.size()%2 == 0);
384 vector<unsigned char> ParseHex(const char* psz)
386 // convert hex dump to vector
387 vector<unsigned char> vch;
390 while (isspace(*psz))
392 signed char c = phexdigit[(unsigned char)*psz++];
393 if (c == (signed char)-1)
395 unsigned char n = (c << 4);
396 c = phexdigit[(unsigned char)*psz++];
397 if (c == (signed char)-1)
405 vector<unsigned char> ParseHex(const string& str)
407 return ParseHex(str.c_str());
410 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
412 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
413 if (name.find("-no") == 0)
415 std::string positive("-");
416 positive.append(name.begin()+3, name.end());
417 if (mapSettingsRet.count(positive) == 0)
419 bool value = !GetBoolArg(name);
420 mapSettingsRet[positive] = (value ? "1" : "0");
425 void ParseParameters(int argc, const char* const argv[])
428 mapMultiArgs.clear();
429 for (int i = 1; i < argc; i++)
431 std::string str(argv[i]);
432 std::string strValue;
433 size_t is_index = str.find('=');
434 if (is_index != std::string::npos)
436 strValue = str.substr(is_index+1);
437 str = str.substr(0, is_index);
440 std::transform(str.begin(), str.end(), str.begin(), ::tolower);
441 if (str.compare(0,1, "/") == 0)
442 str = "-" + str.substr(1);
447 mapArgs[str] = strValue;
448 mapMultiArgs[str].push_back(strValue);
452 for (const auto& entry : mapArgs)
454 string name = entry.first;
456 // interpret --foo as -foo (as long as both are not set)
457 if (name.find("--") == 0)
459 std::string singleDash(name.begin()+1, name.end());
460 if (mapArgs.count(singleDash) == 0)
461 mapArgs[singleDash] = entry.second;
465 // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
466 InterpretNegativeSetting(name, mapArgs);
470 std::string GetArg(const std::string& strArg, const std::string& strDefault)
472 if (mapArgs.count(strArg))
473 return mapArgs[strArg];
477 int64_t GetArg(const std::string& strArg, int64_t nDefault)
479 if (mapArgs.count(strArg))
480 return atoi64(mapArgs[strArg]);
484 int32_t GetArgInt(const std::string& strArg, int32_t nDefault)
486 if (mapArgs.count(strArg))
487 return strtol(mapArgs[strArg]);
491 uint32_t GetArgUInt(const std::string& strArg, uint32_t nDefault)
493 if (mapArgs.count(strArg))
494 return strtoul(mapArgs[strArg]);
498 bool GetBoolArg(const std::string& strArg, bool fDefault)
500 if (mapArgs.count(strArg))
502 if (mapArgs[strArg].empty())
504 return (atoi(mapArgs[strArg]) != 0);
509 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
511 if (mapArgs.count(strArg) || mapMultiArgs.count(strArg))
513 mapArgs[strArg] = strValue;
514 mapMultiArgs[strArg].push_back(strValue);
519 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
522 return SoftSetArg(strArg, std::string("1"));
524 return SoftSetArg(strArg, std::string("0"));
528 string EncodeBase64(const unsigned char* pch, size_t len)
530 static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
533 strRet.reserve((len+2)/3*4);
536 const unsigned char *pchEnd = pch+len;
543 case 0: // we have no bits
544 strRet += pbase64[enc >> 2];
545 left = (enc & 3) << 4;
549 case 1: // we have two bits
550 strRet += pbase64[left | (enc >> 4)];
551 left = (enc & 15) << 2;
555 case 2: // we have four bits
556 strRet += pbase64[left | (enc >> 6)];
557 strRet += pbase64[enc & 63];
565 strRet += pbase64[left];
574 string EncodeBase64(const string& str)
576 return EncodeBase64((const unsigned char*)str.c_str(), str.size());
579 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
581 static const int decode64_table[256] =
583 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
584 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
585 -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
586 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
587 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
588 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
589 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
590 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
591 -1, -1, -1, -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
601 vector<unsigned char> vchRet;
602 vchRet.reserve(strlen(p)*3/4);
609 int dec = decode64_table[(unsigned char)*p];
610 if (dec == -1) break;
614 case 0: // we have no bits and get 6
619 case 1: // we have 6 bits and keep 4
620 vchRet.push_back((left<<2) | (dec>>4));
625 case 2: // we have 4 bits and get 6, we keep 2
626 vchRet.push_back((left<<4) | (dec>>2));
631 case 3: // we have 2 bits and get 6
632 vchRet.push_back((left<<6) | dec);
641 case 0: // 4n base64 characters processed: ok
644 case 1: // 4n+1 base64 character processed: impossible
648 case 2: // 4n+2 base64 characters processed: require '=='
649 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
653 case 3: // 4n+3 base64 characters processed: require '='
654 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
662 string DecodeBase64(const string& str)
664 vector<unsigned char> vchRet = DecodeBase64(str.c_str());
665 return string((const char*)&vchRet[0], vchRet.size());
668 string EncodeBase32(const unsigned char* pch, size_t len)
670 static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
673 strRet.reserve((len+4)/5*8);
676 const unsigned char *pchEnd = pch+len;
683 case 0: // we have no bits
684 strRet += pbase32[enc >> 3];
685 left = (enc & 7) << 2;
689 case 1: // we have three bits
690 strRet += pbase32[left | (enc >> 6)];
691 strRet += pbase32[(enc >> 1) & 31];
692 left = (enc & 1) << 4;
696 case 2: // we have one bit
697 strRet += pbase32[left | (enc >> 4)];
698 left = (enc & 15) << 1;
702 case 3: // we have four bits
703 strRet += pbase32[left | (enc >> 7)];
704 strRet += pbase32[(enc >> 2) & 31];
705 left = (enc & 3) << 3;
709 case 4: // we have two bits
710 strRet += pbase32[left | (enc >> 5)];
711 strRet += pbase32[enc & 31];
716 static const int nPadding[5] = {0, 6, 4, 3, 1};
719 strRet += pbase32[left];
720 for (int n=0; n<nPadding[mode]; n++)
727 string EncodeBase32(const string& str)
729 return EncodeBase32((const unsigned char*)str.c_str(), str.size());
732 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
734 static const int decode32_table[256] =
736 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
737 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
738 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
739 -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
740 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
741 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
742 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
743 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
744 -1, -1, -1, -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
754 vector<unsigned char> vchRet;
755 vchRet.reserve((strlen(p))*5/8);
762 int dec = decode32_table[(unsigned char)*p];
763 if (dec == -1) break;
767 case 0: // we have no bits and get 5
772 case 1: // we have 5 bits and keep 2
773 vchRet.push_back((left<<3) | (dec>>2));
778 case 2: // we have 2 bits and keep 7
779 left = left << 5 | dec;
783 case 3: // we have 7 bits and keep 4
784 vchRet.push_back((left<<1) | (dec>>4));
789 case 4: // we have 4 bits, and keep 1
790 vchRet.push_back((left<<4) | (dec>>1));
795 case 5: // we have 1 bit, and keep 6
796 left = left << 5 | dec;
800 case 6: // we have 6 bits, and keep 3
801 vchRet.push_back((left<<2) | (dec>>3));
806 case 7: // we have 3 bits, and keep 0
807 vchRet.push_back((left<<5) | dec);
816 case 0: // 8n base32 characters processed: ok
819 case 1: // 8n+1 base32 characters processed: impossible
825 case 2: // 8n+2 base32 characters processed: require '======'
826 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
830 case 4: // 8n+4 base32 characters processed: require '===='
831 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
835 case 5: // 8n+5 base32 characters processed: require '==='
836 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
840 case 7: // 8n+7 base32 characters processed: require '='
841 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
849 string DecodeBase32(const string& str)
851 vector<unsigned char> vchRet = DecodeBase32(str.c_str());
852 return string((const char*)&vchRet[0], vchRet.size());
856 int64_t DecodeDumpTime(const std::string& s)
860 for(size_t i=0; i<formats_n; ++i)
862 std::istringstream is(s);
863 is.imbue(formats[i]);
865 if(pt != bt::ptime()) break;
868 return pt_to_time_t(pt);
871 std::string EncodeDumpTime(int64_t nTime) {
872 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
875 std::string EncodeDumpString(const std::string &str) {
876 std::stringstream ret;
877 for (unsigned char c : str) {
878 if (c <= 32 || c >= 128 || c == '%') {
879 ret << '%' << HexStr(&c, &c + 1);
887 std::string DecodeDumpString(const std::string &str) {
888 std::stringstream ret;
889 for (unsigned int pos = 0; pos < str.length(); pos++) {
890 unsigned char c = str[pos];
891 if (c == '%' && pos+2 < str.length()) {
892 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
893 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
901 bool WildcardMatch(const char* psz, const char* mask)
908 return (*psz == '\0');
910 return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
925 bool WildcardMatch(const string& str, const string& mask)
927 return WildcardMatch(str.c_str(), mask.c_str());
937 static std::string FormatException(std::exception* pex, const char* pszThread)
940 char pszModule[MAX_PATH] = "";
941 GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
943 const char* pszModule = "novacoin";
947 "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
950 "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
953 void LogException(std::exception* pex, const char* pszThread)
955 std::string message = FormatException(pex, pszThread);
956 printf("\n%s", message.c_str());
959 void PrintException(std::exception* pex, const char* pszThread)
961 std::string message = FormatException(pex, pszThread);
962 printf("\n\n************************\n%s\n", message.c_str());
963 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
964 strMiscWarning = message;
968 void LogStackTrace() {
969 printf("\n\n******* exception encountered *******\n");
972 #if !defined(WIN32) && !defined(ANDROID)
975 size = backtrace(pszBuffer, 32);
976 backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
981 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
983 std::string message = FormatException(pex, pszThread);
984 printf("\n\n************************\n%s\n", message.c_str());
985 fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
986 strMiscWarning = message;
989 boost::filesystem::path GetDefaultDataDir()
991 namespace fs = boost::filesystem;
992 // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
993 // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
994 // Mac: ~/Library/Application Support/NovaCoin
998 return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1001 char* pszHome = getenv("HOME");
1002 if (pszHome == NULL || strlen(pszHome) == 0)
1003 pathRet = fs::path("/");
1005 pathRet = fs::path(pszHome);
1008 pathRet /= "Library/Application Support";
1009 fs::create_directory(pathRet);
1010 return pathRet / "NovaCoin";
1013 return pathRet / ".novacoin";
1018 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1020 namespace fs = boost::filesystem;
1022 static fs::path pathCached[2];
1023 static CCriticalSection csPathCached;
1024 static bool cachedPath[2] = {false, false};
1026 fs::path &path = pathCached[fNetSpecific];
1028 // This can be called during exceptions by printf, so we cache the
1029 // value so we don't have to do memory allocations after that.
1030 if (cachedPath[fNetSpecific])
1035 if (mapArgs.count("-datadir")) {
1036 path = fs::system_complete(mapArgs["-datadir"]);
1037 if (!fs::is_directory(path)) {
1042 path = GetDefaultDataDir();
1044 if (fNetSpecific && GetBoolArg("-testnet", false))
1047 fs::create_directory(path);
1049 cachedPath[fNetSpecific]=true;
1053 string randomStrGen(int length) {
1054 static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
1056 result.resize(length);
1057 for (int32_t i = 0; i < length; i++)
1058 result[i] = charset[rand() % charset.length()];
1065 srand(static_cast<unsigned int>(time(NULL)));
1068 #if BOOST_FILESYSTEM_VERSION >= 3
1069 pConf.open(GetConfigFile().generic_string().c_str());
1071 pConf.open(GetConfigFile().string().c_str());
1073 pConf << "rpcuser=user\nrpcpassword="
1076 + "\n#(0=off, 1=on) daemon - run in the background as a daemon and accept commands"
1078 + "\n#(0=off, 1=on) server - accept command line and JSON-RPC commands"
1080 + "\nrpcallowip=127.0.0.1";
1084 boost::filesystem::path GetConfigFile()
1086 boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1087 if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1088 return pathConfigFile;
1091 void ReadConfigFile(map<string, string>& mapSettingsRet,
1092 map<string, vector<string> >& mapMultiSettingsRet)
1094 boost::filesystem::ifstream streamConfig(GetConfigFile());
1095 if (!streamConfig.good())
1098 new(&streamConfig) boost::filesystem::ifstream(GetConfigFile());
1099 if(!streamConfig.good())
1103 set<string> setOptions;
1104 setOptions.insert("*");
1106 for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1108 // Don't overwrite existing settings so command line settings override bitcoin.conf
1109 string strKey = string("-") + it->string_key;
1110 if (mapSettingsRet.count(strKey) == 0)
1112 mapSettingsRet[strKey] = it->value[0];
1113 // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1114 InterpretNegativeSetting(strKey, mapSettingsRet);
1116 mapMultiSettingsRet[strKey].push_back(it->value[0]);
1120 boost::filesystem::path GetPidFile()
1122 boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1123 if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1128 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1130 FILE* file = fopen(path.string().c_str(), "w");
1133 fprintf(file, "%d\n", pid);
1139 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1142 return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1143 MOVEFILE_REPLACE_EXISTING) != 0;
1145 int rc = std::rename(src.string().c_str(), dest.string().c_str());
1150 void FileCommit(FILE *fileout)
1152 fflush(fileout); // harmless if redundantly called
1154 _commit(_fileno(fileout));
1156 fsync(fileno(fileout));
1160 int GetFilesize(FILE* file)
1162 int nSavePos = ftell(file);
1164 if (fseek(file, 0, SEEK_END) == 0)
1165 nFilesize = ftell(file);
1166 fseek(file, nSavePos, SEEK_SET);
1170 void ShrinkDebugFile()
1172 // Scroll debug.log if it's getting too big
1173 boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1174 FILE* file = fopen(pathLog.string().c_str(), "r");
1175 if (file && GetFilesize(file) > 10 * 1000000)
1177 // Restart the file with some of the end
1179 vector<char>* vBuf = new vector <char>(200000, 0);
1180 fseek(file, -((long)(vBuf->size())), SEEK_END);
1181 size_t nBytes = fread(&vBuf->operator[](0), 1, vBuf->size(), file);
1183 file = fopen(pathLog.string().c_str(), "w");
1186 fwrite(&vBuf->operator[](0), 1, nBytes, file);
1191 catch (const bad_alloc& e) {
1192 // Bad things happen - no free memory in heap at program startup
1194 printf("Warning: %s in %s:%d\n ShrinkDebugFile failed - debug.log expands further", e.what(), __FILE__, __LINE__);
1205 int64_t now = time(NULL);
1210 string FormatVersion(int nVersion)
1212 if (nVersion%100 == 0)
1213 return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1215 return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1218 string FormatFullVersion()
1220 return CLIENT_BUILD;
1223 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1224 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1226 std::ostringstream ss;
1228 ss << name << ":" << FormatVersion(nClientVersion);
1229 if (!comments.empty())
1232 for (const auto& st : comments)
1235 if (st == comments.back()) break;
1245 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1247 namespace fs = boost::filesystem;
1249 char pszPath[MAX_PATH] = "";
1251 if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1253 return fs::path(pszPath);
1256 printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1257 return fs::path("");
1261 void runCommand(std::string strCommand)
1263 int nErr = ::system(strCommand.c_str());
1265 printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1268 void RenameThread(const char* name)
1270 #if defined(PR_SET_NAME)
1271 // Only the first 15 characters are used (16 - NUL terminator)
1272 ::prctl(PR_SET_NAME, name, 0, 0, 0);
1273 #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
1274 pthread_set_name_np(pthread_self(), name);
1275 #elif defined(__APPLE__)
1276 pthread_setname_np(name);
1278 // Prevent warnings for unused parameters...
1283 bool NewThread(void(*pfn)(void*), void* parg)
1287 boost::thread(pfn, parg); // thread detaches when out of scope
1288 } catch(boost::thread_resource_error &e) {
1289 printf("Error creating thread: %s\n", e.what());
1295 std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
1297 // std::locale takes ownership of the pointer
1298 std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
1299 std::stringstream ss;
1301 ss << boost::posix_time::from_time_t(nTime);