2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-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
26 #include "amule.h" // Interface declarations.
28 #include <include/common/EventIDs.h>
31 #include "config.h" // Needed for HAVE_SYS_RESOURCE_H, HAVE_STRERROR_R and STRERROR_R_CHAR_P, 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>
49 // Prefer the POSIX interface to strerror_r()
51 #define _XOPEN_SOURCE 600
53 #include <string.h> // Do_not_auto_remove
57 #include "Preferences.h" // Needed for CPreferences
58 #include "PartFile.h" // Needed for CPartFile
60 #include <common/Format.h>
61 #include "InternalEvents.h" // Needed for wxEVT_*
62 #include "ThreadTasks.h"
63 #include "GuiEvents.h" // Needed for EVT_MULE_NOTIFY
64 #include "Timer.h" // Needed for EVT_MULE_TIMER
66 #include "ClientUDPSocket.h" // Do_not_auto_remove (forward declaration not enough)
67 #include "ListenSocket.h" // Do_not_auto_remove (forward declaration not enough)
71 #ifdef HAVE_SYS_RESOURCE_H
72 #include <sys/resource.h> // Do_not_auto_remove
76 #ifdef HAVE_SYS_WAIT_H
77 #include <sys/wait.h> // Do_not_auto_remove
80 #include <wx/unix/execute.h>
83 #ifndef HAVE_STRERROR_R
85 // Replacement strerror_r() function for systems that don't have any.
86 // Note that this replacement function is NOT thread-safe!
87 static int rpl_strerror_r(int errnum
, char *buf
, size_t buflen
)
89 char *tmp
= strerror(errnum
);
94 strncpy(buf
, tmp
, buflen
- 1);
95 buf
[buflen
- 1] = '\0';
96 if (strlen(tmp
) >= buflen
) {
104 # define strerror_r(errnum, buf, buflen) rpl_strerror_r(errnum, buf, buflen)
106 # ifdef STRERROR_R_CHAR_P
108 // Replacement strerror_r() function for systems that return a char*.
109 static int rpl_strerror_r(int errnum
, char *buf
, size_t buflen
)
111 char *tmp
= strerror_r(errnum
, buf
, buflen
);
115 } else if (tmp
!= buf
) {
116 strncpy(buf
, tmp
, buflen
- 1);
117 buf
[buflen
- 1] = '\0';
118 if (strlen(tmp
) >= buflen
) {
126 # define strerror_r(errnum, buf, buflen) rpl_strerror_r(errnum, buf, buflen)
130 BEGIN_EVENT_TABLE(CamuleDaemonApp
, wxAppConsole
)
136 EVT_SOCKET(ID_LISTENSOCKET_EVENT
, CamuleDaemonApp::ListenSocketHandler
)
138 // UDP Socket (servers)
139 EVT_SOCKET(ID_SERVERUDPSOCKET_EVENT
, CamuleDaemonApp::UDPSocketHandler
)
140 // UDP Socket (clients)
141 EVT_SOCKET(ID_CLIENTUDPSOCKET_EVENT
, CamuleDaemonApp::UDPSocketHandler
)
143 // Socket timer (TCP)
144 EVT_MULE_TIMER(ID_SERVER_RETRY_TIMER_EVENT
, CamuleDaemonApp::OnTCPTimer
)
147 EVT_MULE_TIMER(ID_CORE_TIMER_EVENT
, CamuleDaemonApp::OnCoreTimer
)
149 EVT_MULE_NOTIFY(CamuleDaemonApp::OnNotifyEvent
)
151 // Async dns handling
152 EVT_MULE_INTERNAL(wxEVT_CORE_UDP_DNS_DONE
, -1, CamuleDaemonApp::OnUDPDnsDone
)
154 EVT_MULE_INTERNAL(wxEVT_CORE_SOURCE_DNS_DONE
, -1, CamuleDaemonApp::OnSourceDnsDone
)
156 EVT_MULE_INTERNAL(wxEVT_CORE_SERVER_DNS_DONE
, -1, CamuleDaemonApp::OnServerDnsDone
)
158 // Hash ended notifier
159 EVT_MULE_HASHING(CamuleDaemonApp::OnFinishedHashing
)
160 EVT_MULE_AICH_HASHING(CamuleDaemonApp::OnFinishedAICHHashing
)
162 // File completion ended notifier
163 EVT_MULE_FILE_COMPLETED(CamuleDaemonApp::OnFinishedCompletion
)
165 // HTTPDownload finished
166 EVT_MULE_INTERNAL(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD
, -1, CamuleDaemonApp::OnFinishedHTTPDownload
)
168 // Disk space preallocation finished
169 EVT_MULE_ALLOC_FINISHED(CamuleDaemonApp::OnFinishedAllocation
)
172 IMPLEMENT_APP(CamuleDaemonApp
)
176 * Socket handling in wxBase
181 int m_fds
[FD_SETSIZE
], m_fd_idx
[FD_SETSIZE
];
182 GSocket
*m_gsocks
[FD_SETSIZE
];
187 void AddSocket(GSocket
*);
188 void RemoveSocket(GSocket
*);
189 void FillSet(int &max_fd
);
191 void Detected(void (GSocket::*func
)());
193 fd_set
*Set() { return &m_set
; }
196 CSocketSet::CSocketSet()
199 for(int i
= 0; i
< FD_SETSIZE
; i
++) {
201 m_fd_idx
[i
] = 0xffff;
206 void CSocketSet::AddSocket(GSocket
*socket
)
210 int fd
= socket
->m_fd
;
216 wxASSERT( (fd
> 2) && (fd
< FD_SETSIZE
) );
218 if ( m_gsocks
[fd
] ) {
222 m_fd_idx
[fd
] = m_count
;
223 m_gsocks
[fd
] = socket
;
227 void CSocketSet::RemoveSocket(GSocket
*socket
)
231 int fd
= socket
->m_fd
;
237 wxASSERT( (fd
> 2) && (fd
< FD_SETSIZE
) );
239 int i
= m_fd_idx
[fd
];
243 wxASSERT(m_fds
[i
] == fd
);
244 m_fds
[i
] = m_fds
[m_count
-1];
246 m_fds
[m_count
-1] = 0;
247 m_fd_idx
[fd
] = 0xffff;
248 m_fd_idx
[m_fds
[i
]] = i
;
252 void CSocketSet::FillSet(int &max_fd
)
256 for(int i
= 0; i
< m_count
; i
++) {
257 FD_SET(m_fds
[i
], &m_set
);
258 if ( m_fds
[i
] > max_fd
) {
264 void CSocketSet::Detected(void (GSocket::*func
)())
266 for (int i
= 0; i
< m_count
; i
++) {
268 if ( FD_ISSET(fd
, &m_set
) ) {
269 GSocket
*socket
= m_gsocks
[fd
];
275 CAmuledGSocketFuncTable::CAmuledGSocketFuncTable() : m_lock(wxMUTEX_RECURSIVE
)
277 m_in_set
= new CSocketSet
;
278 m_out_set
= new CSocketSet
;
283 void CAmuledGSocketFuncTable::AddSocket(GSocket
*socket
, GSocketEvent event
)
285 wxMutexLocker
lock(m_lock
);
287 if ( event
== GSOCK_INPUT
) {
288 m_in_set
->AddSocket(socket
);
290 m_out_set
->AddSocket(socket
);
294 void CAmuledGSocketFuncTable::RemoveSocket(GSocket
*socket
, GSocketEvent event
)
296 wxMutexLocker
lock(m_lock
);
298 if ( event
== GSOCK_INPUT
) {
299 m_in_set
->RemoveSocket(socket
);
301 m_out_set
->RemoveSocket(socket
);
305 void CAmuledGSocketFuncTable::RunSelect()
307 wxMutexLocker
lock(m_lock
);
310 m_in_set
->FillSet(max_fd
);
311 m_out_set
->FillSet(max_fd
);
315 tv
.tv_usec
= 10000; // 10ms
317 int result
= select(max_fd
+ 1, m_in_set
->Set(), m_out_set
->Set(), 0, &tv
);
319 m_in_set
->Detected(&GSocket::Detected_Read
);
320 m_out_set
->Detected(&GSocket::Detected_Write
);
324 GSocketGUIFunctionsTable
*CDaemonAppTraits::GetSocketGUIFunctionsTable()
329 bool CAmuledGSocketFuncTable::OnInit()
334 void CAmuledGSocketFuncTable::OnExit()
338 bool CAmuledGSocketFuncTable::CanUseEventLoop()
341 * FIXME: (lfroen) Not sure whether it's right.
342 * I will review it later.
347 bool CAmuledGSocketFuncTable::Init_Socket(GSocket
*)
352 void CAmuledGSocketFuncTable::Destroy_Socket(GSocket
*)
356 void CAmuledGSocketFuncTable::Install_Callback(GSocket
*sock
, GSocketEvent e
)
361 void CAmuledGSocketFuncTable::Uninstall_Callback(GSocket
*sock
, GSocketEvent e
)
363 RemoveSocket(sock
, e
);
366 void CAmuledGSocketFuncTable::Enable_Events(GSocket
*socket
)
368 Install_Callback(socket
, GSOCK_INPUT
);
369 Install_Callback(socket
, GSOCK_OUTPUT
);
372 void CAmuledGSocketFuncTable::Disable_Events(GSocket
*socket
)
374 Uninstall_Callback(socket
, GSOCK_INPUT
);
375 Uninstall_Callback(socket
, GSOCK_OUTPUT
);
384 CDaemonAppTraits::CDaemonAppTraits(CAmuledGSocketFuncTable
*table
)
386 wxConsoleAppTraits(),
387 m_oldSignalChildAction(),
388 m_newSignalChildAction(),
390 m_lock(wxMUTEX_RECURSIVE
),
397 void CDaemonAppTraits::ScheduleForDestroy(wxObject
*object
)
399 wxMutexLocker
lock(m_lock
);
402 m_sched_delete
.push_back(object
);
405 void CDaemonAppTraits::RemoveFromPendingDelete(wxObject
*object
)
407 wxMutexLocker
lock(m_lock
);
409 for(std::list
<wxObject
*>::iterator i
= m_sched_delete
.begin();
410 i
!= m_sched_delete
.end(); i
++) {
411 if ( *i
== object
) {
412 m_sched_delete
.erase(i
);
418 void CDaemonAppTraits::DeletePending()
420 wxMutexLocker
lock(m_lock
);
422 while ( !m_sched_delete
.empty() ) {
423 std::list
<wxObject
*>::iterator i
= m_sched_delete
.begin();
424 wxObject
*object
= *i
;
427 //m_sched_delete.erase(m_sched_delete.begin(), m_sched_delete.end());
430 wxAppTraits
*CamuleDaemonApp::CreateTraits()
432 return new CDaemonAppTraits(m_table
);
437 CDaemonAppTraits::CDaemonAppTraits()
439 wxConsoleAppTraits(),
440 m_oldSignalChildAction(),
441 m_newSignalChildAction()
445 wxAppTraits
*CamuleDaemonApp::CreateTraits()
447 return new CDaemonAppTraits();
454 #if defined(__WXMAC__) && !wxCHECK_VERSION(2, 9, 0)
455 #include <wx/stdpaths.h> // Do_not_auto_remove (guess)
456 static wxStandardPathsCF gs_stdPaths
;
457 wxStandardPathsBase
& CDaemonAppTraits::GetStandardPaths()
466 CamuleDaemonApp::CamuleDaemonApp()
469 m_table(new CAmuledGSocketFuncTable())
471 wxPendingEventsLocker
= new wxCriticalSection
;
480 static EndProcessDataMap endProcDataMap
;
483 int CDaemonAppTraits::WaitForChild(wxExecuteData
&execData
)
487 // Build the log message
489 msg
<< wxT("WaitForChild() has been called for child process with pid `") <<
493 if (execData
.flags
& wxEXEC_SYNC
) {
494 result
= AmuleWaitPid(execData
.pid
, &status
, 0, &msg
);
495 if (result
== -1 || (!WIFEXITED(status
) && !WIFSIGNALED(status
))) {
496 msg
<< wxT(" Waiting for subprocess termination failed.");
497 AddDebugLogLineN(logGeneral
, msg
);
501 // Give the process a chance to start or forked child to exit
502 // 1 second is enough time to fail on "path not found"
504 result
= AmuleWaitPid(execData
.pid
, &status
, WNOHANG
, &msg
);
506 // Add a WxEndProcessData entry to the map, so that we can
507 // support process termination
508 wxEndProcessData
*endProcData
= new wxEndProcessData();
509 endProcData
->pid
= execData
.pid
;
510 endProcData
->process
= execData
.process
;
511 endProcData
->tag
= 0;
512 endProcDataMap
[execData
.pid
] = endProcData
;
514 status
= execData
.pid
;
516 // if result != 0, then either waitpid() failed (result == -1)
517 // and there is nothing we can do, or the child has changed
518 // status, which means it is probably dead.
523 // Log our passage here
524 AddDebugLogLineN(logGeneral
, msg
);
530 void OnSignalChildHandler(int /*signal*/, siginfo_t
*siginfo
, void * /*ucontext*/)
532 // Build the log message
534 msg
<< wxT("OnSignalChildHandler() has been called for child process with pid `") <<
537 // Make sure we leave no zombies by calling waitpid()
539 pid_t result
= AmuleWaitPid(siginfo
->si_pid
, &status
, WNOHANG
, &msg
);
540 if (result
!= 1 && result
!= 0 && (WIFEXITED(status
) || WIFSIGNALED(status
))) {
541 // Fetch the wxEndProcessData structure corresponding to this pid
542 EndProcessDataMap::iterator it
= endProcDataMap
.find(siginfo
->si_pid
);
543 if (it
!= endProcDataMap
.end()) {
544 wxEndProcessData
*endProcData
= it
->second
;
545 // Remove this entry from the process map
546 endProcDataMap
.erase(siginfo
->si_pid
);
547 // Save the exit code for the wxProcess object to read later
548 endProcData
->exitcode
= result
!= -1 && WIFEXITED(status
) ?
549 WEXITSTATUS(status
) : -1;
550 // Make things work as in wxGUI
551 wxHandleProcessTermination(endProcData
);
553 // wxHandleProcessTermination() will "delete endProcData;"
554 // So we do not delete it again, ok? Do not uncomment this line.
555 //delete endProcData;
557 msg
<< wxT(" Error: the child process pid is not on the pid map.");
561 // Log our passage here
562 AddDebugLogLineN(logGeneral
, msg
);
566 pid_t
AmuleWaitPid(pid_t pid
, int *status
, int options
, wxString
*msg
)
568 // strerror_r() buffer
569 const int ERROR_BUFFER_LEN
= 256;
570 char errorBuffer
[ERROR_BUFFER_LEN
];
573 pid_t result
= waitpid(pid
, status
, options
);
575 strerror_r(errno
, errorBuffer
, ERROR_BUFFER_LEN
);
576 *msg
<< wxT("Error: waitpid() call failed: ") <<
577 char2unicode(errorBuffer
) <<
579 } else if (result
== 0) {
580 if (options
& WNOHANG
) {
581 *msg
<< wxT("The child is alive.");
583 *msg
<< wxT("Error: waitpid() call returned 0 but "
584 "WNOHANG was not specified in options.");
587 if (WIFEXITED(*status
)) {
588 *msg
<< wxT("Child has terminated with status code `") <<
589 WEXITSTATUS(*status
) <<
591 } else if (WIFSIGNALED(*status
)) {
592 *msg
<< wxT("Child was killed by signal `") <<
595 if (WCOREDUMP(*status
)) {
596 *msg
<< wxT(" A core file has been dumped.");
598 } else if (WIFSTOPPED(*status
)) {
599 *msg
<< wxT("Child has been stopped by signal `") <<
602 #ifdef WIFCONTINUED /* Only found in recent kernels. */
603 } else if (WIFCONTINUED(*status
)) {
604 *msg
<< wxT("Child has received `SIGCONT' and has continued execution.");
607 *msg
<< wxT("The program was not able to determine why the child has signaled.");
618 int CamuleDaemonApp::OnRun()
620 if (!thePrefs::AcceptExternalConnections()) {
621 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"));
623 } else if (thePrefs::ECPassword().IsEmpty()) {
624 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"));
629 // strerror_r() buffer
630 const int ERROR_BUFFER_LEN
= 256;
631 char errorBuffer
[ERROR_BUFFER_LEN
];
633 // Process the return code of dead children so that we do not create
634 // zombies. wxBase does not implement wxProcess callbacks, so no one
635 // actualy calls wxHandleProcessTermination() in console applications.
636 // We do our best here.
638 ret
= sigaction(SIGCHLD
, NULL
, &m_oldSignalChildAction
);
639 m_newSignalChildAction
= m_oldSignalChildAction
;
640 m_newSignalChildAction
.sa_sigaction
= OnSignalChildHandler
;
641 m_newSignalChildAction
.sa_flags
|= SA_SIGINFO
;
642 m_newSignalChildAction
.sa_flags
&= ~SA_RESETHAND
;
643 ret
= sigaction(SIGCHLD
, &m_newSignalChildAction
, NULL
);
645 strerror_r(errno
, errorBuffer
, ERROR_BUFFER_LEN
);
646 AddDebugLogLineC(logStandard
, wxString(wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD callback with sigaction() failed: ")) << char2unicode(errorBuffer
) << wxT("."));
648 AddDebugLogLineN(logGeneral
, wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD callback with sigaction() succeeded."));
655 m_table
->RunSelect();
656 ProcessPendingEvents();
657 ((CDaemonAppTraits
*)GetTraits())->DeletePending();
660 // ShutDown is beeing called twice. Once here and again in OnExit().
670 return wxApp::OnRun();
676 bool CamuleDaemonApp::OnInit()
678 if ( !CamuleApp::OnInit() ) {
681 AddLogLineNS(_("amuled: OnInit - starting timer"));
682 core_timer
= new CTimer(this,ID_CORE_TIMER_EVENT
);
683 core_timer
->Start(CORE_TIMER_PERIOD
);
684 glob_prefs
->GetCategory(0)->title
= GetCatTitle(thePrefs::GetAllcatFilter());
685 glob_prefs
->GetCategory(0)->path
= thePrefs::GetIncomingDir();
690 int CamuleDaemonApp::InitGui(bool ,wxString
&)
693 if ( !enable_daemon_fork
) {
696 AddLogLineNS(_("amuled: forking to background - see you"));
697 theLogger
.SetEnabledStdoutLog(false);
699 // fork to background and detach from controlling tty
700 // while redirecting stdout to /dev/null
702 for(int i_fd
= 0;i_fd
< 3; i_fd
++) {
705 int fd
= open("/dev/null",O_RDWR
);
706 if (dup(fd
)){} // prevent GCC warning
717 // Create a Pid file with the Pid of the Child, so any daemon-manager
718 // can easily manage the process
720 if (!m_PidFile
.IsEmpty()) {
721 wxString temp
= CFormat(wxT("%d\n")) % pid
;
722 wxFFile
ff(m_PidFile
, wxT("w"));
727 AddLogLineNS(_("Cannot Create Pid File"));
737 int CamuleDaemonApp::OnExit()
741 * Stop all socket threads before entering
755 const int ERROR_BUFFER_LEN
= 256;
756 char errorBuffer
[ERROR_BUFFER_LEN
];
758 int ret
= sigaction(SIGCHLD
, &m_oldSignalChildAction
, NULL
);
760 strerror_r(errno
, errorBuffer
, ERROR_BUFFER_LEN
);
761 msg
<< wxT("CamuleDaemonApp::OnRun(): second sigaction() failed: ") <<
762 char2unicode(errorBuffer
) <<
764 AddDebugLogLineC(logStandard
, msg
);
766 msg
<< wxT("CamuleDaemonApp::OnRun(): Uninstallation of SIGCHLD "
767 "callback with sigaction() succeeded.");
768 AddDebugLogLineN(logGeneral
, msg
);
772 // lfroen: delete socket threads
773 if (ECServerHandler
) {
779 return CamuleApp::OnExit();
783 int CamuleDaemonApp::ShowAlert(wxString msg
, wxString title
, int flags
)
785 if ( flags
| wxICON_ERROR
) {
786 title
= CFormat(_("ERROR: %s")) % title
;
788 AddLogLineCS(title
+ wxT(" ") + msg
);
790 return 0; // That's neither yes nor no, ok, cancel
793 // File_checked_for_headers