don't allow -daemon in bitcoin-qt (changes only #defines)
[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             "  -dnsseed         \t  "   + _("Find peers using DNS lookup (default: 1)") + "\n" +
201             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
202             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
203             "  -maxreceivebuffer=<n>\t  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
204             "  -maxsendbuffer=<n>\t  "   + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
205 #ifdef USE_UPNP
206 #if USE_UPNP
207             "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 1)") + "\n" +
208 #else
209             "  -upnp            \t  "   + _("Use Universal Plug and Play to map the listening port (default: 0)") + "\n" +
210 #endif
211 #endif
212             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send") + "\n" +
213 #ifdef GUI
214             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands") + "\n" +
215 #endif
216 #if !defined(WIN32) && !defined(GUI)
217             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands") + "\n" +
218 #endif
219             "  -testnet         \t\t  " + _("Use the test network") + "\n" +
220             "  -debug           \t\t  " + _("Output extra debugging information") + "\n" +
221             "  -logtimestamps   \t  "   + _("Prepend debug output with timestamp") + "\n" +
222             "  -printtoconsole  \t  "   + _("Send trace/debug info to console instead of debug.log file") + "\n" +
223 #ifdef WIN32
224             "  -printtodebugger \t  "   + _("Send trace/debug info to debugger") + "\n" +
225 #endif
226             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections") + "\n" +
227             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections") + "\n" +
228             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
229             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
230             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
231             "  -blocknotify=<cmd> "     + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
232             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)") + "\n" +
233             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions") + "\n";
234
235 #ifdef USE_SSL
236         strUsage += string() +
237             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
238             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
239             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)") + "\n" +
240             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)") + "\n" +
241             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
242 #endif
243
244         strUsage += string() +
245             "  -?               \t\t  " + _("This help message") + "\n";
246
247         // Remove tabs
248         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
249         fprintf(stderr, "%s", strUsage.c_str());
250         return false;
251     }
252
253     fTestNet = GetBoolArg("-testnet");
254     fDebug = GetBoolArg("-debug");
255
256 #if !defined(WIN32) && !defined(GUI)
257     fDaemon = GetBoolArg("-daemon");
258 #else
259     fDaemon = false;
260 #endif
261
262     if (fDaemon)
263         fServer = true;
264     else
265         fServer = GetBoolArg("-server");
266
267     /* force fServer when running without GUI */
268 #if !defined(QT_GUI)
269     fServer = true;
270 #endif
271     fPrintToConsole = GetBoolArg("-printtoconsole");
272     fPrintToDebugger = GetBoolArg("-printtodebugger");
273     fLogTimestamps = GetBoolArg("-logtimestamps");
274
275 #ifndef QT_GUI
276     for (int i = 1; i < argc; i++)
277         if (!IsSwitchChar(argv[i][0]) && !(strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0))
278             fCommandLine = true;
279
280     if (fCommandLine)
281     {
282         int ret = CommandLineRPC(argc, argv);
283         exit(ret);
284     }
285 #endif
286
287 #if !defined(WIN32) && !defined(GUI)
288     if (fDaemon)
289     {
290         // Daemonize
291         pid_t pid = fork();
292         if (pid < 0)
293         {
294             fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
295             return false;
296         }
297         if (pid > 0)
298         {
299             CreatePidFile(GetPidFile(), pid);
300             return true;
301         }
302
303         pid_t sid = setsid();
304         if (sid < 0)
305             fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
306     }
307 #endif
308
309     if (!fDebug && !pszSetDataDir[0])
310         ShrinkDebugFile();
311     printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
312     printf("Bitcoin version %s\n", FormatFullVersion().c_str());
313     printf("Default data directory %s\n", GetDefaultDataDir().c_str());
314
315     if (GetBoolArg("-loadblockindextest"))
316     {
317         CTxDB txdb("r");
318         txdb.LoadBlockIndex();
319         PrintBlockTree();
320         return false;
321     }
322
323     // Make sure only a single bitcoin process is using the data directory.
324     string strLockFile = GetDataDir() + "/.lock";
325     FILE* file = fopen(strLockFile.c_str(), "a"); // empty lock file; created if it doesn't exist.
326     if (file) fclose(file);
327     static boost::interprocess::file_lock lock(strLockFile.c_str());
328     if (!lock.try_lock())
329     {
330         wxMessageBox(strprintf(_("Cannot obtain a lock on data directory %s.  Bitcoin is probably already running."), GetDataDir().c_str()), "Bitcoin");
331         return false;
332     }
333
334     std::ostringstream strErrors;
335     //
336     // Load data files
337     //
338     if (fDaemon)
339         fprintf(stdout, "bitcoin server starting\n");
340     int64 nStart;
341
342     InitMessage(_("Loading addresses..."));
343     printf("Loading addresses...\n");
344     nStart = GetTimeMillis();
345     if (!LoadAddresses())
346         strErrors << _("Error loading addr.dat") << "\n";
347     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
348
349     InitMessage(_("Loading block index..."));
350     printf("Loading block index...\n");
351     nStart = GetTimeMillis();
352     if (!LoadBlockIndex())
353         strErrors << _("Error loading blkindex.dat") << "\n";
354     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
355
356     InitMessage(_("Loading wallet..."));
357     printf("Loading wallet...\n");
358     nStart = GetTimeMillis();
359     bool fFirstRun;
360     pwalletMain = new CWallet("wallet.dat");
361     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
362     if (nLoadWalletRet != DB_LOAD_OK)
363     {
364         if (nLoadWalletRet == DB_CORRUPT)
365             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
366         else if (nLoadWalletRet == DB_TOO_NEW)
367             strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
368         else if (nLoadWalletRet == DB_NEED_REWRITE)
369         {
370             strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
371             wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
372             return false;
373         }
374         else
375             strErrors << _("Error loading wallet.dat") << "\n";
376     }
377     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
378
379     RegisterWallet(pwalletMain);
380
381     CBlockIndex *pindexRescan = pindexBest;
382     if (GetBoolArg("-rescan"))
383         pindexRescan = pindexGenesisBlock;
384     else
385     {
386         CWalletDB walletdb("wallet.dat");
387         CBlockLocator locator;
388         if (walletdb.ReadBestBlock(locator))
389             pindexRescan = locator.GetBlockIndex();
390     }
391     if (pindexBest != pindexRescan)
392     {
393         InitMessage(_("Rescanning..."));
394         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
395         nStart = GetTimeMillis();
396         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
397         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
398     }
399
400     InitMessage(_("Done loading"));
401     printf("Done loading\n");
402
403     //// debug print
404     printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
405     printf("nBestHeight = %d\n",            nBestHeight);
406     printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
407     printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
408     printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
409
410     if (!strErrors.str().empty())
411     {
412         wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
413         return false;
414     }
415
416     // Add wallet transactions that aren't already in a block to mapTransactions
417     pwalletMain->ReacceptWalletTransactions();
418
419     // Note: Bitcoin-QT stores several settings in the wallet, so we want
420     // to load the wallet BEFORE parsing command-line arguments, so
421     // the command-line/bitcoin.conf settings override GUI setting.
422
423     //
424     // Parameters
425     //
426     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
427     {
428         PrintBlockTree();
429         return false;
430     }
431
432     if (mapArgs.count("-timeout"))
433     {
434         int nNewTimeout = GetArg("-timeout", 5000);
435         if (nNewTimeout > 0 && nNewTimeout < 600000)
436             nConnectTimeout = nNewTimeout;
437     }
438
439     if (mapArgs.count("-printblock"))
440     {
441         string strMatch = mapArgs["-printblock"];
442         int nFound = 0;
443         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
444         {
445             uint256 hash = (*mi).first;
446             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
447             {
448                 CBlockIndex* pindex = (*mi).second;
449                 CBlock block;
450                 block.ReadFromDisk(pindex);
451                 block.BuildMerkleTree();
452                 block.print();
453                 printf("\n");
454                 nFound++;
455             }
456         }
457         if (nFound == 0)
458             printf("No blocks matching %s were found\n", strMatch.c_str());
459         return false;
460     }
461
462     fGenerateBitcoins = GetBoolArg("-gen");
463
464     if (mapArgs.count("-proxy"))
465     {
466         fUseProxy = true;
467         addrProxy = CService(mapArgs["-proxy"], 9050);
468         if (!addrProxy.IsValid())
469         {
470             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
471             return false;
472         }
473     }
474
475     bool fTor = (fUseProxy && addrProxy.GetPort() == 9050);
476     if (fTor)
477     {
478         // Use SoftSetBoolArg here so user can override any of these if they wish.
479         // Note: the GetBoolArg() calls for all of these must happen later.
480         SoftSetBoolArg("-listen", false);
481         SoftSetBoolArg("-irc", false);
482         SoftSetBoolArg("-dnsseed", false);
483         SoftSetBoolArg("-upnp", false);
484         SoftSetBoolArg("-dns", false);
485     }
486
487     fAllowDNS = GetBoolArg("-dns");
488     fNoListen = !GetBoolArg("-listen", true);
489
490     // This code can be removed once a super-majority of the network has upgraded.
491     if (GetBoolArg("-bip16", true))
492     {
493         if (fTestNet)
494             SoftSetArg("-paytoscripthashtime", "1329264000"); // Feb 15
495         else
496             SoftSetArg("-paytoscripthashtime", "1330578000"); // Mar 1
497
498         // Put "/P2SH/" in the coinbase so everybody can tell when
499         // a majority of miners support it
500         const char* pszP2SH = "/P2SH/";
501         COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
502     }
503     else
504     {
505         const char* pszP2SH = "NOP2SH";
506         COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
507     }
508
509     // Command-line args override in-wallet settings:
510 #if USE_UPNP
511     fUseUPnP = GetBoolArg("-upnp", true);
512 #else
513     fUseUPnP = GetBoolArg("-upnp", false);
514 #endif
515
516     if (!fNoListen)
517     {
518         std::string strError;
519         if (!BindListenPort(strError))
520         {
521             wxMessageBox(strError, "Bitcoin");
522             return false;
523         }
524     }
525
526     if (mapArgs.count("-addnode"))
527     {
528         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
529         {
530             CAddress addr(CService(strAddr, GetDefaultPort(), fAllowDNS));
531             addr.nTime = 0; // so it won't relay unless successfully connected
532             if (addr.IsValid())
533                 AddAddress(addr);
534         }
535     }
536
537     if (mapArgs.count("-paytxfee"))
538     {
539         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
540         {
541             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
542             return false;
543         }
544         if (nTransactionFee > 0.25 * COIN)
545             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
546     }
547
548     //
549     // Start the node
550     //
551     if (!CheckDiskSpace())
552         return false;
553
554     RandAddSeedPerfmon();
555
556     if (!CreateThread(StartNode, NULL))
557         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
558
559     if (fServer)
560         CreateThread(ThreadRPCServer, NULL);
561
562 #ifdef QT_GUI
563     if(GetStartOnSystemStartup())
564         SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
565 #endif
566
567 #if !defined(QT_GUI)
568     while (1)
569         Sleep(5000);
570 #endif
571
572     return true;
573 }
574
575 #ifdef WIN32
576 string StartupShortcutPath()
577 {
578     return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
579 }
580
581 bool GetStartOnSystemStartup()
582 {
583     return filesystem::exists(StartupShortcutPath().c_str());
584 }
585
586 bool SetStartOnSystemStartup(bool fAutoStart)
587 {
588     // If the shortcut exists already, remove it for updating
589     remove(StartupShortcutPath().c_str());
590
591     if (fAutoStart)
592     {
593         CoInitialize(NULL);
594
595         // Get a pointer to the IShellLink interface.
596         IShellLink* psl = NULL;
597         HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
598                                 CLSCTX_INPROC_SERVER, IID_IShellLink,
599                                 reinterpret_cast<void**>(&psl));
600
601         if (SUCCEEDED(hres))
602         {
603             // Get the current executable path
604             TCHAR pszExePath[MAX_PATH];
605             GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
606
607             TCHAR pszArgs[5] = TEXT("-min");
608
609             // Set the path to the shortcut target
610             psl->SetPath(pszExePath);
611             PathRemoveFileSpec(pszExePath);
612             psl->SetWorkingDirectory(pszExePath);
613             psl->SetShowCmd(SW_SHOWMINNOACTIVE);
614             psl->SetArguments(pszArgs);
615
616             // Query IShellLink for the IPersistFile interface for
617             // saving the shortcut in persistent storage.
618             IPersistFile* ppf = NULL;
619             hres = psl->QueryInterface(IID_IPersistFile,
620                                        reinterpret_cast<void**>(&ppf));
621             if (SUCCEEDED(hres))
622             {
623                 WCHAR pwsz[MAX_PATH];
624                 // Ensure that the string is ANSI.
625                 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
626                 // Save the link by calling IPersistFile::Save.
627                 hres = ppf->Save(pwsz, TRUE);
628                 ppf->Release();
629                 psl->Release();
630                 CoUninitialize();
631                 return true;
632             }
633             psl->Release();
634         }
635         CoUninitialize();
636         return false;
637     }
638     return true;
639 }
640
641 #elif defined(LINUX)
642
643 // Follow the Desktop Application Autostart Spec:
644 //  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
645
646 boost::filesystem::path GetAutostartDir()
647 {
648     namespace fs = boost::filesystem;
649
650     char* pszConfigHome = getenv("XDG_CONFIG_HOME");
651     if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
652     char* pszHome = getenv("HOME");
653     if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
654     return fs::path();
655 }
656
657 boost::filesystem::path GetAutostartFilePath()
658 {
659     return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
660 }
661
662 bool GetStartOnSystemStartup()
663 {
664     boost::filesystem::ifstream optionFile(GetAutostartFilePath());
665     if (!optionFile.good())
666         return false;
667     // Scan through file for "Hidden=true":
668     string line;
669     while (!optionFile.eof())
670     {
671         getline(optionFile, line);
672         if (line.find("Hidden") != string::npos &&
673             line.find("true") != string::npos)
674             return false;
675     }
676     optionFile.close();
677
678     return true;
679 }
680
681 bool SetStartOnSystemStartup(bool fAutoStart)
682 {
683     if (!fAutoStart)
684     {
685 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
686         unlink(GetAutostartFilePath().string().c_str());
687 #else
688         unlink(GetAutostartFilePath().native_file_string().c_str());
689 #endif
690     }
691     else
692     {
693         char pszExePath[MAX_PATH+1];
694         memset(pszExePath, 0, sizeof(pszExePath));
695         if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
696             return false;
697
698         boost::filesystem::create_directories(GetAutostartDir());
699
700         boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
701         if (!optionFile.good())
702             return false;
703         // Write a bitcoin.desktop file to the autostart directory:
704         optionFile << "[Desktop Entry]\n";
705         optionFile << "Type=Application\n";
706         optionFile << "Name=Bitcoin\n";
707         optionFile << "Exec=" << pszExePath << " -min\n";
708         optionFile << "Terminal=false\n";
709         optionFile << "Hidden=false\n";
710         optionFile.close();
711     }
712     return true;
713 }
714 #else
715
716 // TODO: OSX startup stuff; see:
717 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
718
719 bool GetStartOnSystemStartup() { return false; }
720 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
721
722 #endif