2 // This file is part of the aMule Project.
4 // Copyright (c) 2004-2008 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
25 #include "ExternalConnector.h"
28 #include "config.h" // Needed for VERSION and readline detection
31 #include <common/ClientVersion.h>
32 #include <common/Format.h> // Needed for CFormat
33 #include <wx/tokenzr.h> // For wxStringTokenizer
36 #ifdef HAVE_LIBREADLINE
37 #if defined(HAVE_READLINE_READLINE_H)
38 #include <readline/readline.h> // Do_not_auto_remove
39 #elif defined(HAVE_READLINE_H)
40 #include <readline.h> // Do_not_auto_remove
41 #else /* !defined(HAVE_READLINE_H) */
42 extern "C" char *readline (const char*);
43 #endif /* !defined(HAVE_READLINE_H) */
44 #else /* !defined(HAVE_READLINE_READLINE_H) */
46 #endif /* HAVE_LIBREADLINE */
49 #ifdef HAVE_READLINE_HISTORY
50 #if defined(HAVE_READLINE_HISTORY_H)
51 #include <readline/history.h> // Do_not_auto_remove
52 #elif defined(HAVE_HISTORY_H)
53 #include <history.h> // Do_not_auto_remove
54 #else /* !defined(HAVE_HISTORY_H) */
55 extern "C" void add_history (const char*);
56 #endif /* defined(HAVE_READLINE_HISTORY_H) */
59 #endif /* HAVE_READLINE_HISTORY */
62 #include <ec/cpp/ECFileConfig.h> // Needed for CECFileConfig
63 #include <common/MD5Sum.h>
65 //-------------------------------------------------------------------
67 CCommandTree::~CCommandTree()
69 for (CmdPos_t it
= m_subcommands
.begin(); it
!= m_subcommands
.end(); ++it
) {
72 m_subcommands
.clear();
76 CCommandTree
* CCommandTree::AddCommand(CCommandTree
* command
)
78 command
->m_parent
= this;
79 const wxString
& cmd
= command
->m_command
;
81 for (it
= m_subcommands
.begin(); it
!= m_subcommands
.end(); ++it
) {
82 if ((*it
)->m_command
> cmd
) {
86 m_subcommands
.insert(it
, command
);
91 int CCommandTree::FindCommandId(const wxString
& command
, wxString
& args
, wxString
& cmdstr
) const
93 wxString cmd
= command
.BeforeFirst(wxT(' ')).Lower();
94 for (CmdPosConst_t it
= m_subcommands
.begin(); it
!= m_subcommands
.end(); ++it
) {
95 if ((*it
)->m_command
.Lower() == cmd
) {
96 args
= command
.AfterFirst(wxT(' ')).Trim(false);
97 return (*it
)->FindCommandId(args
, args
, cmdstr
);
100 cmdstr
= GetFullCommand().Lower();
101 if (m_params
== CMD_PARAM_ALWAYS
&& args
.IsEmpty()) {
102 return CMD_ERR_MUST_HAVE_PARAM
;
103 } else if (m_params
== CMD_PARAM_NEVER
&& !args
.IsEmpty()) {
104 return CMD_ERR_NO_PARAM
;
106 if ((m_cmd_id
>= 0) && (m_cmd_id
& CMD_DEPRECATED
)) {
107 m_app
.Show(wxT('\n') + m_verbose
+ wxT('\n'));
108 return m_cmd_id
& ~CMD_DEPRECATED
;
116 wxString
CCommandTree::GetFullCommand() const
118 wxString cmd
= m_command
;
120 const CCommandTree
*parent
= m_parent
;
121 while (parent
&& parent
->m_parent
) {
122 cmd
= parent
->m_command
+ wxT(" ") + cmd
;
123 parent
= parent
->m_parent
;
130 void CCommandTree::PrintHelpFor(const wxString
& command
) const
132 wxString cmd
= command
.BeforeFirst(wxT(' ')).Lower();
133 if (!cmd
.IsEmpty()) {
134 for (CmdPosConst_t it
= m_subcommands
.begin(); it
!= m_subcommands
.end(); ++it
) {
135 if ((*it
)->m_command
.Lower() == cmd
) {
136 (*it
)->PrintHelpFor(command
.AfterFirst(wxT(' ')).Trim(false));
141 m_app
.Show(CFormat(_("Unknown extension '%s' for the '%s' command.\n")) % command
% GetFullCommand());
143 m_app
.Show(CFormat(_("Unknown command '%s'.\n")) % command
);
146 wxString fullcmd
= GetFullCommand();
147 if (!fullcmd
.IsEmpty()) {
148 m_app
.Show(fullcmd
.Upper() + wxT(": ") + wxGetTranslation(m_short
) + wxT("\n"));
149 if (!m_verbose
.IsEmpty()) {
150 m_app
.Show(wxT("\n"));
151 m_app
.Show(wxGetTranslation(m_verbose
));
154 if (m_params
== CMD_PARAM_NEVER
) {
155 m_app
.Show(_("\nThis command cannot have an argument.\n"));
156 } else if (m_params
== CMD_PARAM_ALWAYS
) {
157 m_app
.Show(_("\nThis command must have an argument.\n"));
159 if (m_cmd_id
== CMD_ERR_INCOMPLETE
) {
160 m_app
.Show(_("\nThis command is incomplete, you must use one of the extensions below.\n"));
162 if (!m_subcommands
.empty()) {
166 m_app
.Show(_("\nAvailable extensions:\n"));
168 m_app
.Show(_("Available commands:\n"));
170 for (it
= m_subcommands
.begin(); it
!= m_subcommands
.end(); ++it
) {
171 if (!((*it
)->m_cmd_id
>= 0 && (*it
)->m_cmd_id
& CMD_DEPRECATED
) || m_parent
) {
172 int len
= (*it
)->m_command
.Length();
179 for (it
= m_subcommands
.begin(); it
!= m_subcommands
.end(); ++it
) {
180 if (!((*it
)->m_cmd_id
>= 0 && (*it
)->m_cmd_id
& CMD_DEPRECATED
) || m_parent
) {
181 m_app
.Show((*it
)->m_command
+ wxString(wxT(' '), maxlen
- (*it
)->m_command
.Length()) + wxGetTranslation((*it
)->m_short
) + wxT("\n"));
185 m_app
.Show(CFormat(_("\nAll commands are case insensitive.\nType '%s <command>' to get detailed info on <command>.\n")) % wxT("help"));
189 m_app
.Show(wxT("\n"));
192 //-------------------------------------------------------------------
194 CaMuleExternalConnector::CaMuleExternalConnector()
195 : m_configFile(NULL
),
202 m_NeedsConfigSave(false),
204 m_strFullVersion(NULL
),
205 m_strOSDescription(NULL
)
207 SetAppName(wxT("aMule")); // Do not change!
209 // Find out Application Name
218 CaMuleExternalConnector::~CaMuleExternalConnector()
222 free(m_strFullVersion
);
223 free(m_strOSDescription
);
226 void CaMuleExternalConnector::OnInitCommandSet()
228 m_commands
.AddCommand(wxT("Quit"), CMD_ID_QUIT
, wxTRANSLATE("Exits from the application."), wxEmptyString
);
229 m_commands
.AddCommand(wxT("Exit"), CMD_ID_QUIT
, wxTRANSLATE("Exits from the application."), wxEmptyString
);
230 m_commands
.AddCommand(wxT("Help"), CMD_ID_HELP
, wxTRANSLATE("Show help."),
232 Do not translate the word 'help', it is a command to the program! */
233 wxTRANSLATE("To get help on a command, type 'help <command>'.\nTo get the full command list type 'help'.\n"));
236 void CaMuleExternalConnector::Show(const wxString
&s
)
239 printf("%s", (const char *)unicode2char(s
));
246 void CaMuleExternalConnector::ShowGreet()
248 wxString text
= GetGreetingTitle();
249 int len
= text
.Length();
250 Show(wxT('\n') + wxString(wxT('-'), 22 + len
) + wxT('\n'));
251 Show(wxT('|') + wxString(wxT(' '), 10) + text
+ wxString(wxT(' '), 10) + wxT('|') + wxT('\n'));
252 Show(wxString(wxT('-'), 22 + len
) + wxT('\n'));
253 // Do not merge the line below, or translators could translate "Help"
254 Show(CFormat(_("\nUse '%s' for command list\n\n")) % wxT("Help"));
257 void CaMuleExternalConnector::Process_Answer(const wxString
& answer
)
259 wxStringTokenizer
tokens(answer
, wxT("\n"));
260 while ( tokens
.HasMoreTokens() ) {
261 Show(wxT(" > ") + tokens
.GetNextToken() + wxT("\n"));
265 bool CaMuleExternalConnector::Parse_Command(const wxString
& buffer
)
268 wxStringTokenizer
tokens(buffer
);
269 while (tokens
.HasMoreTokens()) {
270 cmd
+= tokens
.GetNextToken() + wxT(' ');
274 int cmd_ID
= GetIDFromString(cmd
);
276 cmd_ID
= ProcessCommand(cmd_ID
);
281 m_commands
.PrintHelpFor(GetCmdArgs());
284 error
= _("Syntax error!");
286 case CMD_ERR_PROCESS_CMD
:
287 Show(_("Error processing command - should never happen! Report bug, please\n"));
289 case CMD_ERR_NO_PARAM
:
290 error
= _("This command should not have any parameters.");
292 case CMD_ERR_MUST_HAVE_PARAM
:
293 error
= _("This command must have a parameter.");
295 case CMD_ERR_INVALID_ARG
:
296 error
= _("Invalid argument.");
298 case CMD_ERR_INCOMPLETE
:
299 error
= _("This is an incomplete command.");
302 if (!error
.IsEmpty()) {
303 Show(error
+ wxT('\n'));
304 wxString
helpStr(wxT("help"));
305 if (!GetLastCmdStr().IsEmpty()) {
306 helpStr
<< wxT(' ') << GetLastCmdStr();
308 Show(CFormat(_("Type '%s' to get more help.\n")) % helpStr
);
310 return cmd_ID
== CMD_ID_QUIT
;
313 void CaMuleExternalConnector::GetCommand(const wxString
&prompt
, char* buffer
, size_t buffer_size
)
315 #ifdef HAVE_LIBREADLINE
316 char *text
= readline(unicode2char(prompt
+ wxT("$ ")));
318 (m_InputLine
== 0 || strcmp(text
,m_InputLine
) != 0)) {
325 Show(prompt
+ wxT("$ "));
327 fgets(buffer
, buffer_size
, stdin
);
328 const char *text
= buffer
;
329 #endif /* HAVE_LIBREADLINE */
331 size_t len
= strlen(text
);
332 if (len
> buffer_size
- 2) {
333 len
= buffer_size
- 2;
335 strncpy(buffer
, text
, len
);
339 strncpy(buffer
, "quit", buffer_size
);
343 void CaMuleExternalConnector::TextShell(const wxString
&prompt
)
348 bool The_End
= false;
350 GetCommand(prompt
, buffer
, 256);
351 buf
= char2unicode(buffer
);
352 The_End
= Parse_Command(buf
);
353 } while ((!The_End
) && (m_ECClient
->IsSocketConnected()));
356 void CaMuleExternalConnector::ConnectAndRun(const wxString
&ProgName
, const wxString
& ProgVersion
)
358 if (m_NeedsConfigSave
) {
364 Show(CFormat(_("This is %s %s %s\n")) % wxString::FromAscii(m_appname
) % wxT(VERSION
) % wxT(SVNDATE
));
366 Show(CFormat(_("This is %s %s\n")) % wxString::FromAscii(m_appname
) % wxT(VERSION
));
369 // HostName, Port and Password
370 if ( m_password
.IsEmpty() ) {
373 pass_plain
= char2unicode(getpass("Enter password for mule connection: "));
375 //#warning This way, pass enter is not hidden on windows. Bad thing.
378 printf("Enter password for mule connection: \n");
380 fgets(temp_str
, 512, stdin
);
381 temp_str
[strlen(temp_str
)-1] = '\0';
382 pass_plain
= char2unicode(temp_str
);
384 wxCHECK2(m_password
.Decode(MD5Sum(pass_plain
).GetHash()), /* Do nothing. */ );
385 // MD5 hash for an empty string, according to rfc1321.
386 if (m_password
.Encode() == wxT("D41D8CD98F00B204E9800998ECF8427E")) {
390 // Clear plain-text password
391 pass_plain
= wxT("01234567890123456789");
394 if (!m_password
.IsEmpty()) {
397 Show(_("\nCreating client...\n"));
398 m_ECClient
= new CRemoteConnect(NULL
);
400 // ConnectToCore is blocking since m_ECClient was initialized with NULL
401 if (!m_ECClient
->ConnectToCore(m_host
, m_port
, wxT("foobar"), m_password
.Encode(), ProgName
, ProgVersion
)) {
402 // no connection => close gracefully
403 Show(CFormat(_("Connection Failed. Unable to connect to %s:%d\n")) % m_host
% m_port
);
405 // Authenticate ourselves
406 // ConnectToCore() already authenticated for us.
407 //m_ECClient->ConnectionEstablished();
408 Show(m_ECClient
->GetServerReply()+wxT("\n"));
409 if (m_ECClient
->IsSocketConnected()) {
414 Show(CFormat(_("\nOk, exiting %s...\n")) % ProgName
);
417 m_ECClient
->DestroySocket();
419 Show(_("Cannot connect with an empty password.\nYou must specify a password either in config file\nor on command-line, or enter one when asked.\n\nExiting...\n"));
423 void CaMuleExternalConnector::OnInitCmdLine(wxCmdLineParser
& parser
)
425 parser
.AddSwitch(wxEmptyString
, wxT("help"),
426 _("Show this help text."),
427 wxCMD_LINE_PARAM_OPTIONAL
);
428 parser
.AddOption(wxT("h"), wxT("host"),
429 _("Host where aMule is running. (default: localhost)"),
430 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_OPTIONAL
);
431 parser
.AddOption(wxT("p"), wxT("port"),
432 _("aMule's port for External Connection. (default: 4712)"),
433 wxCMD_LINE_VAL_NUMBER
, wxCMD_LINE_PARAM_OPTIONAL
);
434 parser
.AddOption(wxT("P"), wxT("password"),
435 _("External Connection password."),
436 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_OPTIONAL
);
437 parser
.AddOption(wxT("f"), wxT("config-file"),
438 _("Read configuration from file."),
439 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_OPTIONAL
);
440 parser
.AddSwitch(wxT("q"), wxT("quiet"),
441 _("Do not print any output to stdout."),
442 wxCMD_LINE_PARAM_OPTIONAL
);
443 parser
.AddSwitch(wxT("v"), wxT("verbose"),
444 _("Be verbose - show also debug messages."),
445 wxCMD_LINE_PARAM_OPTIONAL
);
446 parser
.AddOption(wxT("l"), wxT("locale"),
447 _("Sets program locale (language)."),
448 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_OPTIONAL
);
449 parser
.AddSwitch(wxT("w"), wxT("write-config"),
450 _("Write command line options to config file."),
451 wxCMD_LINE_PARAM_OPTIONAL
);
452 parser
.AddOption(wxEmptyString
, wxT("create-config-from"),
453 _("Creates config file based on aMule's config file."),
454 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_OPTIONAL
);
455 parser
.AddSwitch(wxEmptyString
, wxT("version"),
456 _("Print program version."),
457 wxCMD_LINE_PARAM_OPTIONAL
);
460 bool CaMuleExternalConnector::OnCmdLineParsed(wxCmdLineParser
& parser
)
462 if (parser
.Found(wxT("version"))) {
463 printf("%s %s\n", m_appname
, (const char *)unicode2char(GetMuleVersion()));
467 if (!parser
.Found(wxT("config-file"), &m_configFileName
)) {
468 m_configFileName
= GetConfigDir() + wxT("remote.conf");
471 wxString aMuleConfigFile
;
472 if (parser
.Found(wxT("create-config-from"), &aMuleConfigFile
)) {
473 aMuleConfigFile
= FinalizeFilename(aMuleConfigFile
);
474 if (!::wxFileExists(aMuleConfigFile
)) {
475 fprintf(stderr
, "%s\n", (const char *)unicode2char(wxT("FATAL ERROR: File does not exist: ") + aMuleConfigFile
));
478 CECFileConfig
aMuleConfig(aMuleConfigFile
);
479 LoadAmuleConfig(aMuleConfig
);
481 m_configFile
->Flush();
487 if ( !parser
.Found(wxT("host"), &m_host
) ) {
488 if ( m_host
.IsEmpty() ) {
489 m_host
= wxT("localhost");
494 if (!parser
.Found(wxT("port"), &port
)) {
503 if (parser
.Found(wxT("password"), &pass_plain
)) {
504 if (!pass_plain
.IsEmpty()) {
505 m_password
.Decode(MD5Sum(pass_plain
).GetHash());
511 if (parser
.Found(wxT("write-config"))) {
512 m_NeedsConfigSave
= true;
515 parser
.Found(wxT("locale"), &m_language
);
517 if (parser
.Found(wxT("help"))) {
522 m_KeepQuiet
= parser
.Found(wxT("quiet"));
523 m_Verbose
= parser
.Found(wxT("verbose"));
528 void CaMuleExternalConnector::LoadAmuleConfig(CECFileConfig
& cfg
)
530 m_host
= wxT("localhost");
531 m_port
= cfg
.Read(wxT("/ExternalConnect/ECPort"), -1l);
532 cfg
.ReadHash(wxT("/ExternalConnect/ECPassword"), &m_password
);
533 m_language
= cfg
.Read(wxT("/eMule/Language"), wxEmptyString
);
537 void CaMuleExternalConnector::LoadConfigFile()
540 m_configFile
= new CECFileConfig(m_configFileName
);
543 m_language
= m_configFile
->Read(wxT("/Locale"), wxEmptyString
);
544 m_host
= m_configFile
->Read(wxT("/EC/Host"), wxEmptyString
);
545 m_port
= m_configFile
->Read(wxT("/EC/Port"), -1l);
546 m_configFile
->ReadHash(wxT("/EC/Password"), &m_password
);
550 void CaMuleExternalConnector::SaveConfigFile()
552 if (!wxFileName::DirExists(GetConfigDir())) {
553 wxFileName::Mkdir(GetConfigDir());
556 m_configFile
= new CECFileConfig(m_configFileName
);
559 m_configFile
->Write(wxT("/Locale"), m_language
);
560 m_configFile
->Write(wxT("/EC/Host"), m_host
);
561 m_configFile
->Write(wxT("/EC/Port"), m_port
);
562 m_configFile
->WriteHash(wxT("/EC/Password"), m_password
);
566 bool CaMuleExternalConnector::OnInit()
569 // catch fatal exceptions
570 wxHandleFatalExceptions(true);
573 m_strFullVersion
= strdup((const char *)unicode2char(GetMuleVersion()));
574 m_strOSDescription
= strdup((const char *)unicode2char(wxGetOsDescription()));
576 // Handle uncaught exceptions
577 InstallMuleExceptionHandler();
579 bool retval
= wxApp::OnInit();
581 InitCustomLanguages();
582 SetLocale(m_language
);
586 wxString
CaMuleExternalConnector::SetLocale(const wxString
& language
)
588 if (!language
.IsEmpty()) {
589 m_language
= language
;
593 m_locale
= new wxLocale
;
594 InitLocale(*m_locale
, StrLang2wx(language
));
597 return m_locale
== NULL
? wxString() : m_locale
->GetCanonicalName();
600 #if !wxUSE_GUI && defined(__WXMAC__)
602 #include <wx/apptrait.h> // Do_not_auto_remove
603 #include <wx/stdpaths.h> // Do_not_auto_remove
605 class CaMuleExternalConnectorTraits
: public wxConsoleAppTraits
608 virtual wxStandardPathsBase
& GetStandardPaths()
614 static wxStandardPathsCF s_stdPaths
;
617 wxStandardPathsCF
CaMuleExternalConnectorTraits::s_stdPaths
;
619 wxAppTraits
* CaMuleExternalConnector::CreateTraits()
621 return new CaMuleExternalConnectorTraits
;
626 // Gracefully handle fatal exceptions and print backtrace if possible
627 void CaMuleExternalConnector::OnFatalException()
629 /* Print the backtrace */
630 fprintf(stderr
, "\n--------------------------------------------------------------------------------\n");
631 fprintf(stderr
, "A fatal error has occurred and %s has crashed.\n", m_appname
);
632 fprintf(stderr
, "Please assist us in fixing this problem by posting the backtrace below in our\n");
633 fprintf(stderr
, "'aMule Crashes' forum and include as much information as possible regarding the\n");
634 fprintf(stderr
, "circumstances of this crash. The forum is located here:\n");
635 fprintf(stderr
, " http://forum.amule.org/index.php?board=67.0\n");
636 fprintf(stderr
, "If possible, please try to generate a real backtrace of this crash:\n");
637 fprintf(stderr
, " http://www.amule.org/wiki/index.php/Backtraces\n\n");
638 fprintf(stderr
, "----------------------------=| BACKTRACE FOLLOWS: |=----------------------------\n");
639 fprintf(stderr
, "Current version is: %s %s\n", m_appname
, m_strFullVersion
);
640 fprintf(stderr
, "Running on: %s\n\n", m_strOSDescription
);
642 print_backtrace(1); // 1 == skip this function.
644 fprintf(stderr
, "\n--------------------------------------------------------------------------------\n");
648 void CaMuleExternalConnector::OnAssertFailure(const wxChar
*file
, int line
, const wxChar
*func
, const wxChar
*cond
, const wxChar
*msg
)
650 #if !defined wxUSE_STACKWALKER || !wxUSE_STACKWALKER
651 wxString errmsg
= CFormat( wxT("%s:%s:%d: Assertion '%s' failed. %s") ) % file
% func
% line
% cond
% ( msg
? msg
: wxT("") );
653 fprintf(stderr
, "Assertion failed: %s\n", (const char*)unicode2char(errmsg
));
655 // Skip the function-calls directly related to the assert call.
656 fprintf(stderr
, "\nBacktrace follows:\n");
658 fprintf(stderr
, "\n");
660 wxApp::OnAssertFailure(file
, line
, func
, cond
, msg
);
664 // File_checked_for_headers