fix warnings: array subscript is of type 'char' [-Wchar-subscripts]
[novacoin.git] / src / util.cpp
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 license.txt or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "headers.h"
7 #include "strlcpy.h"
8 #include <boost/algorithm/string/join.hpp>
9
10 // Work around clang compilation problem in Boost 1.46:
11 // /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
12 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
13 //           http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
14 namespace boost {
15     namespace program_options {
16         std::string to_internal(const std::string&);
17     }
18 }
19
20 #include <boost/program_options/detail/config_file.hpp>
21 #include <boost/program_options/parsers.hpp>
22 #include <boost/filesystem.hpp>
23 #include <boost/filesystem/fstream.hpp>
24 #include <boost/interprocess/sync/interprocess_mutex.hpp>
25 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
26 #include <boost/foreach.hpp>
27
28 using namespace std;
29 using namespace boost;
30
31 map<string, string> mapArgs;
32 map<string, vector<string> > mapMultiArgs;
33 bool fDebug = false;
34 bool fPrintToConsole = false;
35 bool fPrintToDebugger = false;
36 bool fRequestShutdown = false;
37 bool fShutdown = false;
38 bool fDaemon = false;
39 bool fServer = false;
40 bool fCommandLine = false;
41 string strMiscWarning;
42 bool fTestNet = false;
43 bool fNoListen = false;
44 bool fLogTimestamps = false;
45 CMedianFilter<int64> vTimeOffsets(200,0);
46
47 // Init openssl library multithreading support
48 static boost::interprocess::interprocess_mutex** ppmutexOpenSSL;
49 void locking_callback(int mode, int i, const char* file, int line)
50 {
51     if (mode & CRYPTO_LOCK)
52         ppmutexOpenSSL[i]->lock();
53     else
54         ppmutexOpenSSL[i]->unlock();
55 }
56
57 // Init
58 class CInit
59 {
60 public:
61     CInit()
62     {
63         // Init openssl library multithreading support
64         ppmutexOpenSSL = (boost::interprocess::interprocess_mutex**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(boost::interprocess::interprocess_mutex*));
65         for (int i = 0; i < CRYPTO_num_locks(); i++)
66             ppmutexOpenSSL[i] = new boost::interprocess::interprocess_mutex();
67         CRYPTO_set_locking_callback(locking_callback);
68
69 #ifdef WIN32
70         // Seed random number generator with screen scrape and other hardware sources
71         RAND_screen();
72 #endif
73
74         // Seed random number generator with performance counter
75         RandAddSeed();
76     }
77     ~CInit()
78     {
79         // Shutdown openssl library multithreading support
80         CRYPTO_set_locking_callback(NULL);
81         for (int i = 0; i < CRYPTO_num_locks(); i++)
82             delete ppmutexOpenSSL[i];
83         OPENSSL_free(ppmutexOpenSSL);
84     }
85 }
86 instance_of_cinit;
87
88
89
90
91
92
93
94
95 void RandAddSeed()
96 {
97     // Seed with CPU performance counter
98     int64 nCounter = GetPerformanceCounter();
99     RAND_add(&nCounter, sizeof(nCounter), 1.5);
100     memset(&nCounter, 0, sizeof(nCounter));
101 }
102
103 void RandAddSeedPerfmon()
104 {
105     RandAddSeed();
106
107     // This can take up to 2 seconds, so only do it every 10 minutes
108     static int64 nLastPerfmon;
109     if (GetTime() < nLastPerfmon + 10 * 60)
110         return;
111     nLastPerfmon = GetTime();
112
113 #ifdef WIN32
114     // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
115     // Seed with the entire set of perfmon data
116     unsigned char pdata[250000];
117     memset(pdata, 0, sizeof(pdata));
118     unsigned long nSize = sizeof(pdata);
119     long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
120     RegCloseKey(HKEY_PERFORMANCE_DATA);
121     if (ret == ERROR_SUCCESS)
122     {
123         RAND_add(pdata, nSize, nSize/100.0);
124         memset(pdata, 0, nSize);
125         printf("%s RandAddSeed() %d bytes\n", DateTimeStrFormat("%x %H:%M", GetTime()).c_str(), nSize);
126     }
127 #endif
128 }
129
130 uint64 GetRand(uint64 nMax)
131 {
132     if (nMax == 0)
133         return 0;
134
135     // The range of the random source must be a multiple of the modulus
136     // to give every possible output value an equal possibility
137     uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
138     uint64 nRand = 0;
139     do
140         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
141     while (nRand >= nRange);
142     return (nRand % nMax);
143 }
144
145 int GetRandInt(int nMax)
146 {
147     return GetRand(nMax);
148 }
149
150
151
152
153
154
155
156
157
158
159
160 inline int OutputDebugStringF(const char* pszFormat, ...)
161 {
162     int ret = 0;
163     if (fPrintToConsole)
164     {
165         // print to console
166         va_list arg_ptr;
167         va_start(arg_ptr, pszFormat);
168         ret = vprintf(pszFormat, arg_ptr);
169         va_end(arg_ptr);
170     }
171     else
172     {
173         // print to debug.log
174         static FILE* fileout = NULL;
175
176         if (!fileout)
177         {
178             boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
179             fileout = fopen(pathDebug.string().c_str(), "a");
180             if (fileout) setbuf(fileout, NULL); // unbuffered
181         }
182         if (fileout)
183         {
184             static bool fStartedNewLine = true;
185
186             // Debug print useful for profiling
187             if (fLogTimestamps && fStartedNewLine)
188                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
189             if (pszFormat[strlen(pszFormat) - 1] == '\n')
190                 fStartedNewLine = true;
191             else
192                 fStartedNewLine = false;
193
194             va_list arg_ptr;
195             va_start(arg_ptr, pszFormat);
196             ret = vfprintf(fileout, pszFormat, arg_ptr);
197             va_end(arg_ptr);
198         }
199     }
200
201 #ifdef WIN32
202     if (fPrintToDebugger)
203     {
204         static CCriticalSection cs_OutputDebugStringF;
205
206         // accumulate a line at a time
207         {
208             LOCK(cs_OutputDebugStringF);
209             static char pszBuffer[50000];
210             static char* pend;
211             if (pend == NULL)
212                 pend = pszBuffer;
213             va_list arg_ptr;
214             va_start(arg_ptr, pszFormat);
215             int limit = END(pszBuffer) - pend - 2;
216             int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
217             va_end(arg_ptr);
218             if (ret < 0 || ret >= limit)
219             {
220                 pend = END(pszBuffer) - 2;
221                 *pend++ = '\n';
222             }
223             else
224                 pend += ret;
225             *pend = '\0';
226             char* p1 = pszBuffer;
227             char* p2;
228             while (p2 = strchr(p1, '\n'))
229             {
230                 p2++;
231                 char c = *p2;
232                 *p2 = '\0';
233                 OutputDebugStringA(p1);
234                 *p2 = c;
235                 p1 = p2;
236             }
237             if (p1 != pszBuffer)
238                 memmove(pszBuffer, p1, pend - p1 + 1);
239             pend -= (p1 - pszBuffer);
240         }
241     }
242 #endif
243     return ret;
244 }
245
246
247 // Safer snprintf
248 //  - prints up to limit-1 characters
249 //  - output string is always null terminated even if limit reached
250 //  - return value is the number of characters actually printed
251 int my_snprintf(char* buffer, size_t limit, const char* format, ...)
252 {
253     if (limit == 0)
254         return 0;
255     va_list arg_ptr;
256     va_start(arg_ptr, format);
257     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
258     va_end(arg_ptr);
259     if (ret < 0 || ret >= limit)
260     {
261         ret = limit - 1;
262         buffer[limit-1] = 0;
263     }
264     return ret;
265 }
266
267 string real_strprintf(const std::string &format, int dummy, ...)
268 {
269     char buffer[50000];
270     char* p = buffer;
271     int limit = sizeof(buffer);
272     int ret;
273     loop
274     {
275         va_list arg_ptr;
276         va_start(arg_ptr, dummy);
277         ret = _vsnprintf(p, limit, format.c_str(), arg_ptr);
278         va_end(arg_ptr);
279         if (ret >= 0 && ret < limit)
280             break;
281         if (p != buffer)
282             delete[] p;
283         limit *= 2;
284         p = new char[limit];
285         if (p == NULL)
286             throw std::bad_alloc();
287     }
288     string str(p, p+ret);
289     if (p != buffer)
290         delete[] p;
291     return str;
292 }
293
294 bool error(const char *format, ...)
295 {
296     char buffer[50000];
297     int limit = sizeof(buffer);
298     va_list arg_ptr;
299     va_start(arg_ptr, format);
300     int ret = _vsnprintf(buffer, limit, format, arg_ptr);
301     va_end(arg_ptr);
302     if (ret < 0 || ret >= limit)
303     {
304         ret = limit - 1;
305         buffer[limit-1] = 0;
306     }
307     printf("ERROR: %s\n", buffer);
308     return false;
309 }
310
311
312 void ParseString(const string& str, char c, vector<string>& v)
313 {
314     if (str.empty())
315         return;
316     string::size_type i1 = 0;
317     string::size_type i2;
318     loop
319     {
320         i2 = str.find(c, i1);
321         if (i2 == str.npos)
322         {
323             v.push_back(str.substr(i1));
324             return;
325         }
326         v.push_back(str.substr(i1, i2-i1));
327         i1 = i2+1;
328     }
329 }
330
331
332 string FormatMoney(int64 n, bool fPlus)
333 {
334     // Note: not using straight sprintf here because we do NOT want
335     // localized number formatting.
336     int64 n_abs = (n > 0 ? n : -n);
337     int64 quotient = n_abs/COIN;
338     int64 remainder = n_abs%COIN;
339     string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
340
341     // Right-trim excess 0's before the decimal point:
342     int nTrim = 0;
343     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
344         ++nTrim;
345     if (nTrim)
346         str.erase(str.size()-nTrim, nTrim);
347
348     if (n < 0)
349         str.insert((unsigned int)0, 1, '-');
350     else if (fPlus && n > 0)
351         str.insert((unsigned int)0, 1, '+');
352     return str;
353 }
354
355
356 bool ParseMoney(const string& str, int64& nRet)
357 {
358     return ParseMoney(str.c_str(), nRet);
359 }
360
361 bool ParseMoney(const char* pszIn, int64& nRet)
362 {
363     string strWhole;
364     int64 nUnits = 0;
365     const char* p = pszIn;
366     while (isspace(*p))
367         p++;
368     for (; *p; p++)
369     {
370         if (*p == '.')
371         {
372             p++;
373             int64 nMult = CENT*10;
374             while (isdigit(*p) && (nMult > 0))
375             {
376                 nUnits += nMult * (*p++ - '0');
377                 nMult /= 10;
378             }
379             break;
380         }
381         if (isspace(*p))
382             break;
383         if (!isdigit(*p))
384             return false;
385         strWhole.insert(strWhole.end(), *p);
386     }
387     for (; *p; p++)
388         if (!isspace(*p))
389             return false;
390     if (strWhole.size() > 10) // guard against 63 bit overflow
391         return false;
392     if (nUnits < 0 || nUnits > COIN)
393         return false;
394     int64 nWhole = atoi64(strWhole);
395     int64 nValue = nWhole*COIN + nUnits;
396
397     nRet = nValue;
398     return true;
399 }
400
401
402 static char phexdigit[256] =
403 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
404   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
405   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
406   0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
407   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
408   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
409   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1
410   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
411   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
412   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
413   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
414   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
415   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
416   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
417   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
418   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
419
420 bool IsHex(const string& str)
421 {
422     BOOST_FOREACH(unsigned char c, str)
423     {
424         if (phexdigit[c] < 0)
425             return false;
426     }
427     return (str.size() > 0) && (str.size()%2 == 0);
428 }
429
430 vector<unsigned char> ParseHex(const char* psz)
431 {
432     // convert hex dump to vector
433     vector<unsigned char> vch;
434     loop
435     {
436         while (isspace(*psz))
437             psz++;
438         char c = phexdigit[(unsigned char)*psz++];
439         if (c == (char)-1)
440             break;
441         unsigned char n = (c << 4);
442         c = phexdigit[(unsigned char)*psz++];
443         if (c == (char)-1)
444             break;
445         n |= c;
446         vch.push_back(n);
447     }
448     return vch;
449 }
450
451 vector<unsigned char> ParseHex(const string& str)
452 {
453     return ParseHex(str.c_str());
454 }
455
456 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
457 {
458     // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
459     if (name.find("-no") == 0)
460     {
461         std::string positive("-");
462         positive.append(name.begin()+3, name.end());
463         if (mapSettingsRet.count(positive) == 0)
464         {
465             bool value = !GetBoolArg(name);
466             mapSettingsRet[positive] = (value ? "1" : "0");
467         }
468     }
469 }
470
471 void ParseParameters(int argc, const char*const argv[])
472 {
473     mapArgs.clear();
474     mapMultiArgs.clear();
475     for (int i = 1; i < argc; i++)
476     {
477         char psz[10000];
478         strlcpy(psz, argv[i], sizeof(psz));
479         char* pszValue = (char*)"";
480         if (strchr(psz, '='))
481         {
482             pszValue = strchr(psz, '=');
483             *pszValue++ = '\0';
484         }
485         #ifdef WIN32
486         _strlwr(psz);
487         if (psz[0] == '/')
488             psz[0] = '-';
489         #endif
490         if (psz[0] != '-')
491             break;
492
493         mapArgs[psz] = pszValue;
494         mapMultiArgs[psz].push_back(pszValue);
495     }
496
497     // New 0.6 features:
498     BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
499     {
500         string name = entry.first;
501
502         //  interpret --foo as -foo (as long as both are not set)
503         if (name.find("--") == 0)
504         {
505             std::string singleDash(name.begin()+1, name.end());
506             if (mapArgs.count(singleDash) == 0)
507                 mapArgs[singleDash] = entry.second;
508             name = singleDash;
509         }
510
511         // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
512         InterpretNegativeSetting(name, mapArgs);
513     }
514 }
515
516 std::string GetArg(const std::string& strArg, const std::string& strDefault)
517 {
518     if (mapArgs.count(strArg))
519         return mapArgs[strArg];
520     return strDefault;
521 }
522
523 int64 GetArg(const std::string& strArg, int64 nDefault)
524 {
525     if (mapArgs.count(strArg))
526         return atoi64(mapArgs[strArg]);
527     return nDefault;
528 }
529
530 bool GetBoolArg(const std::string& strArg, bool fDefault)
531 {
532     if (mapArgs.count(strArg))
533     {
534         if (mapArgs[strArg].empty())
535             return true;
536         return (atoi(mapArgs[strArg]) != 0);
537     }
538     return fDefault;
539 }
540
541 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
542 {
543     if (mapArgs.count(strArg))
544         return false;
545     mapArgs[strArg] = strValue;
546     return true;
547 }
548
549 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
550 {
551     if (fValue)
552         return SoftSetArg(strArg, std::string("1"));
553     else
554         return SoftSetArg(strArg, std::string("0"));
555 }
556
557
558 string EncodeBase64(const unsigned char* pch, size_t len)
559 {
560     static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
561
562     string strRet="";
563     strRet.reserve((len+2)/3*4);
564
565     int mode=0, left=0;
566     const unsigned char *pchEnd = pch+len;
567
568     while (pch<pchEnd)
569     {
570         int enc = *(pch++);
571         switch (mode)
572         {
573             case 0: // we have no bits
574                 strRet += pbase64[enc >> 2];
575                 left = (enc & 3) << 4;
576                 mode = 1;
577                 break;
578
579             case 1: // we have two bits
580                 strRet += pbase64[left | (enc >> 4)];
581                 left = (enc & 15) << 2;
582                 mode = 2;
583                 break;
584
585             case 2: // we have four bits
586                 strRet += pbase64[left | (enc >> 6)];
587                 strRet += pbase64[enc & 63];
588                 mode = 0;
589                 break;
590         }
591     }
592
593     if (mode)
594     {
595         strRet += pbase64[left];
596         strRet += '=';
597         if (mode == 1)
598             strRet += '=';
599     }
600
601     return strRet;
602 }
603
604 string EncodeBase64(const string& str)
605 {
606     return EncodeBase64((const unsigned char*)str.c_str(), str.size());
607 }
608
609 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
610 {
611     static const int decode64_table[256] =
612     {
613         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
614         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
615         -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
616         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
617         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
618         29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
619         49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
620         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
621         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
622         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
623         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
624         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
625         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
626     };
627
628     if (pfInvalid)
629         *pfInvalid = false;
630
631     vector<unsigned char> vchRet;
632     vchRet.reserve(strlen(p)*3/4);
633
634     int mode = 0;
635     int left = 0;
636
637     while (1)
638     {
639          int dec = decode64_table[(unsigned char)*p];
640          if (dec == -1) break;
641          p++;
642          switch (mode)
643          {
644              case 0: // we have no bits and get 6
645                  left = dec;
646                  mode = 1;
647                  break;
648
649               case 1: // we have 6 bits and keep 4
650                   vchRet.push_back((left<<2) | (dec>>4));
651                   left = dec & 15;
652                   mode = 2;
653                   break;
654
655              case 2: // we have 4 bits and get 6, we keep 2
656                  vchRet.push_back((left<<4) | (dec>>2));
657                  left = dec & 3;
658                  mode = 3;
659                  break;
660
661              case 3: // we have 2 bits and get 6
662                  vchRet.push_back((left<<6) | dec);
663                  mode = 0;
664                  break;
665          }
666     }
667
668     if (pfInvalid)
669         switch (mode)
670         {
671             case 0: // 4n base64 characters processed: ok
672                 break;
673
674             case 1: // 4n+1 base64 character processed: impossible
675                 *pfInvalid = true;
676                 break;
677
678             case 2: // 4n+2 base64 characters processed: require '=='
679                 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
680                     *pfInvalid = true;
681                 break;
682
683             case 3: // 4n+3 base64 characters processed: require '='
684                 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
685                     *pfInvalid = true;
686                 break;
687         }
688
689     return vchRet;
690 }
691
692 string DecodeBase64(const string& str)
693 {
694     vector<unsigned char> vchRet = DecodeBase64(str.c_str());
695     return string((const char*)&vchRet[0], vchRet.size());
696 }
697
698
699 bool WildcardMatch(const char* psz, const char* mask)
700 {
701     loop
702     {
703         switch (*mask)
704         {
705         case '\0':
706             return (*psz == '\0');
707         case '*':
708             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
709         case '?':
710             if (*psz == '\0')
711                 return false;
712             break;
713         default:
714             if (*psz != *mask)
715                 return false;
716             break;
717         }
718         psz++;
719         mask++;
720     }
721 }
722
723 bool WildcardMatch(const string& str, const string& mask)
724 {
725     return WildcardMatch(str.c_str(), mask.c_str());
726 }
727
728
729
730
731
732
733
734
735 void FormatException(char* pszMessage, std::exception* pex, const char* pszThread)
736 {
737 #ifdef WIN32
738     char pszModule[MAX_PATH];
739     pszModule[0] = '\0';
740     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
741 #else
742     const char* pszModule = "bitcoin";
743 #endif
744     if (pex)
745         snprintf(pszMessage, 1000,
746             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
747     else
748         snprintf(pszMessage, 1000,
749             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
750 }
751
752 void LogException(std::exception* pex, const char* pszThread)
753 {
754     char pszMessage[10000];
755     FormatException(pszMessage, pex, pszThread);
756     printf("\n%s", pszMessage);
757 }
758
759 void PrintException(std::exception* pex, const char* pszThread)
760 {
761     char pszMessage[10000];
762     FormatException(pszMessage, pex, pszThread);
763     printf("\n\n************************\n%s\n", pszMessage);
764     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
765     strMiscWarning = pszMessage;
766     throw;
767 }
768
769 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
770 {
771     char pszMessage[10000];
772     FormatException(pszMessage, pex, pszThread);
773     printf("\n\n************************\n%s\n", pszMessage);
774     fprintf(stderr, "\n\n************************\n%s\n", pszMessage);
775     strMiscWarning = pszMessage;
776 }
777
778 #ifdef WIN32
779 boost::filesystem::path MyGetSpecialFolderPath(int nFolder, bool fCreate)
780 {
781     namespace fs = boost::filesystem;
782
783     char pszPath[MAX_PATH] = "";
784     if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
785     {
786         return fs::path(pszPath);
787     }
788     else if (nFolder == CSIDL_STARTUP)
789     {
790         return fs::path(getenv("USERPROFILE")) / "Start Menu" / "Programs" / "Startup";
791     }
792     else if (nFolder == CSIDL_APPDATA)
793     {
794         return fs::path(getenv("APPDATA"));
795     }
796     return fs::path("");
797 }
798 #endif
799
800 boost::filesystem::path GetDefaultDataDir()
801 {
802     namespace fs = boost::filesystem;
803
804     // Windows: C:\Documents and Settings\username\Application Data\Bitcoin
805     // Mac: ~/Library/Application Support/Bitcoin
806     // Unix: ~/.bitcoin
807 #ifdef WIN32
808     // Windows
809     return MyGetSpecialFolderPath(CSIDL_APPDATA, true) / "Bitcoin";
810 #else
811     fs::path pathRet;
812     char* pszHome = getenv("HOME");
813     if (pszHome == NULL || strlen(pszHome) == 0)
814         pathRet = fs::path("/");
815     else
816         pathRet = fs::path(pszHome);
817 #ifdef MAC_OSX
818     // Mac
819     pathRet /= "Library/Application Support";
820     filesystem::create_directory(pathRet);
821     return pathRet / "Bitcoin";
822 #else
823     // Unix
824     return pathRet / ".bitcoin";
825 #endif
826 #endif
827 }
828
829 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
830 {
831     namespace fs = boost::filesystem;
832
833     static fs::path pathCached[2];
834     static CCriticalSection csPathCached;
835     static bool cachedPath[2] = {false, false};
836
837     fs::path &path = pathCached[fNetSpecific];
838
839     // This can be called during exceptions by printf, so we cache the
840     // value so we don't have to do memory allocations after that.
841     if (cachedPath[fNetSpecific])
842         return path;
843
844     LOCK(csPathCached);
845
846     if (mapArgs.count("-datadir")) {
847         path = mapArgs["-datadir"];
848     } else {
849         path = GetDefaultDataDir();
850     }
851     if (fNetSpecific && GetBoolArg("-testnet", false))
852         path /= "testnet";
853
854     fs::create_directory(path);
855
856     cachedPath[fNetSpecific]=true;
857     return path;
858 }
859
860 boost::filesystem::path GetConfigFile()
861 {
862     namespace fs = boost::filesystem;
863
864     fs::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
865     if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
866     return pathConfigFile;
867 }
868
869 bool ReadConfigFile(map<string, string>& mapSettingsRet,
870                     map<string, vector<string> >& mapMultiSettingsRet)
871 {
872     namespace fs = boost::filesystem;
873     namespace pod = boost::program_options::detail;
874
875     fs::ifstream streamConfig(GetConfigFile());
876     if (!streamConfig.good())
877         return true; // No bitcoin.conf file is OK
878
879     set<string> setOptions;
880     setOptions.insert("*");
881
882     for (pod::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
883     {
884         // Don't overwrite existing settings so command line settings override bitcoin.conf
885         string strKey = string("-") + it->string_key;
886         if (mapSettingsRet.count(strKey) == 0)
887         {
888             mapSettingsRet[strKey] = it->value[0];
889             //  interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
890             InterpretNegativeSetting(strKey, mapSettingsRet);
891         }
892         mapMultiSettingsRet[strKey].push_back(it->value[0]);
893     }
894     return true;
895 }
896
897 boost::filesystem::path GetPidFile()
898 {
899     namespace fs = boost::filesystem;
900
901     fs::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
902     if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
903     return pathPidFile;
904 }
905
906 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
907 {
908     FILE* file = fopen(path.string().c_str(), "w");
909     if (file)
910     {
911         fprintf(file, "%d\n", pid);
912         fclose(file);
913     }
914 }
915
916 int GetFilesize(FILE* file)
917 {
918     int nSavePos = ftell(file);
919     int nFilesize = -1;
920     if (fseek(file, 0, SEEK_END) == 0)
921         nFilesize = ftell(file);
922     fseek(file, nSavePos, SEEK_SET);
923     return nFilesize;
924 }
925
926 void ShrinkDebugFile()
927 {
928     // Scroll debug.log if it's getting too big
929     boost::filesystem::path pathLog = GetDataDir() / "debug.log";
930     FILE* file = fopen(pathLog.string().c_str(), "r");
931     if (file && GetFilesize(file) > 10 * 1000000)
932     {
933         // Restart the file with some of the end
934         char pch[200000];
935         fseek(file, -sizeof(pch), SEEK_END);
936         int nBytes = fread(pch, 1, sizeof(pch), file);
937         fclose(file);
938
939         file = fopen(pathLog.string().c_str(), "w");
940         if (file)
941         {
942             fwrite(pch, 1, nBytes, file);
943             fclose(file);
944         }
945     }
946 }
947
948
949
950
951
952
953
954
955 //
956 // "Never go to sea with two chronometers; take one or three."
957 // Our three time sources are:
958 //  - System clock
959 //  - Median of other nodes's clocks
960 //  - The user (asking the user to fix the system clock if the first two disagree)
961 //
962 static int64 nMockTime = 0;  // For unit testing
963
964 int64 GetTime()
965 {
966     if (nMockTime) return nMockTime;
967
968     return time(NULL);
969 }
970
971 void SetMockTime(int64 nMockTimeIn)
972 {
973     nMockTime = nMockTimeIn;
974 }
975
976 static int64 nTimeOffset = 0;
977
978 int64 GetAdjustedTime()
979 {
980     return GetTime() + nTimeOffset;
981 }
982
983 void AddTimeData(const CNetAddr& ip, int64 nTime)
984 {
985     int64 nOffsetSample = nTime - GetTime();
986
987     // Ignore duplicates
988     static set<CNetAddr> setKnown;
989     if (!setKnown.insert(ip).second)
990         return;
991
992     // Add data
993     vTimeOffsets.input(nOffsetSample);
994     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
995     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
996     {
997         int64 nMedian = vTimeOffsets.median();
998         std::vector<int64> vSorted = vTimeOffsets.sorted();
999         // Only let other nodes change our time by so much
1000         if (abs64(nMedian) < 70 * 60)
1001         {
1002             nTimeOffset = nMedian;
1003         }
1004         else
1005         {
1006             nTimeOffset = 0;
1007
1008             static bool fDone;
1009             if (!fDone)
1010             {
1011                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1012                 bool fMatch = false;
1013                 BOOST_FOREACH(int64 nOffset, vSorted)
1014                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1015                         fMatch = true;
1016
1017                 if (!fMatch)
1018                 {
1019                     fDone = true;
1020                     string strMessage = _("Warning: Please check that your computer's date and time are correct.  If your clock is wrong Bitcoin will not work properly.");
1021                     strMiscWarning = strMessage;
1022                     printf("*** %s\n", strMessage.c_str());
1023                     ThreadSafeMessageBox(strMessage+" ", string("Bitcoin"), wxOK | wxICON_EXCLAMATION);
1024                 }
1025             }
1026         }
1027         if (fDebug) {
1028             BOOST_FOREACH(int64 n, vSorted)
1029                 printf("%+"PRI64d"  ", n);
1030             printf("|  ");
1031         }
1032         printf("nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1033     }
1034 }
1035
1036
1037
1038
1039
1040
1041
1042
1043 string FormatVersion(int nVersion)
1044 {
1045     if (nVersion%100 == 0)
1046         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1047     else
1048         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1049 }
1050
1051 string FormatFullVersion()
1052 {
1053     return CLIENT_BUILD;
1054 }
1055
1056 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1057 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1058 {
1059     std::ostringstream ss;
1060     ss << "/";
1061     ss << name << ":" << FormatVersion(nClientVersion);
1062     if (!comments.empty())
1063         ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1064     ss << "/";
1065     return ss.str();
1066 }
1067
1068
1069
1070 #ifdef DEBUG_LOCKORDER
1071 //
1072 // Early deadlock detection.
1073 // Problem being solved:
1074 //    Thread 1 locks  A, then B, then C
1075 //    Thread 2 locks  D, then C, then A
1076 //     --> may result in deadlock between the two threads, depending on when they run.
1077 // Solution implemented here:
1078 // Keep track of pairs of locks: (A before B), (A before C), etc.
1079 // Complain if any thread trys to lock in a different order.
1080 //
1081
1082 struct CLockLocation
1083 {
1084     CLockLocation(const char* pszName, const char* pszFile, int nLine)
1085     {
1086         mutexName = pszName;
1087         sourceFile = pszFile;
1088         sourceLine = nLine;
1089     }
1090
1091     std::string ToString() const
1092     {
1093         return mutexName+"  "+sourceFile+":"+itostr(sourceLine);
1094     }
1095
1096 private:
1097     std::string mutexName;
1098     std::string sourceFile;
1099     int sourceLine;
1100 };
1101
1102 typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
1103
1104 static boost::interprocess::interprocess_mutex dd_mutex;
1105 static std::map<std::pair<void*, void*>, LockStack> lockorders;
1106 static boost::thread_specific_ptr<LockStack> lockstack;
1107
1108
1109 static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
1110 {
1111     printf("POTENTIAL DEADLOCK DETECTED\n");
1112     printf("Previous lock order was:\n");
1113     BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
1114     {
1115         if (i.first == mismatch.first) printf(" (1)");
1116         if (i.first == mismatch.second) printf(" (2)");
1117         printf(" %s\n", i.second.ToString().c_str());
1118     }
1119     printf("Current lock order is:\n");
1120     BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
1121     {
1122         if (i.first == mismatch.first) printf(" (1)");
1123         if (i.first == mismatch.second) printf(" (2)");
1124         printf(" %s\n", i.second.ToString().c_str());
1125     }
1126 }
1127
1128 static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
1129 {
1130     bool fOrderOK = true;
1131     if (lockstack.get() == NULL)
1132         lockstack.reset(new LockStack);
1133
1134     if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
1135     dd_mutex.lock();
1136
1137     (*lockstack).push_back(std::make_pair(c, locklocation));
1138
1139     if (!fTry) BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack))
1140     {
1141         if (i.first == c) break;
1142
1143         std::pair<void*, void*> p1 = std::make_pair(i.first, c);
1144         if (lockorders.count(p1))
1145             continue;
1146         lockorders[p1] = (*lockstack);
1147
1148         std::pair<void*, void*> p2 = std::make_pair(c, i.first);
1149         if (lockorders.count(p2))
1150         {
1151             potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
1152             break;
1153         }
1154     }
1155     dd_mutex.unlock();
1156 }
1157
1158 static void pop_lock()
1159 {
1160     if (fDebug) 
1161     {
1162         const CLockLocation& locklocation = (*lockstack).rbegin()->second;
1163         printf("Unlocked: %s\n", locklocation.ToString().c_str());
1164     }
1165     dd_mutex.lock();
1166     (*lockstack).pop_back();
1167     dd_mutex.unlock();
1168 }
1169
1170 void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
1171 {
1172     push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
1173 }
1174
1175 void LeaveCritical()
1176 {
1177     pop_lock();
1178 }
1179
1180 #endif /* DEBUG_LOCKORDER */