MSVC
[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
6 #include "util.h"
7 #include "sync.h"
8 #include "strlcpy.h"
9 #include "version.h"
10 #include "ui_interface.h"
11 #include <boost/algorithm/string/join.hpp>
12
13 // Work around clang compilation problem in Boost 1.46:
14 // /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
15 // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
16 //           http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
17 namespace boost {
18     namespace program_options {
19         std::string to_internal(const std::string&);
20     }
21 }
22
23 #include <boost/program_options/detail/config_file.hpp>
24 #include <boost/program_options/parsers.hpp>
25 #include <boost/filesystem.hpp>
26 #include <boost/filesystem/fstream.hpp>
27
28 #include <boost/date_time/posix_time/posix_time.hpp>
29 #include <boost/foreach.hpp>
30 #include <boost/thread.hpp>
31 #include <openssl/crypto.h>
32 #include <openssl/rand.h>
33 #include <stdarg.h>
34
35 #ifdef WIN32
36 #ifdef _MSC_VER
37 #pragma warning(disable:4786)
38 #pragma warning(disable:4804)
39 #pragma warning(disable:4805)
40 #pragma warning(disable:4717)
41 #endif
42 #ifdef _WIN32_WINNT
43 #undef _WIN32_WINNT
44 #endif
45 #define _WIN32_WINNT 0x0501
46 #ifdef _WIN32_IE
47 #undef _WIN32_IE
48 #endif
49 #define _WIN32_IE 0x0501
50 #define WIN32_LEAN_AND_MEAN 1
51 #ifndef NOMINMAX
52 #define NOMINMAX
53 #endif
54 #include <io.h> /* for _commit */
55 #include "shlobj.h"
56 #elif defined(__linux__)
57 # include <sys/prctl.h>
58 #endif
59
60 #ifndef WIN32
61 #include <execinfo.h>
62 #endif
63
64
65 using namespace std;
66 namespace bt = boost::posix_time;
67
68 map<string, string> mapArgs;
69 map<string, vector<string> > mapMultiArgs;
70 bool fDebug = false;
71 bool fDebugNet = false;
72 bool fPrintToConsole = false;
73 bool fPrintToDebugger = false;
74 bool fRequestShutdown = false;
75 bool fShutdown = false;
76 bool fDaemon = false;
77 bool fServer = false;
78 bool fCommandLine = false;
79 string strMiscWarning;
80 bool fTestNet = false;
81 bool fNoListen = false;
82 bool fLogTimestamps = false;
83 CMedianFilter<int64> vTimeOffsets(200,0);
84 bool fReopenDebugLog = false;
85
86 // Extended DecodeDumpTime implementation, see this page for details:
87 // http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
88 const std::locale formats[] = {
89     std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
90     std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
91     std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
92     std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
93     std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
94 };
95
96 const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
97
98 std::time_t pt_to_time_t(const bt::ptime& pt)
99 {
100     bt::ptime timet_start(boost::gregorian::date(1970,1,1));
101     bt::time_duration diff = pt - timet_start;
102     return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
103 }
104
105 // Init OpenSSL library multithreading support
106 static CCriticalSection** ppmutexOpenSSL;
107 void locking_callback(int mode, int i, const char* file, int line)
108 {
109     if (mode & CRYPTO_LOCK) {
110         ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
111     } else {
112         LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
113     }
114 }
115
116 LockedPageManager LockedPageManager::instance;
117
118 // Init
119 class CInit
120 {
121 public:
122     CInit()
123     {
124         // Init OpenSSL library multithreading support
125         ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
126         for (int i = 0; i < CRYPTO_num_locks(); i++)
127             ppmutexOpenSSL[i] = new CCriticalSection();
128         CRYPTO_set_locking_callback(locking_callback);
129
130 #ifdef WIN32
131         // Seed random number generator with screen scrape and other hardware sources
132         RAND_screen();
133 #endif
134
135         // Seed random number generator with performance counter
136         RandAddSeed();
137     }
138     ~CInit()
139     {
140         // Shutdown OpenSSL library multithreading support
141         CRYPTO_set_locking_callback(NULL);
142         for (int i = 0; i < CRYPTO_num_locks(); i++)
143             delete ppmutexOpenSSL[i];
144         OPENSSL_free(ppmutexOpenSSL);
145     }
146 }
147 instance_of_cinit;
148
149
150
151
152
153
154
155
156 void RandAddSeed()
157 {
158     // Seed with CPU performance counter
159     int64 nCounter = GetPerformanceCounter();
160     RAND_add(&nCounter, sizeof(nCounter), 1.5);
161     memset(&nCounter, 0, sizeof(nCounter));
162 }
163
164 void RandAddSeedPerfmon()
165 {
166     RandAddSeed();
167
168     // This can take up to 2 seconds, so only do it every 10 minutes
169     static int64 nLastPerfmon;
170     if (GetTime() < nLastPerfmon + 10 * 60)
171         return;
172     nLastPerfmon = GetTime();
173
174 #ifdef WIN32
175     // Don't need this on Linux, OpenSSL automatically uses /dev/urandom
176     // Seed with the entire set of perfmon data
177     unsigned char pdata[250000];
178     memset(pdata, 0, sizeof(pdata));
179     unsigned long nSize = sizeof(pdata);
180     long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
181     RegCloseKey(HKEY_PERFORMANCE_DATA);
182     if (ret == ERROR_SUCCESS)
183     {
184         RAND_add(pdata, nSize, nSize/100.0);
185         memset(pdata, 0, nSize);
186         printf("RandAddSeed() %lu bytes\n", nSize);
187     }
188 #endif
189 }
190
191 uint64 GetRand(uint64 nMax)
192 {
193     if (nMax == 0)
194         return 0;
195
196     // The range of the random source must be a multiple of the modulus
197     // to give every possible output value an equal possibility
198     uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax;
199     uint64 nRand = 0;
200     do
201         RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
202     while (nRand >= nRange);
203     return (nRand % nMax);
204 }
205
206 int GetRandInt(int nMax)
207 {
208     return GetRand(nMax);
209 }
210
211 uint256 GetRandHash()
212 {
213     uint256 hash;
214     RAND_bytes((unsigned char*)&hash, sizeof(hash));
215     return hash;
216 }
217
218
219
220
221
222
223 static FILE* fileout = NULL;
224
225 inline int OutputDebugStringF(const char* pszFormat, ...)
226 {
227     int ret = 0;
228     if (fPrintToConsole)
229     {
230         // print to console
231         va_list arg_ptr;
232         va_start(arg_ptr, pszFormat);
233         ret = vprintf(pszFormat, arg_ptr);
234         va_end(arg_ptr);
235     }
236     else if (!fPrintToDebugger)
237     {
238         // print to debug.log
239
240         if (!fileout)
241         {
242             boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
243             fileout = fopen(pathDebug.string().c_str(), "a");
244             if (fileout) setbuf(fileout, NULL); // unbuffered
245         }
246         if (fileout)
247         {
248             static bool fStartedNewLine = true;
249
250             // This routine may be called by global destructors during shutdown.
251             // Since the order of destruction of static/global objects is undefined,
252             // allocate mutexDebugLog on the heap the first time this routine
253             // is called to avoid crashes during shutdown.
254             static boost::mutex* mutexDebugLog = NULL;
255             if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
256             boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
257
258             // reopen the log file, if requested
259             if (fReopenDebugLog) {
260                 fReopenDebugLog = false;
261                 boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
262                 if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
263                     setbuf(fileout, NULL); // unbuffered
264             }
265
266             // Debug print useful for profiling
267             if (fLogTimestamps && fStartedNewLine)
268                 fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
269             if (pszFormat[strlen(pszFormat) - 1] == '\n')
270                 fStartedNewLine = true;
271             else
272                 fStartedNewLine = false;
273
274             va_list arg_ptr;
275             va_start(arg_ptr, pszFormat);
276             ret = vfprintf(fileout, pszFormat, arg_ptr);
277             va_end(arg_ptr);
278         }
279     }
280
281 #ifdef WIN32
282     if (fPrintToDebugger)
283     {
284         static CCriticalSection cs_OutputDebugStringF;
285
286         // accumulate and output a line at a time
287         {
288             LOCK(cs_OutputDebugStringF);
289             static std::string buffer;
290
291             va_list arg_ptr;
292             va_start(arg_ptr, pszFormat);
293             buffer += vstrprintf(pszFormat, arg_ptr);
294             va_end(arg_ptr);
295
296             int line_start = 0, line_end;
297             while((line_end = buffer.find('\n', line_start)) != -1)
298             {
299                 OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
300                 line_start = line_end + 1;
301             }
302             buffer.erase(0, line_start);
303         }
304     }
305 #endif
306     return ret;
307 }
308
309 string vstrprintf(const char *format, va_list ap)
310 {
311     char buffer[50000];
312     char* p = buffer;
313     int limit = sizeof(buffer);
314     int ret;
315     while (true)
316     {
317 #ifndef _MSC_VER
318         va_list arg_ptr;
319         va_copy(arg_ptr, ap);
320 #else
321         va_list arg_ptr = ap;
322 #endif;
323 #ifdef WIN32
324         ret = _vsnprintf(p, limit, format, arg_ptr);
325 #else
326         ret = vsnprintf(p, limit, format, arg_ptr);
327 #endif
328         va_end(arg_ptr);
329         if (ret >= 0 && ret < limit)
330             break;
331         if (p != buffer)
332             delete[] p;
333         limit *= 2;
334         p = new char[limit];
335         if (p == NULL)
336             throw std::bad_alloc();
337     }
338     string str(p, p+ret);
339     if (p != buffer)
340         delete[] p;
341     return str;
342 }
343
344 string real_strprintf(const char *format, int dummy, ...)
345 {
346     va_list arg_ptr;
347     va_start(arg_ptr, dummy);
348     string str = vstrprintf(format, arg_ptr);
349     va_end(arg_ptr);
350     return str;
351 }
352
353 string real_strprintf(const std::string &format, int dummy, ...)
354 {
355     va_list arg_ptr;
356     va_start(arg_ptr, dummy);
357     string str = vstrprintf(format.c_str(), arg_ptr);
358     va_end(arg_ptr);
359     return str;
360 }
361
362 bool error(const char *format, ...)
363 {
364     va_list arg_ptr;
365     va_start(arg_ptr, format);
366     std::string str = vstrprintf(format, arg_ptr);
367     va_end(arg_ptr);
368     printf("ERROR: %s\n", str.c_str());
369     return false;
370 }
371
372
373 void ParseString(const string& str, char c, vector<string>& v)
374 {
375     if (str.empty())
376         return;
377     string::size_type i1 = 0;
378     string::size_type i2;
379     while (true)
380     {
381         i2 = str.find(c, i1);
382         if (i2 == str.npos)
383         {
384             v.push_back(str.substr(i1));
385             return;
386         }
387         v.push_back(str.substr(i1, i2-i1));
388         i1 = i2+1;
389     }
390 }
391
392
393 string FormatMoney(int64 n, bool fPlus)
394 {
395     // Note: not using straight sprintf here because we do NOT want
396     // localized number formatting.
397     int64 n_abs = (n > 0 ? n : -n);
398     int64 quotient = n_abs/COIN;
399     int64 remainder = n_abs%COIN;
400     string str = strprintf("%"PRI64d".%06"PRI64d, quotient, remainder);
401
402     // Right-trim excess zeros before the decimal point:
403     int nTrim = 0;
404     for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
405         ++nTrim;
406     if (nTrim)
407         str.erase(str.size()-nTrim, nTrim);
408
409     if (n < 0)
410         str.insert((unsigned int)0, 1, '-');
411     else if (fPlus && n > 0)
412         str.insert((unsigned int)0, 1, '+');
413     return str;
414 }
415
416
417 bool ParseMoney(const string& str, int64& nRet)
418 {
419     return ParseMoney(str.c_str(), nRet);
420 }
421
422 bool ParseMoney(const char* pszIn, int64& nRet)
423 {
424     string strWhole;
425     int64 nUnits = 0;
426     const char* p = pszIn;
427     while (isspace(*p))
428         p++;
429     for (; *p; p++)
430     {
431         if (*p == '.')
432         {
433             p++;
434             int64 nMult = CENT*10;
435             while (isdigit(*p) && (nMult > 0))
436             {
437                 nUnits += nMult * (*p++ - '0');
438                 nMult /= 10;
439             }
440             break;
441         }
442         if (isspace(*p))
443             break;
444         if (!isdigit(*p))
445             return false;
446         strWhole.insert(strWhole.end(), *p);
447     }
448     for (; *p; p++)
449         if (!isspace(*p))
450             return false;
451     if (strWhole.size() > 10) // guard against 63 bit overflow
452         return false;
453     if (nUnits < 0 || nUnits > COIN)
454         return false;
455     int64 nWhole = atoi64(strWhole);
456     int64 nValue = nWhole*COIN + nUnits;
457
458     nRet = nValue;
459     return true;
460 }
461
462
463 static const signed char phexdigit[256] =
464 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
465   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
466   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
467   0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
468   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
469   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
470   -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
471   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
472   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
473   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
474   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
475   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
476   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
477   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
478   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
479   -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
480
481 bool IsHex(const string& str)
482 {
483     BOOST_FOREACH(unsigned char c, str)
484     {
485         if (phexdigit[c] < 0)
486             return false;
487     }
488     return (str.size() > 0) && (str.size()%2 == 0);
489 }
490
491 vector<unsigned char> ParseHex(const char* psz)
492 {
493     // convert hex dump to vector
494     vector<unsigned char> vch;
495     while (true)
496     {
497         while (isspace(*psz))
498             psz++;
499         signed char c = phexdigit[(unsigned char)*psz++];
500         if (c == (signed char)-1)
501             break;
502         unsigned char n = (c << 4);
503         c = phexdigit[(unsigned char)*psz++];
504         if (c == (signed char)-1)
505             break;
506         n |= c;
507         vch.push_back(n);
508     }
509     return vch;
510 }
511
512 vector<unsigned char> ParseHex(const string& str)
513 {
514     return ParseHex(str.c_str());
515 }
516
517 static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
518 {
519     // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
520     if (name.find("-no") == 0)
521     {
522         std::string positive("-");
523         positive.append(name.begin()+3, name.end());
524         if (mapSettingsRet.count(positive) == 0)
525         {
526             bool value = !GetBoolArg(name);
527             mapSettingsRet[positive] = (value ? "1" : "0");
528         }
529     }
530 }
531
532 void ParseParameters(int argc, const char* const argv[])
533 {
534     mapArgs.clear();
535     mapMultiArgs.clear();
536     for (int i = 1; i < argc; i++)
537     {
538         char psz[10000];
539         strlcpy(psz, argv[i], sizeof(psz));
540         char* pszValue = (char*)"";
541         if (strchr(psz, '='))
542         {
543             pszValue = strchr(psz, '=');
544             *pszValue++ = '\0';
545         }
546         #ifdef WIN32
547         _strlwr(psz);
548         if (psz[0] == '/')
549             psz[0] = '-';
550         #endif
551         if (psz[0] != '-')
552             break;
553
554         mapArgs[psz] = pszValue;
555         mapMultiArgs[psz].push_back(pszValue);
556     }
557
558     // New 0.6 features:
559     BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
560     {
561         string name = entry.first;
562
563         //  interpret --foo as -foo (as long as both are not set)
564         if (name.find("--") == 0)
565         {
566             std::string singleDash(name.begin()+1, name.end());
567             if (mapArgs.count(singleDash) == 0)
568                 mapArgs[singleDash] = entry.second;
569             name = singleDash;
570         }
571
572         // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
573         InterpretNegativeSetting(name, mapArgs);
574     }
575 }
576
577 std::string GetArg(const std::string& strArg, const std::string& strDefault)
578 {
579     if (mapArgs.count(strArg))
580         return mapArgs[strArg];
581     return strDefault;
582 }
583
584 int64 GetArg(const std::string& strArg, int64 nDefault)
585 {
586     if (mapArgs.count(strArg))
587         return atoi64(mapArgs[strArg]);
588     return nDefault;
589 }
590
591 bool GetBoolArg(const std::string& strArg, bool fDefault)
592 {
593     if (mapArgs.count(strArg))
594     {
595         if (mapArgs[strArg].empty())
596             return true;
597         return (atoi(mapArgs[strArg]) != 0);
598     }
599     return fDefault;
600 }
601
602 bool SoftSetArg(const std::string& strArg, const std::string& strValue)
603 {
604     if (mapArgs.count(strArg))
605         return false;
606     mapArgs[strArg] = strValue;
607     return true;
608 }
609
610 bool SoftSetBoolArg(const std::string& strArg, bool fValue)
611 {
612     if (fValue)
613         return SoftSetArg(strArg, std::string("1"));
614     else
615         return SoftSetArg(strArg, std::string("0"));
616 }
617
618
619 string EncodeBase64(const unsigned char* pch, size_t len)
620 {
621     static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
622
623     string strRet="";
624     strRet.reserve((len+2)/3*4);
625
626     int mode=0, left=0;
627     const unsigned char *pchEnd = pch+len;
628
629     while (pch<pchEnd)
630     {
631         int enc = *(pch++);
632         switch (mode)
633         {
634             case 0: // we have no bits
635                 strRet += pbase64[enc >> 2];
636                 left = (enc & 3) << 4;
637                 mode = 1;
638                 break;
639
640             case 1: // we have two bits
641                 strRet += pbase64[left | (enc >> 4)];
642                 left = (enc & 15) << 2;
643                 mode = 2;
644                 break;
645
646             case 2: // we have four bits
647                 strRet += pbase64[left | (enc >> 6)];
648                 strRet += pbase64[enc & 63];
649                 mode = 0;
650                 break;
651         }
652     }
653
654     if (mode)
655     {
656         strRet += pbase64[left];
657         strRet += '=';
658         if (mode == 1)
659             strRet += '=';
660     }
661
662     return strRet;
663 }
664
665 string EncodeBase64(const string& str)
666 {
667     return EncodeBase64((const unsigned char*)str.c_str(), str.size());
668 }
669
670 vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
671 {
672     static const int decode64_table[256] =
673     {
674         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
675         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
676         -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
677         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
678         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
679         29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
680         49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
681         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
682         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
683         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
684         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
685         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
686         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
687     };
688
689     if (pfInvalid)
690         *pfInvalid = false;
691
692     vector<unsigned char> vchRet;
693     vchRet.reserve(strlen(p)*3/4);
694
695     int mode = 0;
696     int left = 0;
697
698     while (1)
699     {
700          int dec = decode64_table[(unsigned char)*p];
701          if (dec == -1) break;
702          p++;
703          switch (mode)
704          {
705              case 0: // we have no bits and get 6
706                  left = dec;
707                  mode = 1;
708                  break;
709
710               case 1: // we have 6 bits and keep 4
711                   vchRet.push_back((left<<2) | (dec>>4));
712                   left = dec & 15;
713                   mode = 2;
714                   break;
715
716              case 2: // we have 4 bits and get 6, we keep 2
717                  vchRet.push_back((left<<4) | (dec>>2));
718                  left = dec & 3;
719                  mode = 3;
720                  break;
721
722              case 3: // we have 2 bits and get 6
723                  vchRet.push_back((left<<6) | dec);
724                  mode = 0;
725                  break;
726          }
727     }
728
729     if (pfInvalid)
730         switch (mode)
731         {
732             case 0: // 4n base64 characters processed: ok
733                 break;
734
735             case 1: // 4n+1 base64 character processed: impossible
736                 *pfInvalid = true;
737                 break;
738
739             case 2: // 4n+2 base64 characters processed: require '=='
740                 if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
741                     *pfInvalid = true;
742                 break;
743
744             case 3: // 4n+3 base64 characters processed: require '='
745                 if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
746                     *pfInvalid = true;
747                 break;
748         }
749
750     return vchRet;
751 }
752
753 string DecodeBase64(const string& str)
754 {
755     vector<unsigned char> vchRet = DecodeBase64(str.c_str());
756     return string((const char*)&vchRet[0], vchRet.size());
757 }
758
759 string EncodeBase32(const unsigned char* pch, size_t len)
760 {
761     static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
762
763     string strRet="";
764     strRet.reserve((len+4)/5*8);
765
766     int mode=0, left=0;
767     const unsigned char *pchEnd = pch+len;
768
769     while (pch<pchEnd)
770     {
771         int enc = *(pch++);
772         switch (mode)
773         {
774             case 0: // we have no bits
775                 strRet += pbase32[enc >> 3];
776                 left = (enc & 7) << 2;
777                 mode = 1;
778                 break;
779
780             case 1: // we have three bits
781                 strRet += pbase32[left | (enc >> 6)];
782                 strRet += pbase32[(enc >> 1) & 31];
783                 left = (enc & 1) << 4;
784                 mode = 2;
785                 break;
786
787             case 2: // we have one bit
788                 strRet += pbase32[left | (enc >> 4)];
789                 left = (enc & 15) << 1;
790                 mode = 3;
791                 break;
792
793             case 3: // we have four bits
794                 strRet += pbase32[left | (enc >> 7)];
795                 strRet += pbase32[(enc >> 2) & 31];
796                 left = (enc & 3) << 3;
797                 mode = 4;
798                 break;
799
800             case 4: // we have two bits
801                 strRet += pbase32[left | (enc >> 5)];
802                 strRet += pbase32[enc & 31];
803                 mode = 0;
804         }
805     }
806
807     static const int nPadding[5] = {0, 6, 4, 3, 1};
808     if (mode)
809     {
810         strRet += pbase32[left];
811         for (int n=0; n<nPadding[mode]; n++)
812              strRet += '=';
813     }
814
815     return strRet;
816 }
817
818 string EncodeBase32(const string& str)
819 {
820     return EncodeBase32((const unsigned char*)str.c_str(), str.size());
821 }
822
823 vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
824 {
825     static const int decode32_table[256] =
826     {
827         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
828         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
829         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
830         -1, -1, -1, -1, -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
831         15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1,  0,  1,  2,
832          3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
833         23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
834         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
835         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
836         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
837         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
838         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
839         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
840     };
841
842     if (pfInvalid)
843         *pfInvalid = false;
844
845     vector<unsigned char> vchRet;
846     vchRet.reserve((strlen(p))*5/8);
847
848     int mode = 0;
849     int left = 0;
850
851     while (1)
852     {
853          int dec = decode32_table[(unsigned char)*p];
854          if (dec == -1) break;
855          p++;
856          switch (mode)
857          {
858              case 0: // we have no bits and get 5
859                  left = dec;
860                  mode = 1;
861                  break;
862
863               case 1: // we have 5 bits and keep 2
864                   vchRet.push_back((left<<3) | (dec>>2));
865                   left = dec & 3;
866                   mode = 2;
867                   break;
868
869              case 2: // we have 2 bits and keep 7
870                  left = left << 5 | dec;
871                  mode = 3;
872                  break;
873
874              case 3: // we have 7 bits and keep 4
875                  vchRet.push_back((left<<1) | (dec>>4));
876                  left = dec & 15;
877                  mode = 4;
878                  break;
879
880              case 4: // we have 4 bits, and keep 1
881                  vchRet.push_back((left<<4) | (dec>>1));
882                  left = dec & 1;
883                  mode = 5;
884                  break;
885
886              case 5: // we have 1 bit, and keep 6
887                  left = left << 5 | dec;
888                  mode = 6;
889                  break;
890
891              case 6: // we have 6 bits, and keep 3
892                  vchRet.push_back((left<<2) | (dec>>3));
893                  left = dec & 7;
894                  mode = 7;
895                  break;
896
897              case 7: // we have 3 bits, and keep 0
898                  vchRet.push_back((left<<5) | dec);
899                  mode = 0;
900                  break;
901          }
902     }
903
904     if (pfInvalid)
905         switch (mode)
906         {
907             case 0: // 8n base32 characters processed: ok
908                 break;
909
910             case 1: // 8n+1 base32 characters processed: impossible
911             case 3: //   +3
912             case 6: //   +6
913                 *pfInvalid = true;
914                 break;
915
916             case 2: // 8n+2 base32 characters processed: require '======'
917                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
918                     *pfInvalid = true;
919                 break;
920
921             case 4: // 8n+4 base32 characters processed: require '===='
922                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
923                     *pfInvalid = true;
924                 break;
925
926             case 5: // 8n+5 base32 characters processed: require '==='
927                 if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
928                     *pfInvalid = true;
929                 break;
930
931             case 7: // 8n+7 base32 characters processed: require '='
932                 if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
933                     *pfInvalid = true;
934                 break;
935         }
936
937     return vchRet;
938 }
939
940 string DecodeBase32(const string& str)
941 {
942     vector<unsigned char> vchRet = DecodeBase32(str.c_str());
943     return string((const char*)&vchRet[0], vchRet.size());
944 }
945
946
947 int64 DecodeDumpTime(const std::string& s)
948 {
949     bt::ptime pt;
950
951     for(size_t i=0; i<formats_n; ++i)
952     {
953         std::istringstream is(s);
954         is.imbue(formats[i]);
955         is >> pt;
956         if(pt != bt::ptime()) break;
957     }
958
959     return pt_to_time_t(pt);
960 }
961
962 std::string EncodeDumpTime(int64 nTime) {
963     return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
964 }
965
966 std::string EncodeDumpString(const std::string &str) {
967     std::stringstream ret;
968     BOOST_FOREACH(unsigned char c, str) {
969         if (c <= 32 || c >= 128 || c == '%') {
970             ret << '%' << HexStr(&c, &c + 1);
971         } else {
972             ret << c;
973         }
974     }
975     return ret.str();
976 }
977
978 std::string DecodeDumpString(const std::string &str) {
979     std::stringstream ret;
980     for (unsigned int pos = 0; pos < str.length(); pos++) {
981         unsigned char c = str[pos];
982         if (c == '%' && pos+2 < str.length()) {
983             c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | 
984                 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
985             pos += 2;
986         }
987         ret << c;
988     }
989     return ret.str();
990 }
991
992 bool WildcardMatch(const char* psz, const char* mask)
993 {
994     while (true)
995     {
996         switch (*mask)
997         {
998         case '\0':
999             return (*psz == '\0');
1000         case '*':
1001             return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
1002         case '?':
1003             if (*psz == '\0')
1004                 return false;
1005             break;
1006         default:
1007             if (*psz != *mask)
1008                 return false;
1009             break;
1010         }
1011         psz++;
1012         mask++;
1013     }
1014 }
1015
1016 bool WildcardMatch(const string& str, const string& mask)
1017 {
1018     return WildcardMatch(str.c_str(), mask.c_str());
1019 }
1020
1021
1022
1023
1024
1025
1026
1027
1028 static std::string FormatException(std::exception* pex, const char* pszThread)
1029 {
1030 #ifdef WIN32
1031     char pszModule[MAX_PATH] = "";
1032     GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
1033 #else
1034     const char* pszModule = "novacoin";
1035 #endif
1036     if (pex)
1037         return strprintf(
1038             "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
1039     else
1040         return strprintf(
1041             "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
1042 }
1043
1044 void LogException(std::exception* pex, const char* pszThread)
1045 {
1046     std::string message = FormatException(pex, pszThread);
1047     printf("\n%s", message.c_str());
1048 }
1049
1050 void PrintException(std::exception* pex, const char* pszThread)
1051 {
1052     std::string message = FormatException(pex, pszThread);
1053     printf("\n\n************************\n%s\n", message.c_str());
1054     fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1055     strMiscWarning = message;
1056     throw;
1057 }
1058
1059 void LogStackTrace() {
1060     printf("\n\n******* exception encountered *******\n");
1061     if (fileout)
1062     {
1063 #ifndef WIN32
1064         void* pszBuffer[32];
1065         size_t size;
1066         size = backtrace(pszBuffer, 32);
1067         backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
1068 #endif
1069     }
1070 }
1071
1072 void PrintExceptionContinue(std::exception* pex, const char* pszThread)
1073 {
1074     std::string message = FormatException(pex, pszThread);
1075     printf("\n\n************************\n%s\n", message.c_str());
1076     fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
1077     strMiscWarning = message;
1078 }
1079
1080 boost::filesystem::path GetDefaultDataDir()
1081 {
1082     namespace fs = boost::filesystem;
1083     // Windows < Vista: C:\Documents and Settings\Username\Application Data\NovaCoin
1084     // Windows >= Vista: C:\Users\Username\AppData\Roaming\NovaCoin
1085     // Mac: ~/Library/Application Support/NovaCoin
1086     // Unix: ~/.novacoin
1087 #ifdef WIN32
1088     // Windows
1089     return GetSpecialFolderPath(CSIDL_APPDATA) / "NovaCoin";
1090 #else
1091     fs::path pathRet;
1092     char* pszHome = getenv("HOME");
1093     if (pszHome == NULL || strlen(pszHome) == 0)
1094         pathRet = fs::path("/");
1095     else
1096         pathRet = fs::path(pszHome);
1097 #ifdef MAC_OSX
1098     // Mac
1099     pathRet /= "Library/Application Support";
1100     fs::create_directory(pathRet);
1101     return pathRet / "NovaCoin";
1102 #else
1103     // Unix
1104     return pathRet / ".novacoin";
1105 #endif
1106 #endif
1107 }
1108
1109 const boost::filesystem::path &GetDataDir(bool fNetSpecific)
1110 {
1111     namespace fs = boost::filesystem;
1112
1113     static fs::path pathCached[2];
1114     static CCriticalSection csPathCached;
1115     static bool cachedPath[2] = {false, false};
1116
1117     fs::path &path = pathCached[fNetSpecific];
1118
1119     // This can be called during exceptions by printf, so we cache the
1120     // value so we don't have to do memory allocations after that.
1121     if (cachedPath[fNetSpecific])
1122         return path;
1123
1124     LOCK(csPathCached);
1125
1126     if (mapArgs.count("-datadir")) {
1127         path = fs::system_complete(mapArgs["-datadir"]);
1128         if (!fs::is_directory(path)) {
1129             path = "";
1130             return path;
1131         }
1132     } else {
1133         path = GetDefaultDataDir();
1134     }
1135     if (fNetSpecific && GetBoolArg("-testnet", false))
1136         path /= "testnet2";
1137
1138     fs::create_directory(path);
1139
1140     cachedPath[fNetSpecific]=true;
1141     return path;
1142 }
1143
1144 boost::filesystem::path GetConfigFile()
1145 {
1146     boost::filesystem::path pathConfigFile(GetArg("-conf", "novacoin.conf"));
1147     if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
1148     return pathConfigFile;
1149 }
1150
1151 void ReadConfigFile(map<string, string>& mapSettingsRet,
1152                     map<string, vector<string> >& mapMultiSettingsRet)
1153 {
1154     boost::filesystem::ifstream streamConfig(GetConfigFile());
1155     if (!streamConfig.good())
1156         return; // No bitcoin.conf file is OK
1157
1158     set<string> setOptions;
1159     setOptions.insert("*");
1160
1161     for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
1162     {
1163         // Don't overwrite existing settings so command line settings override bitcoin.conf
1164         string strKey = string("-") + it->string_key;
1165         if (mapSettingsRet.count(strKey) == 0)
1166         {
1167             mapSettingsRet[strKey] = it->value[0];
1168             // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
1169             InterpretNegativeSetting(strKey, mapSettingsRet);
1170         }
1171         mapMultiSettingsRet[strKey].push_back(it->value[0]);
1172     }
1173 }
1174
1175 boost::filesystem::path GetPidFile()
1176 {
1177     boost::filesystem::path pathPidFile(GetArg("-pid", "novacoind.pid"));
1178     if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
1179     return pathPidFile;
1180 }
1181
1182 #ifndef WIN32
1183 void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
1184 {
1185     FILE* file = fopen(path.string().c_str(), "w");
1186     if (file)
1187     {
1188         fprintf(file, "%d\n", pid);
1189         fclose(file);
1190     }
1191 }
1192 #endif
1193
1194 bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
1195 {
1196 #ifdef WIN32
1197     return MoveFileExA(src.string().c_str(), dest.string().c_str(),
1198                       MOVEFILE_REPLACE_EXISTING);
1199 #else
1200     int rc = std::rename(src.string().c_str(), dest.string().c_str());
1201     return (rc == 0);
1202 #endif /* WIN32 */
1203 }
1204
1205 void FileCommit(FILE *fileout)
1206 {
1207     fflush(fileout);                // harmless if redundantly called
1208 #ifdef WIN32
1209     _commit(_fileno(fileout));
1210 #else
1211     fsync(fileno(fileout));
1212 #endif
1213 }
1214
1215 int GetFilesize(FILE* file)
1216 {
1217     int nSavePos = ftell(file);
1218     int nFilesize = -1;
1219     if (fseek(file, 0, SEEK_END) == 0)
1220         nFilesize = ftell(file);
1221     fseek(file, nSavePos, SEEK_SET);
1222     return nFilesize;
1223 }
1224
1225 void ShrinkDebugFile()
1226 {
1227     // Scroll debug.log if it's getting too big
1228     boost::filesystem::path pathLog = GetDataDir() / "debug.log";
1229     FILE* file = fopen(pathLog.string().c_str(), "r");
1230     if (file && GetFilesize(file) > 10 * 1000000)
1231     {
1232         // Restart the file with some of the end
1233         char pch[200000];
1234         fseek(file, -sizeof(pch), SEEK_END);
1235         int nBytes = fread(pch, 1, sizeof(pch), file);
1236         fclose(file);
1237
1238         file = fopen(pathLog.string().c_str(), "w");
1239         if (file)
1240         {
1241             fwrite(pch, 1, nBytes, file);
1242             fclose(file);
1243         }
1244     }
1245 }
1246
1247
1248
1249
1250
1251
1252
1253
1254 //
1255 // "Never go to sea with two chronometers; take one or three."
1256 // Our three time sources are:
1257 //  - System clock
1258 //  - Median of other nodes clocks
1259 //  - The user (asking the user to fix the system clock if the first two disagree)
1260 //
1261 static int64 nMockTime = 0;  // For unit testing
1262
1263 int64 GetTime()
1264 {
1265     if (nMockTime) return nMockTime;
1266
1267     return time(NULL);
1268 }
1269
1270 void SetMockTime(int64 nMockTimeIn)
1271 {
1272     nMockTime = nMockTimeIn;
1273 }
1274
1275 static int64 nTimeOffset = 0;
1276
1277 int64 GetTimeOffset()
1278 {
1279     return nTimeOffset;
1280 }
1281
1282 int64 GetAdjustedTime()
1283 {
1284     return GetTime() + GetTimeOffset();
1285 }
1286
1287 void AddTimeData(const CNetAddr& ip, int64 nTime)
1288 {
1289     int64 nOffsetSample = nTime - GetTime();
1290
1291     // Ignore duplicates
1292     static set<CNetAddr> setKnown;
1293     if (!setKnown.insert(ip).second)
1294         return;
1295
1296     // Add data
1297     vTimeOffsets.input(nOffsetSample);
1298     printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
1299     if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
1300     {
1301         int64 nMedian = vTimeOffsets.median();
1302         std::vector<int64> vSorted = vTimeOffsets.sorted();
1303         // Only let other nodes change our time by so much
1304         if (abs64(nMedian) < 70 * 60)
1305         {
1306             nTimeOffset = nMedian;
1307         }
1308         else
1309         {
1310             nTimeOffset = 0;
1311
1312             static bool fDone;
1313             if (!fDone)
1314             {
1315                 // If nobody has a time different than ours but within 5 minutes of ours, give a warning
1316                 bool fMatch = false;
1317                 BOOST_FOREACH(int64 nOffset, vSorted)
1318                     if (nOffset != 0 && abs64(nOffset) < 5 * 60)
1319                         fMatch = true;
1320
1321                 if (!fMatch)
1322                 {
1323                     fDone = true;
1324                     string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong NovaCoin will not work properly.");
1325                     strMiscWarning = strMessage;
1326                     printf("*** %s\n", strMessage.c_str());
1327                     uiInterface.ThreadSafeMessageBox(strMessage+" ", string("NovaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
1328                 }
1329             }
1330         }
1331         if (fDebug) {
1332             BOOST_FOREACH(int64 n, vSorted)
1333                 printf("%+"PRI64d"  ", n);
1334             printf("|  ");
1335         }
1336         printf("nTimeOffset = %+"PRI64d"  (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
1337     }
1338 }
1339
1340
1341
1342
1343
1344
1345
1346
1347 string FormatVersion(int nVersion)
1348 {
1349     if (nVersion%100 == 0)
1350         return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
1351     else
1352         return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
1353 }
1354
1355 string FormatFullVersion()
1356 {
1357     return CLIENT_BUILD;
1358 }
1359
1360 // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
1361 std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
1362 {
1363     std::ostringstream ss;
1364     ss << "/";
1365     ss << name << ":" << FormatVersion(nClientVersion);
1366     if (!comments.empty())
1367         ss << "(" << boost::algorithm::join(comments, "; ") << ")";
1368     ss << "/";
1369     return ss.str();
1370 }
1371
1372 #ifdef WIN32
1373 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
1374 {
1375     namespace fs = boost::filesystem;
1376
1377     char pszPath[MAX_PATH] = "";
1378
1379     if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
1380     {
1381         return fs::path(pszPath);
1382     }
1383
1384     printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
1385     return fs::path("");
1386 }
1387 #endif
1388
1389 void runCommand(std::string strCommand)
1390 {
1391     int nErr = ::system(strCommand.c_str());
1392     if (nErr)
1393         printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
1394 }
1395
1396 void RenameThread(const char* name)
1397 {
1398 #if defined(PR_SET_NAME)
1399     // Only the first 15 characters are used (16 - NUL terminator)
1400     ::prctl(PR_SET_NAME, name, 0, 0, 0);
1401 #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
1402     // TODO: This is currently disabled because it needs to be verified to work
1403     //       on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
1404     //       removed.
1405     pthread_set_name_np(pthread_self(), name);
1406
1407 // This is XCode 10.6-and-later; bring back if we drop 10.5 support:
1408 // #elif defined(MAC_OSX)
1409 //    pthread_setname_np(name);
1410
1411 #else
1412     // Prevent warnings for unused parameters...
1413     (void)name;
1414 #endif
1415 }
1416
1417 bool NewThread(void(*pfn)(void*), void* parg)
1418 {
1419     try
1420     {
1421         boost::thread(pfn, parg); // thread detaches when out of scope
1422     } catch(boost::thread_resource_error &e) {
1423         printf("Error creating thread: %s\n", e.what());
1424         return false;
1425     }
1426     return true;
1427 }