diff --git a/configure.ac b/configure.ac index d988c917..41535f52 100644 --- a/configure.ac +++ b/configure.ac @@ -133,10 +133,10 @@ AC_ARG_ENABLE( [optimization], decrease memory usage while compiling]), [OPTIMIZE="$enableval"], [OPTIMIZE="yes"]) -AC_ARG_ENABLE( [c-ares], - AS_HELP_STRING([--disable-c-ares], [disable c-ares usage]), - [ARES="$enableval"], - [ARES="auto"]) +AC_ARG_ENABLE( [tdns], + AS_HELP_STRING([--disable-tdns], [disable threads usage for DNS resolving]), + [TDNS="$enableval"], + [TDNS="auto"]) AC_ARG_ENABLE( [run-from-source], AS_HELP_STRING([--enable-run-from-source], [ZNC will be runnable without installation]), [if test "x$enableval" = "xyes" ; then @@ -201,32 +201,24 @@ PKG_PROG_PKG_CONFIG() AC_SEARCH_LIBS([dlopen], [dl], [], [AC_MSG_ERROR([Could not find dlopen. ZNC will not work on this box until you upgrade this ancient system or at least install the necessary system libraries.])]) -# ----- Check for c-ares +# ----- Check for pthreads -if test "x$ARES" != "xno"; then - old_ARES=$ARES - if test -z "$PKG_CONFIG" - then - ARES=no - ZNC_AUTO_FAIL([ARES], - [pkg-config not found. Try --disable-c-ares. -Disabling c-ares may result in a slight performance decrease but will not have any other side-effects], - [pkg-config was not found and thus c-ares was disabled]) - else - PKG_CHECK_MODULES([c_ares], [libcares >= 1.5.0],, ARES=no) - - if test "x$ARES" = "xno" ; then - ZNC_AUTO_FAIL([ARES], - [c-ares not found. Try --disable-c-ares. -Disabling c-ares may result in a slight performance decrease but will not have any other side-effects], - [c-ares was not found and thus disabled]) - else - AC_DEFINE([HAVE_C_ARES], [1], [Define if c-ares is enabled]) - appendCXX $c_ares_CFLAGS - appendLib $c_ares_LIBS - ARES=yes - fi - fi +if test "x$TDNS" != "xno"; then + old_TDNS=$TDNS + AX_PTHREAD([ + TDNS=yes + DNS_TEXT=threads + AC_DEFINE([HAVE_THREADED_DNS], [1], [Define if threaded DNS is enabled]) + appendCXX "$PTHREAD_CFLAGS" + appendLib "$PTHREAD_LIBS" + ], [ + TDNS=no + DNS_TEXT=blocking + ZNC_AUTO_FAIL([TDNS], + [threads not found. Try --disable-tdns. +Disabling threads may result in a slight performance decrease but will not have any other side-effects], + [threads not found, so DNS resolving will be blocking]) + ]) fi # ----- Check for openssl @@ -538,7 +530,7 @@ echo "prefix: $prefix" echo "debug: $DEBUG" echo "ipv6: $IPV6" echo "openssl: $SSL" -echo "c-ares: $ARES" +echo "dns: $DNS_TEXT" echo "perl: $PERL" echo "python: $PYTHON" echo "swig: $USESWIG" diff --git a/include/znc/Csocket.h b/include/znc/Csocket.h index c5ea37e7..3121d85f 100644 --- a/include/znc/Csocket.h +++ b/include/znc/Csocket.h @@ -910,6 +910,14 @@ public: * Don't bother using these callbacks if you are using this class directly (without Socket Manager) * as the Socket Manager calls most of these callbacks * + * A sock error occured event + */ + virtual void SockTextError( const CS_STRING & sError ) { SockError(-1); } + /** + * Override these functions for an easy interface when using the Socket Manager + * Don't bother using these callbacks if you are using this class directly (without Socket Manager) + * as the Socket Manager calls most of these callbacks + * * * Incoming Connection Event * return false and the connection will fail diff --git a/include/znc/IRCSock.h b/include/znc/IRCSock.h index 26a79e4e..b69550b2 100644 --- a/include/znc/IRCSock.h +++ b/include/znc/IRCSock.h @@ -50,6 +50,7 @@ public: virtual void Disconnected(); virtual void ConnectionRefused(); virtual void SockError(int iErrno); + virtual void SockTextError(const CString& sError); virtual void Timeout(); virtual void ReachedMaxBuffer(); diff --git a/include/znc/Socket.h b/include/znc/Socket.h index 086410c8..5ca73528 100644 --- a/include/znc/Socket.h +++ b/include/znc/Socket.h @@ -31,8 +31,8 @@ enum EAddrType { class CSockManager : public TSocketManager { public: - CSockManager() {} - virtual ~CSockManager() {} + CSockManager(); + virtual ~CSockManager(); bool ListenHost(u_short iPort, const CString& sSockName, const CString& sBindHost, bool bSSL = false, int iMaxConns = SOMAXCONN, CZNCSock *pcSock = NULL, u_int iTimeout = 0, EAddrType eAddr = ADDR_ALL) { CSListener L(iPort, sBindHost); @@ -95,18 +95,48 @@ public: return(ListenRand(sSockName, "", bSSL, iMaxConns, pcSock, iTimeout, eAddr)); } - void Connect(const CString& sHostname, u_short iPort , const CString& sSockName, int iTimeout = 60, bool bSSL = false, const CString& sBindHost = "", CZNCSock *pcSock = NULL) { - CSConnection C(sHostname, iPort, iTimeout); - - C.SetSockName(sSockName); - C.SetIsSSL(bSSL); - C.SetBindHost(sBindHost); - - TSocketManager::Connect(C, pcSock); - } + void Connect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout = 60, bool bSSL = false, const CString& sBindHost = "", CZNCSock *pcSock = NULL); unsigned int GetAnonConnectionCount(const CString &sIP) const; private: + void FinishConnect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock); + +#ifdef HAVE_THREADED_DNS + int m_iTDNSpipe[2]; + pthread_mutex_t* m_mTDNSmutex; + + class CTDNSMonitorFD; + friend class CTDNSMonitorFD; + struct TDNSTask { + CString sHostname; + u_short iPort; + CString sSockName; + int iTimeout; + bool bSSL; + CString sBindhost; + CZNCSock* pcSock; + + bool bDoneTarget; + bool bDoneBind; + addrinfo* aiTarget; + addrinfo* aiBind; + }; + struct TDNSArg { + CString sHostname; + TDNSTask* task; + pthread_mutex_t* mutex; + int fd; + bool bBind; + + int iRes; + addrinfo* aiResult; + }; + void StartTDNSThread(TDNSTask* task, bool bBind); + void SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* aiResult); + void TryToFinishTDNSTask(TDNSTask* task); + void RetrieveTDNSResult(); + static void* TDNSThread(void* argument); +#endif protected: }; diff --git a/m4/ax_pthread.m4 b/m4/ax_pthread.m4 new file mode 100644 index 00000000..60239852 --- /dev/null +++ b/m4/ax_pthread.m4 @@ -0,0 +1,309 @@ +# =========================================================================== +# http://www.gnu.org/software/autoconf-archive/ax_pthread.html +# =========================================================================== +# +# SYNOPSIS +# +# AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]]) +# +# DESCRIPTION +# +# This macro figures out how to build C programs using POSIX threads. It +# sets the PTHREAD_LIBS output variable to the threads library and linker +# flags, and the PTHREAD_CFLAGS output variable to any special C compiler +# flags that are needed. (The user can also force certain compiler +# flags/libs to be tested by setting these environment variables.) +# +# Also sets PTHREAD_CC to any special C compiler that is needed for +# multi-threaded programs (defaults to the value of CC otherwise). (This +# is necessary on AIX to use the special cc_r compiler alias.) +# +# NOTE: You are assumed to not only compile your program with these flags, +# but also link it with them as well. e.g. you should link with +# $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS +# +# If you are only building threads programs, you may wish to use these +# variables in your default LIBS, CFLAGS, and CC: +# +# LIBS="$PTHREAD_LIBS $LIBS" +# CFLAGS="$CFLAGS $PTHREAD_CFLAGS" +# CC="$PTHREAD_CC" +# +# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant +# has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to that name +# (e.g. PTHREAD_CREATE_UNDETACHED on AIX). +# +# Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the +# PTHREAD_PRIO_INHERIT symbol is defined when compiling with +# PTHREAD_CFLAGS. +# +# ACTION-IF-FOUND is a list of shell commands to run if a threads library +# is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it +# is not found. If ACTION-IF-FOUND is not specified, the default action +# will define HAVE_PTHREAD. +# +# Please let the authors know if this macro fails on any platform, or if +# you have any other suggestions or comments. This macro was based on work +# by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help +# from M. Frigo), as well as ac_pthread and hb_pthread macros posted by +# Alejandro Forero Cuervo to the autoconf macro repository. We are also +# grateful for the helpful feedback of numerous users. +# +# Updated for Autoconf 2.68 by Daniel Richard G. +# +# LICENSE +# +# Copyright (c) 2008 Steven G. Johnson +# Copyright (c) 2011 Daniel Richard G. +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the +# Free Software Foundation, either version 3 of the License, or (at your +# option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. + +#serial 17 + +AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD]) +AC_DEFUN([AX_PTHREAD], [ +AC_REQUIRE([AC_CANONICAL_HOST]) +AC_LANG_PUSH([C++]) +ax_pthread_ok=no + +# We used to check for pthread.h first, but this fails if pthread.h +# requires special compiler flags (e.g. on True64 or Sequent). +# It gets checked for in the link test anyway. + +# First of all, check if the user has set any of the PTHREAD_LIBS, +# etcetera environment variables, and if threads linking works using +# them: +if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then + save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + save_LIBS="$LIBS" + LIBS="$PTHREAD_LIBS $LIBS" + AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS]) + AC_TRY_LINK_FUNC(pthread_join, ax_pthread_ok=yes) + AC_MSG_RESULT($ax_pthread_ok) + if test x"$ax_pthread_ok" = xno; then + PTHREAD_LIBS="" + PTHREAD_CFLAGS="" + fi + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" +fi + +# We must check for the threads library under a number of different +# names; the ordering is very important because some systems +# (e.g. DEC) have both -lpthread and -lpthreads, where one of the +# libraries is broken (non-POSIX). + +# Create a list of thread flags to try. Items starting with a "-" are +# C compiler flags, and other items are library names, except for "none" +# which indicates that we try without any flags at all, and "pthread-config" +# which is a program returning the flags for the Pth emulation library. + +ax_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config" + +# The ordering *is* (sometimes) important. Some notes on the +# individual items follow: + +# pthreads: AIX (must check this before -lpthread) +# none: in case threads are in libc; should be tried before -Kthread and +# other compiler flags to prevent continual compiler warnings +# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h) +# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able) +# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread) +# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads) +# -pthreads: Solaris/gcc +# -mthreads: Mingw32/gcc, Lynx/gcc +# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it +# doesn't hurt to check since this sometimes defines pthreads too; +# also defines -D_REENTRANT) +# ... -mt is also the pthreads flag for HP/aCC +# pthread: Linux, etcetera +# --thread-safe: KAI C++ +# pthread-config: use pthread-config program (for GNU Pth library) + +case "${host_cpu}-${host_os}" in + *solaris*) + + # On Solaris (at least, for some versions), libc contains stubbed + # (non-functional) versions of the pthreads routines, so link-based + # tests will erroneously succeed. (We need to link with -pthreads/-mt/ + # -lpthread.) (The stubs are missing pthread_cleanup_push, or rather + # a function called by this macro, so we could check for that, but + # who knows whether they'll stub that too in a future libc.) So, + # we'll just look for -pthreads and -lpthread first: + + ax_pthread_flags="-pthreads pthread -mt -pthread $ax_pthread_flags" + ;; + + *-darwin*) + ax_pthread_flags="-pthread $ax_pthread_flags" + ;; +esac + +if test x"$ax_pthread_ok" = xno; then +for flag in $ax_pthread_flags; do + + case $flag in + none) + AC_MSG_CHECKING([whether pthreads work without any flags]) + ;; + + -*) + AC_MSG_CHECKING([whether pthreads work with $flag]) + PTHREAD_CFLAGS="$flag" + ;; + + pthread-config) + AC_CHECK_PROG(ax_pthread_config, pthread-config, yes, no) + if test x"$ax_pthread_config" = xno; then continue; fi + PTHREAD_CFLAGS="`pthread-config --cflags`" + PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`" + ;; + + *) + AC_MSG_CHECKING([for the pthreads library -l$flag]) + PTHREAD_LIBS="-l$flag" + ;; + esac + + save_LIBS="$LIBS" + save_CFLAGS="$CFLAGS" + LIBS="$PTHREAD_LIBS $LIBS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + + # Check for various functions. We must include pthread.h, + # since some functions may be macros. (On the Sequent, we + # need a special flag -Kthread to make this header compile.) + # We check for pthread_join because it is in -lpthread on IRIX + # while pthread_create is in libc. We check for pthread_attr_init + # due to DEC craziness with -lpthreads. We check for + # pthread_cleanup_push because it is one of the few pthread + # functions on Solaris that doesn't have a non-functional libc stub. + # We try pthread_create on general principles. + AC_LINK_IFELSE([AC_LANG_PROGRAM([#include + static void routine(void *a) { a = 0; } + static void *start_routine(void *a) { return a; }], + [pthread_t th; pthread_attr_t attr; + pthread_create(&th, 0, start_routine, 0); + pthread_join(th, 0); + pthread_attr_init(&attr); + pthread_cleanup_push(routine, 0); + pthread_cleanup_pop(0) /* ; */])], + [ax_pthread_ok=yes], + []) + + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" + + AC_MSG_RESULT($ax_pthread_ok) + if test "x$ax_pthread_ok" = xyes; then + break; + fi + + PTHREAD_LIBS="" + PTHREAD_CFLAGS="" +done +fi + +# Various other checks: +if test "x$ax_pthread_ok" = xyes; then + save_LIBS="$LIBS" + LIBS="$PTHREAD_LIBS $LIBS" + save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $PTHREAD_CFLAGS" + + # Detect AIX lossage: JOINABLE attribute is called UNDETACHED. + AC_MSG_CHECKING([for joinable pthread attribute]) + attr_name=unknown + for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do + AC_LINK_IFELSE([AC_LANG_PROGRAM([#include ], + [int attr = $attr; return attr /* ; */])], + [attr_name=$attr; break], + []) + done + AC_MSG_RESULT($attr_name) + if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then + AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name, + [Define to necessary symbol if this constant + uses a non-standard name on your system.]) + fi + + AC_MSG_CHECKING([if more special flags are required for pthreads]) + flag=no + case "${host_cpu}-${host_os}" in + *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";; + *-osf* | *-hpux*) flag="-D_REENTRANT";; + *solaris*) + if test "$GCC" = "yes"; then + flag="-D_REENTRANT" + else + flag="-mt -D_REENTRANT" + fi + ;; + esac + AC_MSG_RESULT(${flag}) + if test "x$flag" != xno; then + PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS" + fi + + AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT], + ax_cv_PTHREAD_PRIO_INHERIT, [ + AC_LINK_IFELSE([ + AC_LANG_PROGRAM([[#include ]], [[int i = PTHREAD_PRIO_INHERIT;]])], + [ax_cv_PTHREAD_PRIO_INHERIT=yes], + [ax_cv_PTHREAD_PRIO_INHERIT=no]) + ]) + AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes"], + AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], 1, [Have PTHREAD_PRIO_INHERIT.])) + + LIBS="$save_LIBS" + CFLAGS="$save_CFLAGS" + + # More AIX lossage: must compile with xlc_r or cc_r + if test x"$GCC" != xyes; then + AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC}) + else + PTHREAD_CC=$CC + fi +else + PTHREAD_CC="$CC" +fi + +AC_SUBST(PTHREAD_LIBS) +AC_SUBST(PTHREAD_CFLAGS) +AC_SUBST(PTHREAD_CC) + +# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND: +if test x"$ax_pthread_ok" = xyes; then + ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1]) + : +else + ax_pthread_ok=no + $2 +fi +AC_LANG_POP +])dnl AX_PTHREAD diff --git a/src/IRCSock.cpp b/src/IRCSock.cpp index 7534f488..aa55b77e 100644 --- a/src/IRCSock.cpp +++ b/src/IRCSock.cpp @@ -972,6 +972,11 @@ void CIRCSock::SockError(int iErrno) { DEBUG(GetSockName() << " == SockError(" << iErrno << " " << sError << ")"); + SockTextError(sError); +} + +void CIRCSock::SockTextError(const CString& sError) { + DEBUG(GetSockName() << " == SockError(" << sError << ")"); if (!m_pNetwork->GetUser()->IsBeingDeleted()) { if (GetConState() != CST_OK) { m_pNetwork->PutStatus("Cannot connect to IRC (" + sError + "). Retrying..."); diff --git a/src/Socket.cpp b/src/Socket.cpp index 60947bc7..dc449b4c 100644 --- a/src/Socket.cpp +++ b/src/Socket.cpp @@ -35,6 +35,267 @@ CS_STRING CZNCSock::ConvertAddress(void *addr, bool ipv6) { return sRet; } +#ifdef HAVE_THREADED_DNS +class CSockManager::CTDNSMonitorFD : public CSMonitorFD { + CSockManager* m_Manager; +public: + CTDNSMonitorFD(CSockManager* mgr) { + m_Manager = mgr; + Add(mgr->m_iTDNSpipe[0], ECT_Read); + } + + virtual bool FDsThatTriggered(const std::map& miiReadyFds) { + if (miiReadyFds.find(m_Manager->m_iTDNSpipe[0])->second) { + m_Manager->RetrieveTDNSResult(); + } + return true; + } +}; + +void* CSockManager::TDNSThread(void* argument) { + TDNSArg* a = (TDNSArg*)argument; + int iCount = 0; + while (true) { + addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + hints.ai_flags = AI_ADDRCONFIG; + a->iRes = getaddrinfo(a->sHostname.c_str(), NULL, &hints, &a->aiResult); + if (EAGAIN != a->iRes) { + break; + } + + iCount++; + if (iCount > 5) { + a->iRes = ETIMEDOUT; + break; + } + sleep(5); // wait 5 seconds before next try + } + + pthread_mutex_lock(a->mutex); + int wrote = 0; + int need = sizeof(TDNSArg*); + char* x = (char*)&a; + while (wrote < need) { + int w = write(a->fd, x, need - wrote); + if (-1 == w) { + DEBUG("Something bad happened during write() to a pipe from TDNSThread: " << strerror(errno)); + exit(1); + } + wrote += w; + x += w; + } + pthread_mutex_unlock(a->mutex); + return NULL; +} + +void CSockManager::StartTDNSThread(TDNSTask* task, bool bBind) { + CString sHostname = bBind ? task->sBindhost : task->sHostname; + TDNSArg* arg = new TDNSArg; + arg->sHostname = sHostname; + arg->task = task; + arg->mutex = m_mTDNSmutex; + arg->fd = m_iTDNSpipe[1]; + arg->bBind = bBind; + arg->iRes = 0; + arg->aiResult = NULL; + + pthread_attr_t attr; + if (pthread_attr_init(&attr)) { + CString sError = "Couldn't init pthread_attr for " + sHostname; + DEBUG(sError); + CZNC::Get().Broadcast(sError, /* bAdminOnly = */ true); + SetTDNSThreadFinished(task, bBind, NULL); + return; + } + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + + pthread_t thr; + if (pthread_create(&thr, &attr, TDNSThread, arg)) { + CString sError = "Couldn't create thread for " + sHostname; + DEBUG(sError); + CZNC::Get().Broadcast(sError, /* bAdminOnly = */ true); + delete arg; + pthread_attr_destroy(&attr); + SetTDNSThreadFinished(task, bBind, NULL); + return; + } + pthread_attr_destroy(&attr); +} + +void CSockManager::SetTDNSThreadFinished(TDNSTask* task, bool bBind, addrinfo* aiResult) { + if (bBind) { + task->aiBind = aiResult; + task->bDoneBind = true; + } else { + task->aiTarget = aiResult; + task->bDoneTarget = true; + } + TryToFinishTDNSTask(task); +} + +void CSockManager::TryToFinishTDNSTask(TDNSTask* task) { + if (!task->bDoneBind || !task->bDoneTarget) { + return; + } + addrinfo* aiTarget = NULL; + addrinfo* aiBind = NULL; + + try { + addrinfo* aiTarget4 = task->aiTarget; + addrinfo* aiBind4 = task->aiBind; + while (aiTarget4 && aiTarget4->ai_family != AF_INET) aiTarget4 = aiTarget4->ai_next; + while (aiBind4 && aiBind4->ai_family != AF_INET) aiBind4 = aiBind4->ai_next; + + addrinfo* aiTarget6 = NULL; + addrinfo* aiBind6 = NULL; +#ifdef HAVE_IPV6 + aiTarget6 = task->aiTarget; + aiBind6 = task->aiBind; + while (aiTarget6 && aiTarget6->ai_family != AF_INET6) aiTarget6 = aiTarget6->ai_next; + while (aiBind6 && aiBind6->ai_family != AF_INET6) aiBind6 = aiBind6->ai_next; +#endif + + if (!aiTarget4 && !aiTarget6) { + throw "Can't resolve server hostname"; + } else if (task->sBindhost.empty()) { +#ifdef HAVE_IPV6 + aiTarget = task->aiTarget; +#else + aiTarget = aiTarget4; +#endif + } else if (!aiBind4 && !aiBind6) { + throw "Can't resolve bind hostname. Try /znc clearbindhost"; + } else if (aiBind6 && aiTarget6) { + aiTarget = aiTarget6; + aiBind = aiBind6; + } else if (aiBind4 && aiTarget4) { + aiTarget = aiTarget4; + aiBind = aiBind4; + } else { + throw "Address family of bindhost doesn't match address family of server"; + } + + CString sBindhost; + CString sTargetHost; + if (!task->sBindhost.empty()) { + char s[40] = {}; // 40 is enough for both ipv4 and ipv6 addresses, including 0 terminator. + getnameinfo(aiBind->ai_addr, aiBind->ai_addrlen, s, sizeof(s), NULL, 0, NI_NUMERICHOST); + sBindhost = s; + } + char s[40] = {}; + getnameinfo(aiTarget->ai_addr, aiTarget->ai_addrlen, s, sizeof(s), NULL, 0, NI_NUMERICHOST); + sTargetHost = s; + + DEBUG("TDNS: " << task->sSockName << ", connecting to [" << sTargetHost << "] using bindhost [" << sBindhost << "]"); + + FinishConnect(sTargetHost, task->iPort, task->sSockName, task->iTimeout, task->bSSL, sBindhost, task->pcSock); + } catch (const char* s) { + DEBUG(task->sSockName << ", dns resolving error: " << s); + task->pcSock->SetSockName(task->sSockName); + task->pcSock->SockTextError(s); + delete task->pcSock; + } + + if (task->aiTarget) freeaddrinfo(task->aiTarget); + if (task->aiBind) freeaddrinfo(task->aiBind); + + delete task; +} + +void CSockManager::RetrieveTDNSResult() { + TDNSArg* a = NULL; + int readed = 0; + int need = sizeof(TDNSArg*); + char* x = (char*)&a; + while (readed < need) { + int r = read(m_iTDNSpipe[0], x, need - readed); + if (-1 == r) { + DEBUG("Something bad happened during read() from a pipe when getting result of TDNSThread: " << strerror(errno)); + exit(1); + } + readed += r; + x += r; + } + TDNSTask* task = a->task; + if (0 != a->iRes) { + DEBUG("Error in threaded DNS: " << gai_strerror(a->iRes)); + if (a->aiResult) { + DEBUG("And aiResult is not NULL..."); + } + a->aiResult = NULL; // just for case. Maybe to call freeaddrinfo()? + } + SetTDNSThreadFinished(task, a->bBind, a->aiResult); + delete a; +} +#endif /* HAVE_THREADED_DNS */ + +CSockManager::CSockManager() { +#ifdef HAVE_THREADED_DNS + m_mTDNSmutex = new pthread_mutex_t; + int m = pthread_mutex_init(m_mTDNSmutex, NULL); + if (m) { + DEBUG("Ouch, can't init mutex for threaded DNS resolving: " << strerror(m)); + exit(1); + } + if (pipe(m_iTDNSpipe)) { + DEBUG("Ouch, can't open pipe for threaded DNS resolving: " << strerror(errno)); + exit(1); + } + + MonitorFD(new CTDNSMonitorFD(this)); +#endif +} + +CSockManager::~CSockManager() { +#ifdef HAVE_THREADED_DNS + // Here pthread_mutex_destroy(m_mTDNSmutex); and delete m_mTDNSmutex; should be called... + // But lifetime of CSockManager is the same of CZNC, and if to destroy the mutex now, + // lock() from inside TDNSThread will fail. + // So here is a resource and memory leak, but this znc process will die in few moments anyway. +#endif +} + +void CSockManager::Connect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock) { +#ifdef HAVE_THREADED_DNS + TDNSTask* task = new TDNSTask; + task->sHostname = sHostname; + task->iPort = iPort; + task->sSockName = sSockName; + task->iTimeout = iTimeout; + task->bSSL = bSSL; + task->sBindhost = sBindHost; + task->pcSock = pcSock; + task->aiTarget = NULL; + task->aiBind = NULL; + task->bDoneTarget = false; + if (sBindHost.empty()) { + task->bDoneBind = true; + } else { + task->bDoneBind = false; + StartTDNSThread(task, true); + } + StartTDNSThread(task, false); +#else /* HAVE_THREADED_DNS */ + // Just let Csocket handle DNS itself + FinishConnect(sHostname, iPort, sSockName, iTimeout, bSSL, sBindHost, pcSock); +#endif +} + +void CSockManager::FinishConnect(const CString& sHostname, u_short iPort, const CString& sSockName, int iTimeout, bool bSSL, const CString& sBindHost, CZNCSock *pcSock) { + CSConnection C(sHostname, iPort, iTimeout); + + C.SetSockName(sSockName); + C.SetIsSSL(bSSL); + C.SetBindHost(sBindHost); + + TSocketManager::Connect(C, pcSock); +} + + /////////////////// CSocket /////////////////// CSocket::CSocket(CModule* pModule) : CZNCSock() { m_pModule = pModule;