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>
30 // amuled doesn't run on Windows.
31 // To make it at least compile some code has to be excluded.
32 // For a real port all usages of TODO_MSW have to be resolved !
38 #include "config.h" // Needed for HAVE_SYS_RESOURCE_H, HAVE_STRERROR_R and STRERROR_R_CHAR_P
41 // Prefer the POSIX interface to strerror_r()
42 #define _XOPEN_SOURCE 600
43 #include <string.h> // Do_not_auto_remove
47 #include "Preferences.h" // Needed for CPreferences
48 #include "PartFile.h" // Needed for CPartFile
50 #include <common/Format.h>
51 #include "InternalEvents.h" // Needed for wxEVT_*
52 #include "ThreadTasks.h"
53 #include "GuiEvents.h" // Needed for EVT_MULE_NOTIFY
54 #include "Timer.h" // Needed for EVT_MULE_TIMER
56 #include "ClientUDPSocket.h" // Do_not_auto_remove (forward declaration not enough)
57 #include "ListenSocket.h" // Do_not_auto_remove (forward declaration not enough)
61 #ifdef HAVE_SYS_RESOURCE_H
62 #include <sys/resource.h> // Do_not_auto_remove
66 #ifdef HAVE_SYS_WAIT_H
67 #include <sys/wait.h> // Do_not_auto_remove
70 #include <wx/unix/execute.h>
73 #ifndef HAVE_STRERROR_R
75 // Replacement strerror_r() function for systems that don't have any.
76 // Note that this replacement function is NOT thread-safe!
77 static int rpl_strerror_r(int errnum
, char *buf
, size_t buflen
)
79 char *tmp
= strerror(errnum
);
84 strncpy(buf
, tmp
, buflen
- 1);
85 buf
[buflen
- 1] = '\0';
86 if (strlen(tmp
) >= buflen
) {
94 # define strerror_r(errnum, buf, buflen) rpl_strerror_r(errnum, buf, buflen)
96 # ifdef STRERROR_R_CHAR_P
98 // Replacement strerror_r() function for systems that return a char*.
99 static int rpl_strerror_r(int errnum
, char *buf
, size_t buflen
)
101 char *tmp
= strerror_r(errnum
, buf
, buflen
);
105 } else if (tmp
!= buf
) {
106 strncpy(buf
, tmp
, buflen
- 1);
107 buf
[buflen
- 1] = '\0';
108 if (strlen(tmp
) >= buflen
) {
116 # define strerror_r(errnum, buf, buflen) rpl_strerror_r(errnum, buf, buflen)
120 BEGIN_EVENT_TABLE(CamuleDaemonApp
, wxAppConsole
)
126 EVT_SOCKET(ID_LISTENSOCKET_EVENT
, CamuleDaemonApp::ListenSocketHandler
)
128 // UDP Socket (servers)
129 EVT_SOCKET(ID_SERVERUDPSOCKET_EVENT
, CamuleDaemonApp::UDPSocketHandler
)
130 // UDP Socket (clients)
131 EVT_SOCKET(ID_CLIENTUDPSOCKET_EVENT
, CamuleDaemonApp::UDPSocketHandler
)
133 // Socket timer (TCP)
134 EVT_MULE_TIMER(ID_SERVER_RETRY_TIMER_EVENT
, CamuleDaemonApp::OnTCPTimer
)
137 EVT_MULE_TIMER(ID_CORE_TIMER_EVENT
, CamuleDaemonApp::OnCoreTimer
)
139 EVT_MULE_NOTIFY(CamuleDaemonApp::OnNotifyEvent
)
141 // Async dns handling
142 EVT_MULE_INTERNAL(wxEVT_CORE_UDP_DNS_DONE
, -1, CamuleDaemonApp::OnUDPDnsDone
)
144 EVT_MULE_INTERNAL(wxEVT_CORE_SOURCE_DNS_DONE
, -1, CamuleDaemonApp::OnSourceDnsDone
)
146 EVT_MULE_INTERNAL(wxEVT_CORE_SERVER_DNS_DONE
, -1, CamuleDaemonApp::OnServerDnsDone
)
148 // Hash ended notifier
149 EVT_MULE_HASHING(CamuleDaemonApp::OnFinishedHashing
)
150 EVT_MULE_AICH_HASHING(CamuleDaemonApp::OnFinishedAICHHashing
)
152 // File completion ended notifier
153 EVT_MULE_FILE_COMPLETED(CamuleDaemonApp::OnFinishedCompletion
)
155 // HTTPDownload finished
156 EVT_MULE_INTERNAL(wxEVT_CORE_FINISHED_HTTP_DOWNLOAD
, -1, CamuleDaemonApp::OnFinishedHTTPDownload
)
158 // Disk space preallocation finished
159 EVT_MULE_ALLOC_FINISHED(CamuleDaemonApp::OnFinishedAllocation
)
162 IMPLEMENT_APP(CamuleDaemonApp
)
165 * Socket handling in wxBase
170 int m_fds
[FD_SETSIZE
], m_fd_idx
[FD_SETSIZE
];
171 GSocket
*m_gsocks
[FD_SETSIZE
];
176 void AddSocket(GSocket
*);
177 void RemoveSocket(GSocket
*);
178 void FillSet(int &max_fd
);
180 void Detected(void (GSocket::*func
)());
182 fd_set
*Set() { return &m_set
; }
185 CSocketSet::CSocketSet()
188 for(int i
= 0; i
< FD_SETSIZE
; i
++) {
190 m_fd_idx
[i
] = 0xffff;
195 void CSocketSet::AddSocket(GSocket
*socket
)
199 int fd
= socket
->m_fd
;
205 wxASSERT( (fd
> 2) && (fd
< FD_SETSIZE
) );
207 if ( m_gsocks
[fd
] ) {
211 m_fd_idx
[fd
] = m_count
;
212 m_gsocks
[fd
] = socket
;
216 void CSocketSet::RemoveSocket(GSocket
*socket
)
220 int fd
= socket
->m_fd
;
226 wxASSERT( (fd
> 2) && (fd
< FD_SETSIZE
) );
228 int i
= m_fd_idx
[fd
];
232 wxASSERT(m_fds
[i
] == fd
);
233 m_fds
[i
] = m_fds
[m_count
-1];
235 m_fds
[m_count
-1] = 0;
236 m_fd_idx
[fd
] = 0xffff;
237 m_fd_idx
[m_fds
[i
]] = i
;
241 void CSocketSet::FillSet(int &max_fd
)
245 for(int i
= 0; i
< m_count
; i
++) {
246 FD_SET(m_fds
[i
], &m_set
);
247 if ( m_fds
[i
] > max_fd
) {
253 void CSocketSet::Detected(void (GSocket::*func
)())
255 for (int i
= 0; i
< m_count
; i
++) {
257 if ( FD_ISSET(fd
, &m_set
) ) {
258 GSocket
*socket
= m_gsocks
[fd
];
264 CAmuledGSocketFuncTable::CAmuledGSocketFuncTable() : m_lock(wxMUTEX_RECURSIVE
)
266 m_in_set
= new CSocketSet
;
267 m_out_set
= new CSocketSet
;
272 void CAmuledGSocketFuncTable::AddSocket(GSocket
*socket
, GSocketEvent event
)
274 wxMutexLocker
lock(m_lock
);
276 if ( event
== GSOCK_INPUT
) {
277 m_in_set
->AddSocket(socket
);
279 m_out_set
->AddSocket(socket
);
283 void CAmuledGSocketFuncTable::RemoveSocket(GSocket
*socket
, GSocketEvent event
)
285 wxMutexLocker
lock(m_lock
);
287 if ( event
== GSOCK_INPUT
) {
288 m_in_set
->RemoveSocket(socket
);
290 m_out_set
->RemoveSocket(socket
);
294 void CAmuledGSocketFuncTable::RunSelect()
297 // This is why it doesn't work on Windows
298 wxMutexLocker
lock(m_lock
);
301 m_in_set
->FillSet(max_fd
);
302 m_out_set
->FillSet(max_fd
);
306 tv
.tv_usec
= 10000; // 10ms
308 int result
= select(max_fd
+ 1, m_in_set
->Set(), m_out_set
->Set(), 0, &tv
);
310 m_in_set
->Detected(&GSocket::Detected_Read
);
311 m_out_set
->Detected(&GSocket::Detected_Write
);
317 GSocketGUIFunctionsTable
*CDaemonAppTraits::GetSocketGUIFunctionsTable()
322 bool CAmuledGSocketFuncTable::OnInit()
327 void CAmuledGSocketFuncTable::OnExit()
331 bool CAmuledGSocketFuncTable::CanUseEventLoop()
334 * FIXME: (lfroen) Not sure whether it's right.
335 * I will review it later.
340 bool CAmuledGSocketFuncTable::Init_Socket(GSocket
*)
345 void CAmuledGSocketFuncTable::Destroy_Socket(GSocket
*)
349 void CAmuledGSocketFuncTable::Install_Callback(GSocket
*sock
, GSocketEvent e
)
354 void CAmuledGSocketFuncTable::Uninstall_Callback(GSocket
*sock
, GSocketEvent e
)
356 RemoveSocket(sock
, e
);
359 void CAmuledGSocketFuncTable::Enable_Events(GSocket
*socket
)
361 Install_Callback(socket
, GSOCK_INPUT
);
362 Install_Callback(socket
, GSOCK_OUTPUT
);
365 void CAmuledGSocketFuncTable::Disable_Events(GSocket
*socket
)
367 Uninstall_Callback(socket
, GSOCK_INPUT
);
368 Uninstall_Callback(socket
, GSOCK_OUTPUT
);
372 CDaemonAppTraits::CDaemonAppTraits(CAmuledGSocketFuncTable
*table
)
374 wxConsoleAppTraits(),
376 m_lock(wxMUTEX_RECURSIVE
),
379 ,m_oldSignalChildAction(),
380 m_newSignalChildAction()
387 void CDaemonAppTraits::ScheduleForDestroy(wxObject
*object
)
389 wxMutexLocker
lock(m_lock
);
392 m_sched_delete
.push_back(object
);
395 void CDaemonAppTraits::RemoveFromPendingDelete(wxObject
*object
)
397 wxMutexLocker
lock(m_lock
);
399 for(std::list
<wxObject
*>::iterator i
= m_sched_delete
.begin();
400 i
!= m_sched_delete
.end(); i
++) {
401 if ( *i
== object
) {
402 m_sched_delete
.erase(i
);
408 void CDaemonAppTraits::DeletePending()
410 wxMutexLocker
lock(m_lock
);
412 while ( !m_sched_delete
.empty() ) {
413 std::list
<wxObject
*>::iterator i
= m_sched_delete
.begin();
414 wxObject
*object
= *i
;
417 //m_sched_delete.erase(m_sched_delete.begin(), m_sched_delete.end());
422 #include <wx/stdpaths.h> // Do_not_auto_remove (guess)
423 static wxStandardPathsCF gs_stdPaths
;
424 wxStandardPathsBase
& CDaemonAppTraits::GetStandardPaths()
431 CamuleDaemonApp::CamuleDaemonApp()
434 m_table(new CAmuledGSocketFuncTable())
436 wxPendingEventsLocker
= new wxCriticalSection
;
440 wxAppTraits
*CamuleDaemonApp::CreateTraits()
442 return new CDaemonAppTraits(m_table
);
449 static EndProcessDataMap endProcDataMap
;
452 int CDaemonAppTraits::WaitForChild(wxExecuteData
&execData
)
456 // Build the log message
458 msg
<< wxT("WaitForChild() has been called for child process with pid `") <<
462 if (execData
.flags
& wxEXEC_SYNC
) {
463 result
= AmuleWaitPid(execData
.pid
, &status
, 0, &msg
);
464 if (result
== -1 || (!WIFEXITED(status
) && !WIFSIGNALED(status
))) {
465 msg
<< wxT(" Waiting for subprocess termination failed.");
466 AddDebugLogLineM(false, logGeneral
, msg
);
470 // Give the process a chance to start or forked child to exit
471 // 1 second is enough time to fail on "path not found"
473 result
= AmuleWaitPid(execData
.pid
, &status
, WNOHANG
, &msg
);
475 // Add a WxEndProcessData entry to the map, so that we can
476 // support process termination
477 wxEndProcessData
*endProcData
= new wxEndProcessData();
478 endProcData
->pid
= execData
.pid
;
479 endProcData
->process
= execData
.process
;
480 endProcData
->tag
= 0;
481 endProcDataMap
[execData
.pid
] = endProcData
;
483 status
= execData
.pid
;
485 // if result != 0, then either waitpid() failed (result == -1)
486 // and there is nothing we can do, or the child has changed
487 // status, which means it is probably dead.
492 // Log our passage here
493 AddDebugLogLineM(false, logGeneral
, msg
);
499 void OnSignalChildHandler(int /*signal*/, siginfo_t
*siginfo
, void * /*ucontext*/)
501 // Build the log message
503 msg
<< wxT("OnSignalChildHandler() has been called for child process with pid `") <<
506 // Make sure we leave no zombies by calling waitpid()
508 pid_t result
= AmuleWaitPid(siginfo
->si_pid
, &status
, WNOHANG
, &msg
);
509 if (result
!= 1 && result
!= 0 && (WIFEXITED(status
) || WIFSIGNALED(status
))) {
510 // Fetch the wxEndProcessData structure corresponding to this pid
511 EndProcessDataMap::iterator it
= endProcDataMap
.find(siginfo
->si_pid
);
512 if (it
!= endProcDataMap
.end()) {
513 wxEndProcessData
*endProcData
= it
->second
;
514 // Remove this entry from the process map
515 endProcDataMap
.erase(siginfo
->si_pid
);
516 // Save the exit code for the wxProcess object to read later
517 endProcData
->exitcode
= result
!= -1 && WIFEXITED(status
) ?
518 WEXITSTATUS(status
) : -1;
519 // Make things work as in wxGUI
520 wxHandleProcessTermination(endProcData
);
522 // wxHandleProcessTermination() will "delete endProcData;"
523 // So we do not delete it again, ok? Do not uncomment this line.
524 //delete endProcData;
526 msg
<< wxT(" Error: the child process pid is not on the pid map.");
530 // Log our passage here
531 AddDebugLogLineM(false, logGeneral
, msg
);
535 pid_t
AmuleWaitPid(pid_t pid
, int *status
, int options
, wxString
*msg
)
537 // strerror_r() buffer
538 const int ERROR_BUFFER_LEN
= 256;
539 char errorBuffer
[ERROR_BUFFER_LEN
];
542 pid_t result
= waitpid(pid
, status
, options
);
544 strerror_r(errno
, errorBuffer
, ERROR_BUFFER_LEN
);
545 *msg
<< wxT("Error: waitpid() call failed: ") <<
546 char2unicode(errorBuffer
) <<
548 } else if (result
== 0) {
549 if (options
& WNOHANG
) {
550 *msg
<< wxT("The child is alive.");
552 *msg
<< wxT("Error: waitpid() call returned 0 but "
553 "WNOHANG was not specified in options.");
556 if (WIFEXITED(*status
)) {
557 *msg
<< wxT("Child has terminated with status code `") <<
558 WEXITSTATUS(*status
) <<
560 } else if (WIFSIGNALED(*status
)) {
561 *msg
<< wxT("Child was killed by signal `") <<
564 if (WCOREDUMP(*status
)) {
565 *msg
<< wxT(" A core file has been dumped.");
567 } else if (WIFSTOPPED(*status
)) {
568 *msg
<< wxT("Child has been stopped by signal `") <<
571 #ifdef WIFCONTINUED /* Only found in recent kernels. */
572 } else if (WIFCONTINUED(*status
)) {
573 *msg
<< wxT("Child has received `SIGCONT' and has continued execution.");
576 *msg
<< wxT("The program was not able to determine why the child has signaled.");
587 int CamuleDaemonApp::OnRun()
589 if (!thePrefs::AcceptExternalConnections()) {
590 AddLogLineMS(true, _("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"));
592 } else if (thePrefs::ECPassword().IsEmpty()) {
593 AddLogLineMS(true, _("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"));
598 // strerror_r() buffer
599 const int ERROR_BUFFER_LEN
= 256;
600 char errorBuffer
[ERROR_BUFFER_LEN
];
603 // Process the return code of dead children so that we do not create
604 // zombies. wxBase does not implement wxProcess callbacks, so no one
605 // actualy calls wxHandleProcessTermination() in console applications.
606 // We do our best here.
608 ret
= sigaction(SIGCHLD
, NULL
, &m_oldSignalChildAction
);
609 m_newSignalChildAction
= m_oldSignalChildAction
;
610 m_newSignalChildAction
.sa_sigaction
= OnSignalChildHandler
;
611 m_newSignalChildAction
.sa_flags
|= SA_SIGINFO
;
612 m_newSignalChildAction
.sa_flags
&= ~SA_RESETHAND
;
613 ret
= sigaction(SIGCHLD
, &m_newSignalChildAction
, NULL
);
615 strerror_r(errno
, errorBuffer
, ERROR_BUFFER_LEN
);
616 msg
<< wxT("CamuleDaemonApp::OnRun(): "
617 "Installation of SIGCHLD callback with sigaction() failed: ") <<
618 char2unicode(errorBuffer
) <<
620 AddLogLineM(true, msg
);
622 msg
<< wxT("CamuleDaemonApp::OnRun(): Installation of SIGCHLD "
623 "callback with sigaction() succeeded.");
624 AddDebugLogLineM(false, logGeneral
, msg
);
629 m_table
->RunSelect();
630 ProcessPendingEvents();
631 ((CDaemonAppTraits
*)GetTraits())->DeletePending();
634 // ShutDown is beeing called twice. Once here and again in OnExit().
639 ret
= sigaction(SIGCHLD
, &m_oldSignalChildAction
, NULL
);
641 strerror_r(errno
, errorBuffer
, ERROR_BUFFER_LEN
);
642 msg
<< wxT("CamuleDaemonApp::OnRun(): second sigaction() failed: ") <<
643 char2unicode(errorBuffer
) <<
645 AddLogLineM(true, msg
);
647 msg
<< wxT("CamuleDaemonApp::OnRun(): Uninstallation of SIGCHLD "
648 "callback with sigaction() succeeded.");
649 AddDebugLogLineM(false, logGeneral
, msg
);
656 bool CamuleDaemonApp::OnInit()
658 AddLogLineNS(_("amuled: OnInit - starting timer"));
659 if ( !CamuleApp::OnInit() ) {
662 core_timer
= new CTimer(this,ID_CORE_TIMER_EVENT
);
663 core_timer
->Start(300);
664 glob_prefs
->GetCategory(0)->title
= GetCatTitle(thePrefs::GetAllcatType());
665 glob_prefs
->GetCategory(0)->path
= thePrefs::GetIncomingDir();
670 int CamuleDaemonApp::InitGui(bool ,wxString
&)
673 if ( !enable_daemon_fork
) {
676 AddLogLineNS(_("amuled: forking to background - see you"));
677 theLogger
.SetEnabledStdoutLog(false);
679 // fork to background and detouch from controlling tty
680 // while redirecting stdout to /dev/null
682 for(int i_fd
= 0;i_fd
< 3; i_fd
++) {
685 int fd
= open("/dev/null",O_RDWR
);
703 int CamuleDaemonApp::OnExit()
706 * Stop all socket threads before entering
718 // lfroen: delete socket threads
719 if (ECServerHandler
) {
725 return CamuleApp::OnExit();
729 void CamuleDaemonApp::ShowAlert(wxString msg
, wxString title
, int flags
)
731 if ( flags
| wxICON_ERROR
) {
732 title
= CFormat(_("ERROR: %s")) % title
;
734 AddLogLineCS(title
+ wxT(" ") + msg
);
737 // File_checked_for_headers