Whitespace
[amule.git] / src / amuleAppCommon.cpp
blob78f7c731b39253238441350a9f68e93b86400a99
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5 //
6 // Any parts of this program derived from the xMule, lMule or eMule project,
7 // or contributed by third-party developers are copyrighted by their
8 // respective authors.
9 //
10 // This program is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU General Public License as published by
12 // the Free Software Foundation; either version 2 of the License, or
13 // (at your option) any later version.
15 // This program is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 // This file is for functions common to all three apps (amule, amuled, amulegui),
27 // but preprocessor-dependent (using theApp, thePrefs), so it is compiled seperately for each app.
31 #include <wx/wx.h>
32 #include <wx/cmdline.h> // Needed for wxCmdLineParser
33 #include <wx/snglinst.h> // Needed for wxSingleInstanceChecker
34 #include <wx/textfile.h> // Needed for wxTextFile
35 #include <wx/config.h> // Do_not_auto_remove (win32)
36 #include <wx/fileconf.h>
38 #include "amule.h" // Interface declarations.
39 #include <common/Format.h> // Needed for CFormat
40 #include "CFile.h" // Needed for CFile
41 #include "ED2KLink.h" // Needed for command line passing of links
42 #include "FileLock.h" // Needed for CFileLock
43 #include "GuiEvents.h" // Needed for Notify_*
44 #include "KnownFile.h"
45 #include "Logger.h"
46 #include "MagnetURI.h" // Needed for CMagnetURI
47 #include "Preferences.h"
48 #include "ScopedPtr.h"
50 #ifndef CLIENT_GUI
51 #include "DownloadQueue.h"
52 #endif
54 CamuleAppCommon::CamuleAppCommon()
56 m_singleInstance = NULL;
57 ec_config = false;
58 m_geometryEnabled = false;
59 if (IsRemoteGui()) {
60 m_appName = wxT("aMuleGUI");
61 m_configFile = wxT("remote.conf");
62 m_logFile = wxT("remotelogfile");
63 } else {
64 m_configFile = wxT("amule.conf");
65 m_logFile = wxT("logfile");
67 if (IsDaemon()) {
68 m_appName = wxT("aMuleD");
69 } else {
70 m_appName = wxT("aMule");
75 CamuleAppCommon::~CamuleAppCommon()
77 #if defined(__WXMAC__) && defined(AMULE_DAEMON)
78 //#warning TODO: fix wxSingleInstanceChecker for amuled on Mac (wx link problems)
79 #else
80 delete m_singleInstance;
81 #endif
84 void CamuleAppCommon::RefreshSingleInstanceChecker()
86 #if defined(__WXMAC__) && defined(AMULE_DAEMON)
87 //#warning TODO: fix wxSingleInstanceChecker for amuled on Mac (wx link problems)
88 #else
89 delete m_singleInstance;
90 m_singleInstance = new wxSingleInstanceChecker(wxT("muleLock"), thePrefs::GetConfigDir());
91 #endif
94 void CamuleAppCommon::AddLinksFromFile()
96 const wxString fullPath = thePrefs::GetConfigDir() + wxT("ED2KLinks");
97 if (!wxFile::Exists(fullPath)) {
98 return;
101 // Attempt to lock the ED2KLinks file.
102 CFileLock lock((const char*)unicode2char(fullPath));
104 wxTextFile file(fullPath);
105 if ( file.Open() ) {
106 for ( unsigned int i = 0; i < file.GetLineCount(); i++ ) {
107 wxString line = file.GetLine( i ).Strip( wxString::both );
109 if ( !line.IsEmpty() ) {
110 // Special case! used by a secondary running mule to raise this one.
111 if (line == wxT("RAISE_DIALOG")) {
112 Notify_ShowGUI();
113 continue;
115 unsigned long category = 0;
116 if (line.AfterLast(wxT(':')).ToULong(&category) == true) {
117 line = line.BeforeLast(wxT(':'));
118 } else { // If ToULong returns false the category still can have been changed!
119 // This is fixed in wx 2.9
120 category = 0;
122 theApp->downloadqueue->AddLink(line, category);
126 file.Close();
127 } else {
128 AddLogLineNS(_("Failed to open ED2KLinks file."));
131 // Delete the file.
132 wxRemoveFile(thePrefs::GetConfigDir() + wxT("ED2KLinks"));
136 // Returns a magnet ed2k URI
137 wxString CamuleAppCommon::CreateMagnetLink(const CAbstractFile *f)
139 CMagnetURI uri;
141 uri.AddField(wxT("dn"), f->GetFileName().Cleanup(false).GetPrintable());
142 uri.AddField(wxT("xt"), wxString(wxT("urn:ed2k:")) + f->GetFileHash().Encode().Lower());
143 uri.AddField(wxT("xt"), wxString(wxT("urn:ed2khash:")) + f->GetFileHash().Encode().Lower());
144 uri.AddField(wxT("xl"), CFormat(wxT("%d")) % f->GetFileSize());
146 return uri.GetLink();
150 // Returns a ed2k file URL
151 wxString CamuleAppCommon::CreateED2kLink(const CAbstractFile *f, bool add_source, bool use_hostname, bool add_cryptoptions, bool add_AICH)
153 wxASSERT(!(!add_source && (use_hostname || add_cryptoptions)));
154 // Construct URL like this: ed2k://|file|<filename>|<size>|<hash>|/
155 wxString strURL = CFormat(wxT("ed2k://|file|%s|%i|%s|"))
156 % f->GetFileName().Cleanup(false)
157 % f->GetFileSize() % f->GetFileHash().Encode();
159 // Append the AICH info
160 if (add_AICH) {
161 const CKnownFile* kf = dynamic_cast<const CKnownFile*>(f);
162 if (kf && kf->HasProperAICHHashSet()) {
163 strURL << wxT("h=") << kf->GetAICHMasterHash() << wxT("|");
167 strURL << wxT("/");
169 if (add_source && theApp->IsConnected() && !theApp->IsFirewalled()) {
170 // Create the first part of the URL
171 strURL << wxT("|sources,");
172 if (use_hostname) {
173 strURL << thePrefs::GetYourHostname();
174 } else {
175 uint32 clientID = theApp->GetID();
176 strURL = CFormat(wxT("%s%u.%u.%u.%u"))
177 % strURL
178 % (clientID & 0xff)
179 % ((clientID >> 8) & 0xff)
180 % ((clientID >> 16) & 0xff)
181 % ((clientID >> 24) & 0xff);
184 strURL << wxT(":") <<
185 thePrefs::GetPort();
187 if (add_cryptoptions) {
188 uint8 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
189 uint8 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
190 uint8 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
191 uint16 byCryptOptions = (uRequiresCryptLayer << 2) | (uRequestsCryptLayer << 1) | (uSupportsCryptLayer << 0) | (uSupportsCryptLayer ? 0x80 : 0x00);
193 strURL << wxT(":") << byCryptOptions;
195 if (byCryptOptions & 0x80) {
196 strURL << wxT(":") << thePrefs::GetUserHash().Encode();
199 strURL << wxT("|/");
200 } else if (add_source) {
201 AddLogLineC(_("WARNING: You can't add yourself as a source for an eD2k link while having a lowid."));
204 // Result is "ed2k://|file|<filename>|<size>|<hash>|[h=<AICH master hash>|]/|sources,[(<ip>|<hostname>):<port>[:cryptoptions[:hash]]]|/"
205 return strURL;
209 bool CamuleAppCommon::InitCommon(int argc, wxChar ** argv)
211 theApp->SetAppName(wxT("aMule"));
212 FullMuleVersion = GetFullMuleVersion();
213 OSDescription = wxGetOsDescription();
214 OSType = OSDescription.BeforeFirst( wxT(' ') );
215 if ( OSType.IsEmpty() ) {
216 OSType = wxT("Unknown");
219 // Parse cmdline arguments.
220 wxCmdLineParser cmdline(argc, argv);
222 // Handle these arguments.
223 cmdline.AddSwitch(wxT("v"), wxT("version"), wxT("Displays the current version number."));
224 cmdline.AddSwitch(wxT("h"), wxT("help"), wxT("Displays this information."));
225 cmdline.AddOption(wxT("c"), wxT("config-dir"), wxT("read config from <dir> instead of home"));
226 #ifdef AMULE_DAEMON
227 cmdline.AddSwitch(wxT("f"), wxT("full-daemon"), wxT("Fork to background."));
228 cmdline.AddOption(wxT("p"), wxT("pid-file"), wxT("After fork, create a pid-file in the given fullname file."));
229 cmdline.AddSwitch(wxT("e"), wxT("ec-config"), wxT("Configure EC (External Connections)."));
230 #else
232 #ifdef __WINDOWS__
233 // MSW shows help otions in a dialog box, and the formatting doesn't fit there
234 #define HELPTAB wxT("\t")
235 #else
236 #define HELPTAB wxT("\t\t\t")
237 #endif
239 cmdline.AddOption(wxT("geometry"), wxEmptyString,
240 wxT("Sets the geometry of the app.\n")
241 HELPTAB wxT("<str> uses the same format as standard X11 apps:\n")
242 HELPTAB wxT("[=][<width>{xX}<height>][{+-}<xoffset>{+-}<yoffset>]"));
243 #endif // !AMULE_DAEMON
245 cmdline.AddSwitch(wxT("o"), wxT("log-stdout"), wxT("Print log messages to stdout."));
246 cmdline.AddSwitch(wxT("r"), wxT("reset-config"), wxT("Resets config to default values."));
248 #ifdef CLIENT_GUI
249 cmdline.AddSwitch(wxT("s"), wxT("skip"), wxT("Skip connection dialog."));
250 #else
251 // Change webserver path. This is also a config option, so this switch will go at some time.
252 cmdline.AddOption(wxT("w"), wxT("use-amuleweb"), wxT("Specify location of amuleweb binary."));
253 #endif
254 #ifndef __WINDOWS__
255 cmdline.AddSwitch(wxT("d"), wxT("disable-fatal"), wxT("Do not handle fatal exception."));
256 // Keep stdin open to run valgrind --gen_suppressions
257 cmdline.AddSwitch(wxT("i"), wxT("enable-stdin"), wxT("Do not disable stdin."));
258 #endif
260 // Allow passing of links to the app
261 cmdline.AddOption(wxT("t"), wxT("category"), wxT("Set category for passed ED2K links."), wxCMD_LINE_VAL_NUMBER);
262 cmdline.AddParam(wxT("ED2K link"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE);
264 // wx asserts in debug mode if there is a check for an option that wasn't added.
265 // So we have to wrap around the same #ifdefs as above. >:(
267 // Show help on --help or invalid commands
268 if ( cmdline.Parse() ) {
269 return false;
270 } else if (cmdline.Found(wxT("help"))) {
271 cmdline.Usage();
272 return false;
275 if ( cmdline.Found(wxT("version"))) {
276 // This looks silly with logging macros that add a timestamp.
277 printf("%s\n", (const char*)unicode2char(wxString(CFormat(wxT("%s (OS: %s)")) % FullMuleVersion % OSType)));
278 return false;
281 wxString configdir;
282 if (cmdline.Found(wxT("config-dir"), &configdir)) {
283 // Make an absolute path from the config dir
284 wxFileName fn(configdir);
285 fn.MakeAbsolute();
286 configdir = fn.GetFullPath();
287 if (configdir.Last() != wxFileName::GetPathSeparator()) {
288 configdir += wxFileName::GetPathSeparator();
290 thePrefs::SetConfigDir(configdir);
291 } else {
292 thePrefs::SetConfigDir(/*OtherFunctions::*/GetConfigDir(m_configFile));
295 // Backtracing works in MSW.
296 // Problem is just that the backtraces are useless, because apparently the context gets lost
297 // in the try/catch somewhere.
298 // So leave it out.
299 #ifndef __WINDOWS__
300 #if wxUSE_ON_FATAL_EXCEPTION
301 if ( !cmdline.Found(wxT("disable-fatal")) ) {
302 // catch fatal exceptions
303 wxHandleFatalExceptions(true);
305 #endif
306 #endif
308 theLogger.SetEnabledStdoutLog(cmdline.Found(wxT("log-stdout")));
309 #ifdef AMULE_DAEMON
310 enable_daemon_fork = cmdline.Found(wxT("full-daemon"));
311 if ( cmdline.Found(wxT("pid-file"), &m_PidFile) ) {
312 // Remove any existing PidFile
313 if ( wxFileExists (m_PidFile) ) wxRemoveFile (m_PidFile);
315 ec_config = cmdline.Found(wxT("ec-config"));
316 #else
317 enable_daemon_fork = false;
319 // Default geometry of the GUI. Can be changed with a cmdline argument...
320 if ( cmdline.Found(wxT("geometry"), &m_geometryString) ) {
321 m_geometryEnabled = true;
323 #endif
325 if (theLogger.IsEnabledStdoutLog()) {
326 if ( enable_daemon_fork ) {
327 AddLogLineNS(wxT("Daemon will fork to background - log to stdout disabled")); // localization not active yet
328 theLogger.SetEnabledStdoutLog(false);
329 } else {
330 AddLogLineNS(wxT("Logging to stdout enabled"));
334 AddLogLineNS(wxT("Initialising ") + FullMuleVersion);
336 // Ensure that "~/.aMule/" is accessible.
337 CPath outDir;
338 if (!CheckMuleDirectory(wxT("configuration"), CPath(thePrefs::GetConfigDir()), wxEmptyString, outDir)) {
339 return false;
342 if (cmdline.Found(wxT("reset-config"))) {
343 // Make a backup first.
344 wxRemoveFile(thePrefs::GetConfigDir() + m_configFile + wxT(".backup"));
345 wxRenameFile(thePrefs::GetConfigDir() + m_configFile, thePrefs::GetConfigDir() + m_configFile + wxT(".backup"));
346 AddLogLineNS(CFormat(wxT("Your settings have been reset to default values.\nThe old config file has been saved as %s.backup\n")) % m_configFile);
349 size_t linksPassed = cmdline.GetParamCount(); // number of links from the command line
350 // cppcheck-suppress variableScope
351 int linksActuallyPassed = 0; // number of links that pass the syntax check
352 if (linksPassed) {
353 long cat = 0;
354 if (!cmdline.Found(wxT("t"), &cat)) {
355 cat = 0;
358 wxTextFile ed2kFile(thePrefs::GetConfigDir() + wxT("ED2KLinks"));
359 if (!ed2kFile.Exists()) {
360 ed2kFile.Create();
362 if (ed2kFile.Open()) {
363 for (size_t i = 0; i < linksPassed; i++) {
364 wxString link;
365 if (CheckPassedLink(cmdline.GetParam(i), link, cat)) {
366 ed2kFile.AddLine(link);
367 linksActuallyPassed++;
370 ed2kFile.Write();
371 } else {
372 AddLogLineCS(wxT("Failed to open 'ED2KLinks', cannot add links."));
376 #if defined(__WXMAC__) && defined(AMULE_DAEMON)
377 //#warning TODO: fix wxSingleInstanceChecker for amuled on Mac (wx link problems)
378 AddLogLineCS(wxT("WARNING: The check for other instances is currently disabled in amuled.\n"
379 "Please make sure that no other instance of aMule is running or your files might be corrupted.\n"));
380 #else
381 AddLogLineNS(wxT("Checking if there is an instance already running..."));
383 m_singleInstance = new wxSingleInstanceChecker();
384 wxString lockfile = IsRemoteGui() ? wxT("muleLockRGUI") : wxT("muleLock");
385 if (m_singleInstance->Create(lockfile, thePrefs::GetConfigDir())
386 && m_singleInstance->IsAnotherRunning()) {
387 AddLogLineCS(CFormat(wxT("There is an instance of %s already running")) % m_appName);
388 AddLogLineNS(CFormat(wxT("(lock file: %s%s)")) % thePrefs::GetConfigDir() % lockfile);
389 if (linksPassed) {
390 AddLogLineNS(CFormat(wxT("passed %d %s to it, finished")) % linksActuallyPassed
391 % (linksPassed == 1 ? wxT("link") : wxT("links")));
392 return false;
395 // This is very tricky. The most secure way to communicate is via ED2K links file
396 wxTextFile ed2kFile(thePrefs::GetConfigDir() + wxT("ED2KLinks"));
397 if (!ed2kFile.Exists()) {
398 ed2kFile.Create();
401 if (ed2kFile.Open()) {
402 ed2kFile.AddLine(wxT("RAISE_DIALOG"));
403 ed2kFile.Write();
405 AddLogLineNS(wxT("Raising current running instance."));
406 } else {
407 AddLogLineCS(wxT("Failed to open 'ED2KFile', cannot signal running instance."));
410 return false;
411 } else {
412 AddLogLineNS(wxT("No other instances are running."));
414 #endif
416 #ifndef __WINDOWS__
417 // Close standard-input
418 if ( !cmdline.Found(wxT("enable-stdin")) ) {
419 // The full daemon will close all std file-descriptors by itself,
420 // so closing it here would lead to the closing on the first open
421 // file, which is the logfile opened below
422 if (!enable_daemon_fork) {
423 close(0);
426 #endif
428 // Create the CFG file we shall use and set the config object as the global cfg file
429 wxConfig::Set(new wxFileConfig( wxEmptyString, wxEmptyString, thePrefs::GetConfigDir() + m_configFile));
431 // Make a backup of the log file
432 CPath logfileName = CPath(thePrefs::GetConfigDir() + m_logFile);
433 if (logfileName.FileExists()) {
434 CPath::BackupFile(logfileName, wxT(".bak"));
437 // Open the log file
438 if (!theLogger.OpenLogfile(logfileName.GetRaw())) {
439 // use std err as last resolt to indicate problem
440 fputs("ERROR: unable to open log file\n", stderr);
441 // failure to open log is serious problem
442 return false;
445 // Load Preferences
446 CPreferences::BuildItemList(thePrefs::GetConfigDir());
447 CPreferences::LoadAllItems( wxConfigBase::Get() );
449 #ifdef CLIENT_GUI
450 m_skipConnectionDialog = cmdline.Found(wxT("skip"));
451 #else
452 wxString amulewebPath;
453 if (cmdline.Found(wxT("use-amuleweb"), &amulewebPath)) {
454 thePrefs::SetWSPath(amulewebPath);
455 AddLogLineNS(CFormat(wxT("Using amuleweb in '%s'.")) % amulewebPath);
457 #endif
459 return true;
463 * Returns a description of the version of aMule being used.
465 * @return A detailed description of the aMule version, including application
466 * name and wx information.
468 const wxString CamuleAppCommon::GetFullMuleVersion() const
470 return GetMuleAppName() + wxT(" ") + GetMuleVersion();
473 bool CamuleAppCommon::CheckPassedLink(const wxString &in, wxString &out, int cat)
475 wxString link(in);
477 // restore ASCII-encoded pipes
478 link.Replace(wxT("%7C"), wxT("|"));
479 link.Replace(wxT("%7c"), wxT("|"));
481 if (link.compare(0, 7, wxT("magnet:")) == 0) {
482 link = CMagnetED2KConverter(link);
483 if (link.empty()) {
484 AddLogLineCS(CFormat(wxT("Cannot convert magnet link to eD2k: %s")) % in);
485 return false;
489 try {
490 CScopedPtr<CED2KLink> uri(CED2KLink::CreateLinkFromUrl(link));
491 out = uri.get()->GetLink();
492 if (cat && uri.get()->GetKind() == CED2KLink::kFile) {
493 out += CFormat(wxT(":%d")) % cat;
495 return true;
496 } catch ( const wxString& err ) {
497 AddLogLineCS(CFormat(wxT("Invalid eD2k link \"%s\" - ERROR: %s")) % link % err);
499 return false;
504 * Checks permissions on a aMule directory, creating if needed.
506 * @param desc A description of the directory in question, used for error messages.
507 * @param directory The directory in question.
508 * @param alternative If the dir specified with 'directory' could not be created, try this instead.
509 * @param outDir Returns the used path.
510 * @return False on error.
512 bool CamuleAppCommon::CheckMuleDirectory(const wxString& desc, const CPath& directory, const wxString& alternative, CPath& outDir)
514 wxString msg;
516 if (directory.IsDir(CPath::readwritable)) {
517 outDir = directory;
518 return true;
519 } else if (directory.DirExists()) {
520 // Strings are not translated here because translation isn't up yet.
521 msg = CFormat(wxT("Permissions on the %s directory too strict!\n")
522 wxT("aMule cannot proceed. To fix this, you must set read/write/exec\n")
523 wxT("permissions for the folder '%s'"))
524 % desc % directory;
525 } else if (CPath::MakeDir(directory)) {
526 outDir = directory;
527 return true;
528 } else {
529 msg << CFormat(wxT("Could not create the %s directory at '%s'."))
530 % desc % directory;
533 // Attempt to use fallback directory.
534 const CPath fallback(alternative);
535 if (fallback.IsOk() && (directory != fallback)) {
536 msg << wxT("\nAttempting to use default directory at location \n'")
537 << alternative << wxT("'.");
538 if (theApp->ShowAlert(msg, wxT("Error accessing directory."), wxICON_ERROR | wxOK | wxCANCEL) == wxCANCEL) {
539 outDir = CPath(wxEmptyString);
540 return false;
543 return CheckMuleDirectory(desc, fallback, wxEmptyString, outDir);
546 theApp->ShowAlert(msg, wxT("Fatal error."), wxICON_ERROR | wxOK);
547 outDir = CPath(wxEmptyString);
548 return false;