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