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 #include "amule.h" // Interface declarations.
28 #include <include/common/EventIDs.h>
31 #include "config.h" // Needed for HAVE_SYS_RESOURCE_H, etc
34 // Include the necessary headers for select(2), properly guarded
35 #if defined HAVE_SYS_SELECT_H && !defined __IRIX__
36 # include <sys/select.h>
38 # ifdef HAVE_SYS_TIME_H
39 # include <sys/time.h>
41 # ifdef HAVE_SYS_TYPES_H
42 # include <sys/types.h>
51 #include "Preferences.h" // Needed for CPreferences
52 #include "PartFile.h" // Needed for CPartFile
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
69 #ifdef HAVE_SYS_WAIT_H
70 #include <sys/wait.h> // Do_not_auto_remove
75 #ifdef AMULED_APPTRAITS
76 #include <wx/unix/execute.h>
80 BEGIN_EVENT_TABLE(CamuleDaemonApp
, wxAppConsole
)
88 EVT_SOCKET(ID_LISTENSOCKET_EVENT
, CamuleDaemonApp::ListenSocketHandler
)
90 // UDP Socket (servers)
91 EVT_SOCKET(ID_SERVERUDPSOCKET_EVENT
, CamuleDaemonApp::UDPSocketHandler
)
92 // UDP Socket (clients)
93 EVT_SOCKET(ID_CLIENTUDPSOCKET_EVENT
, CamuleDaemonApp::UDPSocketHandler
)
97 EVT_MULE_TIMER(ID_SERVER_RETRY_TIMER_EVENT
, CamuleDaemonApp::OnTCPTimer
)
100 EVT_MULE_TIMER(ID_CORE_TIMER_EVENT
, CamuleDaemonApp::OnCoreTimer
)
102 EVT_MULE_NOTIFY(CamuleDaemonApp::OnNotifyEvent
)
104 // Async dns handling
105 EVT_MULE_INTERNAL(wxEVT_CORE_UDP_DNS_DONE
, -1, CamuleDaemonApp::OnUDPDnsDone
)
107 EVT_MULE_INTERNAL(wxEVT_CORE_SOURCE_DNS_DONE
, -1, CamuleDaemonApp::OnSourceDnsDone
)
109 EVT_MULE_INTERNAL(wxEVT_CORE_SERVER_DNS_DONE
, -1, CamuleDaemonApp::OnServerDnsDone
)
111 // Hash ended notifier
112 EVT_MULE_HASHING(CamuleDaemonApp::OnFinishedHashing
)
113 EVT_MULE_AICH_HASHING(CamuleDaemonApp::OnFinishedAICHHashing
)
115 // File completion ended notifier
116 EVT_MULE_FILE_COMPLETED(CamuleDaemonApp::OnFinishedCompletion
)
118 // HTTPDownload finished
119 EVT_MULE_INTERNAL(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD
, -1, CamuleDaemonApp::OnFinishedHTTPDownload
)
121 // Disk space preallocation finished
122 EVT_MULE_ALLOC_FINISHED(CamuleDaemonApp::OnFinishedAllocation
)
125 IMPLEMENT_APP(CamuleDaemonApp
)
127 #ifdef AMULED28_SOCKETS
129 * Socket handling in wxBase
134 int m_fds
[FD_SETSIZE
], m_fd_idx
[FD_SETSIZE
];
135 GSocket
*m_gsocks
[FD_SETSIZE
];
140 void AddSocket(GSocket
*);
141 void RemoveSocket(GSocket
*);
142 void FillSet(int &max_fd
);
144 void Detected(void (GSocket::*func
)());
146 fd_set
*Set() { return &m_set
; }
149 CSocketSet::CSocketSet()
152 for(int i
= 0; i
< FD_SETSIZE
; i
++) {
154 m_fd_idx
[i
] = 0xffff;
159 void CSocketSet::AddSocket(GSocket
*socket
)
163 int fd
= socket
->m_fd
;
169 wxASSERT( (fd
> 2) && (fd
< FD_SETSIZE
) );
171 if ( m_gsocks
[fd
] ) {
175 m_fd_idx
[fd
] = m_count
;
176 m_gsocks
[fd
] = socket
;
180 void CSocketSet::RemoveSocket(GSocket
*socket
)
184 int fd
= socket
->m_fd
;
190 wxASSERT( (fd
> 2) && (fd
< FD_SETSIZE
) );
192 int i
= m_fd_idx
[fd
];
196 wxASSERT(m_fds
[i
] == fd
);
197 m_fds
[i
] = m_fds
[m_count
-1];
199 m_fds
[m_count
-1] = 0;
200 m_fd_idx
[fd
] = 0xffff;
201 m_fd_idx
[m_fds
[i
]] = i
;
205 void CSocketSet::FillSet(int &max_fd
)
209 for(int i
= 0; i
< m_count
; i
++) {
210 FD_SET(m_fds
[i
], &m_set
);
211 if ( m_fds
[i
] > max_fd
) {
217 void CSocketSet::Detected(void (GSocket::*func
)())
219 for (int i
= 0; i
< m_count
; i
++) {
221 if ( FD_ISSET(fd
, &m_set
) ) {
222 GSocket
*socket
= m_gsocks
[fd
];
228 CAmuledGSocketFuncTable::CAmuledGSocketFuncTable() : m_lock(wxMUTEX_RECURSIVE
)
230 m_in_set
= new CSocketSet
;
231 m_out_set
= new CSocketSet
;
236 void CAmuledGSocketFuncTable::AddSocket(GSocket
*socket
, GSocketEvent event
)
238 wxMutexLocker
lock(m_lock
);
240 if ( event
== GSOCK_INPUT
) {
241 m_in_set
->AddSocket(socket
);
243 m_out_set
->AddSocket(socket
);
247 void CAmuledGSocketFuncTable::RemoveSocket(GSocket
*socket
, GSocketEvent event
)
249 wxMutexLocker
lock(m_lock
);
251 if ( event
== GSOCK_INPUT
) {
252 m_in_set
->RemoveSocket(socket
);
254 m_out_set
->RemoveSocket(socket
);
258 void CAmuledGSocketFuncTable::RunSelect()
260 wxMutexLocker
lock(m_lock
);
263 m_in_set
->FillSet(max_fd
);
264 m_out_set
->FillSet(max_fd
);
268 tv
.tv_usec
= 10000; // 10ms
270 int result
= select(max_fd
+ 1, m_in_set
->Set(), m_out_set
->Set(), 0, &tv
);
272 m_in_set
->Detected(&GSocket::Detected_Read
);
273 m_out_set
->Detected(&GSocket::Detected_Write
);
277 GSocketGUIFunctionsTable
*CDaemonAppTraits::GetSocketGUIFunctionsTable()
282 bool CAmuledGSocketFuncTable::OnInit()
287 void CAmuledGSocketFuncTable::OnExit()
291 bool CAmuledGSocketFuncTable::CanUseEventLoop()
294 * FIXME: (lfroen) Not sure whether it's right.
295 * I will review it later.
300 bool CAmuledGSocketFuncTable::Init_Socket(GSocket
*)
305 void CAmuledGSocketFuncTable::Destroy_Socket(GSocket
*)
309 void CAmuledGSocketFuncTable::Install_Callback(GSocket
*sock
, GSocketEvent e
)
314 void CAmuledGSocketFuncTable::Uninstall_Callback(GSocket
*sock
, GSocketEvent e
)
316 RemoveSocket(sock
, e
);
319 void CAmuledGSocketFuncTable::Enable_Events(GSocket
*socket
)
321 Install_Callback(socket
, GSOCK_INPUT
);
322 Install_Callback(socket
, GSOCK_OUTPUT
);
325 void CAmuledGSocketFuncTable::Disable_Events(GSocket
*socket
)
327 Uninstall_Callback(socket
, GSOCK_INPUT
);
328 Uninstall_Callback(socket
, GSOCK_OUTPUT
);
332 CDaemonAppTraits::CDaemonAppTraits(CAmuledGSocketFuncTable
*table
)
334 wxConsoleAppTraits(),
335 m_oldSignalChildAction(),
336 m_newSignalChildAction(),
338 m_lock(wxMUTEX_RECURSIVE
),
345 void CDaemonAppTraits::ScheduleForDestroy(wxObject
*object
)
347 wxMutexLocker
lock(m_lock
);
350 m_sched_delete
.push_back(object
);
353 void CDaemonAppTraits::RemoveFromPendingDelete(wxObject
*object
)
355 wxMutexLocker
lock(m_lock
);
357 for(std::list
<wxObject
*>::iterator i
= m_sched_delete
.begin();
358 i
!= m_sched_delete
.end(); i
++) {
359 if ( *i
== object
) {
360 m_sched_delete
.erase(i
);
366 void CDaemonAppTraits::DeletePending()
368 wxMutexLocker
lock(m_lock
);
370 while ( !m_sched_delete
.empty() ) {
371 std::list
<wxObject
*>::iterator i
= m_sched_delete
.begin();
372 wxObject
*object
= *i
;
375 //m_sched_delete.erase(m_sched_delete.begin(), m_sched_delete.end());
378 wxAppTraits
*CamuleDaemonApp::CreateTraits()
380 return new CDaemonAppTraits(m_table
);
383 #else // AMULED28_SOCKETS
385 #ifdef AMULED_APPTRAITS
387 CDaemonAppTraits::CDaemonAppTraits()
389 wxConsoleAppTraits(),
390 m_oldSignalChildAction(),
391 m_newSignalChildAction()
395 wxAppTraits
*CamuleDaemonApp::CreateTraits()
397 return new CDaemonAppTraits();
400 #endif // AMULED_APPTRAITS
402 #endif // !AMULED28_SOCKETS
404 #if defined(__WXMAC__) && !wxCHECK_VERSION(2, 9, 0)
405 #include <wx/stdpaths.h> // Do_not_auto_remove (guess)
406 static wxStandardPathsCF gs_stdPaths
;
407 wxStandardPathsBase
& CDaemonAppTraits::GetStandardPaths()
414 #ifdef AMULED28_EVENTLOOP
416 CamuleDaemonApp::CamuleDaemonApp()
419 #ifdef AMULED28_SOCKETS
420 ,m_table(new CAmuledGSocketFuncTable())
423 // work around problem from http://trac.wxwidgets.org/ticket/2145
424 wxPendingEventsLocker
= new wxCriticalSection
;
427 #endif // AMULED28_EVENTLOOP
430 #ifdef AMULED_APPTRAITS
432 static EndProcessDataMap endProcDataMap
;
434 int CDaemonAppTraits::WaitForChild(wxExecuteData
&execData
)
438 // Build the log message
440 msg
<< wxT("WaitForChild() has been called for child process with pid `") <<
444 if (execData
.flags
& wxEXEC_SYNC
) {
445 result
= AmuleWaitPid(execData
.pid
, &status
, 0, &msg
);
446 if (result
== -1 || (!WIFEXITED(status
) && !WIFSIGNALED(status
))) {
447 msg
<< wxT(" Waiting for subprocess termination failed.");
448 AddDebugLogLineN(logGeneral
, msg
);
452 // Give the process a chance to start or forked child to exit
453 // 1 second is enough time to fail on "path not found"
455 result
= AmuleWaitPid(execData
.pid
, &status
, WNOHANG
, &msg
);
457 // Add a WxEndProcessData entry to the map, so that we can
458 // support process termination
459 wxEndProcessData
*endProcData
= new wxEndProcessData();
460 endProcData
->pid
= execData
.pid
;
461 endProcData
->process
= execData
.process
;
462 endProcData
->tag
= 0;
463 endProcDataMap
[execData
.pid
] = endProcData
;
465 status
= execData
.pid
;
467 // if result != 0, then either waitpid() failed (result == -1)
468 // and there is nothing we can do, or the child has changed
469 // status, which means it is probably dead.
474 // Log our passage here
475 AddDebugLogLineN(logGeneral
, msg
);
481 void OnSignalChildHandler(int /*signal*/, siginfo_t
*siginfo
, void * /*ucontext*/)
483 // Build the log message
485 msg
<< wxT("OnSignalChildHandler() has been called for child process with pid `") <<
488 // Make sure we leave no zombies by calling waitpid()
490 pid_t result
= AmuleWaitPid(siginfo
->si_pid
, &status
, WNOHANG
, &msg
);
491 if (result
!= 1 && result
!= 0 && (WIFEXITED(status
) || WIFSIGNALED(status
))) {
492 // Fetch the wxEndProcessData structure corresponding to this pid
493 EndProcessDataMap::iterator it
= endProcDataMap
.find(siginfo
->si_pid
);
494 if (it
!= endProcDataMap
.end()) {
495 wxEndProcessData
*endProcData
= it
->second
;
496 // Remove this entry from the process map
497 endProcDataMap
.erase(siginfo
->si_pid
);
498 // Save the exit code for the wxProcess object to read later
499 endProcData
->exitcode
= result
!= -1 && WIFEXITED(status
) ?
500 WEXITSTATUS(status
) : -1;
501 // Make things work as in wxGUI
502 wxHandleProcessTermination(endProcData
);
504 // wxHandleProcessTermination() will "delete endProcData;"
505 // So we do not delete it again, ok? Do not uncomment this line.
506 //delete endProcData;
508 msg
<< wxT(" Error: the child process pid is not on the pid map.");
512 // Log our passage here
513 AddDebugLogLineN(logGeneral
, msg
);
517 pid_t
AmuleWaitPid(pid_t pid
, int *status
, int options
, wxString
*msg
)
520 pid_t result
= waitpid(pid
, status
, options
);
522 *msg
<< CFormat(wxT("Error: waitpid() call failed: %m."));
523 } else if (result
== 0) {
524 if (options
& WNOHANG
) {
525 *msg
<< wxT("The child is alive.");
527 *msg
<< wxT("Error: waitpid() call returned 0 but "
528 "WNOHANG was not specified in options.");
531 if (WIFEXITED(*status
)) {
532 *msg
<< wxT("Child has terminated with status code `") <<
533 WEXITSTATUS(*status
) <<
535 } else if (WIFSIGNALED(*status
)) {
536 *msg
<< wxT("Child was killed by signal `") <<
539 if (WCOREDUMP(*status
)) {
540 *msg
<< wxT(" A core file has been dumped.");
542 } else if (WIFSTOPPED(*status
)) {
543 *msg
<< wxT("Child has been stopped by signal `") <<
546 #ifdef WIFCONTINUED /* Only found in recent kernels. */
547 } else if (WIFCONTINUED(*status
)) {
548 *msg
<< wxT("Child has received `SIGCONT' and has continued execution.");
551 *msg
<< wxT("The program was not able to determine why the child has signaled.");
558 #endif // AMULED_APPTRAITS
564 // see http://msdn.microsoft.com/en-us/library/windows/desktop/ms685049%28v=vs.85%29.aspx
566 static BOOL
CtrlHandler(DWORD fdwCtrlType
)
568 switch (fdwCtrlType
) {
570 case CTRL_CLOSE_EVENT
:
571 case CTRL_BREAK_EVENT
:
573 AddLogLineNS(wxT("Received break event, exit main loop"));
574 theApp
->ExitMainLoop();
577 case CTRL_LOGOFF_EVENT
:
578 case CTRL_SHUTDOWN_EVENT
:
580 // don't handle these
586 #endif // __WINDOWS__
589 int CamuleDaemonApp::OnRun()
591 if (!thePrefs::AcceptExternalConnections()) {
592 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"));
594 } else if (thePrefs::ECPassword().IsEmpty()) {
595 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"));
600 SetConsoleCtrlHandler((PHANDLER_ROUTINE
) CtrlHandler
, TRUE
);
601 #endif // __WINDOWS__
603 #ifdef AMULED_APPTRAITS
604 // Process the return code of dead children so that we do not create
605 // zombies. wxBase does not implement wxProcess callbacks, so no one
606 // actualy calls wxHandleProcessTermination() in console applications.
607 // We do our best here.
608 DEBUG_ONLY( int ret
= 0; )
609 DEBUG_ONLY( ret
= ) sigaction(SIGCHLD
, NULL
, &m_oldSignalChildAction
);
610 m_newSignalChildAction
= m_oldSignalChildAction
;
611 m_newSignalChildAction
.sa_sigaction
= OnSignalChildHandler
;
612 m_newSignalChildAction
.sa_flags
|= SA_SIGINFO
;
613 m_newSignalChildAction
.sa_flags
&= ~SA_RESETHAND
;
614 DEBUG_ONLY( ret
= ) sigaction(SIGCHLD
, &m_newSignalChildAction
, NULL
);
617 AddDebugLogLineC(logStandard
, CFormat(wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD callback with sigaction() failed: %m.")));
619 AddDebugLogLineN(logGeneral
, wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD callback with sigaction() succeeded."));
622 #endif // AMULED_APPTRAITS
624 #ifdef AMULED28_EVENTLOOP
627 #ifdef AMULED28_SOCKETS
628 m_table
->RunSelect();
629 ProcessPendingEvents();
630 ((CDaemonAppTraits
*)GetTraits())->DeletePending();
633 ProcessPendingEvents();
637 // ShutDown is beeing called twice. Once here and again in OnExit().
643 return wxApp::OnRun();
647 bool CamuleDaemonApp::OnInit()
649 if ( !CamuleApp::OnInit() ) {
652 AddLogLineNS(_("amuled: OnInit - starting timer"));
653 core_timer
= new CTimer(this,ID_CORE_TIMER_EVENT
);
654 core_timer
->Start(CORE_TIMER_PERIOD
);
655 glob_prefs
->GetCategory(0)->title
= GetCatTitle(thePrefs::GetAllcatFilter());
656 glob_prefs
->GetCategory(0)->path
= thePrefs::GetIncomingDir();
661 int CamuleDaemonApp::InitGui(bool ,wxString
&)
664 if ( !enable_daemon_fork
) {
667 AddLogLineNS(_("amuled: forking to background - see you"));
668 theLogger
.SetEnabledStdoutLog(false);
670 // fork to background and detach from controlling tty
671 // while redirecting stdout to /dev/null
673 for(int i_fd
= 0;i_fd
< 3; i_fd
++) {
676 int fd
= open("/dev/null",O_RDWR
);
677 if (dup(fd
)){} // prevent GCC warning
688 // Create a Pid file with the Pid of the Child, so any daemon-manager
689 // can easily manage the process
691 if (!m_PidFile
.IsEmpty()) {
692 wxString temp
= CFormat(wxT("%d\n")) % pid
;
693 wxFFile
ff(m_PidFile
, wxT("w"));
698 AddLogLineNS(_("Cannot Create Pid File"));
708 int CamuleDaemonApp::OnExit()
710 #ifdef AMULED28_SOCKETS
712 * Stop all socket threads before entering
725 #ifdef AMULED_APPTRAITS
726 DEBUG_ONLY( int ret
= ) sigaction(SIGCHLD
, &m_oldSignalChildAction
, NULL
);
729 AddDebugLogLineC(logStandard
, CFormat(wxT("CamuleDaemonApp::OnRun(): second sigaction() failed: %m.")));
731 AddDebugLogLineN(logGeneral
, wxT("CamuleDaemonApp::OnRun(): Uninstallation of SIGCHLD callback with sigaction() succeeded."));
734 #endif // AMULED_APPTRAITS
738 return CamuleApp::OnExit();
742 int CamuleDaemonApp::ShowAlert(wxString msg
, wxString title
, int flags
)
744 if ( flags
| wxICON_ERROR
) {
745 title
= CFormat(_("ERROR: %s")) % title
;
747 AddLogLineCS(title
+ wxT(" ") + msg
);
749 return 0; // That's neither yes nor no, ok, cancel
752 // File_checked_for_headers