From: Kees Monshouwer Date: Thu, 3 Oct 2013 21:08:53 +0000 (+0200) Subject: remove all windows code from PowerDNS X-Git-Tag: rec-3.6.0-rc1~399^2 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=76473b92548dc743ea69529df473fb60a2062590;p=pdns remove all windows code from PowerDNS --- diff --git a/pdns/Makefile-recursor.win32 b/pdns/Makefile-recursor.win32 deleted file mode 100644 index d9bde56d6..000000000 --- a/pdns/Makefile-recursor.win32 +++ /dev/null @@ -1,70 +0,0 @@ -# user editable stuff: -CONFIGDIR="/etc/powerdns/" -OPTFLAGS?=-O3 -CXXFLAGS:= $(CXXFLAGS) -Wall $(OPTFLAGS) $(PROFILEFLAGS) -g -CFLAGS:=$(CFLAGS) -Wall $(OPTFLAGS) $(PROFILEFLAGS) -LINKCC=i586-mingw32msvc-g++ -CC=i586-mingw32msvc-gcc -CXX=i586-mingw32msvc-g++ -# static dependencies - -PDNS_RECURSOR_OBJECTS=syncres.o misc.o win32_utility.o qtype.o \ -arguments.o lwres.o pdns_recursor.o recursor_cache.o dnsparser.o \ -dnswriter.o dnsrecords.o rcpgenerator.o base64.o zoneparser-tng.o \ -malloc.o selectmplexer.o win32_logger.o win32_rec_channel.o rec_channel_rec.o \ -recursorservice.o ntservice.o - -# REC_CONTROL_OBJECTS=rec_channel.o rec_control.o arguments.o - -# what we need -all: message pdns_recursor.exe - -LDFLAGS += -lwinmm -lwsock32 -lws2_32 $(PROFILEFLAGS) $(STATICFLAGS) - -message: - @echo - @echo PLEASE READ: If you get an error mentioning \#include '', please read README - @echo PLEASE READ: for an easy fix! - @echo - -basic_checks: - @-rm -f pdns_hw - -$(CXX) $(CXXFLAGS) pdns_hw.cc -o pdns_hw - @echo - @if test -x ./pdns_hw ; \ - then if ./pdns_hw; then echo Everything ok, now run $(MAKE) using same settings \(if any\) you passed ./configure; else echo Could compile binary, but not run it, read README please ; fi; \ - else \ - echo; echo Could not compile simple binary, read README please; \ - rm -f dep ; \ - fi - -install: all - -mkdir -p $(DESTDIR)/$(SBINDIR) - mv pdns_recursor $(DESTDIR)/$(SBINDIR) - strip $(DESTDIR)/$(SBINDIR)/pdns_recursor - mkdir -p $(DESTDIR)/$(BINDIR) - mv rec_control $(DESTDIR)/$(BINDIR) - strip $(DESTDIR)/$(BINDIR)/rec_control - -mkdir -p $(DESTDIR)/$(CONFIGDIR) - $(DESTDIR)/$(SBINDIR)/pdns_recursor --config > $(DESTDIR)/$(CONFIGDIR)/recursor.conf-dist - -mkdir -p $(DESTDIR)/usr/share/man/man1 - cp pdns_recursor.1 rec_control.1 $(DESTDIR)/usr/share/man/man1 - $(OS_SPECIFIC_INSTALL) - -clean: - -rm -f dep *.o *~ pdns_recursor rec_control optional/*.o - -dep: - $(CXX) $(CXXFLAGS) -MM -MG *.cc *.hh > $@ - --include dep - -optional: - mkdir optional - -pdns_recursor.exe: optional $(OPTIONALS) $(PDNS_RECURSOR_OBJECTS) - $(LINKCC) $(PDNS_RECURSOR_OBJECTS) $(wildcard optional/*.o) $(LDFLAGS) -o $@ - -rec_control: $(REC_CONTROL_OBJECTS) - $(LINKCC) $(REC_CONTROL_OBJECTS) $(LDFLAGS) -o $@ - diff --git a/pdns/PowerDNS Recursor.sln b/pdns/PowerDNS Recursor.sln deleted file mode 100644 index dce8d27ab..000000000 --- a/pdns/PowerDNS Recursor.sln +++ /dev/null @@ -1,26 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual C++ Express 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PowerDNS Recursor", "PowerDNS Recursor.vcproj", "{E43D2E84-6056-49C6-9DA1-7044BA08E87A}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Eventlogger", "Eventlogger\Eventlogger.vcproj", "{36E5DAC2-6761-4692-BC72-7B5DE6B57628}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E43D2E84-6056-49C6-9DA1-7044BA08E87A}.Debug|Win32.ActiveCfg = Debug|Win32 - {E43D2E84-6056-49C6-9DA1-7044BA08E87A}.Debug|Win32.Build.0 = Debug|Win32 - {E43D2E84-6056-49C6-9DA1-7044BA08E87A}.Release|Win32.ActiveCfg = Release|Win32 - {E43D2E84-6056-49C6-9DA1-7044BA08E87A}.Release|Win32.Build.0 = Release|Win32 - {36E5DAC2-6761-4692-BC72-7B5DE6B57628}.Debug|Win32.ActiveCfg = Debug|Win32 - {36E5DAC2-6761-4692-BC72-7B5DE6B57628}.Debug|Win32.Build.0 = Debug|Win32 - {36E5DAC2-6761-4692-BC72-7B5DE6B57628}.Release|Win32.ActiveCfg = Release|Win32 - {36E5DAC2-6761-4692-BC72-7B5DE6B57628}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/pdns/PowerDNS Recursor.vcproj b/pdns/PowerDNS Recursor.vcproj deleted file mode 100644 index 47d3affa2..000000000 --- a/pdns/PowerDNS Recursor.vcproj +++ /dev/null @@ -1,378 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/pdns/arguments.cc b/pdns/arguments.cc index c0ea903f1..1ce73c3b8 100644 --- a/pdns/arguments.cc +++ b/pdns/arguments.cc @@ -175,7 +175,6 @@ const string & ArgvMap::operator[](const string &arg) return params[arg]; } -#ifndef WIN32 mode_t ArgvMap::asMode(const string &arg) { mode_t mode; @@ -233,7 +232,6 @@ uid_t ArgvMap::asUid(const string &arg) } return uid; } -#endif int ArgvMap::asNum(const string &arg) { diff --git a/pdns/arguments.hh b/pdns/arguments.hh index eea831224..fad499d3e 100644 --- a/pdns/arguments.hh +++ b/pdns/arguments.hh @@ -27,11 +27,9 @@ #include #include "misc.hh" #include "pdnsexception.hh" -#ifndef WIN32 -# include -# include -# include -#endif +#include +#include +#include #include "namespaces.hh" @@ -95,11 +93,9 @@ public: bool parmIsset(const string &var); //!< Checks if a parameter is set to *a* value bool mustDo(const string &var); //!< if a switch is given, if we must do something (--help) int asNum(const string &var); //!< return a variable value as a number -#ifndef WIN32 mode_t asMode(const string &var); // #include diff --git a/pdns/backends/gsql/ssql.hh b/pdns/backends/gsql/ssql.hh index 2900381a6..10fc1d00c 100644 --- a/pdns/backends/gsql/ssql.hh +++ b/pdns/backends/gsql/ssql.hh @@ -4,10 +4,6 @@ #ifndef SSQL_HH #define SSQL_HH -#ifdef WIN32 -# pragma warning ( disable: 4786 ) -#endif // WIN32 - #include #include #include "../../namespaces.hh" diff --git a/pdns/common_startup.cc b/pdns/common_startup.cc index d021c31b0..7368c81d9 100644 --- a/pdns/common_startup.cc +++ b/pdns/common_startup.cc @@ -336,7 +336,6 @@ void mainthread() DNSPacket::s_ednssubnetcodes.push_back(boost::lexical_cast(code)); } } -#ifndef WIN32 if(!::arg()["chroot"].empty()) { if(::arg().mustDo("master") || ::arg().mustDo("slave")) gethostbyname("a.root-servers.net"); // this forces all lookup libraries to be loaded @@ -347,7 +346,6 @@ void mainthread() else L< using namespace boost::multi_index; -#ifndef WIN32 -# include -# include -# include -#endif // WIN32 +#include +#include +#include #include "lock.hh" #include "packethandler.hh" diff --git a/pdns/distributor.hh b/pdns/distributor.hh index dd610b4d1..de691b299 100644 --- a/pdns/distributor.hh +++ b/pdns/distributor.hh @@ -20,18 +20,13 @@ #ifndef DISTRIBUTOR_HH #define DISTRIBUTOR_HH - #include #include #include #include #include #include - -#ifndef WIN32 -# include -#endif // WIN32 - +#include #include "logger.hh" #include "dns.hh" #include "dnsbackend.hh" diff --git a/pdns/dns.hh b/pdns/dns.hh index 4fafa8051..0acdb101d 100644 --- a/pdns/dns.hh +++ b/pdns/dns.hh @@ -123,13 +123,8 @@ public: } }; -#ifdef _MSC_VER -# pragma pack ( push ) -# pragma pack ( 1 ) -# define GCCPACKATTRIBUTE -#else -# define GCCPACKATTRIBUTE __attribute__((packed)) -#endif +#define GCCPACKATTRIBUTE __attribute__((packed)) + struct dnsrecordheader { uint16_t d_type; @@ -143,9 +138,6 @@ struct EDNS0Record uint8_t extRCode, version; uint16_t Z; } GCCPACKATTRIBUTE; -#ifdef _MSC_VER -#pragma pack (pop) -#endif enum { ns_t_invalid = 0, /* Cookie. */ @@ -208,10 +200,7 @@ enum { ns_t_any = 255, /* Wildcard match. */ }; -#ifdef WIN32 -#define BYTE_ORDER 1 -#define LITTLE_ENDIAN 1 -#elif __FreeBSD__ || __APPLE__ || __OpenBSD__ +#if __FreeBSD__ || __APPLE__ || __OpenBSD__ #include #elif __linux__ # include diff --git a/pdns/dnsbackend.cc b/pdns/dnsbackend.cc index 418c895c8..7ababc55d 100644 --- a/pdns/dnsbackend.cc +++ b/pdns/dnsbackend.cc @@ -96,7 +96,6 @@ vector BackendMakerClass::getModules() void BackendMakerClass::load_all() { // TODO: Implement this? -#ifndef WIN32 DIR *dir=opendir(arg()["module-dir"].c_str()); if(!dir) { L<d_name); } closedir(dir); -#endif // WIN32 } void BackendMakerClass::load(const string &module) diff --git a/pdns/dnsbackend.hh b/pdns/dnsbackend.hh index 8472787f1..3a71ef7ba 100644 --- a/pdns/dnsbackend.hh +++ b/pdns/dnsbackend.hh @@ -29,12 +29,8 @@ class DNSPacket; #include "pdnsexception.hh" #include #include - -#ifndef WIN32 -# include -# include -#endif // WIN32 - +#include +#include #include "misc.hh" #include "qtype.hh" #include "dns.hh" diff --git a/pdns/dnspacket.hh b/pdns/dnspacket.hh index 64d41740a..6a9fa16ad 100644 --- a/pdns/dnspacket.hh +++ b/pdns/dnspacket.hh @@ -34,15 +34,12 @@ #include "iputils.hh" #include "ednssubnet.hh" -#ifndef WIN32 #include #include #include #include #include -#endif // WIN32 - #include #include #include @@ -59,13 +56,6 @@ #endif // HAVE_CONFIG_H -#ifdef WIN32 -# ifdef BYTE_ORDER -# undef BYTE_ORDER -# endif // BYTE_ORDER -# define BYTE_ORDER LITTLE_ENDIAN -#endif // WIN32 - class DNSBackend; class DNSSECKeeper; diff --git a/pdns/dnsproxy.hh b/pdns/dnsproxy.hh index 6ebbafc3a..b380f4e32 100644 --- a/pdns/dnsproxy.hh +++ b/pdns/dnsproxy.hh @@ -20,13 +20,9 @@ #define PDNS_DNSPROXY #include #include - -#ifndef WIN32 -# include -# include -# include -#endif // WIN32 - +#include +#include +#include #include "dnspacket.hh" #include "lock.hh" #include "iputils.hh" diff --git a/pdns/dnswriter.hh b/pdns/dnswriter.hh index 6bed390c3..7d42d0543 100644 --- a/pdns/dnswriter.hh +++ b/pdns/dnswriter.hh @@ -4,11 +4,6 @@ #include #include #include -#if !defined SOLARIS8 && !defined WIN32 - -#elif defined WIN32 -#include "utility.hh" -#endif #include "dns.hh" #include "namespaces.hh" diff --git a/pdns/dynhandler.cc b/pdns/dynhandler.cc index 952de7d3e..eda4391c8 100644 --- a/pdns/dynhandler.cc +++ b/pdns/dynhandler.cc @@ -60,20 +60,8 @@ string DLCurrentConfigHandler(const vector&parts, Utility::pid_t ppid) string DLRQuitHandler(const vector&parts, Utility::pid_t ppid) { -#ifndef WIN32 signal(SIGALRM, dokill); - alarm(1); - -#else - - if ( !PDNSService::instance()->isRunningAsService()) - GenerateConsoleCtrlEvent( CTRL_C_EVENT, 0 ); - else - PDNSService::instance()->stop(); - -#endif // WIN32 - return "Exiting"; } diff --git a/pdns/dynhandler.hh b/pdns/dynhandler.hh index 9b284090e..a20ce4adb 100644 --- a/pdns/dynhandler.hh +++ b/pdns/dynhandler.hh @@ -24,12 +24,8 @@ #include #include -#ifndef WIN32 -# include "config.h" -# include -#else -# include "pdnsservice.hh" -#endif // WIN32 +#include "config.h" +#include #include "namespaces.hh" diff --git a/pdns/dynlistener.hh b/pdns/dynlistener.hh index bcec327b3..f21f9475f 100644 --- a/pdns/dynlistener.hh +++ b/pdns/dynlistener.hh @@ -28,14 +28,11 @@ #include #include "iputils.hh" #include -#ifndef WIN32 #include #include #include - #include #include -#endif // WIN32 #include "namespaces.hh" @@ -65,10 +62,6 @@ private: void listenOnTCP(const ComboAddress&); void createSocketAndBind(int family, struct sockaddr*local, size_t len); -#ifdef WIN32 - HANDLE m_pipeHandle; -#endif // WIN32 - Utility::socklen_t d_addrlen; NetmaskGroup d_tcprange; int d_s; diff --git a/pdns/dynmessenger.hh b/pdns/dynmessenger.hh index 59ad1004f..5a78a9c92 100644 --- a/pdns/dynmessenger.hh +++ b/pdns/dynmessenger.hh @@ -21,19 +21,11 @@ #include #include - -#ifndef WIN32 -# include -# include -# include -# include -# include - -#else -# include "pdnsservice.hh" - -#endif // WIN32 - +#include +#include +#include +#include +#include #include #include "iputils.hh" #include "pdnsexception.hh" @@ -45,14 +37,9 @@ class DynMessenger { int d_s; -#ifndef WIN32 struct sockaddr_un d_local; // our local address struct sockaddr_un d_remote; // our remote address -#else - HANDLE m_pipeHandle; // Named pipe handle. - -#endif // WIN32 DynMessenger(const DynMessenger &); // NOT IMPLEMENTED public: diff --git a/pdns/iputils.hh b/pdns/iputils.hh index c435a221e..59920f9a2 100644 --- a/pdns/iputils.hh +++ b/pdns/iputils.hh @@ -20,13 +20,9 @@ #define PDNS_IPUTILSHH #include - -#ifndef WIN32 #include #include #include -#endif // WIN32 - #include #include #include diff --git a/pdns/logger.hh b/pdns/logger.hh index d6ee95ec9..3c7b2ccbb 100644 --- a/pdns/logger.hh +++ b/pdns/logger.hh @@ -25,64 +25,21 @@ #include #include #include "config.h" -#ifndef WIN32 -# include +#include #include -#else -# define WINDOWS_LEAN_AND_MEAN -# include -typedef int pthread_mutex_t; -typedef int pthread_t; -#endif // WIN32 - #include "namespaces.hh" //! The Logger class can be used to log messages in various ways. class Logger { public: -#ifndef WIN32 Logger(const string &, int facility=LOG_DAEMON); //!< pass the identification you wish to appear in the log //! The urgency of a log message enum Urgency {All=99999,NTLog=12345,Alert=LOG_ALERT, Critical=LOG_CRIT, Error=LOG_ERR, Warning=LOG_WARNING, Notice=LOG_NOTICE,Info=LOG_INFO, Debug=LOG_DEBUG, None=-1}; -#else - Logger( const string &, int facility = 0 ); //!< pass the identification you wish to appear in the log - - //! The urgency of a log message - enum Urgency - { - All = 99999, - NTLog = 12345, - Alert = EVENTLOG_ERROR_TYPE, - Critical= EVENTLOG_ERROR_TYPE, - Error = EVENTLOG_ERROR_TYPE, - Warning = EVENTLOG_WARNING_TYPE, - Notice = EVENTLOG_INFORMATION_TYPE, - Info = EVENTLOG_INFORMATION_TYPE, - Debug = EVENTLOG_INFORMATION_TYPE, - None = -1 - }; - - void toNTLog( void ); - -private: - //! Handle used to communicate with the event log. - HANDLE m_eventLogHandle; - - //! Log file handle. - FILE *m_pLogFile; - - //! Log current message to the NT log? - map< pthread_t, bool > m_toNTLog; - -public: - -#endif // WIN32 - /** Log a message. \param msg Message you wish to log \param Urgency Urgency of the message you wish to log @@ -117,12 +74,7 @@ public: Logger& operator<<(unsigned long long); //!< log an unsigned 64 bit int Logger& operator<<(Urgency); //!< set the urgency, << style -#ifndef WIN32 Logger& operator<<(std::ostream & (&)(std::ostream &)); //!< this is to recognise the endl, and to commit the log -#else - // This is a hack to keep MSVC from generating a internal compiler error. - Logger& operator<<(ostream & (hack)(ostream &)); //!< this is to recognise the endl, and to commit the log -#endif // WIN32 private: mapd_strings; diff --git a/pdns/lwres.hh b/pdns/lwres.hh index c54be2a09..56de782f1 100644 --- a/pdns/lwres.hh +++ b/pdns/lwres.hh @@ -24,17 +24,15 @@ #include #include "misc.hh" #include "iputils.hh" -#ifndef WIN32 -# include -# include -# include -# include -# include -# include -# include -# include -# undef res_mkquery -#endif // WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#undef res_mkquery #include "pdnsexception.hh" #include "dns.hh" diff --git a/pdns/misc.cc b/pdns/misc.cc index 874a9561d..e66abde41 100644 --- a/pdns/misc.cc +++ b/pdns/misc.cc @@ -17,7 +17,6 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifndef WIN32 #include #include #include @@ -25,8 +24,6 @@ #include #include #include -#endif // WIN32 - #include "misc.hh" #include #include @@ -407,11 +404,8 @@ string urlEncode(const string &text) string getHostname() { -#ifdef WIN32 -# define MAXHOSTNAMELEN 1025 -#endif // WIN32 #ifndef MAXHOSTNAMELEN -# define MAXHOSTNAMELEN 255 +#define MAXHOSTNAMELEN 255 #endif char tmp[MAXHOSTNAMELEN]; @@ -441,25 +435,10 @@ string stringerror() return strerror(errno); } -#ifdef WIN32 -string netstringerror() -{ - char buf[512]; - int err=WSAGetLastError(); - if(FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, - 0, buf, sizeof(buf)-1, NULL)) { - return string(buf); - } - else { - return strerror(err); - } -} -#else string netstringerror() { return stringerror(); } -#endif void cleanSlashes(string &str) { diff --git a/pdns/misc.hh b/pdns/misc.hh index 505db2982..682441779 100644 --- a/pdns/misc.hh +++ b/pdns/misc.hh @@ -51,17 +51,11 @@ struct TSCTimer #include "utility.hh" #include "dns.hh" -#ifndef WIN32 -# include -# include -# include -# include -# include -#else -# define WINDOWS_LEAN_AND_MEAN -# include -# include "utility.hh" -#endif // WIN32 +#include +#include +#include +#include +#include #include #include #include diff --git a/pdns/mtasker.hh b/pdns/mtasker.hh index 226dbbf20..ed5487e2d 100644 --- a/pdns/mtasker.hh +++ b/pdns/mtasker.hh @@ -19,14 +19,10 @@ #ifndef MTASKER_HH #define MTASKER_HH -#ifdef WIN32 -# include "win32_mtasker.hh" -#else - #include #include #include -#include +#include #include #include #include @@ -113,6 +109,5 @@ private: }; #include "mtasker.cc" -#endif // WIN32 #endif // MTASKER_HH diff --git a/pdns/nameserver.cc b/pdns/nameserver.cc index 1729e9e9e..6ea51c808 100644 --- a/pdns/nameserver.cc +++ b/pdns/nameserver.cc @@ -181,7 +181,7 @@ bool AddressIsUs(const ComboAddress& remote) void UDPNameserver::bindIPv6() { -#if !WIN32 && HAVE_IPV6 +#if HAVE_IPV6 vector locals; stringtok(locals,::arg()["local-ipv6"]," ,"); @@ -223,7 +223,7 @@ void UDPNameserver::bindIPv6() L< -# include -# include -# include -# include -# include -# include -# include - -#endif // WIN32 - +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include "statbag.hh" diff --git a/pdns/ntservice.cc b/pdns/ntservice.cc deleted file mode 100644 index 4ae2fde74..000000000 --- a/pdns/ntservice.cc +++ /dev/null @@ -1,302 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2002 PowerDNS.COM BV - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License version 2 - as published by the Free Software Foundation - - - 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, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -/*! -\file ntservice.cpp -\brief This file contains the NTService class implementation. -*/ - -#include "utility.hh" -#include -#include -#include "logger.hh" -#include "ntservice.hh" - -#define L theL("pdns") - - -// Default constructor. -NTService::NTService( void ) -{ - m_runningAsService = false; - m_errorCode = 0; - m_statusCode = 0; - m_serviceStatusHandle = NULL; -} - - -// Destructor. -NTService::~NTService( void ) -{ -} - - -// Returns whether the program is running as a service. -bool NTService::isRunningAsService( void ) -{ - return m_runningAsService; -} - - -// Registers the service. -bool NTService::registerService( const std::string & description, bool registerLog ) -{ - std::stringstream str; - HKEY key, pkey; - SC_HANDLE sc; - char temp[ 512 ]; - DWORD flags; - - sc = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS ); - if ( sc == NULL ) - return false; // Could not open the Service Control Manager. - - GetModuleFileName( NULL, temp, sizeof( temp )); - - str << temp << " --ntservice"; - - if ( CreateService( - sc, - getServiceName().c_str(), - getServiceName().c_str(), - SERVICE_ALL_ACCESS, - SERVICE_WIN32_OWN_PROCESS, - SERVICE_AUTO_START, - SERVICE_ERROR_NORMAL, - str.str().c_str(), - NULL, - NULL, - NULL, - NULL, - NULL ) == NULL ) - { - if(GetLastError() != ERROR_SERVICE_EXISTS) - return false; // Don't we all like functions with 43 billion parameters? - } - CloseServiceHandle( sc ); - - str.str( "" ); - - // Set description. - if ( !description.empty()) - { - str << "SYSTEM\\CurrentControlSet\\Services\\" << getServiceName(); - - if ( RegCreateKey( HKEY_LOCAL_MACHINE, str.str().c_str(), &key ) != ERROR_SUCCESS ) - return false; - - if ( RegSetValueEx( key, "Description", 0, REG_SZ, reinterpret_cast< const unsigned char * >( description.c_str()), description.length()) != ERROR_SUCCESS ) - { - RegCloseKey( key ); - return false; - } - - RegCloseKey( key ); - } - - // Register event log. - if ( registerLog ) - { - str.str( "" ); - - str << "SYSTEM\\CurrentControlSet\\Services\\Eventlog\\Application\\" << getServiceName(); - if ( RegCreateKey( HKEY_LOCAL_MACHINE, str.str().c_str(), &pkey ) != ERROR_SUCCESS ) - return false; - - flags = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; - - if ( RegSetValueEx( pkey, "TypesSupported", 0, REG_DWORD, reinterpret_cast< const unsigned char * >( &flags ), sizeof( flags )) != ERROR_SUCCESS ) - { - RegCloseKey( pkey ); - return false; - } - - // For the message file this function assumes %SystemRoot%\\System32\\msg.dll - str.str( "" ); - - char path[ MAX_PATH ]; - GetCurrentDirectory( sizeof( path ), path ); - - // FIXME: This really should be: str << path << "\\" << getServiceName() << "msg.dll"; - str << path << "\\Eventlogger.dll"; - if ( RegSetValueEx( pkey, "EventMessageFile", 0, REG_SZ, reinterpret_cast< const unsigned char * >( str.str().c_str()), str.str().length()) != ERROR_SUCCESS ) - { - RegCloseKey( pkey ); - return false; - } - - RegCloseKey( pkey ); - } - - return true; -} - - -// Calls the control handler. -void WINAPI NTService::s_ctrlHandler( DWORD controlCode ) -{ - NTService::instance()->ctrlHandler( controlCode ); -} - - -// Calls the service's main function. -void WINAPI NTService::s_serviceMain( DWORD argc, LPTSTR *argv ) -{ - // IEEEEUUWWWW!! - - NTService::instance()->m_serviceStatusHandle = RegisterServiceCtrlHandler( NTService::instance()->getServiceName().c_str(), s_ctrlHandler ); - if ( NTService::instance()->m_serviceStatusHandle == 0 ) - { - // Could not register service ctrl handler. - return; - } - - NTService::instance()->setStatus( SERVICE_START_PENDING ); - // Initialize. - if ( !NTService::instance()->init()) - { - NTService::instance()->setStatus( SERVICE_STOPPED, -1 ); - return; - } - - NTService::instance()->setStatus( SERVICE_RUNNING ); - - // Run. - NTService::instance()->main( argc, argv ); - - NTService::instance()->setStatus( SERVICE_STOP_PENDING ); - - // Shut down. - NTService::instance()->shutdown(); - - NTService::instance()->setStatus( SERVICE_STOPPED ); -} - - -// Sets the service's status. -void NTService::setStatus( DWORD status, DWORD error ) -{ - SERVICE_STATUS stat; - - if ( !m_serviceStatusHandle ) - return; - - stat.dwServiceType = SERVICE_WIN32_OWN_PROCESS; - stat.dwCurrentState = status; - stat.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; - stat.dwWin32ExitCode = ( error ? ERROR_SERVICE_SPECIFIC_ERROR : NO_ERROR ); - stat.dwServiceSpecificExitCode = error; - stat.dwCheckPoint = 0; - stat.dwWaitHint = 0; - - SetServiceStatus( m_serviceStatusHandle, &stat ); -} - - -// Starts the service. -int NTService::start( int argc, char *argv[], bool asService ) -{ - int res = 0; - char name[ 128 ]; - - strncpy( name, getServiceName().c_str(), sizeof( name )); - - SERVICE_TABLE_ENTRY entries[] = - { - { name, s_serviceMain }, - { NULL, NULL } - }; - - if ( asService ) - { - // Run as service. - m_runningAsService = true; - - if ( StartServiceCtrlDispatcher( entries )) - return 0; // Success! - - // StartServiceCtrlDispatcher() failed, check if we should run as a normal - // console program. - if ( GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT ) - return -1; - - } - - DLOG( L << "Running as a normal (console) program." << endl ); - - // Run as normal (console) program. - m_runningAsService = false; - - if ( !init()) - return -1; // Could not initialize. - - // Run. - res = main( argc, argv ); - - shutdown(); - - return res; -} - - -// Stops the service. -bool NTService::stop( void ) -{ - if ( !isRunningAsService()) - exit( 0 ); - - setStatus( SERVICE_STOPPED, 0 ); - - return true; -} - - -// Unregister service. -bool NTService::unregisterService( void ) -{ - HKEY key; - SC_HANDLE sc, svc; - - sc = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS ); - if ( sc == NULL ) - return false; - - svc = OpenService( sc, getServiceName().c_str(), DELETE ); - if ( GetLastError() != ERROR_SERVICE_DOES_NOT_EXIST ) - { - if ( svc == NULL ) - { - CloseServiceHandle( sc ); - return false; - } - - DeleteService( svc ); - CloseServiceHandle( svc ); - CloseServiceHandle( sc ); - } - - if ( RegOpenKeyEx( HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application", 0, KEY_WRITE, &key ) != ERROR_SUCCESS ) - return false; - - RegDeleteKey( key, getServiceName().c_str()); - - RegCloseKey( key ); - - return true; -} diff --git a/pdns/ntservice.hh b/pdns/ntservice.hh deleted file mode 100644 index 1b21eefa9..000000000 --- a/pdns/ntservice.hh +++ /dev/null @@ -1,102 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2002 PowerDNS.COM BV - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License version 2 - as published by the Free Software Foundation - - - 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, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -/*! -\file ntservice.hh -\brief This file contains the NTService class specification. -*/ - -#ifndef NTSERVICE_HH -#define NTSERVICE_HH -#include "utility.hh" - -#include -#include "singleton.hh" - - -//! The NTService class is responsible for giving the program NT Service characteristics. -class NTService : public Singleton< NTService > -{ -private: - //! Is the program running as a NT Service? - bool m_runningAsService; - - //! Service status handle. - SERVICE_STATUS_HANDLE m_serviceStatusHandle; - -protected: - //! Status code. - DWORD m_statusCode; - - //! Error code. - DWORD m_errorCode; - - //! Main function. - virtual int main( int argc, char *argv[] ) - { - return 0; - } - - //! Control handler. - virtual void ctrlHandler( DWORD controlCode ) - { - } - - //! Sets the service's status and error codes. - void setStatus( DWORD status, DWORD error = 0 ); - -public: - //! Default constructor. - NTService( void ); - - //! Destructor. - virtual ~NTService( void ); - - //! Starts the service. - int start( int argc, char *argv[], bool asService = true ); - - //! Control handler (calls NTService::ctrlHandler()). - static void WINAPI s_ctrlHandler( DWORD controlCode ); - - //! Service main (calls NTService::main()). - static void WINAPI s_serviceMain( DWORD argc, LPTSTR *argv ); - - //! Returns the name of the service. - virtual std::string getServiceName( void ) - { - return "NTService"; - } - - //! Returns whether the program is running as a service or not. - bool isRunningAsService( void ); - - //! Registers the service with the system. - bool registerService( const std::string & description, bool registerLog = true ); - - //! Unregisters the service. - bool unregisterService( void ); - - //! Stops the service. - bool stop( void ); - -}; - - -#endif // NTSERVICE_H - diff --git a/pdns/packethandler.hh b/pdns/packethandler.hh index b8f61a94c..ac11e538d 100644 --- a/pdns/packethandler.hh +++ b/pdns/packethandler.hh @@ -19,12 +19,9 @@ #ifndef PACKETHANDLER_HH #define PACKETHANDLER_HH -#ifndef WIN32 -# include -# include -# include -#endif // WIN32 - +#include +#include +#include #include "ueberbackend.hh" #include "dnspacket.hh" #include "packetcache.hh" diff --git a/pdns/pdns_recursor.cc b/pdns/pdns_recursor.cc index ee5a1690c..2f04a574a 100644 --- a/pdns/pdns_recursor.cc +++ b/pdns/pdns_recursor.cc @@ -16,15 +16,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifndef WIN32 -# include -# include -# include -#else - #include "ntservice.hh" - #include "recursorservice.hh" -#endif // WIN32 - +#include +#include +#include #include #include "json_ws.hh" #include @@ -701,7 +695,6 @@ void makeControlChannelSocket(int processNum=-1) sockname+=".controlsocket"; s_rcc.listen(sockname); -#ifndef WIN32 int sockowner = -1; int sockgroup = -1; @@ -721,7 +714,6 @@ void makeControlChannelSocket(int processNum=-1) mode_t sockmode=::arg().asMode("socket-mode"); chmod(sockname.c_str(), sockmode); } -#endif } void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var) @@ -1056,7 +1048,6 @@ void makeUDPServerSockets() } -#ifndef WIN32 void daemonize(void) { if(fork()) @@ -1074,7 +1065,6 @@ void daemonize(void) close(i); } } -#endif uint64_t counter; bool statsWanted; @@ -1796,7 +1786,6 @@ int serviceMain(int argc, char*argv[]) if(!s_pidfname.empty()) unlink(s_pidfname.c_str()); // remove possible old pid file -#ifndef WIN32 if(::arg().mustDo("daemon")) { L< 1 ? forks : -1); int newgid=0; @@ -1981,25 +1969,6 @@ catch(...) { return 0; } -#ifdef WIN32 -void doWindowsServiceArguments(RecursorService& recursor) -{ - if(::arg().mustDo( "register-service" )) { - if ( !recursor.registerService( "The PowerDNS Recursor.", true )) { - cerr << "Could not register service." << endl; - exit( 99 ); - } - - exit( 0 ); - } - - if ( ::arg().mustDo( "unregister-service" )) { - recursor.unregisterService(); - exit( 0 ); - } -} -#endif - int main(int argc, char **argv) { @@ -2011,14 +1980,6 @@ int main(int argc, char **argv) reportOtherTypes(); int ret = EXIT_SUCCESS; -#ifdef WIN32 - RecursorService service; - WSADATA wsaData; - if(WSAStartup( MAKEWORD( 2, 2 ), &wsaData )) { - cerr<<"Unable to initialize winsock\n"; - exit(1); - } -#endif // WIN32 try { ::arg().set("stack-size","stack size per mthread")="200000"; @@ -2039,25 +2000,14 @@ int main(int argc, char **argv) ::arg().set("threads", "Launch this number of threads")="2"; ::arg().set("processes", "Launch this number of processes (EXPERIMENTAL, DO NOT CHANGE)")="1"; ::arg().set("config-name","Name of this virtual configuration - will rename the binary image")=""; -#ifdef WIN32 - ::arg().set("quiet","Suppress logging of questions and answers")="off"; - ::arg().setSwitch( "register-service", "Register the service" )= "no"; - ::arg().setSwitch( "unregister-service", "Unregister the service" )= "no"; - ::arg().setSwitch( "ntservice", "Run as service" )= "no"; - ::arg().setSwitch( "use-ntlog", "Use the NT logging facilities" )= "yes"; - ::arg().setSwitch( "use-logfile", "Use a log file" )= "no"; -#else ::arg().set( "experimental-logfile", "Filename of the log file for JSON parser" )= "/var/log/pdns.log"; ::arg().setSwitch( "experimental-json-interface", "If we should run a JSON webserver") = "no"; ::arg().set("quiet","Suppress logging of questions and answers")=""; ::arg().set("logging-facility","Facility to log messages as. 0 corresponds to local0")=""; -#endif ::arg().set("config-dir","Location of configuration directory (recursor.conf)")=SYSCONFDIR; -#ifndef WIN32 ::arg().set("socket-owner","Owner of socket")=""; ::arg().set("socket-group","Group of socket")=""; ::arg().set("socket-mode", "Permissions for socket")=""; -#endif ::arg().set("socket-dir","Where the controlsocket will live")=LOCALSTATEDIR; ::arg().set("delegation-only","Which domains we only accept delegations from")=""; @@ -2135,14 +2085,7 @@ int main(int argc, char **argv) exit(99); } -#ifndef WIN32 serviceMain(argc, argv); -#else - doWindowsServiceArguments(service); - L.toNTLog(); - RecursorService::instance()->start( argc, argv, ::arg().mustDo( "ntservice" )); -#endif - } catch(PDNSException &ae) { L< - - -// Message dll used for logging. -BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved ) -{ - return TRUE; -} diff --git a/pdns/pdnsmsg.mc b/pdns/pdnsmsg.mc deleted file mode 100644 index 1c3cf2fc9..000000000 --- a/pdns/pdnsmsg.mc +++ /dev/null @@ -1,30 +0,0 @@ - -MessageId=0x3 -Severity=Error -Facility=Application -SymbolicName=MSG_ERROR -Language=English -%1 -. - - -MessageId=0x2 -Severity=Warning -Facility=Application -SymbolicName=MSG_WARNING -Language=English -%1 -. - - -MessageId=0x1 -Severity=Informational -Facility=Application -SymbolicName=MSG_INFO -Language=English -%1 -. - - - - diff --git a/pdns/powerdns.dsw b/pdns/powerdns.dsw deleted file mode 100644 index 44c50a379..000000000 --- a/pdns/powerdns.dsw +++ /dev/null @@ -1,113 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "installer"=".\installer.dsp" - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name pdns - End Project Dependency - Begin Project Dependency - Project_Dep_Name zone2sql - End Project Dependency - Begin Project Dependency - Project_Dep_Name pdns_recursor - End Project Dependency - Begin Project Dependency - Project_Dep_Name pdns_control - End Project Dependency -}}} - -############################################################################### - -Project: "pdns"=".\pdns.dsp" - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name odbcbackend - End Project Dependency - Begin Project Dependency - Project_Dep_Name pdnsmsg - End Project Dependency -}}} - -############################################################################### - -Project: "pdns_control"=".\pdns_control.dsp" - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Project: "pdns_recursor"=".\pdns_recursor.dsp" - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name pdnsmsg - End Project Dependency -}}} - -############################################################################### - -Project: "pdnsmsg"=".\pdnsmsg.dsp" - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Project: "zone2sql"=".\zone2sql.dsp" - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ - Begin Project Dependency - Project_Dep_Name pdnsmsg - End Project Dependency -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/pdns/rcpgenerator.cc b/pdns/rcpgenerator.cc index 0aaa09357..7548245bf 100644 --- a/pdns/rcpgenerator.cc +++ b/pdns/rcpgenerator.cc @@ -450,16 +450,8 @@ void RecordTextWriter::xfrTime(const uint32_t& val) struct tm tm; time_t time=val; // Y2038 bug! -#ifndef WIN32 Utility::gmtime_r(&time, &tm); -#else - struct tm* tmptr; - tmptr=gmtime(&time); - if(!tmptr) - throw RecordTextException("Unable to convert timestamp into pretty printable time"); - tm=*tmptr; -#endif - + char tmp[16]; snprintf(tmp,sizeof(tmp)-1, "%04d%02d%02d" "%02d%02d%02d", tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, diff --git a/pdns/rcpgenerator.hh b/pdns/rcpgenerator.hh index f594337fc..f772385b9 100644 --- a/pdns/rcpgenerator.hh +++ b/pdns/rcpgenerator.hh @@ -22,11 +22,6 @@ #include #include #include -#if !defined SOLARIS8 && !defined WIN32 - -#elif defined WIN32 -# include "utility.hh" -#endif #include "namespaces.hh" diff --git a/pdns/rec_channel.hh b/pdns/rec_channel.hh index f8e34bcfd..aa4ba344b 100644 --- a/pdns/rec_channel.hh +++ b/pdns/rec_channel.hh @@ -3,18 +3,8 @@ #include #include #include -#if !defined SOLARIS8 && !defined WIN32 - -#elif defined WIN32 -#include "utility.hh" -#endif - -#ifndef WIN32 #include -#else -// ? -struct sockaddr_un {}; -#endif + /** this class is used both to send and answer channel commands to the PowerDNS Recursor */ class RecursorControlChannel diff --git a/pdns/rec_channel_rec.cc b/pdns/rec_channel_rec.cc index 2fd181d05..2afdee5c5 100644 --- a/pdns/rec_channel_rec.cc +++ b/pdns/rec_channel_rec.cc @@ -18,13 +18,11 @@ #include "logger.hh" #include "dnsparser.hh" #include "arguments.hh" -#ifndef WIN32 #include #include -#endif #include "namespaces.hh" -#include "namespaces.hh" + map d_get32bitpointers; map d_get64bitpointers; map > d_get32bitmembers; @@ -245,7 +243,6 @@ string doWipeCache(T begin, T end) return "wiped "+lexical_cast(count)+" records, "+lexical_cast(countNeg)+" negative records\n"; } -#ifndef WIN32 static uint64_t getSysTimeMsec() { struct rusage ru; @@ -259,7 +256,6 @@ static uint64_t getUserTimeMsec() getrusage(RUSAGE_SELF, &ru); return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000); } -#endif static uint64_t calculateUptime() { @@ -499,11 +495,9 @@ RecursorControlParser::RecursorControlParser() addGetStat("uptime", calculateUptime); -#ifndef WIN32 // addGetStat("query-rate", getQueryRate); addGetStat("user-msec", getUserTimeMsec); addGetStat("sys-msec", getSysTimeMsec); -#endif } static void doExitGeneric(bool nicely) diff --git a/pdns/resolver.hh b/pdns/resolver.hh index 36d7e91e4..4089097a1 100644 --- a/pdns/resolver.hh +++ b/pdns/resolver.hh @@ -21,17 +21,15 @@ #include #include #include "iputils.hh" -#ifndef WIN32 -# include -# include -# include -# include -# include -# include -# include -# include -# undef res_mkquery -#endif // WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#undef res_mkquery #include "pdnsexception.hh" #include "dns.hh" diff --git a/pdns/session.hh b/pdns/session.hh index c2902520a..ccb71a7af 100644 --- a/pdns/session.hh +++ b/pdns/session.hh @@ -22,18 +22,16 @@ #include #include -#ifndef WIN32 -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#endif // WIN32 #include "iputils.hh" #include "pdnsexception.hh" diff --git a/pdns/singleton.hh b/pdns/singleton.hh deleted file mode 100644 index 20038b18e..000000000 --- a/pdns/singleton.hh +++ /dev/null @@ -1,127 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2002 PowerDNS.COM BV - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License version 2 - as published by the Free Software Foundation - - - 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, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef SINGLETON_HH -#define SINGLETON_HH - -#define WINDOWS_LEAN_AND_MEAN -#include - - -//! A common singleton template class. -template -class Singleton -{ -private: - static long m_refCount; //! Reference counter. - static _Ty *m_pInstance; //! Pointer to the actual instance. - - //! No assign operator allowed. - const _Ty & operator=( const _Ty & rhv ) - { - } - - //! No copy constructor. - Singleton( const _Ty & copy ) - { - } - -protected: -public: - //! Default constructor. - Singleton( void ) - { - if ( m_refCount == 0 ) - { - m_pInstance = reinterpret_cast< _Ty * >( this ); - } - - // Increase refcount. - InterlockedIncrement( &m_refCount ); - } - - //! Destructor. - virtual ~Singleton( void ) - { - if ( m_refCount == 0 ) - return; - - if ( InterlockedDecrement( &m_refCount ) == 0 ) - { - m_pInstance = NULL; - } - } - - //! Creates the singleton. - static _Ty *create( void ) - { - if ( m_refCount == 0 ) - { - m_pInstance = new _Ty; - } - - // Increase refcount. - InterlockedIncrement( &m_refCount ); - - return m_pInstance; - } - - //! Releases the singleton. - static void release( void ) - { - if ( m_refCount == 0 ) - return; - - if ( InterlockedDecrement( &m_refCount ) == 0 ) - { - // No more instances needed, delete object. - delete m_pInstance; - m_pInstance = NULL; - } - } - - //! Returns a pointer to the singleton. - static _Ty *instance( void ) - { - return m_pInstance; - } - - //! Initializes the singleton. - virtual bool init( void ) - { - return true; - } - - //! Shuts the singleton down. - virtual bool shutdown( void ) - { - return true; - } - -}; - - -template -_Ty *Singleton< _Ty >::m_pInstance = NULL; - -template -long Singleton< _Ty >::m_refCount = 0; - - -#endif // SINGLETON_HH diff --git a/pdns/ssqlite3.cc b/pdns/ssqlite3.cc index b9041ffc4..a35571a92 100644 --- a/pdns/ssqlite3.cc +++ b/pdns/ssqlite3.cc @@ -11,14 +11,7 @@ #include #include "pdns/logger.hh" #include "misc.hh" - -#ifdef WIN32 -# include -# define access _access -# define F_OK 0 -#else // WIN32 -# include -#endif // Unix +#include // Constructor. SSQLite3::SSQLite3( const std::string & database, bool creat ) diff --git a/pdns/sstuff.hh b/pdns/sstuff.hh index ab1d6a4b5..1106073fb 100644 --- a/pdns/sstuff.hh +++ b/pdns/sstuff.hh @@ -7,13 +7,11 @@ #include "iputils.hh" #include #include -#ifndef WIN32 #include #include #include #include #include -#endif #include #include #include diff --git a/pdns/tcpreceiver.cc b/pdns/tcpreceiver.cc index ff89654ad..84e77f356 100644 --- a/pdns/tcpreceiver.cc +++ b/pdns/tcpreceiver.cc @@ -147,11 +147,7 @@ void connectWithTimeout(int fd, struct sockaddr* remote, size_t socklen) int err; Utility::socklen_t len=sizeof(err); -#ifndef WIN32 - if((err=connect(fd, remote, socklen))<0 && errno!=EINPROGRESS) -#else - if((err=connect(clisock, remote, socklen))<0 && WSAGetLastError() != WSAEWOULDBLOCK ) -#endif // WIN32 + if((err=connect(fd, remote, socklen))<0 && errno!=EINPROGRESS) throw NetworkError("connect: "+stringerror()); if(!err) @@ -860,9 +856,7 @@ TCPNameserver::TCPNameserver() d_ng.addMask( *i ); } -#ifndef WIN32 signal(SIGPIPE,SIG_IGN); -#endif // WIN32 for(vector::const_iterator laddr=locals.begin();laddr!=locals.end();++laddr) { int s=socket(AF_INET,SOCK_STREAM,0); @@ -896,7 +890,7 @@ TCPNameserver::TCPNameserver() d_prfds.push_back(pfd); } -#if !WIN32 && HAVE_IPV6 +#if HAVE_IPV6 for(vector::const_iterator laddr=locals6.begin();laddr!=locals6.end();++laddr) { int s=socket(AF_INET6,SOCK_STREAM,0); @@ -931,7 +925,7 @@ TCPNameserver::TCPNameserver() d_prfds.push_back(pfd); } -#endif // WIN32 +#endif } diff --git a/pdns/tcpreceiver.hh b/pdns/tcpreceiver.hh index 89671bae0..70df64e98 100644 --- a/pdns/tcpreceiver.hh +++ b/pdns/tcpreceiver.hh @@ -26,18 +26,15 @@ #include #include #include - -#ifndef WIN32 -# include -# include -# include -# include -# include -# include -# include -# include -# include -#endif // WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "namespaces.hh" diff --git a/pdns/ueberbackend.cc b/pdns/ueberbackend.cc index c56af858b..3d94b0061 100644 --- a/pdns/ueberbackend.cc +++ b/pdns/ueberbackend.cc @@ -67,7 +67,7 @@ int UeberBackend::s_s=-1; // ? bool UeberBackend::loadmodule(const string &name) { // TODO: Implement dynamic loading? -#if !defined(WIN32) && !defined(DARWIN) +#if !defined(DARWIN) void *dlib=dlopen(name.c_str(), RTLD_NOW); if(dlib == NULL) { @@ -83,8 +83,7 @@ bool UeberBackend::loadmodule(const string &name) L << Logger::Warning << "This version doesn't support dynamic loading (yet)." << endl; return false; -#endif // WIN32 - +#endif } void UeberBackend::go(void) diff --git a/pdns/ueberbackend.hh b/pdns/ueberbackend.hh index 35fd71765..05faec5c6 100644 --- a/pdns/ueberbackend.hh +++ b/pdns/ueberbackend.hh @@ -26,7 +26,6 @@ #include #include -#ifndef WIN32 #include #include #include @@ -35,7 +34,6 @@ #include #include #include -#endif // WIN32 #include #include "dnspacket.hh" #include "dnsbackend.hh" diff --git a/pdns/utility.hh b/pdns/utility.hh index eaa1846e7..9f3a7796b 100644 --- a/pdns/utility.hh +++ b/pdns/utility.hh @@ -21,15 +21,6 @@ #ifndef UTILITY_HH #define UTILITY_HH -#ifndef WIN32 -// # include "config.h" -#endif // WIN32 - -#ifdef _MSC_VER -# define NEED_POSIX_TYPEDEF -# pragma warning (disable:4996) -#endif // _MSC_VER - #ifdef NEED_POSIX_TYPEDEF typedef unsigned char uint8_t; typedef unsigned short int uint16_t; @@ -37,38 +28,17 @@ typedef unsigned int uint32_t; typedef unsigned long long uint64_t; #endif - -#ifndef WIN32 -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#else -typedef int socklen_t; -#define _WIN32_WINNT 0x0400 -#include -#include -#include -# define WINDOWS_LEAN_AND_MEAN -# include -# include -# include - -#ifndef ETIMEDOUT -# define ETIMEDOUT WSAETIMEDOUT -#endif // ETIMEDOUT - -# define EINPROGRESS WSAEWOULDBLOCK - -# define snprintf _snprintf -#endif // WIN32 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include "namespaces.hh" @@ -78,17 +48,6 @@ class Semaphore { private: sem_t *m_pSemaphore; -#ifdef WIN32 - typedef int sem_value_t; - - //! The semaphore. - - - - //! Semaphore counter. - long m_counter; - -#else typedef int sem_value_t; #if DARWIN || _AIX || __APPLE__ @@ -98,7 +57,6 @@ private: sem_value_t m_count; uint32_t m_nwaiters; #endif // DARWIN || _AIX || __APPLE__ -#endif // WIN32 protected: public: @@ -124,38 +82,11 @@ public: //! This is a utility class used for platform independant abstraction. class Utility { -#ifdef WIN32 -private: - static int inet_pton4( const char *src, void *dst ); - static int inet_pton6( const char *src, void *dst ); - - static const char *inet_ntop4( const char *src, char *dst, size_t size ); - static const char *inet_ntop6( const char *src, char *dst, size_t size ); - -#endif // WIN32 - public: -#ifdef WIN32 - - //! iovec structure for windows. - typedef struct - { - void *iov_base; //!< Base address. - size_t iov_len; //!< Number of bytes. - } iovec; - - // A few type defines. - typedef DWORD pid_t; - typedef SOCKET sock_t; - typedef int socklen_t; - -#else typedef ::iovec iovec; - typedef ::pid_t pid_t; - typedef int sock_t; - typedef ::socklen_t socklen_t; - -#endif // WIN32 + typedef ::pid_t pid_t; + typedef int sock_t; + typedef ::socklen_t socklen_t; //! Closes a socket. static int closesocket( sock_t socket ); diff --git a/pdns/version.cc b/pdns/version.cc index 8cb17a36b..b932d9312 100644 --- a/pdns/version.cc +++ b/pdns/version.cc @@ -28,8 +28,6 @@ string compilerVersion() return string("clang "__clang_version__); #elif defined(__GNUC__) return string("gcc "__VERSION__); -#elif defined(_MSC_VER) - return string("MSVC "<<_MSC_VER); #else // add other compilers here return string("Unknown compiler"); #endif diff --git a/pdns/win32_dynlistener.cc b/pdns/win32_dynlistener.cc deleted file mode 100644 index 436e9f295..000000000 --- a/pdns/win32_dynlistener.cc +++ /dev/null @@ -1,177 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2002 PowerDNS.COM BV - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License version 2 - as published by the Free Software Foundation - - - 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, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -// $Id$ -/* (C) Copyright 2002 PowerDNS.COM BV */ -#include "utility.hh" -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include "misc.hh" -#include "dns.hh" -#include "arguments.hh" -#include "dnsbackend.hh" -#include "dynlistener.hh" -#include "dnspacket.hh" -#include "logger.hh" -#include "statbag.hh" -#include "pdnsservice.hh" - - - -extern StatBag S; - -DynListener::DynListener(const string &pname) -{ - d_restfunc=0; - string programname=pname; - - if(!programname.empty()) { - string pipename = "\\\\.\\pipe\\" + programname; - - m_pipeHandle = CreateNamedPipe( - pipename.c_str(), - PIPE_ACCESS_DUPLEX, - PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, - PIPE_UNLIMITED_INSTANCES, - 1024, - 1024, - 5000, - NULL ); - - if ( m_pipeHandle == INVALID_HANDLE_VALUE ) - { - L << Logger::Error << "creating named pipe for dynlistener failed." << endl; - exit( 1 ); - } - - L<(p); - us->theListener(); - return 0; -} - -string DynListener::getLine() -{ - char mesg[512]; - memset(mesg,0,512); - - DWORD bytesRead; - - if ( !ConnectNamedPipe( m_pipeHandle, NULL )) - throw PDNSException( "Reading from named pipe failed." ); - - if ( !ReadFile( m_pipeHandle, mesg, sizeof( mesg ), &bytesRead, NULL )) - throw PDNSException( "Reading from named pipe failed." ); - - return mesg; -} - -void DynListener::sendlines(const string &l) -{ - unsigned long bytesWritten; - - string line = l; - line.append( "\r\n" ); - - if ( !WriteFile( m_pipeHandle, line.c_str(), line.length(), &bytesWritten, NULL )) - return; // Could not write. - - FlushFileBuffers( m_pipeHandle ); - DisconnectNamedPipe( m_pipeHandle ); -} - -void DynListener::registerFunc(const string &name, g_funk_t *gf) -{ - d_funcdb[name]=gf; -} - -void DynListener::registerRestFunc(g_funk_t *gf) -{ - d_restfunc=gf; -} - -void DynListener::theListener() -{ - try { - map parameters; - - for(;;) { - string line=getLine(); - boost::trim_right(line); - - vectorparts; - stringtok(parts,line," "); - if(parts.empty()) { - sendlines("Empty line"); - continue; - } - parts[0] = toUpper( parts[0] ); - if(!d_funcdb[parts[0]]) { - if(d_restfunc) - sendlines((*d_restfunc)(parts,d_ppid)); - else - sendlines("Unknown command: '"+parts[0]+"'"); - continue; - } - - sendlines((*d_funcdb[parts[0]])(parts,d_ppid)); - } - } - catch(PDNSException &AE) - { - L< -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "pdnsexception.hh" -#include "misc.hh" -#include "dynmessenger.hh" -#include "arguments.hh" -#include "statbag.hh" -#include "misc.hh" -#include "namespaces.hh" - -ArgvMap &arg() -{ - static ArgvMap arg; - return arg; -} - -StatBag S; - -int main(int argc, char **argv) -{ - string s_programname="pdns"; - string localdir; - - arg().set("config-dir","Location of configuration directory (pdns.conf)")="./"; - arg().set("config-name","Name of this virtual configuration - will rename the binary image")=""; - arg().laxParse(argc,argv); - - if(arg()["config-name"]!="") - s_programname+="-"+arg()["config-name"]; - - string configname=arg()["config-dir"]+"/"+s_programname+".conf"; - cleanSlashes(configname); - - arg().laxFile(configname.c_str()); - - const vector&commands=arg().getCommands(); - - if(commands.empty()) { - cerr<<"No command passed"<::const_iterator i=commands.begin();i!=commands.end();++i) { - if(i!=commands.begin()) - message+=" "; - message+=*i; - } - - if( command=="show") { - message="SHOW "; - for(unsigned int n=1;n -#include -#include -#include -#include - - -DynMessenger::DynMessenger(const string &dname, const string &fname) -{ - string pipename = "\\\\.\\pipe\\" + fname; - - m_pipeHandle = CreateFile( pipename.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL ); - if ( m_pipeHandle == INVALID_HANDLE_VALUE ) - throw PDNSException( "Could not create named pipe (are you on Windows NT, 2000 or XP? 98 doesn't work!)" ); -} - -DynMessenger::~DynMessenger() -{ - CloseHandle( m_pipeHandle ); -} - -int DynMessenger::send(const string &msg) const -{ - unsigned long bytesWritten; - - if ( !WriteFile( m_pipeHandle, msg.c_str(), msg.length(), &bytesWritten, NULL )) - return -1; // Could not write. - - FlushFileBuffers( m_pipeHandle ); - - return 0; -} - -string DynMessenger::receive() const -{ - char buffer[1024]; - - DWORD bytesRead; - - if ( !ReadFile( m_pipeHandle, buffer, sizeof( buffer ) - 1, &bytesRead, NULL )) - return ""; - - buffer[ bytesRead ] = 0; - - return buffer; -} - - diff --git a/pdns/win32_logger.cc b/pdns/win32_logger.cc deleted file mode 100644 index 38e9ddcb8..000000000 --- a/pdns/win32_logger.cc +++ /dev/null @@ -1,181 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2002 PowerDNS.COM BV - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License version 2 - as published by the Free Software Foundation - - - 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, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "utility.hh" -#include "logger.hh" -#include "ntservice.hh" -#include "pdnsmsg.hh" -#include "namespaces.hh" - -Logger &theL(const string &pname) -{ - static Logger l(""); - if(!pname.empty()) - l.setName(pname); - return l; -} - -void Logger::log(const string &msg, Urgency u) -{ - const char *tmp[ 2 ]; - - tmp[ 0 ] = msg.c_str(); - tmp[ 1 ] = NULL; - - char timestr[ 128 ]; - time_t curtime= time( NULL ); - strftime( timestr, sizeof( timestr ), "%a %d %b %X", localtime( &curtime )); - - if ( m_pLogFile != NULL ) - { - ostringstream message; - message << timestr << " (" << u << "): " << msg << endl; - fwrite( message.str().c_str(), sizeof( char ), message.str().length(), m_pLogFile ); - fflush( m_pLogFile ); - } - if(m_eventLogHandle) - ReportEvent( m_eventLogHandle, u, 0, MSG_WARNING, NULL, 1, 0, tmp, NULL ); - - clog << timestr<<" " <getServiceName().c_str()); -} - -void Logger::open() -{ - opened=true; -} - -void Logger::setName(const string &_name) -{ - name=_name; - open(); -} - -Logger::Logger(const string &n, int facility) -{ - opened=false; - flags=0; - d_facility=facility; - consoleUrgency=Error; - name=n; - m_pLogFile = NULL; - m_eventLogHandle = NULL; - open(); -} - -Logger& Logger::operator<<(Urgency u) -{ - d_outputurgencies[0]=u; - return *this; -} - -Logger& Logger::operator<<(const string &s) -{ - if(!d_outputurgencies.count(0)) // default urgency - d_outputurgencies[0]=Info; - - if ( !m_toNTLog.count( 0)) - m_toNTLog[ 0 ] = false; - - // if(d_outputurgencies[0]<=(unsigned int)consoleUrgency) // prevent building strings we won't ever print - d_strings[0].append(s); - - return *this; -} - -Logger& Logger::operator<<(int i) -{ - ostringstream tmp; - tmp< -#include - - -/** \mainpage - Simple system for implementing cooperative multitasking of functions, with - support for waiting on events which can return values. - - \section copyright Copyright and License - MTasker is (c) 2002 by bert hubert. It is licensed to you under the terms of the GPL version 2. - Quick and dirty port to Win32 by Christof Meerwald. - - \section overview High level overview - MTasker is designed to support very simple cooperative multitasking to facilitate writing - code that would ordinarily require a statemachine, for which the author does not consider - himself smart enough. - - This class does not perform any magic it only makes calls to makecontext() and swapcontext(). - Getting the details right however is complicated and MTasker does that for you. - - If preemptive multitasking or more advanced concepts such as semaphores, locks or mutexes - are required, the use of POSIX threads is advised. - - MTasker is designed to offer the performance of statemachines while maintaining simple thread semantics. It is not - a replacement for a full threading system. - - \section concepts Concepts - - There are two important concepts, the 'kernel' and the 'thread'. Each thread starts out as a function, - which is passed to MTasker::makeThread(), together with a possible argument. - - This function is now free to do whatever it wants, but realise that MTasker implements cooperative - multitasking, which means that the coder has the responsiblilty of not taking the CPU overly long. - Other threads can only get the CPU if MTasker::yield() is called or if a thread sleeps to wait for an event, - using the MTasker::waitEvent() method. - - \section kernel The Kernel - The Kernel consists of functions that do housekeeping, but also of code that the client coder - can call to report events. A minimal kernel loop looks like this: - \code - for(;;) { - MT.schedule(); - if(MT.noProcesses()) // exit if no processes are left - break; - } - \endcode - - The kernel typically starts from the main() function of your program. New threads are also - created from the kernel. This can also happen before entering the main loop. To start a thread, - the method MTasker::makeThread is provided. - - \section events Events - By default, Events are recognized by an int and their value is also an int. - This can be overridden by specifying the EventKey and EventVal template parameters. - - An event can be a keypress, but also a UDP packet, or a bit of data from a TCP socket. The - sample code provided works with keypresses, but that is just a not very useful example. - - A thread can also wait for an event only for a limited time, and receive a timeout of that - event did not occur within the specified timeframe. - - \section example A simple menu system - \code -MTasker<> MT; - -void menuHandler(void *p) -{ - int num=(int)p; - cout<<"Key handler for key "<int MTasker::waitEvent(EventKey &key, EventVal *val, unsigned int timeout) -{ - if(d_waiters.count(key)) { // there was already an exact same waiter - return -1; - } - - Waiter w; - w.context=GetCurrentFiber(); - w.ttd= timeout ? time(0)+timeout : 0; - w.tid=d_tid; - w.key=key; - - d_waiters.insert(w); - - SwitchToFiber(d_kernel); - if(val && d_waitstatus==Answer) - *val=d_waitval; - d_tid=w.tid; - return d_waitstatus; -} - -//! yields control to the kernel or other threads -/** Hands over control to the kernel, allowing other processes to run, or events to arrive */ - -templatevoid MTasker::yield() -{ - d_runQueue.push(d_tid); - SwitchToFiber(d_kernel); // give control to the kernel -} - -//! reports that an event took place for which threads may be waiting -/** From the kernel loop, sendEvent can be called to report that something occured for which there may be waiters. - \param key Key of the event for which threads may be waiting - \param val If non-zero, pointer to the content of the event - \return Returns -1 in case of error, 0 if there were no waiters, 1 if a thread was woken up. -*/ -templateint MTasker::sendEvent(const EventKey& key, const EventVal* val) -{ - - typename waiters_t::iterator waiter=d_waiters.find(key); - - if(waiter == d_waiters.end()) { - // cout<<"Event sent nobody was waiting for!"<context; - d_tid=waiter->tid; // set tid - d_eventkey=waiter->key; // pass waitEvent the exact key it was woken for - d_waiters.erase(waiter); // removes the waitpoint - SwitchToFiber(userspace); // swaps back to the above point 'A' - - return 1; -} - -//! launches a new thread -/** The kernel can call this to make a new thread, which starts at the function start and gets passed the val void pointer. - \param start Pointer to the function which will form the start of the thread - \param val A void pointer that can be used to pass data to the thread -*/ -templatevoid MTasker::makeThread(tfunc_t *start, void* val) -{ - ThreadParam *param = new ThreadParam; - - param->tf = start; - param->self = this; - param->tid = d_maxtid; - param->val = val; - - LPVOID uc = CreateFiber(d_stacksize, threadWrapper, param); - - d_threads[d_maxtid]=uc; - d_runQueue.push(d_maxtid++); // will run at next schedule invocation -} - - -//! needs to be called periodically so threads can run and housekeeping can be performed -/** The kernel should call this function every once in a while. It makes sense - to call this function if you: - - reported an event - - called makeThread - - want to have threads running waitEvent() to get a timeout if enough time passed - - \return Returns if there is more work scheduled and recalling schedule now would be useful - -*/ -templatebool MTasker::schedule() -{ - - if(!d_runQueue.empty()) { - d_tid=d_runQueue.front(); - SwitchToFiber(d_threads[d_tid]); - d_runQueue.pop(); - return true; - } - if(!d_zombiesQueue.empty()) { - DeleteFiber(d_threads[d_zombiesQueue.front()]); - d_threads.erase(d_zombiesQueue.front()); - d_zombiesQueue.pop(); - return true; - } - - if(!d_waiters.empty()) { - typedef typename waiters_t::template index::type waiters_by_ttd_index_t; - // waiters_by_ttd_index_t& ttdindex=d_waiters.template get(); - waiters_by_ttd_index_t& ttdindex=boost::multi_index::get(d_waiters); - - for(typename waiters_by_ttd_index_t::iterator i=ttdindex.begin(); i != ttdindex.end(); ) { - if(i->ttd && (unsigned int)i->ttd < now) { - d_waitstatus=TimeOut; - SwitchToFiber(i->context); - ttdindex.erase(i++); // removes the waitpoint - } - else if(i->ttd) - break; - } - } - return false; -} - -//! returns true if there are no processes -/** Call this to check if no processes are running anymore - \return true if no processes are left - */ -templatebool MTasker::noProcesses() -{ - return d_threads.empty(); -} - -//! returns the number of processes running -/** Call this to perhaps limit activities if too many threads are running - \return number of processes running - */ -templateunsigned int MTasker::numProcesses() -{ - return (unsigned int)d_threads.size(); -} - -//! gives access to the list of Events threads are waiting for -/** The kernel can call this to get a list of Events threads are waiting for. This is very useful - to setup 'select' or 'poll' or 'aio' events needed to satisfy these requests. - getEvents clears the events parameter before filling it. - - \param events Vector which is to be filled with keys threads are waiting for -*/ -templatevoid MTasker::getEvents(std::vector& events) -{ - events.clear(); - for(typename waiters_t::const_iterator i=d_waiters.begin();i!=d_waiters.end();++i) { - events.push_back(i->first); - } -} - - -//! Returns the current Thread ID (tid) -/** Processes can call this to get a numerical representation of their current thread ID. - This can be useful for logging purposes. -*/ -templateint MTasker::getTid() -{ - return d_tid; -} - - -template -VOID WINAPI MTasker::threadWrapper(LPVOID lpFiberParameter) -{ - ThreadParam *param = (ThreadParam *) lpFiberParameter; - - tfunc_t *tf = param->tf; - - tf(param->val); - - MTasker *self = param->self; - self->d_zombiesQueue.push(param->tid); - delete param; - - SwitchToFiber(self->d_kernel); -} diff --git a/pdns/win32_mtasker.hh b/pdns/win32_mtasker.hh deleted file mode 100644 index 3c177b9d2..000000000 --- a/pdns/win32_mtasker.hh +++ /dev/null @@ -1,113 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2002 PowerDNS.COM BV - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -#ifndef WIN32_MTASKER_HH -#define WIN32_MTASKER_HH - -#define WINDOWS_LEAN_AND_MEAN -#include - -#include -#include -#include -#include -#include - -struct KeyTag {}; - -//! The main MTasker class -/** The main MTasker class. See the main page for more information. - \param EventKey Type of the key with which events are to be identified. Defaults to int. - \param EventVal Type of the content or value of an event. Defaults to int. Cannot be set to void. - \note The EventKey needs to have an operator< defined because it is used as the key of an associative array -*/ -template class MTasker -{ -public: - struct Waiter - { - LPVOID context; - time_t ttd; - int tid; - EventKey key; - }; - typedef multi_index_container< - Waiter, - indexed_by < - ordered_unique >, - ordered_non_unique, member > - > - > waiters_t; - - waiters_t d_waiters; - -private: - LPVOID d_kernel; - std::queue d_runQueue; - std::queue d_zombiesQueue; - - - std::map d_threads; - int d_tid; - int d_maxtid; - size_t d_stacksize; - - EventVal d_waitval; - EventKey d_eventkey; - enum {Error=-1,TimeOut=0,Answer} d_waitstatus; - -public: - //! Constructor - /** Constructor with a small default stacksize. If any of your threads exceeds this stack, your application will crash. - This limit applies solely to the stack, the heap is not limited in any way. If threads need to allocate a lot of data, - the use of new/delete is suggested. - */ - MTasker(size_t stacksize=8192) : d_stacksize(stacksize) - { - d_kernel=ConvertThreadToFiber( NULL ); - d_maxtid=0; - } - - typedef void tfunc_t(void *); //!< type of the pointer that starts a thread - int waitEvent(EventKey &key, EventVal *val=0, unsigned int timeout=0); - void yield(); - int sendEvent(const EventKey& key, const EventVal* val=0); - void getEvents(std::vector& events); - void makeThread(tfunc_t *start, void* val); - bool schedule(); - bool noProcesses(); - unsigned int numProcesses(); - int getTid(); - -private: - //! This structure holds some fiber data that is passed to the threadWrapper. - struct ThreadParam - { - tfunc_t *tf; - MTasker *self; - int tid; - LPVOID val; - }; - - static void WINAPI threadWrapper( LPVOID lpFiberParameter ); -}; - -#include "win32_mtasker.cc" - -#endif // WIN32_MTASKER_HH - diff --git a/pdns/win32_pdns_recursor.cc b/pdns/win32_pdns_recursor.cc deleted file mode 100644 index c9403ef21..000000000 --- a/pdns/win32_pdns_recursor.cc +++ /dev/null @@ -1,733 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2002 PowerDNS.COM BV - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License version 2 - as published by the Free Software Foundation - - - 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, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "utility.hh" -#include -#include -#include -#include -#include -#include -#include -#include -#include "mtasker.hh" -#include -#include "dnspacket.hh" -#include "statbag.hh" -#include "arguments.hh" -#include "syncres.hh" -#include -#include -#include "recursorservice.hh" - -string s_programname="recursor"; - -#ifndef WIN32 -extern "C" { - int sem_init(sem_t*, int, unsigned int){return 0;} - int sem_wait(sem_t*){return 0;} - int sem_trywait(sem_t*){return 0;} - int sem_post(sem_t*){return 0;} - int sem_getvalue(sem_t*, int*){return 0;} - pthread_t pthread_self(void){return (pthread_t) 0;} - int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr){ return 0; } - int pthread_mutex_lock(pthread_mutex_t *mutex){ return 0; } - int pthread_mutex_unlock(pthread_mutex_t *mutex) { return 0; } - -} -#endif // WIN32 - -StatBag S; -ArgvMap &arg() -{ - static ArgvMap theArg; - return theArg; -} -int d_clientsock; -int d_serversock; -int d_tcpserversock; - -struct PacketID -{ - uint16_t id; - struct sockaddr_in remote; -}; - -bool operator<(const PacketID& a, const PacketID& b) -{ - if(a.id* MT; - -/* these two functions are used by LWRes */ -int asendto(const char *data, int len, int flags, struct sockaddr *toaddr, int addrlen, int id) -{ - return sendto(d_clientsock, data, len, flags, toaddr, addrlen); -} - -int arecvfrom(char *data, int len, int flags, struct sockaddr *toaddr, Utility::socklen_t *addrlen, int *d_len, int id) -{ - PacketID pident; - pident.id=id; - memcpy(&pident.remote,toaddr,sizeof(pident.remote)); - - string packet; - if(!MT->waitEvent(pident,&packet,1)) { // timeout - return 0; - } - - *d_len=packet.size(); - memcpy(data,packet.c_str(),min(len,*d_len)); - - return 1; -} - -typedef map > cache_t; -static cache_t cache; -int cacheHits, cacheMisses; -int getCache(const string &qname, const QType& qt, set* res) -{ - cache_t::const_iterator j=cache.find(toLower(qname)+"|"+qt.getName()); - if(j!=cache.end() && j->first==toLower(qname)+"|"+qt.getName() && j->second.begin()->ttl>(unsigned int)time(0)) { - if(res) - *res=j->second; - - return (unsigned int)j->second.begin()->ttl-time(0); - } - - return -1; -} - -void replaceCache(const string &qname, const QType& qt, const set& content) -{ - - // bogus code to generate root with very low ttl - /* - if((0 && qname.empty()) || qname.rfind(".root-servers.net")==1) { - cout<<"qname: '"< changed; - for(set::const_iterator i=content.begin();i!=content.end();++i) { - DNSResourceRecord j=*i; - j.ttl=time(0)+20; - changed.insert(j); - } - cache[qname+"|"+qt.getName()]=changed; - } - else - */ - cache[toLower(qname)+"|"+qt.getName()]=content; -} - -void doPrune(void) -{ - unsigned int names=0, records=0; - - for(cache_t::iterator j=cache.begin();j!=cache.end();){ - for(set::iterator k=j->second.begin();k!=j->second.end();) - if((unsigned int)k->ttl < (unsigned int)time(0)) { - j->second.erase(k++); - records++; - } - else - ++k; - - if(j->second.empty()) { // everything is gone - cache.erase(j++); - names++; - - } - else { - ++j; - } - } -} - - -void primeHints(void) -{ - // prime root cache - static char*ips[]={"198.41.0.4", "192.228.79.201", "192.33.4.12", "199.7.91.13", "192.203.230.10", "192.5.5.241", "192.112.36.4", "128.63.2.53", - "192.36.148.17","192.58.128.30", "193.0.14.129", "198.32.64.12", "202.12.27.33"}; - DNSResourceRecord arr, nsrr; - arr.qtype=QType::A; - arr.ttl=time(0)+3600000; - nsrr.qtype=QType::NS; - nsrr.ttl=time(0)+3600000; - - setnsset; - for(char c='a';c<='m';++c) { - static char templ[40]; - strncpy(templ,"a.root-servers.net", sizeof(templ) - 1); - *templ=c; - arr.qname=nsrr.content=templ; - arr.content=ips[c-'a']; - setaset; - aset.insert(arr); - replaceCache(string(templ),QType(QType::A),aset); - - nsset.insert(nsrr); - } - replaceCache("",QType(QType::NS),nsset); -} - -void startDoResolve(void *p) -{ - try { - bool quiet=arg().mustDo("quiet"); - DNSPacket P=*(DNSPacket *)p; - - delete (DNSPacket *)p; - - vectorret; - DNSPacket *R=P.replyPacket(); - R->setA(false); - R->setRA(true); - - SyncRes sr; - if(!quiet) - L<getTid()<<"] question for '"<getTid()); - if(!P.d.rd) - sr.setCacheOnly(); - - int res=sr.beginResolve(P.qdomain, P.qtype, ret); - if(res<0) - R->setRcode(RCode::ServFail); - else { - R->setRcode(res); - for(vector::const_iterator i=ret.begin();i!=ret.end();++i) - R->addRecord(*i); - } - - const char *buffer=R->getData(); - if(!R->getSocket()) - sendto(d_serversock,buffer,R->len,0,(struct sockaddr *)(R->remote),R->d_socklen); - else { - char buf[2]; - buf[0]=R->len/256; - buf[1]=R->len%256; - if(send(R->getSocket(),buf,2,0)!=2 || send(R->getSocket(),buffer,R->len,0)!=R->len) - L<getTid()<<"] answer to "<<(P.d.rd?"":"non-rd ")<<"question '"<d.ancount)<<" answers, "<d.arcount)<<" additional, took "<= 0) - break; - - } - if(!tries) - throw PDNSException("Resolver binding to local socket: "+stringerror()); -} - -void makeTCPServerSocket() -{ - d_tcpserversock=socket(AF_INET, SOCK_STREAM,0); - Utility::setCloseOnExec(d_tcpserversock); - - if(d_tcpserversock<0) - throw PDNSException("Making a server socket for resolver: "+stringerror()); - - struct sockaddr_in sin; - memset((char *)&sin,0, sizeof(sin)); - - sin.sin_family = AF_INET; - - if(arg()["local-address"]=="0.0.0.0") { - sin.sin_addr.s_addr = INADDR_ANY; - } - else { - if(!IpToU32(arg()["local-address"], &sin.sin_addr.s_addr)) - throw PDNSException("Unable to resolve local address"); - } - - sin.sin_port = htons(arg().asNum("local-port")); - - if (bind(d_tcpserversock, (struct sockaddr *)&sin, sizeof(sin))<0) - throw PDNSException("TCP Resolver binding to server socket: "+stringerror()); - - int tmp=1; - if(setsockopt(d_tcpserversock,SOL_SOCKET,SO_REUSEADDR,(char*)&tmp,sizeof tmp)<0) { - L<30) { - doPrune(); - last_prune=time(0); - } - if(time(0)-last_stat>1800) { - doStats(); - last_stat=time(0); - } - if(time(0)-last_rootupdate>7200) { - SyncRes sr; - vectorret; - - sr.setNoCache(); - int res=sr.beginResolve("", QType(QType::NS), ret); - if(!res) { - L<(100000); - - char data[1500]; - struct sockaddr_in fromaddr; - - PacketID pident; - primeHints(); - L< tcpconnections; - for(;;) { - while(MT->schedule()); // housekeeping, let threads do their thing - - if(!((counter++)%100)) - MT->makeThread(houseKeeping,0); - if(statsWanted) - doStats(); - - Utility::socklen_t addrlen=sizeof(fromaddr); - int d_len; - DNSPacket P; - - struct timeval tv; - tv.tv_sec=0; - tv.tv_usec=500000; - - fd_set readfds; - FD_ZERO( &readfds ); - FD_SET( d_clientsock, &readfds ); - FD_SET( d_serversock, &readfds ); - FD_SET( d_tcpserversock, &readfds ); - int fdmax=max(d_tcpserversock,max(d_clientsock,d_serversock)); - for(vector::const_iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) { - FD_SET(i->fd, &readfds); - fdmax=max(fdmax,i->fd); - } - - - /* this should listen on a TCP port as well for new connections, */ - int selret = select( fdmax + 1, &readfds, NULL, NULL, &tv ); - if(selret<=0) - if (selret == -1 && errno!=EINTR) - throw PDNSException("Select returned: "+stringerror()); - else - continue; - - if(FD_ISSET(d_clientsock,&readfds)) { // do we have a question response? - d_len=recvfrom(d_clientsock, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen); - if(d_len<0) - continue; - - P.setRemote((struct sockaddr *)&fromaddr, addrlen); - if(P.parse(data,d_len)<0) { - L<sendEvent(pident,&packet); - } - else - L<makeThread(startDoResolve,(void*)new DNSPacket(P)); - - } - } - } - - if(FD_ISSET(d_tcpserversock,&readfds)) { // do we have a new TCP connection - struct sockaddr_in addr; - Utility::socklen_t addrlen=sizeof(addr); - int newsock=accept(d_tcpserversock, (struct sockaddr*)&addr, &addrlen); - Utility::setNonBlocking(newsock); - - if(newsock>0) { - TCPConnection tc; - tc.fd=newsock; - tc.state=TCPConnection::BYTE0; - tc.remote=addr; - L<::iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) { - if(FD_ISSET(i->fd, &readfds)) { - if(i->state==TCPConnection::BYTE0) { - int bytes=recv(i->fd,i->data,2,0); - if(bytes==1) - i->state=TCPConnection::BYTE1; - if(bytes==2) { - i->qlen=(i->data[0]<<8)+i->data[1]; - i->bytesread=0; - i->state=TCPConnection::GETQUESTION; - } - if(!bytes || bytes < 0) { - L<remote,sizeof(i->remote))<<" disconnected"<fd); - tcpconnections.erase(i); - break; - } - } - else if(i->state==TCPConnection::BYTE1) { - int bytes=recv(i->fd,i->data+1,1,0); - if(bytes==1) { - i->state=TCPConnection::GETQUESTION; - i->qlen=(i->data[0]<<8)+i->data[1]; - i->bytesread=0; - } - if(!bytes || bytes < 0) { - L<remote,sizeof(i->remote))<<" disconnected after first byte"<fd); - tcpconnections.erase(i); - break; - } - - } - else if(i->state==TCPConnection::GETQUESTION) { - int bytes=recv(i->fd,i->data + i->bytesread,i->qlen - i->bytesread,0); - if(!bytes || bytes < 0) { - L<remote,sizeof(i->remote))<<" disconnected while reading question body"<fd); - tcpconnections.erase(i); - break; - } - i->bytesread+=bytes; - if(i->bytesread==i->qlen) { - i->state=TCPConnection::BYTE0; - - if(P.parse(i->data,i->qlen)<0) { - L<fd); - tcpconnections.erase(i); - break; - } - else { - P.setSocket(i->fd); - P.setRemote((struct sockaddr *)&i->remote,sizeof(i->remote)); - if(P.d.qr) - L<makeThread(startDoResolve,(void*)new DNSPacket(P)); - } - } - } - } - } - } - } - } - catch(PDNSException &ae) { - L<start( argc, argv, arg().mustDo( "ntservice" )); - - } - catch(PDNSException &ae) { - L< -#include -#include -#include - -#include "pdnsexception.hh" - -#include "namespaces.hh" - -RecursorControlChannel::RecursorControlChannel() -{ -} - -RecursorControlChannel::~RecursorControlChannel() -{ -} - -int RecursorControlChannel::listen(const string& fname) -{ - return 0; -} - -void RecursorControlChannel::connect(const string& path, const string& fname) -{ - -} - -void RecursorControlChannel::send(const std::string& msg, const std::string* remote) -{ - -} - -string RecursorControlChannel::recv(std::string* remote) -{ - return 0; -} - diff --git a/pdns/win32_receiver.cc b/pdns/win32_receiver.cc deleted file mode 100644 index fddd68671..000000000 --- a/pdns/win32_receiver.cc +++ /dev/null @@ -1,305 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2003 PowerDNS.COM BV - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License version 2 - as published by the Free Software Foundation - - - 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, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ -// $Id$ -#ifdef WIN32 -# define WINDOWS_LEAN_AND_MEAN -# include -#else -# include -# include -# include -# include -# include -# include -#endif // WIN32 - -#include "utility.hh" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "dns.hh" -#include "dnsbackend.hh" -#include "ueberbackend.hh" -#include "dnspacket.hh" -#include "nameserver.hh" -#include "distributor.hh" -#include "logger.hh" -#include "arguments.hh" -#include "packethandler.hh" -#include "statbag.hh" -#include "tcpreceiver.hh" -#include "packetcache.hh" -#include "ws.hh" -#include "misc.hh" -#include "dynlistener.hh" -#include "dynhandler.hh" -#include "communicator.hh" -#include "dnsproxy.hh" -#include "utility.hh" -#include "common_startup.hh" - -time_t s_starttime; - -string s_programname="pdns"; // used in packethandler.cc - -char *funnytext= -"*****************************************************************************\n"\ -"Ok, you just ran pdns_server through 'strings' hoping to find funny messages.\n"\ -"Well, you found one. \n"\ -"Two ions are flying through their particle accelerator, says the one to the\n" -"other 'I think I've lost an electron!' \n"\ -"So the other one says, 'Are you sure?'. 'YEAH! I'M POSITIVE!'\n"\ -" the pdns crew - pdns@powerdns.com\n" -"*****************************************************************************\n"; - - -// start (sys)logging - -/** \var Logger L -\brief All logging is done via L, a Logger instance -*/ - - -/** -\file receiver.cc -\brief The main loop of powerdns - -This file is where it all happens - main is here, as are the two pivotal threads qthread() and athread() -*/ - - -static void WIN32_declareArguments() -{ - arg().set("config-dir","Location of configuration directory (pdns.conf)")="./"; - //arg().set("config-name","Name of this virtual configuration - will rename the binary image")=""; - arg().set("module-dir","Default directory for modules")="/../lib"; - - arg().setSwitch( "register-service", "Register the service" )= "no"; - arg().setSwitch( "unregister-service", "Unregister the service" )= "no"; - arg().setSwitch( "ntservice", "Run as service" )= "no"; - - arg().setSwitch( "use-ntlog", "Use the NT logging facilities" )= "yes"; - arg().setSwitch( "use-logfile", "Use a log file" )= "no"; - arg().setSwitch( "logfile", "Filename of the log file" )= "powerdns.log"; -} - -static void loadModules() -{ - L << Logger::Warning << Logger::NTLog << "The Windows version doesn't support dll loading (yet), none of the specified modules loaded" << std::endl; -} - -//! Console handler. -BOOL WINAPI consoleHandler( DWORD ctrl ) -{ - L << Logger::Error << "PowerDNS shutting down..." << endl; - exit( 0 ); - - // This will never be reached. - return true; -} - - -//! The main function of pdns, the pdns process -int main(int argc, char **argv) -{ - s_programname="pdns"; - s_starttime=time(0); - - PDNSService pdns; - - // Initialize winsock. - WSAData wsaData; - - if ( WSAStartup( MAKEWORD( 2, 0 ), &wsaData ) != 0 ) - { - cerr << "Could not initialize winsock.dll" << endl; - return -1; - } - - L.toConsole(Logger::Warning); - try { - declareArguments(); - WIN32_declareArguments(); - - arg().laxParse(argc,argv); // do a lax parse - - // If we have to run as a nt service change the current directory to the executable directory. - if ( arg().mustDo( "ntservice" )) - { - char dir[ MAX_PATH ]; - string newdir; - - GetModuleFileName( NULL, dir, sizeof( dir )); - - newdir = dir; - newdir = newdir.substr( 0, newdir.find_last_of( "\\" )); - - SetCurrentDirectory( newdir.c_str()); - } - - if(arg()["config-name"]!="") - s_programname+="-"+arg()["config-name"]; - - (void)theL(s_programname); - - string configname=arg()["config-dir"]+"/"+s_programname+".conf"; - cleanSlashes(configname); - - if(!arg().mustDo("config") && !arg().mustDo("no-config")) // "config" == print a configuration file - arg().laxFile(configname.c_str()); - - arg().laxParse(argc,argv); // reparse so the commandline still wins - L.toConsole((Logger::Urgency)(arg().asNum("loglevel"))); - - if(arg().mustDo("help") || arg().mustDo("config")) { - arg().set("daemon")="no"; - arg().set("guardian")="no"; - } - - - if ( arg().mustDo( "register-service" )) - { - if ( !pdns.registerService( "An advanced high performance authoritative nameserver.", true )) - { - cerr << "Could not register service." << endl; - exit( 99 ); - } - - // Exit. - exit( 0 ); - } - - if ( arg().mustDo( "unregister-service" )) - { - pdns.unregisterService(); - exit( 0 ); - } - - // we really need to do work - either standalone or as an instance - BackendMakers().launch(arg()["launch"]); // vrooooom! - - if(arg().mustDo("version")) { - cerr<<"Version: "VERSION", compiled on "<<__DATE__", "__TIME__<modules=BackendMakers().getModules(); - cerr<<"Modules available:"<::const_iterator i=modules.begin();i!=modules.end();++i) - cout<<*i<start( argc, argv, arg().mustDo( "ntservice" )); - - WSACleanup(); - - exit(1); - - return 0; -} - - - diff --git a/pdns/win32_utility.cc b/pdns/win32_utility.cc deleted file mode 100644 index 3810ae985..000000000 --- a/pdns/win32_utility.cc +++ /dev/null @@ -1,414 +0,0 @@ -/* - PowerDNS Versatile Database Driven Nameserver - Copyright (C) 2002 - 2006 PowerDNS.COM BV - - 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 2 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, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// Utility class win32 implementation. - -#include "utility.hh" -#include -#include - -// Closes a socket. -int Utility::closesocket( Utility::sock_t socket ) -{ - return ::closesocket( socket ); -} - - -// Drops the program's privileges. -void Utility::dropPrivs( int uid, int gid ) -{ -} - - -// Returns the current process id. -Utility::pid_t Utility::getpid( void ) -{ - return GetCurrentProcessId(); -} - - -// Returns a monotonic clock -int Utility::gettimeofday( struct timeval *tv, void *tz ) -{ - if ( tv == NULL ) - return -1; - - DWORD ticks = timeGetTime(); - tv->tv_sec = 86400 + static_cast< long >( ticks / 1000 ); - tv->tv_usec = static_cast< long >( ticks % 1000 ); - - return 0; -} - - -// Converts an address from dot and numbers format to binary data. -int Utility::inet_aton( const char *cp, struct in_addr *inp ) -{ - if ( cp == NULL ) - return 0; - - if (( inp->s_addr = inet_addr( cp )) == -1 ) - return 0; - - return 1; -} - - -// The inet_ntop() function converts an address from network format (usually a struct in_addr or some other binary form, in network byte order) to presentation format. -const char *Utility::inet_ntop( int af, const char *src, char *dst, size_t size ) -{ - if ( af == AF_INET ) - return inet_ntop4( src, dst, size ); - else if ( af == AF_INET6 ) - return inet_ntop6( src, dst, size ); - - return NULL; -} - - -// Converts an address from presentation format to network format. -int Utility::inet_pton( int af, const char *src, void *dst ) -{ - if ( af == AF_INET ) - return inet_pton4( src, dst ); - else if ( af == AF_INET6 ) - return inet_pton6( src, dst ); - - // TODO: Implement this. - return 0; -} - - -// Converts an ipv4 address from www.xxx.yyy.zzz format to binary data. -int Utility::inet_pton4( const char *src, void *dst ) -{ - struct in_addr tmp; - - if ( inet_aton( src, &tmp ) == -1 ) - return 0; - - memcpy( dst, &tmp, sizeof( struct in_addr )); - - return 1; -} - - -const char *Utility::inet_ntop4( const char *src, char *dst, size_t size ) -{ - char *temp = inet_ntoa( *( reinterpret_cast< const struct in_addr * >( src ))); - - if ( temp == NULL ) - return NULL; - - memcpy( dst, temp, size ); - - return reinterpret_cast< const char * >( dst ); -} - -#define NS_IN6ADDRSZ 16 -#define NS_INT16SZ 2 -#define NS_INADDRSZ 4 - -const char * -Utility::inet_ntop6( const char *src, char *dst, size_t size ) -{ - /* - * Note that int32_t and int16_t need only be "at least" large enough - * to contain a value of the specified size. On some systems, like - * Crays, there is no such thing as an integer variable with 16 bits. - * Keep this in mind if you think this function should have been coded - * to use pointer overlays. All the world's not a VAX. - */ - char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; - struct { int base, len; } best, cur; - uint16_t words[NS_IN6ADDRSZ / NS_INT16SZ]; - int i; - - /* - * Preprocess: - * Copy the input (bytewise) array into a wordwise array. - * Find the longest run of 0x00's in src[] for :: shorthanding. - */ - memset(words, '\0', sizeof words); - for (i = 0; i < NS_IN6ADDRSZ; i++) - words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); - best.base = -1; - cur.base = -1; - for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { - if (words[i] == 0) { - if (cur.base == -1) - cur.base = i, cur.len = 1; - else - cur.len++; - } else { - if (cur.base != -1) { - if (best.base == -1 || cur.len > best.len) - best = cur; - cur.base = -1; - } - } - } - if (cur.base != -1) { - if (best.base == -1 || cur.len > best.len) - best = cur; - } - if (best.base != -1 && best.len < 2) - best.base = -1; - - /* - * Format the result. - */ - tp = tmp; - for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { - /* Are we inside the best run of 0x00's? */ - if (best.base != -1 && i >= best.base && - i < (best.base + best.len)) { - if (i == best.base) - *tp++ = ':'; - continue; - } - /* Are we following an initial run of 0x00s or any real hex? */ - if (i != 0) - *tp++ = ':'; - /* Is this address an encapsulated IPv4? */ - if (i == 6 && best.base == 0 && (best.len == 6 || - (best.len == 7 && words[7] != 0x0001) || - (best.len == 5 && words[5] == 0xffff))) { - if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp))) - return (NULL); - tp += strlen(tp); - break; - } - tp += sprintf(tp, "%x", words[i]); - } - /* Was it a trailing run of 0x00's? */ - if (best.base != -1 && (best.base + best.len) == - (NS_IN6ADDRSZ / NS_INT16SZ)) - *tp++ = ':'; - *tp++ = '\0'; - - /* - * Check for overflow, copy, and we're done. - */ - if ((size_t)(tp - tmp) > size) { - // errno = ENOSPC; - return (NULL); - } - strcpy(dst, tmp); - return (dst); -} - - - -/* int - * inet_pton6(src, dst) - * convert presentation level address to network order binary form. - * return: - * 1 if `src' is a valid [RFC1884 2.2] address, else 0. - * notice: - * (1) does not touch `dst' unless it's returning 1. - * (2) :: in a full address is silently ignored. - * credit: - * inspired by Mark Andrews. - * author: - * Paul Vixie, 1996. - */ -int -Utility::inet_pton6( const char *src, void *dst ) -{ - static const char xdigits_l[] = "0123456789abcdef", - xdigits_u[] = "0123456789ABCDEF"; - u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; - const char *xdigits, *curtok; - int ch, saw_xdigit; - u_int val; - - memset((tp = tmp), '\0', NS_IN6ADDRSZ); - endp = tp + NS_IN6ADDRSZ; - colonp = NULL; - /* Leading :: requires some special handling. */ - if (*src == ':') - if (*++src != ':') - return (0); - curtok = src; - saw_xdigit = 0; - val = 0; - while ((ch = *src++) != '\0') { - const char *pch; - - if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) - pch = strchr((xdigits = xdigits_u), ch); - if (pch != NULL) { - val <<= 4; - val |= (pch - xdigits); - if (val > 0xffff) - return (0); - saw_xdigit = 1; - continue; - } - if (ch == ':') { - curtok = src; - if (!saw_xdigit) { - if (colonp) - return (0); - colonp = tp; - continue; - } else if (*src == '\0') { - return (0); - } - if (tp + NS_INT16SZ > endp) - return (0); - *tp++ = (u_char) (val >> 8) & 0xff; - *tp++ = (u_char) val & 0xff; - saw_xdigit = 0; - val = 0; - continue; - } - if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && - inet_pton4(curtok, tp) > 0) { - tp += NS_INADDRSZ; - saw_xdigit = 0; - break; /* '\0' was seen by inet_pton4(). */ - } - return (0); - } - if (saw_xdigit) { - if (tp + NS_INT16SZ > endp) - return (0); - *tp++ = (u_char) (val >> 8) & 0xff; - *tp++ = (u_char) val & 0xff; - } - if (colonp != NULL) { - /* - * Since some memmove()'s erroneously fail to handle - * overlapping regions, we'll do the shift by hand. - */ - const int n = tp - colonp; - int i; - - if (tp == endp) - return (0); - for (i = 1; i <= n; i++) { - endp[- i] = colonp[n - i]; - colonp[n - i] = 0; - } - tp = endp; - } - if (tp != endp) - return (0); - memcpy(dst, tmp, NS_IN6ADDRSZ); - return (1); -} -#undef NS_IN6ADDRSZ -#undef NS_INT16SZ -#undef NS_INADDRSZ - - -// Returns a random number. -long int Utility::random( void ) -{ - return rand(); -} - - -// Retrieves a gid using a groupname. -int Utility::makeGidNumeric( const std::string & group ) -{ - return 0; -} - - -// Retrieves an uid using a username. -int Utility::makeUidNumeric( const std::string & username ) -{ - return 0; -} - - -// Sets the socket into blocking mode. -bool Utility::setBlocking( Utility::sock_t socket ) -{ - unsigned long tmp = 0; - - if ( ioctlsocket( socket, FIONBIO, &tmp ) == SOCKET_ERROR ) - return false; - - return true; -} - - -// Sets the socket into non-blocking mode. -bool Utility::setNonBlocking( Utility::sock_t socket ) -{ - unsigned long tmp = 1; - - if( ioctlsocket( socket, FIONBIO, &tmp ) == SOCKET_ERROR ) - return false; - - return true; -} - -// Marks the socket to be closed on exec(). -// No-op on Windows. -bool Utility::setCloseOnExec(sock_t sock) -{ - return true; -} - -// Sleeps for a number of seconds. -unsigned int Utility::sleep( unsigned int seconds ) -{ - Sleep( seconds * 1000 ); - return 0; -} - - -// Sets the random seed. -void Utility::srandom( unsigned int seed ) -{ - srand( seed ); -} - - -// Sleeps for a number of microseconds. -void Utility::usleep( unsigned long usec ) -{ - Sleep( usec / 1000 ); -} - - -// Writes a vector. -int Utility::writev( Utility::sock_t socket, const Utility::iovec *vector, size_t count ) -{ - unsigned int i; - int res; - int nbytes = 0; - - for ( i = 0; i < count; i++ ) - { - res = send( socket, reinterpret_cast< const char * >( vector[ i ].iov_base ), vector[ i ].iov_len, 0 ); - if ( res == -1 ) - return -1; - - nbytes += res; - } - - return nbytes; -} - diff --git a/pdns/ws.hh b/pdns/ws.hh index 2113e1ab3..68599b365 100644 --- a/pdns/ws.hh +++ b/pdns/ws.hh @@ -24,10 +24,7 @@ #include #include #include - -#ifndef WIN32 -# include -#endif // WIN32 +#include #ifdef HAVE_CONFIG_H # include