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