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