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