Merge pull request #1054 from sipa/buildinfo
[novacoin.git] / src / init.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #include "headers.h"
6 #include "db.h"
7 #include "bitcoinrpc.h"
8 #include "net.h"
9 #include "init.h"
10 #include "strlcpy.h"
11 #include <boost/filesystem.hpp>
12 #include <boost/filesystem/fstream.hpp>
13 #include <boost/filesystem/convenience.hpp>
14 #include <boost/interprocess/sync/file_lock.hpp>
15
16 #ifdef WIN32
17 #define strncasecmp strnicmp
18 #endif
19
20 using namespace std;
21 using namespace boost;
22
23 CWallet* pwalletMain;
24
25 //////////////////////////////////////////////////////////////////////////////
26 //
27 // Shutdown
28 //
29
30 void ExitTimeout(void* parg)
31 {
32 #ifdef WIN32
33     Sleep(5000);
34     ExitProcess(0);
35 #endif
36 }
37
38 void Shutdown(void* parg)
39 {
40     static CCriticalSection cs_Shutdown;
41     static bool fTaken;
42     bool fFirstThread = false;
43     {
44         TRY_LOCK(cs_Shutdown, lockShutdown);
45         if (lockShutdown)
46         {
47             fFirstThread = !fTaken;
48             fTaken = true;
49         }
50     }
51     static bool fExit;
52     if (fFirstThread)
53     {
54         fShutdown = true;
55         nTransactionsUpdated++;
56         DBFlush(false);
57         StopNode();
58         DBFlush(true);
59         boost::filesystem::remove(GetPidFile());
60         UnregisterWallet(pwalletMain);
61         delete pwalletMain;
62         CreateThread(ExitTimeout, NULL);
63         Sleep(50);
64         printf("Bitcoin exiting\n\n");
65         fExit = true;
66         exit(0);
67     }
68     else
69     {
70         while (!fExit)
71             Sleep(500);
72         Sleep(100);
73         ExitThread(0);
74     }
75 }
76
77 void HandleSIGTERM(int)
78 {
79     fRequestShutdown = true;
80 }
81
82
83
84
85
86
87 //////////////////////////////////////////////////////////////////////////////
88 //
89 // Start
90 //
91 #if !defined(QT_GUI)
92 int main(int argc, char* argv[])
93 {
94     bool fRet = false;
95     fRet = AppInit(argc, argv);
96
97     if (fRet && fDaemon)
98         return 0;
99
100     return 1;
101 }
102 #endif
103
104 bool AppInit(int argc, char* argv[])
105 {
106     bool fRet = false;
107     try
108     {
109         fRet = AppInit2(argc, argv);
110     }
111     catch (std::exception& e) {
112         PrintException(&e, "AppInit()");
113     } catch (...) {
114         PrintException(NULL, "AppInit()");
115     }
116     if (!fRet)
117         Shutdown(NULL);
118     return fRet;
119 }
120
121 bool AppInit2(int argc, char* argv[])
122 {
123 #ifdef _MSC_VER
124     // Turn off microsoft heap dump noise
125     _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
126     _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
127 #endif
128 #if _MSC_VER >= 1400
129     // Disable confusing "helpful" text message on abort, ctrl-c
130     _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
131 #endif
132 #ifndef WIN32
133     umask(077);
134 #endif
135 #ifndef WIN32
136     // Clean shutdown on SIGTERM
137     struct sigaction sa;
138     sa.sa_handler = HandleSIGTERM;
139     sigemptyset(&sa.sa_mask);
140     sa.sa_flags = 0;
141     sigaction(SIGTERM, &sa, NULL);
142     sigaction(SIGINT, &sa, NULL);
143     sigaction(SIGHUP, &sa, NULL);
144 #endif
145
146     //
147     // Parameters
148     //
149     // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
150 #if !defined(QT_GUI)
151     ParseParameters(argc, argv);
152     if (!ReadConfigFile(mapArgs, mapMultiArgs))
153     {
154         fprintf(stderr, "Error: Specified directory does not exist\n");
155         Shutdown(NULL);
156     }
157 #endif
158
159     if (mapArgs.count("-?") || mapArgs.count("--help"))
160     {
161         string strUsage = string() +
162           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
163           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
164             "  bitcoind [options]                   \t  " + "\n" +
165             "  bitcoind [options] <command> [params]\t  " + _("Send command to -server or bitcoind") + "\n" +
166             "  bitcoind [options] help              \t\t  " + _("List commands") + "\n" +
167             "  bitcoind [options] help <command>    \t\t  " + _("Get help for a command") + "\n" +
168           _("Options:") + "\n" +
169             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
170             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
171             "  -gen             \t\t  " + _("Generate coins") + "\n" +
172             "  -gen=0           \t\t  " + _("Don't generate coins") + "\n" +
173             "  -min             \t\t  " + _("Start minimized") + "\n" +
174             "  -splash          \t\t  " + _("Show splash screen on startup (default: 1)") + "\n" +
175             "  -datadir=<dir>   \t\t  " + _("Specify data directory") + "\n" +
176             "  -dbcache=<n>     \t\t  " + _("Set database cache size in megabytes (default: 25)") + "\n" +
177             "  -dblogsize=<n>   \t\t  " + _("Set database disk log size in megabytes (default: 100)") + "\n" +
178             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)") + "\n" +
179             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy") + "\n" +
180             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect") + "\n" +
181             "  -port=<port>     \t\t  " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
182             "  -maxconnections=<n>\t  " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
183             "  -addnode=<ip>    \t  "   + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
184             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node") + "\n" +
185             "  -irc             \t  "   + _("Find peers using internet relay chat (default: 0)") + "\n" +
186             "  -listen          \t  "   + _("Accept connections from outside (default: 1)") + "\n" +
187 #ifdef QT_GUI
188             "  -lang=<lang>     \t\t  " + _("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
189 #endif
190             "  -dnsseed         \t  "   + _("Find peers using DNS lookup (default: 1)") + "\n" +
191             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
192             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
193             "  -maxreceivebuffer=<n>\t  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
194             "  -maxsendbuffer=<n>\t  "   + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
195 #ifdef USE_UPNP
196 #if USE_UPNP
197             "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
198 #else
199             "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
200 #endif
201 #endif
202             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send") + "\n" +
203 #ifdef QT_GUI
204             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands") + "\n" +
205 #endif
206 #if !defined(WIN32) && !defined(QT_GUI)
207             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands") + "\n" +
208 #endif
209             "  -testnet         \t\t  " + _("Use the test network") + "\n" +
210             "  -debug           \t\t  " + _("Output extra debugging information") + "\n" +
211             "  -logtimestamps   \t  "   + _("Prepend debug output with timestamp") + "\n" +
212             "  -printtoconsole  \t  "   + _("Send trace/debug info to console instead of debug.log file") + "\n" +
213 #ifdef WIN32
214             "  -printtodebugger \t  "   + _("Send trace/debug info to debugger") + "\n" +
215 #endif
216             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections") + "\n" +
217             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections") + "\n" +
218             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
219             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
220             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
221             "  -blocknotify=<cmd> "     + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
222             "  -upgradewallet   \t  "   + _("Upgrade wallet to latest format") + "\n" +
223             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)") + "\n" +
224             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions") + "\n" +
225             "  -checkblocks=<n> \t\t  " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" +
226             "  -checklevel=<n>  \t\t  " + _("How thorough the block verification is (0-6, default: 1)") + "\n";
227
228         strUsage += string() +
229             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
230             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
231             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)") + "\n" +
232             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)") + "\n" +
233             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
234
235         strUsage += string() +
236             "  -?               \t\t  " + _("This help message") + "\n";
237
238         // Remove tabs
239         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
240 #if defined(QT_GUI) && defined(WIN32)
241         // On windows, show a message box, as there is no stderr
242         ThreadSafeMessageBox(strUsage, _("Usage"), wxOK | wxMODAL);
243 #else
244         fprintf(stderr, "%s", strUsage.c_str());
245 #endif
246         return false;
247     }
248
249     fTestNet = GetBoolArg("-testnet");
250     if (fTestNet)
251     {
252         SoftSetBoolArg("-irc", true);
253     }
254
255     fDebug = GetBoolArg("-debug");
256
257 #if !defined(WIN32) && !defined(QT_GUI)
258     fDaemon = GetBoolArg("-daemon");
259 #else
260     fDaemon = false;
261 #endif
262
263     if (fDaemon)
264         fServer = true;
265     else
266         fServer = GetBoolArg("-server");
267
268     /* force fServer when running without GUI */
269 #if !defined(QT_GUI)
270     fServer = true;
271 #endif
272     fPrintToConsole = GetBoolArg("-printtoconsole");
273     fPrintToDebugger = GetBoolArg("-printtodebugger");
274     fLogTimestamps = GetBoolArg("-logtimestamps");
275
276 #ifndef QT_GUI
277     for (int i = 1; i < argc; i++)
278         if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
279             fCommandLine = true;
280
281     if (fCommandLine)
282     {
283         int ret = CommandLineRPC(argc, argv);
284         exit(ret);
285     }
286 #endif
287
288 #if !defined(WIN32) && !defined(QT_GUI)
289     if (fDaemon)
290     {
291         // Daemonize
292         pid_t pid = fork();
293         if (pid < 0)
294         {
295             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
296             return false;
297         }
298         if (pid > 0)
299         {
300             CreatePidFile(GetPidFile(), pid);
301             return true;
302         }
303
304         pid_t sid = setsid();
305         if (sid < 0)
306             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
307     }
308 #endif
309
310     if (!fDebug && !pszSetDataDir[0])
311         ShrinkDebugFile();
312     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
313     printf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
314     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
315
316     if (GetBoolArg("-loadblockindextest"))
317     {
318         CTxDB txdb("r");
319         txdb.LoadBlockIndex();
320         PrintBlockTree();
321         return false;
322     }
323
324     // Make sure only a single bitcoin process is using the data directory.
325     string strLockFile = GetDataDir() + "/.lock";
326     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
327     if (file) fclose(file);
328     static boost::interprocess::file_lock lock(strLockFile.c_str());
329     if (!lock.try_lock())
330     {
331         ThreadSafeMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), _("Bitcoin"), wxOK|wxMODAL);
332         return false;
333     }
334
335     std::ostringstream strErrors;
336     //
337     // Load data files
338     //
339     if (fDaemon)
340         fprintf(stdout, "bitcoin server starting\n");
341     int64 nStart;
342
343     InitMessage(_("Loading addresses..."));
344     printf("Loading addresses...\n");
345     nStart = GetTimeMillis();
346     if (!LoadAddresses())
347         strErrors << _("Error loading addr.dat") << "\n";
348     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
349
350     InitMessage(_("Loading block index..."));
351     printf("Loading block index...\n");
352     nStart = GetTimeMillis();
353     if (!LoadBlockIndex())
354         strErrors << _("Error loading blkindex.dat") << "\n";
355     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
356
357     InitMessage(_("Loading wallet..."));
358     printf("Loading wallet...\n");
359     nStart = GetTimeMillis();
360     bool fFirstRun;
361     pwalletMain = new CWallet("wallet.dat");
362     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
363     if (nLoadWalletRet != DB_LOAD_OK)
364     {
365         if (nLoadWalletRet == DB_CORRUPT)
366             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
367         else if (nLoadWalletRet == DB_TOO_NEW)
368             strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
369         else if (nLoadWalletRet == DB_NEED_REWRITE)
370         {
371             strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
372             printf("%s", strErrors.str().c_str());
373             ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
374             return false;
375         }
376         else
377             strErrors << _("Error loading wallet.dat") << "\n";
378     }
379
380     if (GetBoolArg("-upgradewallet", fFirstRun))
381     {
382         int nMaxVersion = GetArg("-upgradewallet", 0);
383         if (nMaxVersion == 0) // the -walletupgrade without argument case
384         {
385             printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
386             nMaxVersion = CLIENT_VERSION;
387             pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
388         }
389         else
390             printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
391         if (nMaxVersion < pwalletMain->GetVersion())
392             strErrors << _("Cannot downgrade wallet") << "\n";
393         pwalletMain->SetMaxVersion(nMaxVersion);
394     }
395
396     if (fFirstRun)
397     {
398         // Create new keyUser and set as default key
399         RandAddSeedPerfmon();
400
401         std::vector<unsigned char> newDefaultKey;
402         if (!pwalletMain->GetKeyFromPool(newDefaultKey, false))
403             strErrors << _("Cannot initialize keypool") << "\n";
404         pwalletMain->SetDefaultKey(newDefaultKey);
405         if (!pwalletMain->SetAddressBookName(CBitcoinAddress(pwalletMain->vchDefaultKey), ""))
406             strErrors << _("Cannot write default address") << "\n";
407     }
408
409     printf("%s", strErrors.str().c_str());
410     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
411
412     RegisterWallet(pwalletMain);
413
414     CBlockIndex *pindexRescan = pindexBest;
415     if (GetBoolArg("-rescan"))
416         pindexRescan = pindexGenesisBlock;
417     else
418     {
419         CWalletDB walletdb("wallet.dat");
420         CBlockLocator locator;
421         if (walletdb.ReadBestBlock(locator))
422             pindexRescan = locator.GetBlockIndex();
423     }
424     if (pindexBest != pindexRescan)
425     {
426         InitMessage(_("Rescanning..."));
427         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
428         nStart = GetTimeMillis();
429         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
430         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
431     }
432
433     InitMessage(_("Done loading"));
434     printf("Done loading\n");
435
436     //// debug print
437     printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
438     printf("nBestHeight = %d\n",            nBestHeight);
439     printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
440     printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
441     printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
442
443     if (!strErrors.str().empty())
444     {
445         ThreadSafeMessageBox(strErrors.str(), _("Bitcoin"), wxOK | wxICON_ERROR | wxMODAL);
446         return false;
447     }
448
449     // Add wallet transactions that aren't already in a block to mapTransactions
450     pwalletMain->ReacceptWalletTransactions();
451
452     // Note: Bitcoin-QT stores several settings in the wallet, so we want
453     // to load the wallet BEFORE parsing command-line arguments, so
454     // the command-line/bitcoin.conf settings override GUI setting.
455
456     //
457     // Parameters
458     //
459     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
460     {
461         PrintBlockTree();
462         return false;
463     }
464
465     if (mapArgs.count("-timeout"))
466     {
467         int nNewTimeout = GetArg("-timeout", 5000);
468         if (nNewTimeout > 0 && nNewTimeout < 600000)
469             nConnectTimeout = nNewTimeout;
470     }
471
472     if (mapArgs.count("-printblock"))
473     {
474         string strMatch = mapArgs["-printblock"];
475         int nFound = 0;
476         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
477         {
478             uint256 hash = (*mi).first;
479             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
480             {
481                 CBlockIndex* pindex = (*mi).second;
482                 CBlock block;
483                 block.ReadFromDisk(pindex);
484                 block.BuildMerkleTree();
485                 block.print();
486                 printf("\n");
487                 nFound++;
488             }
489         }
490         if (nFound == 0)
491             printf("No blocks matching %s were found\n", strMatch.c_str());
492         return false;
493     }
494
495     if (mapArgs.count("-proxy"))
496     {
497         fUseProxy = true;
498         addrProxy = CService(mapArgs["-proxy"], 9050);
499         if (!addrProxy.IsValid())
500         {
501             ThreadSafeMessageBox(_("Invalid -proxy address"), _("Bitcoin"), wxOK | wxMODAL);
502             return false;
503         }
504     }
505
506     bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
507     if (fTor)
508     {
509         // Use SoftSetBoolArg here so user can override any of these if they wish.
510         // Note: the GetBoolArg() calls for all of these must happen later.
511         SoftSetBoolArg("-listen", false);
512         SoftSetBoolArg("-irc", false);
513         SoftSetBoolArg("-dnsseed", false);
514         SoftSetBoolArg("-upnp", false);
515         SoftSetBoolArg("-dns", false);
516     }
517
518     fAllowDNS = GetBoolArg("-dns");
519     fNoListen = !GetBoolArg("-listen", true);
520
521     // Continue to put "/P2SH/" in the coinbase to monitor
522     // BIP16 support.
523     // This can be removed eventually...
524     const char* pszP2SH = "/P2SH/";
525     COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
526
527     if (!fNoListen)
528     {
529         std::string strError;
530         if (!BindListenPort(strError))
531         {
532             ThreadSafeMessageBox(strError, _("Bitcoin"), wxOK | wxMODAL);
533             return false;
534         }
535     }
536
537     if (mapArgs.count("-addnode"))
538     {
539         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
540         {
541             CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
542             addr.nTime = 0; // so it won't relay unless successfully connected
543             if (addr.IsValid())
544                 addrman.Add(addr, CNetAddr("127.0.0.1"));
545         }
546     }
547
548     if (mapArgs.count("-paytxfee"))
549     {
550         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
551         {
552             ThreadSafeMessageBox(_("Invalid amount for -paytxfee=<amount>"), _("Bitcoin"), wxOK | wxMODAL);
553             return false;
554         }
555         if (nTransactionFee > 0.25 * COIN)
556             ThreadSafeMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), _("Bitcoin"), wxOK | wxICON_EXCLAMATION | wxMODAL);
557     }
558
559     //
560     // Start the node
561     //
562     if (!CheckDiskSpace())
563         return false;
564
565     RandAddSeedPerfmon();
566
567     if (!CreateThread(StartNode, NULL))
568         ThreadSafeMessageBox(_("Error: CreateThread(StartNode) failed"), _("Bitcoin"), wxOK | wxMODAL);
569
570     if (fServer)
571         CreateThread(ThreadRPCServer, NULL);
572
573 #ifdef QT_GUI
574     if(GetStartOnSystemStartup())
575         SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
576 #endif
577
578 #if !defined(QT_GUI)
579     while (1)
580         Sleep(5000);
581 #endif
582
583     return true;
584 }
585
586 #ifdef WIN32
587 string StartupShortcutPath()
588 {
589     return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
590 }
591
592 bool GetStartOnSystemStartup()
593 {
594     return filesystem::exists(StartupShortcutPath().c_str());
595 }
596
597 bool SetStartOnSystemStartup(bool fAutoStart)
598 {
599     // If the shortcut exists already, remove it for updating
600     remove(StartupShortcutPath().c_str());
601
602     if (fAutoStart)
603     {
604         CoInitialize(NULL);
605
606         // Get a pointer to the IShellLink interface.
607         IShellLink* psl = NULL;
608         HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
609                                 CLSCTX_INPROC_SERVER, IID_IShellLink,
610                                 reinterpret_cast<void**>(&psl));
611
612         if (SUCCEEDED(hres))
613         {
614             // Get the current executable path
615             TCHAR pszExePath[MAX_PATH];
616             GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
617
618             TCHAR pszArgs[5] = TEXT("-min");
619
620             // Set the path to the shortcut target
621             psl->SetPath(pszExePath);
622             PathRemoveFileSpec(pszExePath);
623             psl->SetWorkingDirectory(pszExePath);
624             psl->SetShowCmd(SW_SHOWMINNOACTIVE);
625             psl->SetArguments(pszArgs);
626
627             // Query IShellLink for the IPersistFile interface for
628             // saving the shortcut in persistent storage.
629             IPersistFile* ppf = NULL;
630             hres = psl->QueryInterface(IID_IPersistFile,
631                                        reinterpret_cast<void**>(&ppf));
632             if (SUCCEEDED(hres))
633             {
634                 WCHAR pwsz[MAX_PATH];
635                 // Ensure that the string is ANSI.
636                 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
637                 // Save the link by calling IPersistFile::Save.
638                 hres = ppf->Save(pwsz, TRUE);
639                 ppf->Release();
640                 psl->Release();
641                 CoUninitialize();
642                 return true;
643             }
644             psl->Release();
645         }
646         CoUninitialize();
647         return false;
648     }
649     return true;
650 }
651
652 #elif defined(LINUX)
653
654 // Follow the Desktop Application Autostart Spec:
655 //  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
656
657 boost::filesystem::path GetAutostartDir()
658 {
659     namespace fs = boost::filesystem;
660
661     char* pszConfigHome = getenv("XDG_CONFIG_HOME");
662     if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
663     char* pszHome = getenv("HOME");
664     if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
665     return fs::path();
666 }
667
668 boost::filesystem::path GetAutostartFilePath()
669 {
670     return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
671 }
672
673 bool GetStartOnSystemStartup()
674 {
675     boost::filesystem::ifstream optionFile(GetAutostartFilePath());
676     if (!optionFile.good())
677         return false;
678     // Scan through file for "Hidden=true":
679     string line;
680     while (!optionFile.eof())
681     {
682         getline(optionFile, line);
683         if (line.find("Hidden") != string::npos &&
684             line.find("true") != string::npos)
685             return false;
686     }
687     optionFile.close();
688
689     return true;
690 }
691
692 bool SetStartOnSystemStartup(bool fAutoStart)
693 {
694     if (!fAutoStart)
695     {
696 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
697         unlink(GetAutostartFilePath().string().c_str());
698 #else
699         unlink(GetAutostartFilePath().native_file_string().c_str());
700 #endif
701     }
702     else
703     {
704         char pszExePath[MAX_PATH+1];
705         memset(pszExePath, 0, sizeof(pszExePath));
706         if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
707             return false;
708
709         boost::filesystem::create_directories(GetAutostartDir());
710
711         boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
712         if (!optionFile.good())
713             return false;
714         // Write a bitcoin.desktop file to the autostart directory:
715         optionFile << "[Desktop Entry]\n";
716         optionFile << "Type=Application\n";
717         optionFile << "Name=Bitcoin\n";
718         optionFile << "Exec=" << pszExePath << " -min\n";
719         optionFile << "Terminal=false\n";
720         optionFile << "Hidden=false\n";
721         optionFile.close();
722     }
723     return true;
724 }
725 #else
726
727 // TODO: OSX startup stuff; see:
728 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
729
730 bool GetStartOnSystemStartup() { return false; }
731 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
732
733 #endif