You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.cpp 37KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2014 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. #if defined(HAVE_CONFIG_H)
  6. #include "config/bitcoin-config.h"
  7. #endif
  8. #include "util.h"
  9. #include "chainparamsbase.h"
  10. #include "random.h"
  11. #include "sync.h"
  12. #include "uint256.h"
  13. #include <stdarg.h>
  14. #include <boost/date_time/posix_time/posix_time.hpp>
  15. #ifndef WIN32
  16. // for posix_fallocate
  17. #ifdef __linux__
  18. #ifdef _POSIX_C_SOURCE
  19. #undef _POSIX_C_SOURCE
  20. #endif
  21. #define _POSIX_C_SOURCE 200112L
  22. #endif // __linux__
  23. #include <algorithm>
  24. #include <fcntl.h>
  25. #include <sys/resource.h>
  26. #include <sys/stat.h>
  27. #else
  28. #ifdef _MSC_VER
  29. #pragma warning(disable:4786)
  30. #pragma warning(disable:4804)
  31. #pragma warning(disable:4805)
  32. #pragma warning(disable:4717)
  33. #endif
  34. #ifdef _WIN32_WINNT
  35. #undef _WIN32_WINNT
  36. #endif
  37. #define _WIN32_WINNT 0x0501
  38. #ifdef _WIN32_IE
  39. #undef _WIN32_IE
  40. #endif
  41. #define _WIN32_IE 0x0501
  42. #define WIN32_LEAN_AND_MEAN 1
  43. #ifndef NOMINMAX
  44. #define NOMINMAX
  45. #endif
  46. #include <io.h> /* for _commit */
  47. #include <shlobj.h>
  48. #endif
  49. #ifdef HAVE_SYS_PRCTL_H
  50. #include <sys/prctl.h>
  51. #endif
  52. #include <boost/algorithm/string/case_conv.hpp> // for to_lower()
  53. #include <boost/algorithm/string/join.hpp>
  54. #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
  55. #include <boost/filesystem.hpp>
  56. #include <boost/filesystem/fstream.hpp>
  57. #include <boost/foreach.hpp>
  58. #include <boost/program_options/detail/config_file.hpp>
  59. #include <boost/program_options/parsers.hpp>
  60. #include <openssl/crypto.h>
  61. #include <openssl/rand.h>
  62. // Work around clang compilation problem in Boost 1.46:
  63. // /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
  64. // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
  65. // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
  66. namespace boost {
  67. namespace program_options {
  68. std::string to_internal(const std::string&);
  69. }
  70. } // namespace boost
  71. using namespace std;
  72. map<string, string> mapArgs;
  73. map<string, vector<string> > mapMultiArgs;
  74. bool fDebug = false;
  75. bool fPrintToConsole = false;
  76. bool fPrintToDebugLog = true;
  77. bool fDaemon = false;
  78. bool fServer = false;
  79. string strMiscWarning;
  80. bool fLogTimestamps = false;
  81. bool fLogIPs = false;
  82. volatile bool fReopenDebugLog = false;
  83. // Init OpenSSL library multithreading support
  84. static CCriticalSection** ppmutexOpenSSL;
  85. void locking_callback(int mode, int i, const char* file, int line)
  86. {
  87. if (mode & CRYPTO_LOCK) {
  88. ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
  89. } else {
  90. LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
  91. }
  92. }
  93. // Init
  94. class CInit
  95. {
  96. public:
  97. CInit()
  98. {
  99. // Init OpenSSL library multithreading support
  100. ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
  101. for (int i = 0; i < CRYPTO_num_locks(); i++)
  102. ppmutexOpenSSL[i] = new CCriticalSection();
  103. CRYPTO_set_locking_callback(locking_callback);
  104. #ifdef WIN32
  105. // Seed OpenSSL PRNG with current contents of the screen
  106. RAND_screen();
  107. #endif
  108. // Seed OpenSSL PRNG with performance counter
  109. RandAddSeed();
  110. }
  111. ~CInit()
  112. {
  113. // Securely erase the memory used by the PRNG
  114. RAND_cleanup();
  115. // Shutdown OpenSSL library multithreading support
  116. CRYPTO_set_locking_callback(NULL);
  117. for (int i = 0; i < CRYPTO_num_locks(); i++)
  118. delete ppmutexOpenSSL[i];
  119. OPENSSL_free(ppmutexOpenSSL);
  120. }
  121. }
  122. instance_of_cinit;
  123. // LogPrintf() has been broken a couple of times now
  124. // by well-meaning people adding mutexes in the most straightforward way.
  125. // It breaks because it may be called by global destructors during shutdown.
  126. // Since the order of destruction of static/global objects is undefined,
  127. // defining a mutex as a global object doesn't work (the mutex gets
  128. // destroyed, and then some later destructor calls OutputDebugStringF,
  129. // maybe indirectly, and you get a core dump at shutdown trying to lock
  130. // the mutex).
  131. static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
  132. // We use boost::call_once() to make sure these are initialized in
  133. // in a thread-safe manner the first time it is called:
  134. static FILE* fileout = NULL;
  135. static boost::mutex* mutexDebugLog = NULL;
  136. static void DebugPrintInit()
  137. {
  138. assert(fileout == NULL);
  139. assert(mutexDebugLog == NULL);
  140. boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
  141. fileout = fopen(pathDebug.string().c_str(), "a");
  142. if (fileout) setbuf(fileout, NULL); // unbuffered
  143. mutexDebugLog = new boost::mutex();
  144. }
  145. bool LogAcceptCategory(const char* category)
  146. {
  147. if (category != NULL)
  148. {
  149. if (!fDebug)
  150. return false;
  151. // Give each thread quick access to -debug settings.
  152. // This helps prevent issues debugging global destructors,
  153. // where mapMultiArgs might be deleted before another
  154. // global destructor calls LogPrint()
  155. static boost::thread_specific_ptr<set<string> > ptrCategory;
  156. if (ptrCategory.get() == NULL)
  157. {
  158. const vector<string>& categories = mapMultiArgs["-debug"];
  159. ptrCategory.reset(new set<string>(categories.begin(), categories.end()));
  160. // thread_specific_ptr automatically deletes the set when the thread ends.
  161. }
  162. const set<string>& setCategories = *ptrCategory.get();
  163. // if not debugging everything and not debugging specific category, LogPrint does nothing.
  164. if (setCategories.count(string("")) == 0 &&
  165. setCategories.count(string(category)) == 0)
  166. return false;
  167. }
  168. return true;
  169. }
  170. int LogPrintStr(const std::string &str)
  171. {
  172. int ret = 0; // Returns total number of characters written
  173. if (fPrintToConsole)
  174. {
  175. // print to console
  176. ret = fwrite(str.data(), 1, str.size(), stdout);
  177. }
  178. else if (fPrintToDebugLog && AreBaseParamsConfigured())
  179. {
  180. static bool fStartedNewLine = true;
  181. boost::call_once(&DebugPrintInit, debugPrintInitFlag);
  182. if (fileout == NULL)
  183. return ret;
  184. boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
  185. // reopen the log file, if requested
  186. if (fReopenDebugLog) {
  187. fReopenDebugLog = false;
  188. boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
  189. if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
  190. setbuf(fileout, NULL); // unbuffered
  191. }
  192. // Debug print useful for profiling
  193. if (fLogTimestamps && fStartedNewLine)
  194. ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
  195. if (!str.empty() && str[str.size()-1] == '\n')
  196. fStartedNewLine = true;
  197. else
  198. fStartedNewLine = false;
  199. ret = fwrite(str.data(), 1, str.size(), fileout);
  200. }
  201. return ret;
  202. }
  203. string FormatMoney(int64_t n, bool fPlus)
  204. {
  205. // Note: not using straight sprintf here because we do NOT want
  206. // localized number formatting.
  207. int64_t n_abs = (n > 0 ? n : -n);
  208. int64_t quotient = n_abs/COIN;
  209. int64_t remainder = n_abs%COIN;
  210. string str = strprintf("%d.%08d", quotient, remainder);
  211. // Right-trim excess zeros before the decimal point:
  212. int nTrim = 0;
  213. for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
  214. ++nTrim;
  215. if (nTrim)
  216. str.erase(str.size()-nTrim, nTrim);
  217. if (n < 0)
  218. str.insert((unsigned int)0, 1, '-');
  219. else if (fPlus && n > 0)
  220. str.insert((unsigned int)0, 1, '+');
  221. return str;
  222. }
  223. bool ParseMoney(const string& str, int64_t& nRet)
  224. {
  225. return ParseMoney(str.c_str(), nRet);
  226. }
  227. bool ParseMoney(const char* pszIn, int64_t& nRet)
  228. {
  229. string strWhole;
  230. int64_t nUnits = 0;
  231. const char* p = pszIn;
  232. while (isspace(*p))
  233. p++;
  234. for (; *p; p++)
  235. {
  236. if (*p == '.')
  237. {
  238. p++;
  239. int64_t nMult = CENT*10;
  240. while (isdigit(*p) && (nMult > 0))
  241. {
  242. nUnits += nMult * (*p++ - '0');
  243. nMult /= 10;
  244. }
  245. break;
  246. }
  247. if (isspace(*p))
  248. break;
  249. if (!isdigit(*p))
  250. return false;
  251. strWhole.insert(strWhole.end(), *p);
  252. }
  253. for (; *p; p++)
  254. if (!isspace(*p))
  255. return false;
  256. if (strWhole.size() > 10) // guard against 63 bit overflow
  257. return false;
  258. if (nUnits < 0 || nUnits > COIN)
  259. return false;
  260. int64_t nWhole = atoi64(strWhole);
  261. int64_t nValue = nWhole*COIN + nUnits;
  262. nRet = nValue;
  263. return true;
  264. }
  265. // safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
  266. // even possibly remotely dangerous like & or >
  267. static string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@");
  268. string SanitizeString(const string& str)
  269. {
  270. string strResult;
  271. for (std::string::size_type i = 0; i < str.size(); i++)
  272. {
  273. if (safeChars.find(str[i]) != std::string::npos)
  274. strResult.push_back(str[i]);
  275. }
  276. return strResult;
  277. }
  278. const signed char p_util_hexdigit[256] =
  279. { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  280. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  281. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  282. 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
  283. -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  284. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  285. -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  286. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  287. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  288. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  289. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  290. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  291. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  292. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  293. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  294. -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
  295. signed char HexDigit(char c)
  296. {
  297. return p_util_hexdigit[(unsigned char)c];
  298. }
  299. bool IsHex(const string& str)
  300. {
  301. BOOST_FOREACH(char c, str)
  302. {
  303. if (HexDigit(c) < 0)
  304. return false;
  305. }
  306. return (str.size() > 0) && (str.size()%2 == 0);
  307. }
  308. vector<unsigned char> ParseHex(const char* psz)
  309. {
  310. // convert hex dump to vector
  311. vector<unsigned char> vch;
  312. while (true)
  313. {
  314. while (isspace(*psz))
  315. psz++;
  316. signed char c = HexDigit(*psz++);
  317. if (c == (signed char)-1)
  318. break;
  319. unsigned char n = (c << 4);
  320. c = HexDigit(*psz++);
  321. if (c == (signed char)-1)
  322. break;
  323. n |= c;
  324. vch.push_back(n);
  325. }
  326. return vch;
  327. }
  328. vector<unsigned char> ParseHex(const string& str)
  329. {
  330. return ParseHex(str.c_str());
  331. }
  332. static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
  333. {
  334. // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
  335. if (name.find("-no") == 0)
  336. {
  337. std::string positive("-");
  338. positive.append(name.begin()+3, name.end());
  339. if (mapSettingsRet.count(positive) == 0)
  340. {
  341. bool value = !GetBoolArg(name, false);
  342. mapSettingsRet[positive] = (value ? "1" : "0");
  343. }
  344. }
  345. }
  346. void ParseParameters(int argc, const char* const argv[])
  347. {
  348. mapArgs.clear();
  349. mapMultiArgs.clear();
  350. for (int i = 1; i < argc; i++)
  351. {
  352. std::string str(argv[i]);
  353. std::string strValue;
  354. size_t is_index = str.find('=');
  355. if (is_index != std::string::npos)
  356. {
  357. strValue = str.substr(is_index+1);
  358. str = str.substr(0, is_index);
  359. }
  360. #ifdef WIN32
  361. boost::to_lower(str);
  362. if (boost::algorithm::starts_with(str, "/"))
  363. str = "-" + str.substr(1);
  364. #endif
  365. if (str[0] != '-')
  366. break;
  367. // Interpret --foo as -foo.
  368. // If both --foo and -foo are set, the last takes effect.
  369. if (str.length() > 1 && str[1] == '-')
  370. str = str.substr(1);
  371. mapArgs[str] = strValue;
  372. mapMultiArgs[str].push_back(strValue);
  373. }
  374. // New 0.6 features:
  375. BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
  376. {
  377. // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
  378. InterpretNegativeSetting(entry.first, mapArgs);
  379. }
  380. }
  381. std::string GetArg(const std::string& strArg, const std::string& strDefault)
  382. {
  383. if (mapArgs.count(strArg))
  384. return mapArgs[strArg];
  385. return strDefault;
  386. }
  387. int64_t GetArg(const std::string& strArg, int64_t nDefault)
  388. {
  389. if (mapArgs.count(strArg))
  390. return atoi64(mapArgs[strArg]);
  391. return nDefault;
  392. }
  393. bool GetBoolArg(const std::string& strArg, bool fDefault)
  394. {
  395. if (mapArgs.count(strArg))
  396. {
  397. if (mapArgs[strArg].empty())
  398. return true;
  399. return (atoi(mapArgs[strArg]) != 0);
  400. }
  401. return fDefault;
  402. }
  403. bool SoftSetArg(const std::string& strArg, const std::string& strValue)
  404. {
  405. if (mapArgs.count(strArg))
  406. return false;
  407. mapArgs[strArg] = strValue;
  408. return true;
  409. }
  410. bool SoftSetBoolArg(const std::string& strArg, bool fValue)
  411. {
  412. if (fValue)
  413. return SoftSetArg(strArg, std::string("1"));
  414. else
  415. return SoftSetArg(strArg, std::string("0"));
  416. }
  417. string EncodeBase64(const unsigned char* pch, size_t len)
  418. {
  419. static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  420. string strRet="";
  421. strRet.reserve((len+2)/3*4);
  422. int mode=0, left=0;
  423. const unsigned char *pchEnd = pch+len;
  424. while (pch<pchEnd)
  425. {
  426. int enc = *(pch++);
  427. switch (mode)
  428. {
  429. case 0: // we have no bits
  430. strRet += pbase64[enc >> 2];
  431. left = (enc & 3) << 4;
  432. mode = 1;
  433. break;
  434. case 1: // we have two bits
  435. strRet += pbase64[left | (enc >> 4)];
  436. left = (enc & 15) << 2;
  437. mode = 2;
  438. break;
  439. case 2: // we have four bits
  440. strRet += pbase64[left | (enc >> 6)];
  441. strRet += pbase64[enc & 63];
  442. mode = 0;
  443. break;
  444. }
  445. }
  446. if (mode)
  447. {
  448. strRet += pbase64[left];
  449. strRet += '=';
  450. if (mode == 1)
  451. strRet += '=';
  452. }
  453. return strRet;
  454. }
  455. string EncodeBase64(const string& str)
  456. {
  457. return EncodeBase64((const unsigned char*)str.c_str(), str.size());
  458. }
  459. vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
  460. {
  461. static const int decode64_table[256] =
  462. {
  463. -1, -1, -1, -1, -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, -1, -1, -1, -1,
  465. -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
  466. -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  467. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
  468. 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
  469. 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -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, -1, -1, -1, -1,
  471. -1, -1, -1, -1, -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, -1, -1, -1, -1,
  473. -1, -1, -1, -1, -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, -1, -1, -1, -1,
  475. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
  476. };
  477. if (pfInvalid)
  478. *pfInvalid = false;
  479. vector<unsigned char> vchRet;
  480. vchRet.reserve(strlen(p)*3/4);
  481. int mode = 0;
  482. int left = 0;
  483. while (1)
  484. {
  485. int dec = decode64_table[(unsigned char)*p];
  486. if (dec == -1) break;
  487. p++;
  488. switch (mode)
  489. {
  490. case 0: // we have no bits and get 6
  491. left = dec;
  492. mode = 1;
  493. break;
  494. case 1: // we have 6 bits and keep 4
  495. vchRet.push_back((left<<2) | (dec>>4));
  496. left = dec & 15;
  497. mode = 2;
  498. break;
  499. case 2: // we have 4 bits and get 6, we keep 2
  500. vchRet.push_back((left<<4) | (dec>>2));
  501. left = dec & 3;
  502. mode = 3;
  503. break;
  504. case 3: // we have 2 bits and get 6
  505. vchRet.push_back((left<<6) | dec);
  506. mode = 0;
  507. break;
  508. }
  509. }
  510. if (pfInvalid)
  511. switch (mode)
  512. {
  513. case 0: // 4n base64 characters processed: ok
  514. break;
  515. case 1: // 4n+1 base64 character processed: impossible
  516. *pfInvalid = true;
  517. break;
  518. case 2: // 4n+2 base64 characters processed: require '=='
  519. if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
  520. *pfInvalid = true;
  521. break;
  522. case 3: // 4n+3 base64 characters processed: require '='
  523. if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
  524. *pfInvalid = true;
  525. break;
  526. }
  527. return vchRet;
  528. }
  529. string DecodeBase64(const string& str)
  530. {
  531. vector<unsigned char> vchRet = DecodeBase64(str.c_str());
  532. return string((const char*)&vchRet[0], vchRet.size());
  533. }
  534. string EncodeBase32(const unsigned char* pch, size_t len)
  535. {
  536. static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
  537. string strRet="";
  538. strRet.reserve((len+4)/5*8);
  539. int mode=0, left=0;
  540. const unsigned char *pchEnd = pch+len;
  541. while (pch<pchEnd)
  542. {
  543. int enc = *(pch++);
  544. switch (mode)
  545. {
  546. case 0: // we have no bits
  547. strRet += pbase32[enc >> 3];
  548. left = (enc & 7) << 2;
  549. mode = 1;
  550. break;
  551. case 1: // we have three bits
  552. strRet += pbase32[left | (enc >> 6)];
  553. strRet += pbase32[(enc >> 1) & 31];
  554. left = (enc & 1) << 4;
  555. mode = 2;
  556. break;
  557. case 2: // we have one bit
  558. strRet += pbase32[left | (enc >> 4)];
  559. left = (enc & 15) << 1;
  560. mode = 3;
  561. break;
  562. case 3: // we have four bits
  563. strRet += pbase32[left | (enc >> 7)];
  564. strRet += pbase32[(enc >> 2) & 31];
  565. left = (enc & 3) << 3;
  566. mode = 4;
  567. break;
  568. case 4: // we have two bits
  569. strRet += pbase32[left | (enc >> 5)];
  570. strRet += pbase32[enc & 31];
  571. mode = 0;
  572. }
  573. }
  574. static const int nPadding[5] = {0, 6, 4, 3, 1};
  575. if (mode)
  576. {
  577. strRet += pbase32[left];
  578. for (int n=0; n<nPadding[mode]; n++)
  579. strRet += '=';
  580. }
  581. return strRet;
  582. }
  583. string EncodeBase32(const string& str)
  584. {
  585. return EncodeBase32((const unsigned char*)str.c_str(), str.size());
  586. }
  587. vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
  588. {
  589. static const int decode32_table[256] =
  590. {
  591. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  592. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  593. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
  594. -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  595. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
  596. 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
  597. 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  598. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  599. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  600. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  601. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  602. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  603. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
  604. };
  605. if (pfInvalid)
  606. *pfInvalid = false;
  607. vector<unsigned char> vchRet;
  608. vchRet.reserve((strlen(p))*5/8);
  609. int mode = 0;
  610. int left = 0;
  611. while (1)
  612. {
  613. int dec = decode32_table[(unsigned char)*p];
  614. if (dec == -1) break;
  615. p++;
  616. switch (mode)
  617. {
  618. case 0: // we have no bits and get 5
  619. left = dec;
  620. mode = 1;
  621. break;
  622. case 1: // we have 5 bits and keep 2
  623. vchRet.push_back((left<<3) | (dec>>2));
  624. left = dec & 3;
  625. mode = 2;
  626. break;
  627. case 2: // we have 2 bits and keep 7
  628. left = left << 5 | dec;
  629. mode = 3;
  630. break;
  631. case 3: // we have 7 bits and keep 4
  632. vchRet.push_back((left<<1) | (dec>>4));
  633. left = dec & 15;
  634. mode = 4;
  635. break;
  636. case 4: // we have 4 bits, and keep 1
  637. vchRet.push_back((left<<4) | (dec>>1));
  638. left = dec & 1;
  639. mode = 5;
  640. break;
  641. case 5: // we have 1 bit, and keep 6
  642. left = left << 5 | dec;
  643. mode = 6;
  644. break;
  645. case 6: // we have 6 bits, and keep 3
  646. vchRet.push_back((left<<2) | (dec>>3));
  647. left = dec & 7;
  648. mode = 7;
  649. break;
  650. case 7: // we have 3 bits, and keep 0
  651. vchRet.push_back((left<<5) | dec);
  652. mode = 0;
  653. break;
  654. }
  655. }
  656. if (pfInvalid)
  657. switch (mode)
  658. {
  659. case 0: // 8n base32 characters processed: ok
  660. break;
  661. case 1: // 8n+1 base32 characters processed: impossible
  662. case 3: // +3
  663. case 6: // +6
  664. *pfInvalid = true;
  665. break;
  666. case 2: // 8n+2 base32 characters processed: require '======'
  667. if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
  668. *pfInvalid = true;
  669. break;
  670. case 4: // 8n+4 base32 characters processed: require '===='
  671. if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
  672. *pfInvalid = true;
  673. break;
  674. case 5: // 8n+5 base32 characters processed: require '==='
  675. if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
  676. *pfInvalid = true;
  677. break;
  678. case 7: // 8n+7 base32 characters processed: require '='
  679. if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
  680. *pfInvalid = true;
  681. break;
  682. }
  683. return vchRet;
  684. }
  685. string DecodeBase32(const string& str)
  686. {
  687. vector<unsigned char> vchRet = DecodeBase32(str.c_str());
  688. return string((const char*)&vchRet[0], vchRet.size());
  689. }
  690. static std::string FormatException(std::exception* pex, const char* pszThread)
  691. {
  692. #ifdef WIN32
  693. char pszModule[MAX_PATH] = "";
  694. GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
  695. #else
  696. const char* pszModule = "bitcoin";
  697. #endif
  698. if (pex)
  699. return strprintf(
  700. "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
  701. else
  702. return strprintf(
  703. "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
  704. }
  705. void PrintExceptionContinue(std::exception* pex, const char* pszThread)
  706. {
  707. std::string message = FormatException(pex, pszThread);
  708. LogPrintf("\n\n************************\n%s\n", message);
  709. fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
  710. strMiscWarning = message;
  711. }
  712. boost::filesystem::path GetDefaultDataDir()
  713. {
  714. namespace fs = boost::filesystem;
  715. // Windows < Vista: C:\Documents and Settings\Username\Application Data\Bitcoin
  716. // Windows >= Vista: C:\Users\Username\AppData\Roaming\Bitcoin
  717. // Mac: ~/Library/Application Support/Bitcoin
  718. // Unix: ~/.bitcoin
  719. #ifdef WIN32
  720. // Windows
  721. return GetSpecialFolderPath(CSIDL_APPDATA) / "Bitcoin";
  722. #else
  723. fs::path pathRet;
  724. char* pszHome = getenv("HOME");
  725. if (pszHome == NULL || strlen(pszHome) == 0)
  726. pathRet = fs::path("/");
  727. else
  728. pathRet = fs::path(pszHome);
  729. #ifdef MAC_OSX
  730. // Mac
  731. pathRet /= "Library/Application Support";
  732. TryCreateDirectory(pathRet);
  733. return pathRet / "Bitcoin";
  734. #else
  735. // Unix
  736. return pathRet / ".bitcoin";
  737. #endif
  738. #endif
  739. }
  740. static boost::filesystem::path pathCached[CBaseChainParams::MAX_NETWORK_TYPES+1];
  741. static CCriticalSection csPathCached;
  742. const boost::filesystem::path &GetDataDir(bool fNetSpecific)
  743. {
  744. namespace fs = boost::filesystem;
  745. LOCK(csPathCached);
  746. int nNet = CBaseChainParams::MAX_NETWORK_TYPES;
  747. if (fNetSpecific) nNet = BaseParams().NetworkID();
  748. fs::path &path = pathCached[nNet];
  749. // This can be called during exceptions by LogPrintf(), so we cache the
  750. // value so we don't have to do memory allocations after that.
  751. if (!path.empty())
  752. return path;
  753. if (mapArgs.count("-datadir")) {
  754. path = fs::system_complete(mapArgs["-datadir"]);
  755. if (!fs::is_directory(path)) {
  756. path = "";
  757. return path;
  758. }
  759. } else {
  760. path = GetDefaultDataDir();
  761. }
  762. if (fNetSpecific)
  763. path /= BaseParams().DataDir();
  764. fs::create_directories(path);
  765. return path;
  766. }
  767. void ClearDatadirCache()
  768. {
  769. std::fill(&pathCached[0], &pathCached[CBaseChainParams::MAX_NETWORK_TYPES+1],
  770. boost::filesystem::path());
  771. }
  772. boost::filesystem::path GetConfigFile()
  773. {
  774. boost::filesystem::path pathConfigFile(GetArg("-conf", "bitcoin.conf"));
  775. if (!pathConfigFile.is_complete())
  776. pathConfigFile = GetDataDir(false) / pathConfigFile;
  777. return pathConfigFile;
  778. }
  779. void ReadConfigFile(map<string, string>& mapSettingsRet,
  780. map<string, vector<string> >& mapMultiSettingsRet)
  781. {
  782. boost::filesystem::ifstream streamConfig(GetConfigFile());
  783. if (!streamConfig.good())
  784. return; // No bitcoin.conf file is OK
  785. set<string> setOptions;
  786. setOptions.insert("*");
  787. for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
  788. {
  789. // Don't overwrite existing settings so command line settings override bitcoin.conf
  790. string strKey = string("-") + it->string_key;
  791. if (mapSettingsRet.count(strKey) == 0)
  792. {
  793. mapSettingsRet[strKey] = it->value[0];
  794. // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
  795. InterpretNegativeSetting(strKey, mapSettingsRet);
  796. }
  797. mapMultiSettingsRet[strKey].push_back(it->value[0]);
  798. }
  799. // If datadir is changed in .conf file:
  800. ClearDatadirCache();
  801. }
  802. boost::filesystem::path GetPidFile()
  803. {
  804. boost::filesystem::path pathPidFile(GetArg("-pid", "bitcoind.pid"));
  805. if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
  806. return pathPidFile;
  807. }
  808. #ifndef WIN32
  809. void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
  810. {
  811. FILE* file = fopen(path.string().c_str(), "w");
  812. if (file)
  813. {
  814. fprintf(file, "%d\n", pid);
  815. fclose(file);
  816. }
  817. }
  818. #endif
  819. bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
  820. {
  821. #ifdef WIN32
  822. return MoveFileExA(src.string().c_str(), dest.string().c_str(),
  823. MOVEFILE_REPLACE_EXISTING);
  824. #else
  825. int rc = std::rename(src.string().c_str(), dest.string().c_str());
  826. return (rc == 0);
  827. #endif /* WIN32 */
  828. }
  829. // Ignores exceptions thrown by Boost's create_directory if the requested directory exists.
  830. // Specifically handles case where path p exists, but it wasn't possible for the user to
  831. // write to the parent directory.
  832. bool TryCreateDirectory(const boost::filesystem::path& p)
  833. {
  834. try
  835. {
  836. return boost::filesystem::create_directory(p);
  837. } catch (boost::filesystem::filesystem_error) {
  838. if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p))
  839. throw;
  840. }
  841. // create_directory didn't create the directory, it had to have existed already
  842. return false;
  843. }
  844. void FileCommit(FILE *fileout)
  845. {
  846. fflush(fileout); // harmless if redundantly called
  847. #ifdef WIN32
  848. HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout));
  849. FlushFileBuffers(hFile);
  850. #else
  851. #if defined(__linux__) || defined(__NetBSD__)
  852. fdatasync(fileno(fileout));
  853. #elif defined(__APPLE__) && defined(F_FULLFSYNC)
  854. fcntl(fileno(fileout), F_FULLFSYNC, 0);
  855. #else
  856. fsync(fileno(fileout));
  857. #endif
  858. #endif
  859. }
  860. bool TruncateFile(FILE *file, unsigned int length) {
  861. #if defined(WIN32)
  862. return _chsize(_fileno(file), length) == 0;
  863. #else
  864. return ftruncate(fileno(file), length) == 0;
  865. #endif
  866. }
  867. // this function tries to raise the file descriptor limit to the requested number.
  868. // It returns the actual file descriptor limit (which may be more or less than nMinFD)
  869. int RaiseFileDescriptorLimit(int nMinFD) {
  870. #if defined(WIN32)
  871. return 2048;
  872. #else
  873. struct rlimit limitFD;
  874. if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
  875. if (limitFD.rlim_cur < (rlim_t)nMinFD) {
  876. limitFD.rlim_cur = nMinFD;
  877. if (limitFD.rlim_cur > limitFD.rlim_max)
  878. limitFD.rlim_cur = limitFD.rlim_max;
  879. setrlimit(RLIMIT_NOFILE, &limitFD);
  880. getrlimit(RLIMIT_NOFILE, &limitFD);
  881. }
  882. return limitFD.rlim_cur;
  883. }
  884. return nMinFD; // getrlimit failed, assume it's fine
  885. #endif
  886. }
  887. // this function tries to make a particular range of a file allocated (corresponding to disk space)
  888. // it is advisory, and the range specified in the arguments will never contain live data
  889. void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
  890. #if defined(WIN32)
  891. // Windows-specific version
  892. HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
  893. LARGE_INTEGER nFileSize;
  894. int64_t nEndPos = (int64_t)offset + length;
  895. nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
  896. nFileSize.u.HighPart = nEndPos >> 32;
  897. SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
  898. SetEndOfFile(hFile);
  899. #elif defined(MAC_OSX)
  900. // OSX specific version
  901. fstore_t fst;
  902. fst.fst_flags = F_ALLOCATECONTIG;
  903. fst.fst_posmode = F_PEOFPOSMODE;
  904. fst.fst_offset = 0;
  905. fst.fst_length = (off_t)offset + length;
  906. fst.fst_bytesalloc = 0;
  907. if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
  908. fst.fst_flags = F_ALLOCATEALL;
  909. fcntl(fileno(file), F_PREALLOCATE, &fst);
  910. }
  911. ftruncate(fileno(file), fst.fst_length);
  912. #elif defined(__linux__)
  913. // Version using posix_fallocate
  914. off_t nEndPos = (off_t)offset + length;
  915. posix_fallocate(fileno(file), 0, nEndPos);
  916. #else
  917. // Fallback version
  918. // TODO: just write one byte per block
  919. static const char buf[65536] = {};
  920. fseek(file, offset, SEEK_SET);
  921. while (length > 0) {
  922. unsigned int now = 65536;
  923. if (length < now)
  924. now = length;
  925. fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
  926. length -= now;
  927. }
  928. #endif
  929. }
  930. void ShrinkDebugFile()
  931. {
  932. // Scroll debug.log if it's getting too big
  933. boost::filesystem::path pathLog = GetDataDir() / "debug.log";
  934. FILE* file = fopen(pathLog.string().c_str(), "r");
  935. if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
  936. {
  937. // Restart the file with some of the end
  938. std::vector <char> vch(200000,0);
  939. fseek(file, -vch.size(), SEEK_END);
  940. int nBytes = fread(begin_ptr(vch), 1, vch.size(), file);
  941. fclose(file);
  942. file = fopen(pathLog.string().c_str(), "w");
  943. if (file)
  944. {
  945. fwrite(begin_ptr(vch), 1, nBytes, file);
  946. fclose(file);
  947. }
  948. }
  949. else if (file != NULL)
  950. fclose(file);
  951. }
  952. static int64_t nMockTime = 0; // For unit testing
  953. int64_t GetTime()
  954. {
  955. if (nMockTime) return nMockTime;
  956. return time(NULL);
  957. }
  958. void SetMockTime(int64_t nMockTimeIn)
  959. {
  960. nMockTime = nMockTimeIn;
  961. }
  962. #ifdef WIN32
  963. boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
  964. {
  965. namespace fs = boost::filesystem;
  966. char pszPath[MAX_PATH] = "";
  967. if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
  968. {
  969. return fs::path(pszPath);
  970. }
  971. LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
  972. return fs::path("");
  973. }
  974. #endif
  975. boost::filesystem::path GetTempPath() {
  976. #if BOOST_FILESYSTEM_VERSION == 3
  977. return boost::filesystem::temp_directory_path();
  978. #else
  979. // TODO: remove when we don't support filesystem v2 anymore
  980. boost::filesystem::path path;
  981. #ifdef WIN32
  982. char pszPath[MAX_PATH] = "";
  983. if (GetTempPathA(MAX_PATH, pszPath))
  984. path = boost::filesystem::path(pszPath);
  985. #else
  986. path = boost::filesystem::path("/tmp");
  987. #endif
  988. if (path.empty() || !boost::filesystem::is_directory(path)) {
  989. LogPrintf("GetTempPath(): failed to find temp path\n");
  990. return boost::filesystem::path("");
  991. }
  992. return path;
  993. #endif
  994. }
  995. void runCommand(std::string strCommand)
  996. {
  997. int nErr = ::system(strCommand.c_str());
  998. if (nErr)
  999. LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
  1000. }
  1001. void RenameThread(const char* name)
  1002. {
  1003. #if defined(PR_SET_NAME)
  1004. // Only the first 15 characters are used (16 - NUL terminator)
  1005. ::prctl(PR_SET_NAME, name, 0, 0, 0);
  1006. #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
  1007. // TODO: This is currently disabled because it needs to be verified to work
  1008. // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
  1009. // removed.
  1010. pthread_set_name_np(pthread_self(), name);
  1011. #elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
  1012. // pthread_setname_np is XCode 10.6-and-later
  1013. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
  1014. pthread_setname_np(name);
  1015. #endif
  1016. #else
  1017. // Prevent warnings for unused parameters...
  1018. (void)name;
  1019. #endif
  1020. }
  1021. bool ParseInt32(const std::string& str, int32_t *out)
  1022. {
  1023. char *endp = NULL;
  1024. errno = 0; // strtol will not set errno if valid
  1025. long int n = strtol(str.c_str(), &endp, 10);
  1026. if(out) *out = (int)n;
  1027. // Note that strtol returns a *long int*, so even if strtol doesn't report a over/underflow
  1028. // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit
  1029. // platforms the size of these types may be different.
  1030. return endp && *endp == 0 && !errno &&
  1031. n >= std::numeric_limits<int32_t>::min() &&
  1032. n <= std::numeric_limits<int32_t>::max();
  1033. }
  1034. void SetupEnvironment()
  1035. {
  1036. #ifndef WIN32
  1037. try
  1038. {
  1039. #if BOOST_FILESYSTEM_VERSION == 3
  1040. boost::filesystem::path::codecvt(); // Raises runtime error if current locale is invalid
  1041. #else // boost filesystem v2
  1042. std::locale(); // Raises runtime error if current locale is invalid
  1043. #endif
  1044. } catch(std::runtime_error &e)
  1045. {
  1046. setenv("LC_ALL", "C", 1); // Force C locale
  1047. }
  1048. #endif
  1049. }
  1050. std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)
  1051. {
  1052. // std::locale takes ownership of the pointer
  1053. std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));
  1054. std::stringstream ss;
  1055. ss.imbue(loc);
  1056. ss << boost::posix_time::from_time_t(nTime);
  1057. return ss.str();
  1058. }
  1059. std::string FormatParagraph(const std::string in, size_t width, size_t indent)
  1060. {
  1061. std::stringstream out;
  1062. size_t col = 0;
  1063. size_t ptr = 0;
  1064. while(ptr < in.size())
  1065. {
  1066. // Find beginning of next word
  1067. ptr = in.find_first_not_of(' ', ptr);
  1068. if (ptr == std::string::npos)
  1069. break;
  1070. // Find end of next word
  1071. size_t endword = in.find_first_of(' ', ptr);
  1072. if (endword == std::string::npos)
  1073. endword = in.size();
  1074. // Add newline and indentation if this wraps over the allowed width
  1075. if (col > 0)
  1076. {
  1077. if ((col + endword - ptr) > width)
  1078. {
  1079. out << '\n';
  1080. for(size_t i=0; i<indent; ++i)
  1081. out << ' ';
  1082. col = 0;
  1083. } else
  1084. out << ' ';
  1085. }
  1086. // Append word
  1087. out << in.substr(ptr, endword - ptr);
  1088. col += endword - ptr;
  1089. ptr = endword;
  1090. }
  1091. return out.str();
  1092. }
  1093. void SetThreadPriority(int nPriority)
  1094. {
  1095. #ifdef WIN32
  1096. SetThreadPriority(GetCurrentThread(), nPriority);
  1097. #else // WIN32
  1098. #ifdef PRIO_THREAD
  1099. setpriority(PRIO_THREAD, 0, nPriority);
  1100. #else // PRIO_THREAD
  1101. setpriority(PRIO_PROCESS, 0, nPriority);
  1102. #endif // PRIO_THREAD
  1103. #endif // WIN32
  1104. }