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