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
73 #include <wx/unix/execute.h>
76 BEGIN_EVENT_TABLE(CamuleDaemonApp
, wxAppConsole
)
82 EVT_SOCKET(ID_LISTENSOCKET_EVENT
, CamuleDaemonApp::ListenSocketHandler
)
84 // UDP Socket (servers)
85 EVT_SOCKET(ID_SERVERUDPSOCKET_EVENT
, CamuleDaemonApp::UDPSocketHandler
)
86 // UDP Socket (clients)
87 EVT_SOCKET(ID_CLIENTUDPSOCKET_EVENT
, CamuleDaemonApp::UDPSocketHandler
)
90 EVT_MULE_TIMER(ID_SERVER_RETRY_TIMER_EVENT
, CamuleDaemonApp::OnTCPTimer
)
93 EVT_MULE_TIMER(ID_CORE_TIMER_EVENT
, CamuleDaemonApp::OnCoreTimer
)
95 EVT_MULE_NOTIFY(CamuleDaemonApp::OnNotifyEvent
)
98 EVT_MULE_INTERNAL(wxEVT_CORE_UDP_DNS_DONE
, -1, CamuleDaemonApp::OnUDPDnsDone
)
100 EVT_MULE_INTERNAL(wxEVT_CORE_SOURCE_DNS_DONE
, -1, CamuleDaemonApp::OnSourceDnsDone
)
102 EVT_MULE_INTERNAL(wxEVT_CORE_SERVER_DNS_DONE
, -1, CamuleDaemonApp::OnServerDnsDone
)
104 // Hash ended notifier
105 EVT_MULE_HASHING(CamuleDaemonApp::OnFinishedHashing
)
106 EVT_MULE_AICH_HASHING(CamuleDaemonApp::OnFinishedAICHHashing
)
108 // File completion ended notifier
109 EVT_MULE_FILE_COMPLETED(CamuleDaemonApp::OnFinishedCompletion
)
111 // HTTPDownload finished
112 EVT_MULE_INTERNAL(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD
, -1, CamuleDaemonApp::OnFinishedHTTPDownload
)
114 // Disk space preallocation finished
115 EVT_MULE_ALLOC_FINISHED(CamuleDaemonApp::OnFinishedAllocation
)
118 IMPLEMENT_APP(CamuleDaemonApp
)
122 * Socket handling in wxBase
127 int m_fds
[FD_SETSIZE
], m_fd_idx
[FD_SETSIZE
];
128 GSocket
*m_gsocks
[FD_SETSIZE
];
133 void AddSocket(GSocket
*);
134 void RemoveSocket(GSocket
*);
135 void FillSet(int &max_fd
);
137 void Detected(void (GSocket::*func
)());
139 fd_set
*Set() { return &m_set
; }
142 CSocketSet::CSocketSet()
145 for(int i
= 0; i
< FD_SETSIZE
; i
++) {
147 m_fd_idx
[i
] = 0xffff;
152 void CSocketSet::AddSocket(GSocket
*socket
)
156 int fd
= socket
->m_fd
;
162 wxASSERT( (fd
> 2) && (fd
< FD_SETSIZE
) );
164 if ( m_gsocks
[fd
] ) {
168 m_fd_idx
[fd
] = m_count
;
169 m_gsocks
[fd
] = socket
;
173 void CSocketSet::RemoveSocket(GSocket
*socket
)
177 int fd
= socket
->m_fd
;
183 wxASSERT( (fd
> 2) && (fd
< FD_SETSIZE
) );
185 int i
= m_fd_idx
[fd
];
189 wxASSERT(m_fds
[i
] == fd
);
190 m_fds
[i
] = m_fds
[m_count
-1];
192 m_fds
[m_count
-1] = 0;
193 m_fd_idx
[fd
] = 0xffff;
194 m_fd_idx
[m_fds
[i
]] = i
;
198 void CSocketSet::FillSet(int &max_fd
)
202 for(int i
= 0; i
< m_count
; i
++) {
203 FD_SET(m_fds
[i
], &m_set
);
204 if ( m_fds
[i
] > max_fd
) {
210 void CSocketSet::Detected(void (GSocket::*func
)())
212 for (int i
= 0; i
< m_count
; i
++) {
214 if ( FD_ISSET(fd
, &m_set
) ) {
215 GSocket
*socket
= m_gsocks
[fd
];
221 CAmuledGSocketFuncTable::CAmuledGSocketFuncTable() : m_lock(wxMUTEX_RECURSIVE
)
223 m_in_set
= new CSocketSet
;
224 m_out_set
= new CSocketSet
;
229 void CAmuledGSocketFuncTable::AddSocket(GSocket
*socket
, GSocketEvent event
)
231 wxMutexLocker
lock(m_lock
);
233 if ( event
== GSOCK_INPUT
) {
234 m_in_set
->AddSocket(socket
);
236 m_out_set
->AddSocket(socket
);
240 void CAmuledGSocketFuncTable::RemoveSocket(GSocket
*socket
, GSocketEvent event
)
242 wxMutexLocker
lock(m_lock
);
244 if ( event
== GSOCK_INPUT
) {
245 m_in_set
->RemoveSocket(socket
);
247 m_out_set
->RemoveSocket(socket
);
251 void CAmuledGSocketFuncTable::RunSelect()
253 wxMutexLocker
lock(m_lock
);
256 m_in_set
->FillSet(max_fd
);
257 m_out_set
->FillSet(max_fd
);
261 tv
.tv_usec
= 10000; // 10ms
263 int result
= select(max_fd
+ 1, m_in_set
->Set(), m_out_set
->Set(), 0, &tv
);
265 m_in_set
->Detected(&GSocket::Detected_Read
);
266 m_out_set
->Detected(&GSocket::Detected_Write
);
270 GSocketGUIFunctionsTable
*CDaemonAppTraits::GetSocketGUIFunctionsTable()
275 bool CAmuledGSocketFuncTable::OnInit()
280 void CAmuledGSocketFuncTable::OnExit()
284 bool CAmuledGSocketFuncTable::CanUseEventLoop()
287 * FIXME: (lfroen) Not sure whether it's right.
288 * I will review it later.
293 bool CAmuledGSocketFuncTable::Init_Socket(GSocket
*)
298 void CAmuledGSocketFuncTable::Destroy_Socket(GSocket
*)
302 void CAmuledGSocketFuncTable::Install_Callback(GSocket
*sock
, GSocketEvent e
)
307 void CAmuledGSocketFuncTable::Uninstall_Callback(GSocket
*sock
, GSocketEvent e
)
309 RemoveSocket(sock
, e
);
312 void CAmuledGSocketFuncTable::Enable_Events(GSocket
*socket
)
314 Install_Callback(socket
, GSOCK_INPUT
);
315 Install_Callback(socket
, GSOCK_OUTPUT
);
318 void CAmuledGSocketFuncTable::Disable_Events(GSocket
*socket
)
320 Uninstall_Callback(socket
, GSOCK_INPUT
);
321 Uninstall_Callback(socket
, GSOCK_OUTPUT
);
330 CDaemonAppTraits::CDaemonAppTraits(CAmuledGSocketFuncTable
*table
)
332 wxConsoleAppTraits(),
333 m_oldSignalChildAction(),
334 m_newSignalChildAction(),
336 m_lock(wxMUTEX_RECURSIVE
),
343 void CDaemonAppTraits::ScheduleForDestroy(wxObject
*object
)
345 wxMutexLocker
lock(m_lock
);
348 m_sched_delete
.push_back(object
);
351 void CDaemonAppTraits::RemoveFromPendingDelete(wxObject
*object
)
353 wxMutexLocker
lock(m_lock
);
355 for(std::list
<wxObject
*>::iterator i
= m_sched_delete
.begin();
356 i
!= m_sched_delete
.end(); i
++) {
357 if ( *i
== object
) {
358 m_sched_delete
.erase(i
);
364 void CDaemonAppTraits::DeletePending()
366 wxMutexLocker
lock(m_lock
);
368 while ( !m_sched_delete
.empty() ) {
369 std::list
<wxObject
*>::iterator i
= m_sched_delete
.begin();
370 wxObject
*object
= *i
;
373 //m_sched_delete.erase(m_sched_delete.begin(), m_sched_delete.end());
376 wxAppTraits
*CamuleDaemonApp::CreateTraits()
378 return new CDaemonAppTraits(m_table
);
383 CDaemonAppTraits::CDaemonAppTraits()
385 wxConsoleAppTraits(),
386 m_oldSignalChildAction(),
387 m_newSignalChildAction()
391 wxAppTraits
*CamuleDaemonApp::CreateTraits()
393 return new CDaemonAppTraits();
400 #if defined(__WXMAC__) && !wxCHECK_VERSION(2, 9, 0)
401 #include <wx/stdpaths.h> // Do_not_auto_remove (guess)
402 static wxStandardPathsCF gs_stdPaths
;
403 wxStandardPathsBase
& CDaemonAppTraits::GetStandardPaths()
412 CamuleDaemonApp::CamuleDaemonApp()
415 m_table(new CAmuledGSocketFuncTable())
417 wxPendingEventsLocker
= new wxCriticalSection
;
426 static EndProcessDataMap endProcDataMap
;
429 int CDaemonAppTraits::WaitForChild(wxExecuteData
&execData
)
433 // Build the log message
435 msg
<< wxT("WaitForChild() has been called for child process with pid `") <<
439 if (execData
.flags
& wxEXEC_SYNC
) {
440 result
= AmuleWaitPid(execData
.pid
, &status
, 0, &msg
);
441 if (result
== -1 || (!WIFEXITED(status
) && !WIFSIGNALED(status
))) {
442 msg
<< wxT(" Waiting for subprocess termination failed.");
443 AddDebugLogLineN(logGeneral
, msg
);
447 // Give the process a chance to start or forked child to exit
448 // 1 second is enough time to fail on "path not found"
450 result
= AmuleWaitPid(execData
.pid
, &status
, WNOHANG
, &msg
);
452 // Add a WxEndProcessData entry to the map, so that we can
453 // support process termination
454 wxEndProcessData
*endProcData
= new wxEndProcessData();
455 endProcData
->pid
= execData
.pid
;
456 endProcData
->process
= execData
.process
;
457 endProcData
->tag
= 0;
458 endProcDataMap
[execData
.pid
] = endProcData
;
460 status
= execData
.pid
;
462 // if result != 0, then either waitpid() failed (result == -1)
463 // and there is nothing we can do, or the child has changed
464 // status, which means it is probably dead.
469 // Log our passage here
470 AddDebugLogLineN(logGeneral
, msg
);
476 void OnSignalChildHandler(int /*signal*/, siginfo_t
*siginfo
, void * /*ucontext*/)
478 // Build the log message
480 msg
<< wxT("OnSignalChildHandler() has been called for child process with pid `") <<
483 // Make sure we leave no zombies by calling waitpid()
485 pid_t result
= AmuleWaitPid(siginfo
->si_pid
, &status
, WNOHANG
, &msg
);
486 if (result
!= 1 && result
!= 0 && (WIFEXITED(status
) || WIFSIGNALED(status
))) {
487 // Fetch the wxEndProcessData structure corresponding to this pid
488 EndProcessDataMap::iterator it
= endProcDataMap
.find(siginfo
->si_pid
);
489 if (it
!= endProcDataMap
.end()) {
490 wxEndProcessData
*endProcData
= it
->second
;
491 // Remove this entry from the process map
492 endProcDataMap
.erase(siginfo
->si_pid
);
493 // Save the exit code for the wxProcess object to read later
494 endProcData
->exitcode
= result
!= -1 && WIFEXITED(status
) ?
495 WEXITSTATUS(status
) : -1;
496 // Make things work as in wxGUI
497 wxHandleProcessTermination(endProcData
);
499 // wxHandleProcessTermination() will "delete endProcData;"
500 // So we do not delete it again, ok? Do not uncomment this line.
501 //delete endProcData;
503 msg
<< wxT(" Error: the child process pid is not on the pid map.");
507 // Log our passage here
508 AddDebugLogLineN(logGeneral
, msg
);
512 pid_t
AmuleWaitPid(pid_t pid
, int *status
, int options
, wxString
*msg
)
515 pid_t result
= waitpid(pid
, status
, options
);
517 *msg
<< CFormat(wxT("Error: waitpid() call failed: %m."));
518 } else if (result
== 0) {
519 if (options
& WNOHANG
) {
520 *msg
<< wxT("The child is alive.");
522 *msg
<< wxT("Error: waitpid() call returned 0 but "
523 "WNOHANG was not specified in options.");
526 if (WIFEXITED(*status
)) {
527 *msg
<< wxT("Child has terminated with status code `") <<
528 WEXITSTATUS(*status
) <<
530 } else if (WIFSIGNALED(*status
)) {
531 *msg
<< wxT("Child was killed by signal `") <<
534 if (WCOREDUMP(*status
)) {
535 *msg
<< wxT(" A core file has been dumped.");
537 } else if (WIFSTOPPED(*status
)) {
538 *msg
<< wxT("Child has been stopped by signal `") <<
541 #ifdef WIFCONTINUED /* Only found in recent kernels. */
542 } else if (WIFCONTINUED(*status
)) {
543 *msg
<< wxT("Child has received `SIGCONT' and has continued execution.");
546 *msg
<< wxT("The program was not able to determine why the child has signaled.");
557 int CamuleDaemonApp::OnRun()
559 if (!thePrefs::AcceptExternalConnections()) {
560 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"));
562 } else if (thePrefs::ECPassword().IsEmpty()) {
563 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"));
568 // Process the return code of dead children so that we do not create
569 // zombies. wxBase does not implement wxProcess callbacks, so no one
570 // actualy calls wxHandleProcessTermination() in console applications.
571 // We do our best here.
573 ret
= sigaction(SIGCHLD
, NULL
, &m_oldSignalChildAction
);
574 m_newSignalChildAction
= m_oldSignalChildAction
;
575 m_newSignalChildAction
.sa_sigaction
= OnSignalChildHandler
;
576 m_newSignalChildAction
.sa_flags
|= SA_SIGINFO
;
577 m_newSignalChildAction
.sa_flags
&= ~SA_RESETHAND
;
578 ret
= sigaction(SIGCHLD
, &m_newSignalChildAction
, NULL
);
580 AddDebugLogLineC(logStandard
, CFormat(wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD callback with sigaction() failed: %m.")));
582 AddDebugLogLineN(logGeneral
, wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD callback with sigaction() succeeded."));
589 m_table
->RunSelect();
590 ProcessPendingEvents();
591 ((CDaemonAppTraits
*)GetTraits())->DeletePending();
594 // ShutDown is beeing called twice. Once here and again in OnExit().
604 return wxApp::OnRun();
610 bool CamuleDaemonApp::OnInit()
612 if ( !CamuleApp::OnInit() ) {
615 AddLogLineNS(_("amuled: OnInit - starting timer"));
616 core_timer
= new CTimer(this,ID_CORE_TIMER_EVENT
);
617 core_timer
->Start(CORE_TIMER_PERIOD
);
618 glob_prefs
->GetCategory(0)->title
= GetCatTitle(thePrefs::GetAllcatFilter());
619 glob_prefs
->GetCategory(0)->path
= thePrefs::GetIncomingDir();
624 int CamuleDaemonApp::InitGui(bool ,wxString
&)
627 if ( !enable_daemon_fork
) {
630 AddLogLineNS(_("amuled: forking to background - see you"));
631 theLogger
.SetEnabledStdoutLog(false);
633 // fork to background and detach from controlling tty
634 // while redirecting stdout to /dev/null
636 for(int i_fd
= 0;i_fd
< 3; i_fd
++) {
639 int fd
= open("/dev/null",O_RDWR
);
640 if (dup(fd
)){} // prevent GCC warning
651 // Create a Pid file with the Pid of the Child, so any daemon-manager
652 // can easily manage the process
654 if (!m_PidFile
.IsEmpty()) {
655 wxString temp
= CFormat(wxT("%d\n")) % pid
;
656 wxFFile
ff(m_PidFile
, wxT("w"));
661 AddLogLineNS(_("Cannot Create Pid File"));
671 int CamuleDaemonApp::OnExit()
675 * Stop all socket threads before entering
689 int ret
= sigaction(SIGCHLD
, &m_oldSignalChildAction
, NULL
);
691 AddDebugLogLineC(logStandard
, CFormat(wxT("CamuleDaemonApp::OnRun(): second sigaction() failed: %m.")));
693 AddDebugLogLineN(logGeneral
, wxT("CamuleDaemonApp::OnRun(): Uninstallation of SIGCHLD callback with sigaction() succeeded."));
697 // lfroen: delete socket threads
698 if (ECServerHandler
) {
704 return CamuleApp::OnExit();
708 int CamuleDaemonApp::ShowAlert(wxString msg
, wxString title
, int flags
)
710 if ( flags
| wxICON_ERROR
) {
711 title
= CFormat(_("ERROR: %s")) % title
;
713 AddLogLineCS(title
+ wxT(" ") + msg
);
715 return 0; // That's neither yes nor no, ok, cancel
718 // File_checked_for_headers