Remove some unused defines
[amule.git] / src / amuled.cpp
blob6aa551e61066e23d1a33ffc5314104e942018271
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 #include "amule.h" // Interface declarations.
28 #include <include/common/EventIDs.h>
30 #ifdef HAVE_CONFIG_H
31 #include "config.h" // Needed for HAVE_SYS_RESOURCE_H, etc
32 #endif
34 // Include the necessary headers for select(2), properly guarded
35 #if defined HAVE_SYS_SELECT_H && !defined __IRIX__
36 # include <sys/select.h>
37 #else
38 # ifdef HAVE_SYS_TIME_H
39 # include <sys/time.h>
40 # endif
41 # ifdef HAVE_SYS_TYPES_H
42 # include <sys/types.h>
43 # endif
44 # ifdef HAVE_UNISTD_H
45 # include <unistd.h>
46 # endif
47 #endif
49 #include <wx/utils.h>
51 #include "Preferences.h" // Needed for CPreferences
52 #include "PartFile.h" // Needed for CPartFile
53 #include "Logger.h"
54 #include <common/Format.h>
55 #include "InternalEvents.h" // Needed for wxEVT_*
56 #include "ThreadTasks.h"
57 #include "GuiEvents.h" // Needed for EVT_MULE_NOTIFY
58 #include "Timer.h" // Needed for EVT_MULE_TIMER
60 #include "ClientUDPSocket.h" // Do_not_auto_remove (forward declaration not enough)
61 #include "ListenSocket.h" // Do_not_auto_remove (forward declaration not enough)
64 #ifdef HAVE_SYS_RESOURCE_H
65 #include <sys/resource.h> // Do_not_auto_remove
66 #endif
68 #ifndef __WINDOWS__
69 #ifdef HAVE_SYS_WAIT_H
70 #include <sys/wait.h> // Do_not_auto_remove
71 #endif
72 #include <wx/ffile.h>
73 #endif
75 #ifdef AMULED_APPTRAITS
76 #include <wx/unix/execute.h>
77 #endif
80 BEGIN_EVENT_TABLE(CamuleDaemonApp, wxAppConsole)
82 // Socket handlers
85 // Listen Socket
86 EVT_SOCKET(ID_LISTENSOCKET_EVENT, CamuleDaemonApp::ListenSocketHandler)
88 // UDP Socket (servers)
89 EVT_SOCKET(ID_SERVERUDPSOCKET_EVENT, CamuleDaemonApp::UDPSocketHandler)
90 // UDP Socket (clients)
91 EVT_SOCKET(ID_CLIENTUDPSOCKET_EVENT, CamuleDaemonApp::UDPSocketHandler)
93 // Socket timer (TCP)
94 EVT_MULE_TIMER(ID_SERVER_RETRY_TIMER_EVENT, CamuleDaemonApp::OnTCPTimer)
96 // Core timer
97 EVT_MULE_TIMER(ID_CORE_TIMER_EVENT, CamuleDaemonApp::OnCoreTimer)
99 EVT_MULE_NOTIFY(CamuleDaemonApp::OnNotifyEvent)
101 // Async dns handling
102 EVT_MULE_INTERNAL(wxEVT_CORE_UDP_DNS_DONE, -1, CamuleDaemonApp::OnUDPDnsDone)
104 EVT_MULE_INTERNAL(wxEVT_CORE_SOURCE_DNS_DONE, -1, CamuleDaemonApp::OnSourceDnsDone)
106 EVT_MULE_INTERNAL(wxEVT_CORE_SERVER_DNS_DONE, -1, CamuleDaemonApp::OnServerDnsDone)
108 // Hash ended notifier
109 EVT_MULE_HASHING(CamuleDaemonApp::OnFinishedHashing)
110 EVT_MULE_AICH_HASHING(CamuleDaemonApp::OnFinishedAICHHashing)
112 // File completion ended notifier
113 EVT_MULE_FILE_COMPLETED(CamuleDaemonApp::OnFinishedCompletion)
115 // HTTPDownload finished
116 EVT_MULE_INTERNAL(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD, -1, CamuleDaemonApp::OnFinishedHTTPDownload)
118 // Disk space preallocation finished
119 EVT_MULE_ALLOC_FINISHED(CamuleDaemonApp::OnFinishedAllocation)
120 END_EVENT_TABLE()
122 IMPLEMENT_APP(CamuleDaemonApp)
124 #ifdef AMULED28_SOCKETS
126 * Socket handling in wxBase
129 class CSocketSet {
130 int m_count;
131 int m_fds[FD_SETSIZE], m_fd_idx[FD_SETSIZE];
132 GSocket *m_gsocks[FD_SETSIZE];
134 fd_set m_set;
135 public:
136 CSocketSet();
137 void AddSocket(GSocket *);
138 void RemoveSocket(GSocket *);
139 void FillSet(int &max_fd);
141 void Detected(void (GSocket::*func)());
143 fd_set *Set() { return &m_set; }
146 CSocketSet::CSocketSet()
148 m_count = 0;
149 for(int i = 0; i < FD_SETSIZE; i++) {
150 m_fds[i] = 0;
151 m_fd_idx[i] = 0xffff;
152 m_gsocks[i] = 0;
156 void CSocketSet::AddSocket(GSocket *socket)
158 wxASSERT(socket);
160 int fd = socket->m_fd;
162 if ( fd == -1 ) {
163 return;
166 wxASSERT( (fd > 2) && (fd < FD_SETSIZE) );
168 if ( m_gsocks[fd] ) {
169 return;
171 m_fds[m_count] = fd;
172 m_fd_idx[fd] = m_count;
173 m_gsocks[fd] = socket;
174 m_count++;
177 void CSocketSet::RemoveSocket(GSocket *socket)
179 wxASSERT(socket);
181 int fd = socket->m_fd;
183 if ( fd == -1 ) {
184 return;
187 wxASSERT( (fd > 2) && (fd < FD_SETSIZE) );
189 int i = m_fd_idx[fd];
190 if ( i == 0xffff ) {
191 return;
193 wxASSERT(m_fds[i] == fd);
194 m_fds[i] = m_fds[m_count-1];
195 m_gsocks[fd] = 0;
196 m_fds[m_count-1] = 0;
197 m_fd_idx[fd] = 0xffff;
198 m_fd_idx[m_fds[i]] = i;
199 m_count--;
202 void CSocketSet::FillSet(int &max_fd)
204 FD_ZERO(&m_set);
206 for(int i = 0; i < m_count; i++) {
207 FD_SET(m_fds[i], &m_set);
208 if ( m_fds[i] > max_fd ) {
209 max_fd = m_fds[i];
214 void CSocketSet::Detected(void (GSocket::*func)())
216 for (int i = 0; i < m_count; i++) {
217 int fd = m_fds[i];
218 if ( FD_ISSET(fd, &m_set) ) {
219 GSocket *socket = m_gsocks[fd];
220 (*socket.*func)();
225 CAmuledGSocketFuncTable::CAmuledGSocketFuncTable() : m_lock(wxMUTEX_RECURSIVE)
227 m_in_set = new CSocketSet;
228 m_out_set = new CSocketSet;
230 m_lock.Unlock();
233 void CAmuledGSocketFuncTable::AddSocket(GSocket *socket, GSocketEvent event)
235 wxMutexLocker lock(m_lock);
237 if ( event == GSOCK_INPUT ) {
238 m_in_set->AddSocket(socket);
239 } else {
240 m_out_set->AddSocket(socket);
244 void CAmuledGSocketFuncTable::RemoveSocket(GSocket *socket, GSocketEvent event)
246 wxMutexLocker lock(m_lock);
248 if ( event == GSOCK_INPUT ) {
249 m_in_set->RemoveSocket(socket);
250 } else {
251 m_out_set->RemoveSocket(socket);
255 void CAmuledGSocketFuncTable::RunSelect()
257 wxMutexLocker lock(m_lock);
259 int max_fd = -1;
260 m_in_set->FillSet(max_fd);
261 m_out_set->FillSet(max_fd);
263 struct timeval tv;
264 tv.tv_sec = 0;
265 tv.tv_usec = 10000; // 10ms
267 int result = select(max_fd + 1, m_in_set->Set(), m_out_set->Set(), 0, &tv);
268 if ( result > 0 ) {
269 m_in_set->Detected(&GSocket::Detected_Read);
270 m_out_set->Detected(&GSocket::Detected_Write);
274 GSocketGUIFunctionsTable *CDaemonAppTraits::GetSocketGUIFunctionsTable()
276 return m_table;
279 bool CAmuledGSocketFuncTable::OnInit()
281 return true;
284 void CAmuledGSocketFuncTable::OnExit()
288 bool CAmuledGSocketFuncTable::CanUseEventLoop()
291 * FIXME: (lfroen) Not sure whether it's right.
292 * I will review it later.
294 return false;
297 bool CAmuledGSocketFuncTable::Init_Socket(GSocket *)
299 return true;
302 void CAmuledGSocketFuncTable::Destroy_Socket(GSocket *)
306 void CAmuledGSocketFuncTable::Install_Callback(GSocket *sock, GSocketEvent e)
308 AddSocket(sock, e);
311 void CAmuledGSocketFuncTable::Uninstall_Callback(GSocket *sock, GSocketEvent e)
313 RemoveSocket(sock, e);
316 void CAmuledGSocketFuncTable::Enable_Events(GSocket *socket)
318 Install_Callback(socket, GSOCK_INPUT);
319 Install_Callback(socket, GSOCK_OUTPUT);
322 void CAmuledGSocketFuncTable::Disable_Events(GSocket *socket)
324 Uninstall_Callback(socket, GSOCK_INPUT);
325 Uninstall_Callback(socket, GSOCK_OUTPUT);
329 CDaemonAppTraits::CDaemonAppTraits(CAmuledGSocketFuncTable *table)
331 wxConsoleAppTraits(),
332 m_oldSignalChildAction(),
333 m_newSignalChildAction(),
334 m_table(table),
335 m_lock(wxMUTEX_RECURSIVE),
336 m_sched_delete()
338 m_lock.Unlock();
342 void CDaemonAppTraits::ScheduleForDestroy(wxObject *object)
344 wxMutexLocker lock(m_lock);
346 //delete object;
347 m_sched_delete.push_back(object);
350 void CDaemonAppTraits::RemoveFromPendingDelete(wxObject *object)
352 wxMutexLocker lock(m_lock);
354 for(std::list<wxObject *>::iterator i = m_sched_delete.begin();
355 i != m_sched_delete.end(); i++) {
356 if ( *i == object ) {
357 m_sched_delete.erase(i);
358 return;
363 void CDaemonAppTraits::DeletePending()
365 wxMutexLocker lock(m_lock);
367 while ( !m_sched_delete.empty() ) {
368 std::list<wxObject *>::iterator i = m_sched_delete.begin();
369 wxObject *object = *i;
370 delete object;
372 //m_sched_delete.erase(m_sched_delete.begin(), m_sched_delete.end());
375 wxAppTraits *CamuleDaemonApp::CreateTraits()
377 return new CDaemonAppTraits(m_table);
380 #else // AMULED28_SOCKETS
382 #ifdef AMULED_APPTRAITS
384 CDaemonAppTraits::CDaemonAppTraits()
386 wxConsoleAppTraits(),
387 m_oldSignalChildAction(),
388 m_newSignalChildAction()
392 wxAppTraits *CamuleDaemonApp::CreateTraits()
394 return new CDaemonAppTraits();
397 #endif // AMULED_APPTRAITS
399 #endif // !AMULED28_SOCKETS
401 #if defined(__WXMAC__) && !wxCHECK_VERSION(2, 9, 0)
402 #include <wx/stdpaths.h> // Do_not_auto_remove (guess)
403 static wxStandardPathsCF gs_stdPaths;
404 wxStandardPathsBase& CDaemonAppTraits::GetStandardPaths()
406 return gs_stdPaths;
408 #endif
411 #ifdef AMULED28_EVENTLOOP
413 CamuleDaemonApp::CamuleDaemonApp()
415 m_Exit(false)
416 #ifdef AMULED28_SOCKETS
417 ,m_table(new CAmuledGSocketFuncTable())
418 #endif
420 // work around problem from http://trac.wxwidgets.org/ticket/2145
421 wxPendingEventsLocker = new wxCriticalSection;
424 #endif // AMULED28_EVENTLOOP
427 #ifdef AMULED_APPTRAITS
429 static EndProcessDataMap endProcDataMap;
431 int CDaemonAppTraits::WaitForChild(wxExecuteData &execData)
433 int status = 0;
434 pid_t result = 0;
435 // Build the log message
436 wxString msg;
437 msg << wxT("WaitForChild() has been called for child process with pid `") <<
438 execData.pid <<
439 wxT("'. ");
441 if (execData.flags & wxEXEC_SYNC) {
442 result = AmuleWaitPid(execData.pid, &status, 0, &msg);
443 if (result == -1 || (!WIFEXITED(status) && !WIFSIGNALED(status))) {
444 msg << wxT(" Waiting for subprocess termination failed.");
445 AddDebugLogLineN(logGeneral, msg);
447 } else {
448 /** wxEXEC_ASYNC */
449 // Give the process a chance to start or forked child to exit
450 // 1 second is enough time to fail on "path not found"
451 wxSleep(1);
452 result = AmuleWaitPid(execData.pid, &status, WNOHANG, &msg);
453 if (result == 0) {
454 // Add a WxEndProcessData entry to the map, so that we can
455 // support process termination
456 wxEndProcessData *endProcData = new wxEndProcessData();
457 endProcData->pid = execData.pid;
458 endProcData->process = execData.process;
459 endProcData->tag = 0;
460 endProcDataMap[execData.pid] = endProcData;
462 status = execData.pid;
463 } else {
464 // if result != 0, then either waitpid() failed (result == -1)
465 // and there is nothing we can do, or the child has changed
466 // status, which means it is probably dead.
467 status = 0;
471 // Log our passage here
472 AddDebugLogLineN(logGeneral, msg);
474 return status;
478 void OnSignalChildHandler(int /*signal*/, siginfo_t *siginfo, void * /*ucontext*/)
480 // Build the log message
481 wxString msg;
482 msg << wxT("OnSignalChildHandler() has been called for child process with pid `") <<
483 siginfo->si_pid <<
484 wxT("'. ");
485 // Make sure we leave no zombies by calling waitpid()
486 int status = 0;
487 pid_t result = AmuleWaitPid(siginfo->si_pid, &status, WNOHANG, &msg);
488 if (result != 1 && result != 0 && (WIFEXITED(status) || WIFSIGNALED(status))) {
489 // Fetch the wxEndProcessData structure corresponding to this pid
490 EndProcessDataMap::iterator it = endProcDataMap.find(siginfo->si_pid);
491 if (it != endProcDataMap.end()) {
492 wxEndProcessData *endProcData = it->second;
493 // Remove this entry from the process map
494 endProcDataMap.erase(siginfo->si_pid);
495 // Save the exit code for the wxProcess object to read later
496 endProcData->exitcode = result != -1 && WIFEXITED(status) ?
497 WEXITSTATUS(status) : -1;
498 // Make things work as in wxGUI
499 wxHandleProcessTermination(endProcData);
501 // wxHandleProcessTermination() will "delete endProcData;"
502 // So we do not delete it again, ok? Do not uncomment this line.
503 //delete endProcData;
504 } else {
505 msg << wxT(" Error: the child process pid is not on the pid map.");
509 // Log our passage here
510 AddDebugLogLineN(logGeneral, msg);
514 pid_t AmuleWaitPid(pid_t pid, int *status, int options, wxString *msg)
516 *status = 0;
517 pid_t result = waitpid(pid, status, options);
518 if (result == -1) {
519 *msg << CFormat(wxT("Error: waitpid() call failed: %m."));
520 } else if (result == 0) {
521 if (options & WNOHANG) {
522 *msg << wxT("The child is alive.");
523 } else {
524 *msg << wxT("Error: waitpid() call returned 0 but "
525 "WNOHANG was not specified in options.");
527 } else {
528 if (WIFEXITED(*status)) {
529 *msg << wxT("Child has terminated with status code `") <<
530 WEXITSTATUS(*status) <<
531 wxT("'.");
532 } else if (WIFSIGNALED(*status)) {
533 *msg << wxT("Child was killed by signal `") <<
534 WTERMSIG(*status) <<
535 wxT("'.");
536 if (WCOREDUMP(*status)) {
537 *msg << wxT(" A core file has been dumped.");
539 } else if (WIFSTOPPED(*status)) {
540 *msg << wxT("Child has been stopped by signal `") <<
541 WSTOPSIG(*status) <<
542 wxT("'.");
543 #ifdef WIFCONTINUED /* Only found in recent kernels. */
544 } else if (WIFCONTINUED(*status)) {
545 *msg << wxT("Child has received `SIGCONT' and has continued execution.");
546 #endif
547 } else {
548 *msg << wxT("The program was not able to determine why the child has signaled.");
552 return result;
555 #endif // AMULED_APPTRAITS
558 #ifdef __WINDOWS__
560 // CTRL-C-Handler
561 // see http://msdn.microsoft.com/en-us/library/windows/desktop/ms685049%28v=vs.85%29.aspx
563 static BOOL CtrlHandler(DWORD fdwCtrlType)
565 switch (fdwCtrlType) {
566 case CTRL_C_EVENT:
567 case CTRL_CLOSE_EVENT:
568 case CTRL_BREAK_EVENT:
569 // handle these
570 AddLogLineNS(wxT("Received break event, exit main loop"));
571 theApp->ExitMainLoop();
572 return TRUE;
573 break;
574 case CTRL_LOGOFF_EVENT:
575 case CTRL_SHUTDOWN_EVENT:
576 default:
577 // don't handle these
578 return FALSE;
579 break;
583 #endif // __WINDOWS__
586 int CamuleDaemonApp::OnRun()
588 if (!thePrefs::AcceptExternalConnections()) {
589 AddLogLineCS(_("ERROR: aMule daemon cannot be used when external connections are disabled. To enable External Connections, use either a normal aMule, start amuled with the option --ec-config or set the key \"AcceptExternalConnections\" to 1 in the file ~/.aMule/amule.conf"));
590 return 0;
591 } else if (thePrefs::ECPassword().IsEmpty()) {
592 AddLogLineCS(_("ERROR: A valid password is required to use external connections, and aMule daemon cannot be used without external connections. To run aMule deamon, you must set the \"ECPassword\" field in the file ~/.aMule/amule.conf with an appropriate value. Execute amuled with the flag --ec-config to set the password. More information can be found at http://wiki.amule.org"));
593 return 0;
596 #ifdef __WINDOWS__
597 SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
598 #endif // __WINDOWS__
600 #ifdef AMULED_APPTRAITS
601 // Process the return code of dead children so that we do not create
602 // zombies. wxBase does not implement wxProcess callbacks, so no one
603 // actualy calls wxHandleProcessTermination() in console applications.
604 // We do our best here.
605 DEBUG_ONLY( int ret = 0; )
606 DEBUG_ONLY( ret = ) sigaction(SIGCHLD, NULL, &m_oldSignalChildAction);
607 m_newSignalChildAction = m_oldSignalChildAction;
608 m_newSignalChildAction.sa_sigaction = OnSignalChildHandler;
609 m_newSignalChildAction.sa_flags |= SA_SIGINFO;
610 m_newSignalChildAction.sa_flags &= ~SA_RESETHAND;
611 DEBUG_ONLY( ret = ) sigaction(SIGCHLD, &m_newSignalChildAction, NULL);
612 #ifdef __DEBUG__
613 if (ret == -1) {
614 AddDebugLogLineC(logStandard, CFormat(wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD callback with sigaction() failed: %m.")));
615 } else {
616 AddDebugLogLineN(logGeneral, wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD callback with sigaction() succeeded."));
618 #endif
619 #endif // AMULED_APPTRAITS
621 #ifdef AMULED28_EVENTLOOP
623 while ( !m_Exit ) {
624 #ifdef AMULED28_SOCKETS
625 m_table->RunSelect();
626 ProcessPendingEvents();
627 ((CDaemonAppTraits *)GetTraits())->DeletePending();
628 #else
629 wxMilliSleep(10);
630 ProcessPendingEvents();
631 #endif
634 // ShutDown is beeing called twice. Once here and again in OnExit().
635 ShutDown();
637 return 0;
639 #else
640 return wxApp::OnRun();
641 #endif
644 bool CamuleDaemonApp::OnInit()
646 if ( !CamuleApp::OnInit() ) {
647 return false;
649 AddLogLineNS(_("amuled: OnInit - starting timer"));
650 core_timer = new CTimer(this,ID_CORE_TIMER_EVENT);
651 core_timer->Start(CORE_TIMER_PERIOD);
652 glob_prefs->GetCategory(0)->title = GetCatTitle(thePrefs::GetAllcatFilter());
653 glob_prefs->GetCategory(0)->path = thePrefs::GetIncomingDir();
655 return true;
658 int CamuleDaemonApp::InitGui(bool ,wxString &)
660 #ifndef __WINDOWS__
661 if ( !enable_daemon_fork ) {
662 return 0;
664 AddLogLineNS(_("amuled: forking to background - see you"));
665 theLogger.SetEnabledStdoutLog(false);
667 // fork to background and detach from controlling tty
668 // while redirecting stdout to /dev/null
670 for(int i_fd = 0;i_fd < 3; i_fd++) {
671 close(i_fd);
673 int fd = open("/dev/null",O_RDWR);
674 if (dup(fd)){} // prevent GCC warning
675 if (dup(fd)){}
676 pid_t pid = fork();
678 wxASSERT(pid != -1);
680 if ( pid ) {
681 exit(0);
682 } else {
683 pid = setsid();
685 // Create a Pid file with the Pid of the Child, so any daemon-manager
686 // can easily manage the process
688 if (!m_PidFile.IsEmpty()) {
689 wxString temp = CFormat(wxT("%d\n")) % pid;
690 wxFFile ff(m_PidFile, wxT("w"));
691 if (!ff.Error()) {
692 ff.Write(temp);
693 ff.Close();
694 } else {
695 AddLogLineNS(_("Cannot Create Pid File"));
700 #endif
701 return 0;
705 int CamuleDaemonApp::OnExit()
707 #ifdef AMULED28_SOCKETS
709 * Stop all socket threads before entering
710 * shutdown sequence.
712 delete listensocket;
713 listensocket = 0;
714 if (clientudp) {
715 delete clientudp;
716 clientudp = NULL;
718 #endif
720 ShutDown();
722 #ifdef AMULED_APPTRAITS
723 DEBUG_ONLY( int ret = ) sigaction(SIGCHLD, &m_oldSignalChildAction, NULL);
724 #ifdef __DEBUG__
725 if (ret == -1) {
726 AddDebugLogLineC(logStandard, CFormat(wxT("CamuleDaemonApp::OnRun(): second sigaction() failed: %m.")));
727 } else {
728 AddDebugLogLineN(logGeneral, wxT("CamuleDaemonApp::OnRun(): Uninstallation of SIGCHLD callback with sigaction() succeeded."));
730 #endif
731 #endif // AMULED_APPTRAITS
733 delete core_timer;
735 return CamuleApp::OnExit();
739 int CamuleDaemonApp::ShowAlert(wxString msg, wxString title, int flags)
741 if ( flags | wxICON_ERROR ) {
742 title = CFormat(_("ERROR: %s")) % title;
744 AddLogLineCS(title + wxT(" ") + msg);
746 return 0; // That's neither yes nor no, ok, cancel
749 // File_checked_for_headers