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