2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
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
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.
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"
46 #include "MagnetURI.h" // Needed for CMagnetURI
47 #include "Preferences.h"
48 #include "ScopedPtr.h"
51 #include "DownloadQueue.h"
54 CamuleAppCommon::CamuleAppCommon()
56 m_singleInstance
= NULL
;
58 m_geometryEnabled
= false;
60 m_appName
= wxT("aMuleGUI");
61 m_configFile
= wxT("remote.conf");
62 m_logFile
= wxT("remotelogfile");
64 m_configFile
= wxT("amule.conf");
65 m_logFile
= wxT("logfile");
68 m_appName
= wxT("aMuleD");
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)
80 delete m_singleInstance
;
84 void CamuleAppCommon::RefreshSingleInstanceChecker()
86 #if defined(__WXMAC__) && defined(AMULE_DAEMON)
87 //#warning TODO: fix wxSingleInstanceChecker for amuled on Mac (wx link problems)
89 delete m_singleInstance
;
90 m_singleInstance
= new wxSingleInstanceChecker(wxT("muleLock"), ConfigDir
);
94 void CamuleAppCommon::AddLinksFromFile()
96 const wxString fullPath
= ConfigDir
+ wxT("ED2KLinks");
97 if (!wxFile::Exists(fullPath
)) {
101 // Attempt to lock the ED2KLinks file.
102 CFileLock
lock((const char*)unicode2char(fullPath
));
104 wxTextFile
file(fullPath
);
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")) {
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
122 theApp
->downloadqueue
->AddLink(line
, category
);
128 AddLogLineNS(_("Failed to open ED2KLinks file."));
132 wxRemoveFile(theApp
->ConfigDir
+ wxT("ED2KLinks"));
136 // Returns a magnet ed2k URI
137 wxString
CamuleAppCommon::CreateMagnetLink(const CAbstractFile
*f
)
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();
149 // Returns a ed2k file URL
150 wxString
CamuleAppCommon::CreateED2kLink(const CAbstractFile
*f
, bool add_source
, bool use_hostname
, bool addcryptoptions
)
152 wxASSERT(!(!add_source
&& (use_hostname
|| addcryptoptions
)));
153 // Construct URL like this: ed2k://|file|<filename>|<size>|<hash>|/
154 wxString strURL
= CFormat(wxT("ed2k://|file|%s|%i|%s|/"))
155 % f
->GetFileName().Cleanup(false)
156 % f
->GetFileSize() % f
->GetFileHash().Encode();
158 if (add_source
&& theApp
->IsConnected() && !theApp
->IsFirewalled()) {
159 // Create the first part of the URL
160 strURL
<< wxT("|sources,");
162 strURL
<< thePrefs::GetYourHostname();
164 uint32 clientID
= theApp
->GetID();
165 strURL
= CFormat(wxT("%s%u.%u.%u.%u"))
168 % ((clientID
>> 8) & 0xff)
169 % ((clientID
>> 16) & 0xff)
170 % ((clientID
>> 24) & 0xff);
173 strURL
<< wxT(":") <<
176 if (addcryptoptions
) {
177 uint8 uSupportsCryptLayer
= thePrefs::IsClientCryptLayerSupported() ? 1 : 0;
178 uint8 uRequestsCryptLayer
= thePrefs::IsClientCryptLayerRequested() ? 1 : 0;
179 uint8 uRequiresCryptLayer
= thePrefs::IsClientCryptLayerRequired() ? 1 : 0;
180 uint16 byCryptOptions
= (uRequiresCryptLayer
<< 2) | (uRequestsCryptLayer
<< 1) | (uSupportsCryptLayer
<< 0) | (uSupportsCryptLayer
? 0x80 : 0x00);
182 strURL
<< wxT(":") << byCryptOptions
;
184 if (byCryptOptions
& 0x80) {
185 strURL
<< wxT(":") << thePrefs::GetUserHash().Encode();
189 } else if (add_source
) {
190 AddLogLineC(_("WARNING: You can't add yourself as a source for an eD2k link while having a lowid."));
193 // Result is "ed2k://|file|<filename>|<size>|<hash>|/|sources,[(<ip>|<hostname>):<port>[:cryptoptions[:hash]]]|/"
197 // Returns a ed2k link with AICH info if available
198 wxString
CamuleAppCommon::CreateED2kAICHLink(const CKnownFile
* f
)
200 // Create the first part of the URL
201 wxString strURL
= CreateED2kLink(f
);
202 // Append the AICH info
203 if (f
->HasProperAICHHashSet()) {
204 strURL
.RemoveLast(); // remove trailing '/'
205 strURL
<< wxT("h=") << f
->GetAICHMasterHash() << wxT("|/");
208 // Result is "ed2k://|file|<filename>|<size>|<hash>|h=<AICH master hash>|/"
212 bool CamuleAppCommon::InitCommon(int argc
, wxChar
** argv
)
214 theApp
->SetAppName(wxT("aMule"));
215 wxString FullMuleVersion
= GetFullMuleVersion();
216 wxString OSDescription
= wxGetOsDescription();
217 strFullMuleVersion
= strdup((const char *)unicode2char(FullMuleVersion
));
218 strOSDescription
= strdup((const char *)unicode2char(OSDescription
));
219 OSType
= OSDescription
.BeforeFirst( wxT(' ') );
220 if ( OSType
.IsEmpty() ) {
221 OSType
= wxT("Unknown");
224 // Parse cmdline arguments.
225 wxCmdLineParser
cmdline(argc
, argv
);
227 // Handle these arguments.
228 cmdline
.AddSwitch(wxT("v"), wxT("version"), wxT("Displays the current version number."));
229 cmdline
.AddSwitch(wxT("h"), wxT("help"), wxT("Displays this information."));
230 cmdline
.AddOption(wxT("c"), wxT("config-dir"), wxT("read config from <dir> instead of home"));
232 cmdline
.AddSwitch(wxT("f"), wxT("full-daemon"), wxT("Fork to background."));
233 cmdline
.AddOption(wxT("p"), wxT("pid-file"), wxT("After fork, create a pid-file in the given fullname file."));
234 cmdline
.AddSwitch(wxT("e"), wxT("ec-config"), wxT("Configure EC (External Connections)."));
238 // MSW shows help otions in a dialog box, and the formatting doesn't fit there
239 #define HELPTAB wxT("\t")
241 #define HELPTAB wxT("\t\t\t")
244 cmdline
.AddOption(wxT("geometry"), wxEmptyString
,
245 wxT("Sets the geometry of the app.\n")
246 HELPTAB
wxT("<str> uses the same format as standard X11 apps:\n")
247 HELPTAB
wxT("[=][<width>{xX}<height>][{+-}<xoffset>{+-}<yoffset>]"));
248 #endif // !AMULE_DAEMON
250 cmdline
.AddSwitch(wxT("o"), wxT("log-stdout"), wxT("Print log messages to stdout."));
251 cmdline
.AddSwitch(wxT("r"), wxT("reset-config"), wxT("Resets config to default values."));
254 cmdline
.AddSwitch(wxT("s"), wxT("skip"), wxT("Skip connection dialog."));
256 // Change webserver path. This is also a config option, so this switch will go at some time.
257 cmdline
.AddOption(wxT("w"), wxT("use-amuleweb"), wxT("Specify location of amuleweb binary."));
260 cmdline
.AddSwitch(wxT("d"), wxT("disable-fatal"), wxT("Do not handle fatal exception."));
261 // Keep stdin open to run valgrind --gen_suppressions
262 cmdline
.AddSwitch(wxT("i"), wxT("enable-stdin"), wxT("Do not disable stdin."));
265 // Allow passing of links to the app
266 cmdline
.AddOption(wxT("t"), wxT("category"), wxT("Set category for passed ED2K links."), wxCMD_LINE_VAL_NUMBER
);
267 cmdline
.AddParam(wxT("ED2K link"), wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
);
269 // wx asserts in debug mode if there is a check for an option that wasn't added.
270 // So we have to wrap around the same #ifdefs as above. >:(
272 // Show help on --help or invalid commands
273 if ( cmdline
.Parse() ) {
275 } else if (cmdline
.Found(wxT("help"))) {
280 if ( cmdline
.Found(wxT("version"))) {
281 // This looks silly with logging macros that add a timestamp.
282 printf("%s\n", (const char*)unicode2char(wxString(CFormat(wxT("%s (OS: %s)")) % FullMuleVersion
% OSType
)));
286 if ( cmdline
.Found(wxT("config-dir"), &ConfigDir
) ) {
287 // Make an absolute path from the config dir
288 wxFileName
fn(ConfigDir
);
290 ConfigDir
= fn
.GetFullPath();
291 if (ConfigDir
.Last() != wxFileName::GetPathSeparator()) {
292 ConfigDir
+= wxFileName::GetPathSeparator();
295 ConfigDir
= GetConfigDir();
299 #if wxUSE_ON_FATAL_EXCEPTION
300 if ( !cmdline
.Found(wxT("disable-fatal")) ) {
301 // catch fatal exceptions
302 wxHandleFatalExceptions(true);
307 theLogger
.SetEnabledStdoutLog(cmdline
.Found(wxT("log-stdout")));
309 enable_daemon_fork
= cmdline
.Found(wxT("full-daemon"));
310 if ( cmdline
.Found(wxT("pid-file"), &m_PidFile
) ) {
311 // Remove any existing PidFile
312 if ( wxFileExists (m_PidFile
) ) wxRemoveFile (m_PidFile
);
314 ec_config
= cmdline
.Found(wxT("ec-config"));
316 enable_daemon_fork
= false;
318 // Default geometry of the GUI. Can be changed with a cmdline argument...
319 if ( cmdline
.Found(wxT("geometry"), &m_geometryString
) ) {
320 m_geometryEnabled
= true;
324 if (theLogger
.IsEnabledStdoutLog()) {
325 if ( enable_daemon_fork
) {
326 AddLogLineNS(wxT("Daemon will fork to background - log to stdout disabled")); // localization not active yet
327 theLogger
.SetEnabledStdoutLog(false);
329 AddLogLineNS(wxT("Logging to stdout enabled"));
333 AddLogLineNS(wxT("Initialising ") + FullMuleVersion
);
335 // Ensure that "~/.aMule/" is accessible.
337 if (!CheckMuleDirectory(wxT("configuration"), CPath(ConfigDir
), wxEmptyString
, outDir
)) {
341 if (cmdline
.Found(wxT("reset-config"))) {
342 // Make a backup first.
343 wxRemoveFile(ConfigDir
+ m_configFile
+ wxT(".backup"));
344 wxRenameFile(ConfigDir
+ m_configFile
, ConfigDir
+ m_configFile
+ wxT(".backup"));
345 AddLogLineNS(CFormat(wxT("Your settings have been reset to default values.\nThe old config file has been saved as %s.backup\n")) % m_configFile
);
348 size_t linksPassed
= cmdline
.GetParamCount(); // number of links from the command line
349 int linksActuallyPassed
= 0; // number of links that pass the syntax check
352 if (!cmdline
.Found(wxT("t"), &cat
)) {
356 wxTextFile
ed2kFile(ConfigDir
+ wxT("ED2KLinks"));
357 if (!ed2kFile
.Exists()) {
360 if (ed2kFile
.Open()) {
361 for (size_t i
= 0; i
< linksPassed
; i
++) {
363 if (CheckPassedLink(cmdline
.GetParam(i
), link
, cat
)) {
364 ed2kFile
.AddLine(link
);
365 linksActuallyPassed
++;
370 AddLogLineCS(wxT("Failed to open 'ED2KLinks', cannot add links."));
374 #if defined(__WXMAC__) && defined(AMULE_DAEMON)
375 //#warning TODO: fix wxSingleInstanceChecker for amuled on Mac (wx link problems)
376 AddLogLineCS(wxT("WARNING: The check for other instances is currently disabled in amuled.\n"
377 "Please make sure that no other instance of aMule is running or your files might be corrupted.\n"));
379 AddLogLineNS(wxT("Checking if there is an instance already running..."));
381 m_singleInstance
= new wxSingleInstanceChecker();
382 wxString lockfile
= IsRemoteGui() ? wxT("muleLockRGUI") : wxT("muleLock");
383 if (m_singleInstance
->Create(lockfile
, ConfigDir
)
384 && m_singleInstance
->IsAnotherRunning()) {
385 AddLogLineCS(CFormat(wxT("There is an instance of %s already running")) % m_appName
);
386 AddLogLineNS(CFormat(wxT("(lock file: %s%s)")) % ConfigDir
% lockfile
);
388 AddLogLineNS(CFormat(wxT("passed %d %s to it, finished")) % linksActuallyPassed
389 % (linksPassed
== 1 ? wxT("link") : wxT("links")));
393 // This is very tricky. The most secure way to communicate is via ED2K links file
394 wxTextFile
ed2kFile(ConfigDir
+ wxT("ED2KLinks"));
395 if (!ed2kFile
.Exists()) {
399 if (ed2kFile
.Open()) {
400 ed2kFile
.AddLine(wxT("RAISE_DIALOG"));
403 AddLogLineNS(wxT("Raising current running instance."));
405 AddLogLineCS(wxT("Failed to open 'ED2KFile', cannot signal running instance."));
410 AddLogLineNS(wxT("No other instances are running."));
415 // Close standard-input
416 if ( !cmdline
.Found(wxT("enable-stdin")) ) {
417 // The full daemon will close all std file-descriptors by itself,
418 // so closing it here would lead to the closing on the first open
419 // file, which is the logfile opened below
420 if (!enable_daemon_fork
) {
426 // Create the CFG file we shall use and set the config object as the global cfg file
427 wxConfig::Set(new wxFileConfig( wxEmptyString
, wxEmptyString
, ConfigDir
+ m_configFile
));
429 // Make a backup of the log file
430 CPath logfileName
= CPath(ConfigDir
+ m_logFile
);
431 if (logfileName
.FileExists()) {
432 CPath::BackupFile(logfileName
, wxT(".bak"));
436 if (!theLogger
.OpenLogfile(logfileName
.GetRaw())) {
437 // use std err as last resolt to indicate problem
438 fputs("ERROR: unable to open log file\n", stderr
);
439 // failure to open log is serious problem
444 CPreferences::BuildItemList(ConfigDir
);
445 CPreferences::LoadAllItems( wxConfigBase::Get() );
448 m_skipConnectionDialog
= cmdline
.Found(wxT("skip"));
450 wxString amulewebPath
;
451 if (cmdline
.Found(wxT("use-amuleweb"), &amulewebPath
)) {
452 thePrefs::SetWSPath(amulewebPath
);
453 AddLogLineNS(CFormat(wxT("Using amuleweb in '%s'.")) % amulewebPath
);
461 * Returns a description of the version of aMule being used.
463 * @return A detailed description of the aMule version, including application
464 * name and wx information.
466 const wxString
CamuleAppCommon::GetFullMuleVersion() const
468 return GetMuleAppName() + wxT(" ") + GetMuleVersion();
471 bool CamuleAppCommon::CheckPassedLink(const wxString
&in
, wxString
&out
, int cat
)
475 // restore ASCII-encoded pipes
476 link
.Replace(wxT("%7C"), wxT("|"));
477 link
.Replace(wxT("%7c"), wxT("|"));
479 if (link
.compare(0, 7, wxT("magnet:")) == 0) {
480 link
= CMagnetED2KConverter(link
);
482 AddLogLineCS(CFormat(wxT("Cannot convert magnet link to eD2k: %s")) % in
);
488 CScopedPtr
<CED2KLink
> uri(CED2KLink::CreateLinkFromUrl(link
));
489 out
= uri
.get()->GetLink();
490 if (cat
&& uri
.get()->GetKind() == CED2KLink::kFile
) {
491 out
+= CFormat(wxT(":%d")) % cat
;
494 } catch ( const wxString
& err
) {
495 AddLogLineCS(CFormat(wxT("Invalid eD2k link \"%s\" - ERROR: %s")) % link
% err
);
502 * Checks permissions on a aMule directory, creating if needed.
504 * @param desc A description of the directory in question, used for error messages.
505 * @param directory The directory in question.
506 * @param alternative If the dir specified with 'directory' could not be created, try this instead.
507 * @param outDir Returns the used path.
508 * @return False on error.
510 bool CamuleAppCommon::CheckMuleDirectory(const wxString
& desc
, const CPath
& directory
, const wxString
& alternative
, CPath
& outDir
)
514 if (directory
.IsDir(CPath::readwritable
)) {
517 } else if (directory
.DirExists()) {
518 // Strings are not translated here because translation isn't up yet.
519 msg
= CFormat(wxT("Permissions on the %s directory too strict!\n")
520 wxT("aMule cannot proceed. To fix this, you must set read/write/exec\n")
521 wxT("permissions for the folder '%s'"))
523 } else if (CPath::MakeDir(directory
)) {
527 msg
<< CFormat(wxT("Could not create the %s directory at '%s'."))
531 // Attempt to use fallback directory.
532 const CPath
fallback(alternative
);
533 if (fallback
.IsOk() && (directory
!= fallback
)) {
534 msg
<< wxT("\nAttempting to use default directory at location \n'")
535 << alternative
<< wxT("'.");
536 if (theApp
->ShowAlert(msg
, wxT("Error accessing directory."), wxICON_ERROR
| wxOK
| wxCANCEL
) == wxCANCEL
) {
537 outDir
= CPath(wxEmptyString
);
541 return CheckMuleDirectory(desc
, fallback
, wxEmptyString
, outDir
);
544 theApp
->ShowAlert(msg
, wxT("Fatal error."), wxICON_ERROR
| wxOK
);
545 outDir
= CPath(wxEmptyString
);