Implement "Start on window system startup" on Win32 + Linux.
[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     ParseParameters(argc, argv);
153
154     if (mapArgs.count("-datadir"))
155     {
156         if (filesystem::is_directory(filesystem::system_complete(mapArgs["-datadir"])))
157         {
158             filesystem::path pathDataDir = filesystem::system_complete(mapArgs["-datadir"]);
159             strlcpy(pszSetDataDir, pathDataDir.string().c_str(), sizeof(pszSetDataDir));
160         }
161         else
162         {
163             fprintf(stderr, "Error: Specified directory does not exist\n");
164             Shutdown(NULL);
165         }
166     }
167
168
169     ReadConfigFile(mapArgs, mapMultiArgs); // Must be done after processing datadir
170
171     if (mapArgs.count("-?") || mapArgs.count("--help"))
172     {
173         string strUsage = string() +
174           _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
175           _("Usage:") + "\t\t\t\t\t\t\t\t\t\t\n" +
176             "  bitcoind [options]                   \t  " + "\n" +
177             "  bitcoind [options] <command> [params]\t  " + _("Send command to -server or bitcoind") + "\n" +
178             "  bitcoind [options] help              \t\t  " + _("List commands") + "\n" +
179             "  bitcoind [options] help <command>    \t\t  " + _("Get help for a command") + "\n" +
180           _("Options:") + "\n" +
181             "  -conf=<file>     \t\t  " + _("Specify configuration file (default: bitcoin.conf)") + "\n" +
182             "  -pid=<file>      \t\t  " + _("Specify pid file (default: bitcoind.pid)") + "\n" +
183             "  -gen             \t\t  " + _("Generate coins") + "\n" +
184             "  -gen=0           \t\t  " + _("Don't generate coins") + "\n" +
185             "  -min             \t\t  " + _("Start minimized") + "\n" +
186             "  -datadir=<dir>   \t\t  " + _("Specify data directory") + "\n" +
187             "  -timeout=<n>     \t  "   + _("Specify connection timeout (in milliseconds)") + "\n" +
188             "  -proxy=<ip:port> \t  "   + _("Connect through socks4 proxy") + "\n" +
189             "  -dns             \t  "   + _("Allow DNS lookups for addnode and connect") + "\n" +
190             "  -port=<port>     \t\t  " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n" +
191             "  -maxconnections=<n>\t  " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
192             "  -addnode=<ip>    \t  "   + _("Add a node to connect to") + "\n" +
193             "  -connect=<ip>    \t\t  " + _("Connect only to the specified node") + "\n" +
194             "  -nolisten        \t  "   + _("Don't accept connections from outside") + "\n" +
195             "  -nodnsseed       \t  "   + _("Don't bootstrap list of peers using DNS") + "\n" +
196             "  -banscore=<n>    \t  "   + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
197             "  -bantime=<n>     \t  "   + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
198             "  -maxreceivebuffer=<n>\t  " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)") + "\n" +
199             "  -maxsendbuffer=<n>\t  "   + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)") + "\n" +
200 #ifdef USE_UPNP
201 #if USE_UPNP
202             "  -noupnp          \t  "   + _("Don't attempt to use UPnP to map the listening port") + "\n" +
203 #else
204             "  -upnp            \t  "   + _("Attempt to use UPnP to map the listening port") + "\n" +
205 #endif
206 #endif
207             "  -paytxfee=<amt>  \t  "   + _("Fee per KB to add to transactions you send") + "\n" +
208 #ifdef GUI
209             "  -server          \t\t  " + _("Accept command line and JSON-RPC commands") + "\n" +
210 #endif
211 #ifndef WIN32
212             "  -daemon          \t\t  " + _("Run in the background as a daemon and accept commands") + "\n" +
213 #endif
214             "  -testnet         \t\t  " + _("Use the test network") + "\n" +
215             "  -debug           \t\t  " + _("Output extra debugging information") + "\n" +
216             "  -logtimestamps   \t  "   + _("Prepend debug output with timestamp") + "\n" +
217             "  -printtoconsole  \t  "   + _("Send trace/debug info to console instead of debug.log file") + "\n" +
218 #ifdef WIN32
219             "  -printtodebugger \t  "   + _("Send trace/debug info to debugger") + "\n" +
220 #endif
221             "  -rpcuser=<user>  \t  "   + _("Username for JSON-RPC connections") + "\n" +
222             "  -rpcpassword=<pw>\t  "   + _("Password for JSON-RPC connections") + "\n" +
223             "  -rpcport=<port>  \t\t  " + _("Listen for JSON-RPC connections on <port> (default: 8332)") + "\n" +
224             "  -rpcallowip=<ip> \t\t  " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
225             "  -rpcconnect=<ip> \t  "   + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
226             "  -keypool=<n>     \t  "   + _("Set key pool size to <n> (default: 100)") + "\n" +
227             "  -rescan          \t  "   + _("Rescan the block chain for missing wallet transactions") + "\n";
228
229 #ifdef USE_SSL
230         strUsage += string() +
231             _("\nSSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" +
232             "  -rpcssl                                \t  " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
233             "  -rpcsslcertificatechainfile=<file.cert>\t  " + _("Server certificate file (default: server.cert)") + "\n" +
234             "  -rpcsslprivatekeyfile=<file.pem>       \t  " + _("Server private key (default: server.pem)") + "\n" +
235             "  -rpcsslciphers=<ciphers>               \t  " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
236 #endif
237
238         strUsage += string() +
239             "  -?               \t\t  " + _("This help message") + "\n";
240
241         // Remove tabs
242         strUsage.erase(std::remove(strUsage.begin(), strUsage.end(), '\t'), strUsage.end());
243         fprintf(stderr, "%s", strUsage.c_str());
244         return false;
245     }
246
247     fDebug = GetBoolArg("-debug");
248     fAllowDNS = GetBoolArg("-dns");
249
250 #ifndef WIN32
251     fDaemon = GetBoolArg("-daemon");
252 #else
253     fDaemon = false;
254 #endif
255
256     if (fDaemon)
257         fServer = true;
258     else
259         fServer = GetBoolArg("-server");
260
261     /* force fServer when running without GUI */
262 #if !defined(QT_GUI)
263     fServer = true;
264 #endif
265     fPrintToConsole = GetBoolArg("-printtoconsole");
266     fPrintToDebugger = GetBoolArg("-printtodebugger");
267
268     fTestNet = GetBoolArg("-testnet");
269     bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
270     fNoListen = GetBoolArg("-nolisten") || fTOR;
271     fLogTimestamps = GetBoolArg("-logtimestamps");
272
273 #ifndef QT_GUI
274     for (int i = 1; i < argc; i++)
275         if (!IsSwitchChar(argv[i][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     // Bind to the port early so we can tell if another instance is already running.
333     if (!fNoListen)
334     {
335         std::string strError;
336         if (!BindListenPort(strError))
337         {
338             wxMessageBox(strError, "Bitcoin");
339             return false;
340         }
341     }
342
343     std::ostringstream strErrors;
344     //
345     // Load data files
346     //
347     if (fDaemon)
348         fprintf(stdout, "bitcoin server starting\n");
349     int64 nStart;
350
351     InitMessage(_("Loading addresses..."));
352     printf("Loading addresses...\n");
353     nStart = GetTimeMillis();
354     if (!LoadAddresses())
355         strErrors << _("Error loading addr.dat") << "\n";
356     printf(" addresses   %15"PRI64d"ms\n", GetTimeMillis() - nStart);
357
358     InitMessage(_("Loading block index..."));
359     printf("Loading block index...\n");
360     nStart = GetTimeMillis();
361     if (!LoadBlockIndex())
362         strErrors << _("Error loading blkindex.dat") << "\n";
363     printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
364
365     InitMessage(_("Loading wallet..."));
366     printf("Loading wallet...\n");
367     nStart = GetTimeMillis();
368     bool fFirstRun;
369     pwalletMain = new CWallet("wallet.dat");
370     int nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
371     if (nLoadWalletRet != DB_LOAD_OK)
372     {
373         if (nLoadWalletRet == DB_CORRUPT)
374             strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
375         else if (nLoadWalletRet == DB_TOO_NEW)
376             strErrors << _("Error loading wallet.dat: Wallet requires newer version of Bitcoin") << "\n";
377         else if (nLoadWalletRet == DB_NEED_REWRITE)
378         {
379             strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
380             wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
381             return false;
382         }
383         else
384             strErrors << _("Error loading wallet.dat") << "\n";
385     }
386     printf(" wallet      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
387
388     RegisterWallet(pwalletMain);
389
390     CBlockIndex *pindexRescan = pindexBest;
391     if (GetBoolArg("-rescan"))
392         pindexRescan = pindexGenesisBlock;
393     else
394     {
395         CWalletDB walletdb("wallet.dat");
396         CBlockLocator locator;
397         if (walletdb.ReadBestBlock(locator))
398             pindexRescan = locator.GetBlockIndex();
399     }
400     if (pindexBest != pindexRescan)
401     {
402         InitMessage(_("Rescanning..."));
403         printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
404         nStart = GetTimeMillis();
405         pwalletMain->ScanForWalletTransactions(pindexRescan, true);
406         printf(" rescan      %15"PRI64d"ms\n", GetTimeMillis() - nStart);
407     }
408
409     InitMessage(_("Done loading"));
410     printf("Done loading\n");
411
412     //// debug print
413     printf("mapBlockIndex.size() = %d\n",   mapBlockIndex.size());
414     printf("nBestHeight = %d\n",            nBestHeight);
415     printf("setKeyPool.size() = %d\n",      pwalletMain->setKeyPool.size());
416     printf("mapWallet.size() = %d\n",       pwalletMain->mapWallet.size());
417     printf("mapAddressBook.size() = %d\n",  pwalletMain->mapAddressBook.size());
418
419     if (!strErrors.str().empty())
420     {
421         wxMessageBox(strErrors.str(), "Bitcoin", wxOK | wxICON_ERROR);
422         return false;
423     }
424
425     // Add wallet transactions that aren't already in a block to mapTransactions
426     pwalletMain->ReacceptWalletTransactions();
427
428     //
429     // Parameters
430     //
431     if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
432     {
433         PrintBlockTree();
434         return false;
435     }
436
437     if (mapArgs.count("-timeout"))
438     {
439         int nNewTimeout = GetArg("-timeout", 5000);
440         if (nNewTimeout > 0 && nNewTimeout < 600000)
441             nConnectTimeout = nNewTimeout;
442     }
443
444     if (mapArgs.count("-printblock"))
445     {
446         string strMatch = mapArgs["-printblock"];
447         int nFound = 0;
448         for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
449         {
450             uint256 hash = (*mi).first;
451             if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
452             {
453                 CBlockIndex* pindex = (*mi).second;
454                 CBlock block;
455                 block.ReadFromDisk(pindex);
456                 block.BuildMerkleTree();
457                 block.print();
458                 printf("\n");
459                 nFound++;
460             }
461         }
462         if (nFound == 0)
463             printf("No blocks matching %s were found\n", strMatch.c_str());
464         return false;
465     }
466
467     fGenerateBitcoins = GetBoolArg("-gen");
468
469     if (mapArgs.count("-proxy"))
470     {
471         fUseProxy = true;
472         addrProxy = CAddress(mapArgs["-proxy"]);
473         if (!addrProxy.IsValid())
474         {
475             wxMessageBox(_("Invalid -proxy address"), "Bitcoin");
476             return false;
477         }
478     }
479
480     if (mapArgs.count("-addnode"))
481     {
482         BOOST_FOREACH(string strAddr, mapMultiArgs["-addnode"])
483         {
484             CAddress addr(strAddr, fAllowDNS);
485             addr.nTime = 0; // so it won't relay unless successfully connected
486             if (addr.IsValid())
487                 AddAddress(addr);
488         }
489     }
490
491     if (mapArgs.count("-paytxfee"))
492     {
493         if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
494         {
495             wxMessageBox(_("Invalid amount for -paytxfee=<amount>"), "Bitcoin");
496             return false;
497         }
498         if (nTransactionFee > 0.25 * COIN)
499             wxMessageBox(_("Warning: -paytxfee is set very high.  This is the transaction fee you will pay if you send a transaction."), "Bitcoin", wxOK | wxICON_EXCLAMATION);
500     }
501
502     if (fHaveUPnP)
503     {
504 #if USE_UPNP
505     if (GetBoolArg("-noupnp"))
506         fUseUPnP = false;
507 #else
508     if (GetBoolArg("-upnp"))
509         fUseUPnP = true;
510 #endif
511     }
512
513     //
514     // Start the node
515     //
516     if (!CheckDiskSpace())
517         return false;
518
519     RandAddSeedPerfmon();
520
521     if (!CreateThread(StartNode, NULL))
522         wxMessageBox(_("Error: CreateThread(StartNode) failed"), "Bitcoin");
523
524     if (fServer)
525         CreateThread(ThreadRPCServer, NULL);
526
527 #ifdef QT_GUI
528     if(GetStartOnSystemStartup())
529         SetStartOnSystemStartup(true); // Remove startup links to bitcoin-wx
530 #endif
531
532 #if !defined(QT_GUI)
533     while (1)
534         Sleep(5000);
535 #endif
536
537     return true;
538 }
539
540 #ifdef WIN32
541 string StartupShortcutPath()
542 {
543     return MyGetSpecialFolderPath(CSIDL_STARTUP, true) + "\\Bitcoin.lnk";
544 }
545
546 bool GetStartOnSystemStartup()
547 {
548     return filesystem::exists(StartupShortcutPath().c_str());
549 }
550
551 bool SetStartOnSystemStartup(bool fAutoStart)
552 {
553     // If the shortcut exists already, remove it for updating
554     remove(StartupShortcutPath().c_str());
555
556     if (fAutoStart)
557     {
558         CoInitialize(NULL);
559
560         // Get a pointer to the IShellLink interface.
561         IShellLink* psl = NULL;
562         HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
563                                 CLSCTX_INPROC_SERVER, IID_IShellLink,
564                                 reinterpret_cast<void**>(&psl));
565
566         if (SUCCEEDED(hres))
567         {
568             // Get the current executable path
569             TCHAR pszExePath[MAX_PATH];
570             GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
571
572             TCHAR pszArgs[5] = TEXT("-min");
573
574             // Set the path to the shortcut target
575             psl->SetPath(pszExePath);
576             PathRemoveFileSpec(pszExePath);
577             psl->SetWorkingDirectory(pszExePath);
578             psl->SetShowCmd(SW_SHOWMINNOACTIVE);
579             psl->SetArguments(pszArgs);
580
581             // Query IShellLink for the IPersistFile interface for
582             // saving the shortcut in persistent storage.
583             IPersistFile* ppf = NULL;
584             hres = psl->QueryInterface(IID_IPersistFile,
585                                        reinterpret_cast<void**>(&ppf));
586             if (SUCCEEDED(hres))
587             {
588                 WCHAR pwsz[MAX_PATH];
589                 // Ensure that the string is ANSI.
590                 MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().c_str(), -1, pwsz, MAX_PATH);
591                 // Save the link by calling IPersistFile::Save.
592                 hres = ppf->Save(pwsz, TRUE);
593                 ppf->Release();
594                 psl->Release();
595                 CoUninitialize();
596                 return true;
597             }
598             psl->Release();
599         }
600         CoUninitialize();
601         return false;
602     }
603     return true;
604 }
605
606 #elif defined(LINUX)
607
608 // Follow the Desktop Application Autostart Spec:
609 //  http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
610
611 boost::filesystem::path GetAutostartDir()
612 {
613     namespace fs = boost::filesystem;
614
615     char* pszConfigHome = getenv("XDG_CONFIG_HOME");
616     if (pszConfigHome) return fs::path(pszConfigHome) / fs::path("autostart");
617     char* pszHome = getenv("HOME");
618     if (pszHome) return fs::path(pszHome) / fs::path(".config/autostart");
619     return fs::path();
620 }
621
622 boost::filesystem::path GetAutostartFilePath()
623 {
624     return GetAutostartDir() / boost::filesystem::path("bitcoin.desktop");
625 }
626
627 bool GetStartOnSystemStartup()
628 {
629     boost::filesystem::ifstream optionFile(GetAutostartFilePath());
630     if (!optionFile.good())
631         return false;
632     // Scan through file for "Hidden=true":
633     string line;
634     while (!optionFile.eof())
635     {
636         getline(optionFile, line);
637         if (line.find("Hidden") != string::npos &&
638             line.find("true") != string::npos)
639             return false;
640     }
641     optionFile.close();
642
643     return true;
644 }
645
646 bool SetStartOnSystemStartup(bool fAutoStart)
647 {
648     if (!fAutoStart)
649     {
650 #if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION >= 3
651         unlink(GetAutostartFilePath().string().c_str());
652 #else
653         unlink(GetAutostartFilePath().native_file_string().c_str());
654 #endif
655     }
656     else
657     {
658         char pszExePath[MAX_PATH+1];
659         memset(pszExePath, 0, sizeof(pszExePath));
660         if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
661             return false;
662
663         boost::filesystem::create_directories(GetAutostartDir());
664
665         boost::filesystem::ofstream optionFile(GetAutostartFilePath(), ios_base::out|ios_base::trunc);
666         if (!optionFile.good())
667             return false;
668         // Write a bitcoin.desktop file to the autostart directory:
669         optionFile << "[Desktop Entry]\n";
670         optionFile << "Type=Application\n";
671         optionFile << "Name=Bitcoin\n";
672         optionFile << "Exec=" << pszExePath << " -min\n";
673         optionFile << "Terminal=false\n";
674         optionFile << "Hidden=false\n";
675         optionFile.close();
676     }
677     return true;
678 }
679 #else
680
681 // TODO: OSX startup stuff; see:
682 // http://developer.apple.com/mac/library/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
683
684 bool GetStartOnSystemStartup() { return false; }
685 bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
686
687 #endif