+++ /dev/null
-# 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 '<boost/something.hpp>', 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 $@
-
+++ /dev/null
-\r
-Microsoft Visual Studio Solution File, Format Version 9.00\r
-# Visual C++ Express 2005\r
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PowerDNS Recursor", "PowerDNS Recursor.vcproj", "{E43D2E84-6056-49C6-9DA1-7044BA08E87A}"\r
-EndProject\r
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Eventlogger", "Eventlogger\Eventlogger.vcproj", "{36E5DAC2-6761-4692-BC72-7B5DE6B57628}"\r
-EndProject\r
-Global\r
- GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
- Debug|Win32 = Debug|Win32\r
- Release|Win32 = Release|Win32\r
- EndGlobalSection\r
- GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
- {E43D2E84-6056-49C6-9DA1-7044BA08E87A}.Debug|Win32.ActiveCfg = Debug|Win32\r
- {E43D2E84-6056-49C6-9DA1-7044BA08E87A}.Debug|Win32.Build.0 = Debug|Win32\r
- {E43D2E84-6056-49C6-9DA1-7044BA08E87A}.Release|Win32.ActiveCfg = Release|Win32\r
- {E43D2E84-6056-49C6-9DA1-7044BA08E87A}.Release|Win32.Build.0 = Release|Win32\r
- {36E5DAC2-6761-4692-BC72-7B5DE6B57628}.Debug|Win32.ActiveCfg = Debug|Win32\r
- {36E5DAC2-6761-4692-BC72-7B5DE6B57628}.Debug|Win32.Build.0 = Debug|Win32\r
- {36E5DAC2-6761-4692-BC72-7B5DE6B57628}.Release|Win32.ActiveCfg = Release|Win32\r
- {36E5DAC2-6761-4692-BC72-7B5DE6B57628}.Release|Win32.Build.0 = Release|Win32\r
- EndGlobalSection\r
- GlobalSection(SolutionProperties) = preSolution\r
- HideSolutionNode = FALSE\r
- EndGlobalSection\r
-EndGlobal\r
+++ /dev/null
-<?xml version="1.0" encoding="Windows-1252"?>\r
-<VisualStudioProject\r
- ProjectType="Visual C++"\r
- Version="8,00"\r
- Name="PowerDNS Recursor"\r
- ProjectGUID="{E43D2E84-6056-49C6-9DA1-7044BA08E87A}"\r
- RootNamespace="PowerDNS Recursor"\r
- Keyword="Win32Proj"\r
- >\r
- <Platforms>\r
- <Platform\r
- Name="Win32"\r
- />\r
- </Platforms>\r
- <ToolFiles>\r
- </ToolFiles>\r
- <Configurations>\r
- <Configuration\r
- Name="Debug|Win32"\r
- OutputDirectory="Debug"\r
- IntermediateDirectory="Debug"\r
- ConfigurationType="1"\r
- >\r
- <Tool\r
- Name="VCPreBuildEventTool"\r
- />\r
- <Tool\r
- Name="VCCustomBuildTool"\r
- />\r
- <Tool\r
- Name="VCXMLDataGeneratorTool"\r
- />\r
- <Tool\r
- Name="VCWebServiceProxyGeneratorTool"\r
- />\r
- <Tool\r
- Name="VCMIDLTool"\r
- />\r
- <Tool\r
- Name="VCCLCompilerTool"\r
- Optimization="0"\r
- AdditionalIncludeDirectories=""$(SolutionDir)\Eventlogger\";"C:\Documents and Settings\ahu\Mijn documenten\boost_1_33_1""\r
- PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;"\r
- MinimalRebuild="true"\r
- BasicRuntimeChecks="3"\r
- RuntimeLibrary="3"\r
- UsePrecompiledHeader="0"\r
- WarningLevel="3"\r
- Detect64BitPortabilityProblems="true"\r
- DebugInformationFormat="4"\r
- />\r
- <Tool\r
- Name="VCManagedResourceCompilerTool"\r
- />\r
- <Tool\r
- Name="VCResourceCompilerTool"\r
- />\r
- <Tool\r
- Name="VCPreLinkEventTool"\r
- />\r
- <Tool\r
- Name="VCLinkerTool"\r
- AdditionalDependencies="winmm.lib wsock32.lib ws2_32.lib"\r
- LinkIncremental="2"\r
- GenerateDebugInformation="true"\r
- SubSystem="1"\r
- TargetMachine="1"\r
- />\r
- <Tool\r
- Name="VCALinkTool"\r
- />\r
- <Tool\r
- Name="VCManifestTool"\r
- />\r
- <Tool\r
- Name="VCXDCMakeTool"\r
- />\r
- <Tool\r
- Name="VCBscMakeTool"\r
- />\r
- <Tool\r
- Name="VCFxCopTool"\r
- />\r
- <Tool\r
- Name="VCAppVerifierTool"\r
- />\r
- <Tool\r
- Name="VCWebDeploymentTool"\r
- />\r
- <Tool\r
- Name="VCPostBuildEventTool"\r
- />\r
- </Configuration>\r
- <Configuration\r
- Name="Release|Win32"\r
- OutputDirectory="Release"\r
- IntermediateDirectory="Release"\r
- ConfigurationType="1"\r
- >\r
- <Tool\r
- Name="VCPreBuildEventTool"\r
- />\r
- <Tool\r
- Name="VCCustomBuildTool"\r
- />\r
- <Tool\r
- Name="VCXMLDataGeneratorTool"\r
- />\r
- <Tool\r
- Name="VCWebServiceProxyGeneratorTool"\r
- />\r
- <Tool\r
- Name="VCMIDLTool"\r
- />\r
- <Tool\r
- Name="VCCLCompilerTool"\r
- AdditionalIncludeDirectories=""$(SolutionDir)\Eventlogger\";"C:\Documents and Settings\ahu\Mijn documenten\boost_1_33_1""\r
- PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;"\r
- RuntimeLibrary="2"\r
- UsePrecompiledHeader="0"\r
- WarningLevel="3"\r
- Detect64BitPortabilityProblems="true"\r
- DebugInformationFormat="3"\r
- />\r
- <Tool\r
- Name="VCManagedResourceCompilerTool"\r
- />\r
- <Tool\r
- Name="VCResourceCompilerTool"\r
- />\r
- <Tool\r
- Name="VCPreLinkEventTool"\r
- />\r
- <Tool\r
- Name="VCLinkerTool"\r
- AdditionalDependencies="winmm.lib wsock32.lib ws2_32.lib"\r
- LinkIncremental="2"\r
- GenerateDebugInformation="true"\r
- SubSystem="1"\r
- OptimizeReferences="2"\r
- EnableCOMDATFolding="2"\r
- TargetMachine="1"\r
- />\r
- <Tool\r
- Name="VCALinkTool"\r
- />\r
- <Tool\r
- Name="VCManifestTool"\r
- />\r
- <Tool\r
- Name="VCXDCMakeTool"\r
- />\r
- <Tool\r
- Name="VCBscMakeTool"\r
- />\r
- <Tool\r
- Name="VCFxCopTool"\r
- />\r
- <Tool\r
- Name="VCAppVerifierTool"\r
- />\r
- <Tool\r
- Name="VCWebDeploymentTool"\r
- />\r
- <Tool\r
- Name="VCPostBuildEventTool"\r
- />\r
- </Configuration>\r
- </Configurations>\r
- <References>\r
- </References>\r
- <Files>\r
- <Filter\r
- Name="Header Files"\r
- Filter="h;hpp;hxx;hm;inl;inc;xsd"\r
- UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"\r
- >\r
- <File\r
- RelativePath=".\config.h"\r
- >\r
- </File>\r
- </Filter>\r
- <Filter\r
- Name="Resource Files"\r
- Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"\r
- UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"\r
- >\r
- </Filter>\r
- <Filter\r
- Name="Source Files"\r
- Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"\r
- UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"\r
- >\r
- <File\r
- RelativePath=".\arguments.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\base64.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\config.h"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\dnsparser.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\dnsrecords.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\dnswriter.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\lwres.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\misc.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\ntservice.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\ntservice.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\pdns_recursor.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\qtype.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\rcpgenerator.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\rec_channel_rec.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\recursor_cache.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\recursorservice.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\recursorservice.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\selectmplexer.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\syncres.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\win32_logger.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\win32_rec_channel.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\win32_utility.cc"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\zoneparser-tng.cc"\r
- >\r
- </File>\r
- </Filter>\r
- <File\r
- RelativePath=".\ahuexception.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\arguments.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\base64.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\dns.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\dnsparser.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\dnsrecords.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\dnswriter.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\iputils.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\lock.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\logger.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\lwres.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\misc.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\mplexer.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\qtype.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\rcpgenerator.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\rec_channel.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\recursor_cache.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\sstuff.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\syncres.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\utility.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\win32_mtasker.hh"\r
- >\r
- </File>\r
- <File\r
- RelativePath=".\zoneparser-tng.hh"\r
- >\r
- </File>\r
- </Files>\r
- <Globals>\r
- </Globals>\r
-</VisualStudioProject>\r
return params[arg];
}
-#ifndef WIN32
mode_t ArgvMap::asMode(const string &arg)
{
mode_t mode;
}
return uid;
}
-#endif
int ArgvMap::asNum(const string &arg)
{
#include <iostream>
#include "misc.hh"
#include "pdnsexception.hh"
-#ifndef WIN32
-# include <sys/types.h>
-# include <pwd.h>
-# include <grp.h>
-#endif
+#include <sys/types.h>
+#include <pwd.h>
+#include <grp.h>
#include "namespaces.hh"
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); //<!< return value interpreted as octal number
uid_t asUid(const string &var); //!< return user id, resolves if necessary
gid_t asGid(const string &var); //!< return group id, resolves if necessary
-#endif
double asDouble(const string &var); //!< return a variable value as a number
string &set(const string &); //!< Gives a writable reference and allocates space for it
string &set(const string &, const string &); //!< Does the same but also allows one to specify a help message
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
-// $Id$
-#ifdef WIN32
-# pragma warning ( disable: 4786 )
-#endif // WIN32
-
#include <string>
#include <map>
#ifndef SSQL_HH
#define SSQL_HH
-#ifdef WIN32
-# pragma warning ( disable: 4786 )
-#endif // WIN32
-
#include <string>
#include <vector>
#include "../../namespaces.hh"
DNSPacket::s_ednssubnetcodes.push_back(boost::lexical_cast<int>(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
else
L<<Logger::Error<<"Chrooted to '"<<::arg()["chroot"]<<"'"<<endl;
}
-#endif
StatWebServer sws;
Utility::dropPrivs(newuid, newgid);
void CommunicatorClass::mainloop(void)
{
try {
-#ifndef WIN32
signal(SIGPIPE,SIG_IGN);
-#endif // WIN32
L<<Logger::Error<<"Master/slave communicator launching"<<endl;
PacketHandler P;
d_tickinterval=::arg().asNum("slave-cycle-interval");
#include <boost/multi_index/sequenced_index.hpp>
using namespace boost::multi_index;
-#ifndef WIN32
-# include <unistd.h>
-# include <fcntl.h>
-# include <netdb.h>
-#endif // WIN32
+#include <unistd.h>
+#include <fcntl.h>
+#include <netdb.h>
#include "lock.hh"
#include "packethandler.hh"
#ifndef DISTRIBUTOR_HH
#define DISTRIBUTOR_HH
-
#include <string>
#include <deque>
#include <queue>
#include <vector>
#include <pthread.h>
#include <semaphore.h>
-
-#ifndef WIN32
-# include <unistd.h>
-#endif // WIN32
-
+#include <unistd.h>
#include "logger.hh"
#include "dns.hh"
#include "dnsbackend.hh"
}
};
-#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;
uint8_t extRCode, version;
uint16_t Z;
} GCCPACKATTRIBUTE;
-#ifdef _MSC_VER
-#pragma pack (pop)
-#endif
enum {
ns_t_invalid = 0, /* Cookie. */
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 <machine/endian.h>
#elif __linux__
# include <endian.h>
void BackendMakerClass::load_all()
{
// TODO: Implement this?
-#ifndef WIN32
DIR *dir=opendir(arg()["module-dir"].c_str());
if(!dir) {
L<<Logger::Error<<"Unable to open module directory '"<<arg()["module-dir"]<<"'"<<endl;
load(entry->d_name);
}
closedir(dir);
-#endif // WIN32
}
void BackendMakerClass::load(const string &module)
#include "pdnsexception.hh"
#include <set>
#include <iostream>
-
-#ifndef WIN32
-# include <sys/socket.h>
-# include <dirent.h>
-#endif // WIN32
-
+#include <sys/socket.h>
+#include <dirent.h>
#include "misc.hh"
#include "qtype.hh"
#include "dns.hh"
#include "iputils.hh"
#include "ednssubnet.hh"
-#ifndef WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <unistd.h>
#include <arpa/inet.h>
-#endif // WIN32
-
#include <iostream>
#include <string>
#include <vector>
#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;
#define PDNS_DNSPROXY
#include <pthread.h>
#include <map>
-
-#ifndef WIN32
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <arpa/inet.h>
-#endif // WIN32
-
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
#include "dnspacket.hh"
#include "lock.hh"
#include "iputils.hh"
#include <string>
#include <vector>
#include <map>
-#if !defined SOLARIS8 && !defined WIN32
-
-#elif defined WIN32
-#include "utility.hh"
-#endif
#include "dns.hh"
#include "namespaces.hh"
string DLRQuitHandler(const vector<string>&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";
}
#include <stdlib.h>
#include <sys/types.h>
-#ifndef WIN32
-# include "config.h"
-# include <unistd.h>
-#else
-# include "pdnsservice.hh"
-#endif // WIN32
+#include "config.h"
+#include <unistd.h>
#include "namespaces.hh"
#include <sstream>
#include "iputils.hh"
#include <boost/utility.hpp>
-#ifndef WIN32
#include <unistd.h>
#include <sys/un.h>
#include <dlfcn.h>
-
#include <sys/socket.h>
#include <netinet/in.h>
-#endif // WIN32
#include "namespaces.hh"
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;
#include <string>
#include <sys/types.h>
-
-#ifndef WIN32
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <sys/un.h>
-# include <unistd.h>
-# include <libgen.h>
-
-#else
-# include "pdnsservice.hh"
-
-#endif // WIN32
-
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <sys/un.h>
+#include <unistd.h>
+#include <libgen.h>
#include <errno.h>
#include "iputils.hh"
#include "pdnsexception.hh"
{
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:
#define PDNS_IPUTILSHH
#include <string>
-
-#ifndef WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
-#endif // WIN32
-
#include <iostream>
#include <stdio.h>
#include <functional>
#include <iostream>
#include <sstream>
#include "config.h"
-#ifndef WIN32
-# include <syslog.h>
+#include <syslog.h>
#include <pthread.h>
-#else
-# define WINDOWS_LEAN_AND_MEAN
-# include <windows.h>
-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
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:
map<pthread_t,string>d_strings;
#include <sys/types.h>
#include "misc.hh"
#include "iputils.hh"
-#ifndef WIN32
-# include <netdb.h>
-# include <unistd.h>
-# include <sys/time.h>
-# include <sys/uio.h>
-# include <fcntl.h>
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <arpa/inet.h>
-# undef res_mkquery
-#endif // WIN32
+#include <netdb.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <sys/uio.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#undef res_mkquery
#include "pdnsexception.hh"
#include "dns.hh"
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
-#ifndef WIN32
#include <sys/param.h>
#include <netdb.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <unistd.h>
-#endif // WIN32
-
#include "misc.hh"
#include <vector>
#include <sstream>
string getHostname()
{
-#ifdef WIN32
-# define MAXHOSTNAMELEN 1025
-#endif // WIN32
#ifndef MAXHOSTNAMELEN
-# define MAXHOSTNAMELEN 255
+#define MAXHOSTNAMELEN 255
#endif
char tmp[MAXHOSTNAMELEN];
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)
{
#include "utility.hh"
#include "dns.hh"
-#ifndef WIN32
-# include <sys/time.h>
-# include <sys/types.h>
-# include <sys/socket.h>
-# include <time.h>
-# include <syslog.h>
-#else
-# define WINDOWS_LEAN_AND_MEAN
-# include <windows.h>
-# include "utility.hh"
-#endif // WIN32
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <syslog.h>
#include <deque>
#include <stdexcept>
#include <string>
#ifndef MTASKER_HH
#define MTASKER_HH
-#ifdef WIN32
-# include "win32_mtasker.hh"
-#else
-
#include <signal.h>
#include <ucontext.h>
#include <queue>
-#include <vector>
+#include <vector>
#include <map>
#include <time.h>
#include <boost/multi_index_container.hpp>
};
#include "mtasker.cc"
-#endif // WIN32
#endif // MTASKER_HH
void UDPNameserver::bindIPv6()
{
-#if !WIN32 && HAVE_IPV6
+#if HAVE_IPV6
vector<string> locals;
stringtok(locals,::arg()["local-ipv6"]," ,");
L<<Logger::Error<<"UDPv6 server bound to "<<locala.toStringWithPort()<<endl;
}
-#endif // WIN32
+#endif
}
UDPNameserver::UDPNameserver()
#ifndef NAMESERVER_HH
#define NAMESERVER_HH
-#ifndef WIN32
-# include <poll.h>
-# include <sys/types.h>
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <sys/time.h>
-# include <unistd.h>
-# include <arpa/inet.h>
-# include <netdb.h>
-
-#endif // WIN32
-
+#include <poll.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <sys/time.h>
+#include <unistd.h>
+#include <arpa/inet.h>
+#include <netdb.h>
#include <vector>
#include <boost/foreach.hpp>
#include "statbag.hh"
+++ /dev/null
-/*
- 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 <sstream>
-#include <iostream>
-#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\\<servicename>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;
-}
+++ /dev/null
-/*
- 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 <string>
-#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
-
#ifndef PACKETHANDLER_HH
#define PACKETHANDLER_HH
-#ifndef WIN32
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <arpa/inet.h>
-#endif // WIN32
-
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
#include "ueberbackend.hh"
#include "dnspacket.hh"
#include "packetcache.hh"
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
-#ifndef WIN32
-# include <netdb.h>
-# include <sys/stat.h>
-# include <unistd.h>
-#else
- #include "ntservice.hh"
- #include "recursorservice.hh"
-#endif // WIN32
-
+#include <netdb.h>
+#include <sys/stat.h>
+#include <unistd.h>
#include <boost/foreach.hpp>
#include "json_ws.hh"
#include <pthread.h>
sockname+=".controlsocket";
s_rcc.listen(sockname);
-#ifndef WIN32
int sockowner = -1;
int sockgroup = -1;
mode_t sockmode=::arg().asMode("socket-mode");
chmod(sockname.c_str(), sockmode);
}
-#endif
}
void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
}
-#ifndef WIN32
void daemonize(void)
{
if(fork())
close(i);
}
}
-#endif
uint64_t counter;
bool statsWanted;
if(!s_pidfname.empty())
unlink(s_pidfname.c_str()); // remove possible old pid file
-#ifndef WIN32
if(::arg().mustDo("daemon")) {
L<<Logger::Warning<<"Calling daemonize, going to background"<<endl;
L.toConsole(Logger::Critical);
signal(SIGUSR2,usr2Handler);
signal(SIGPIPE,SIG_IGN);
writePid();
-#endif
makeControlChannelSocket( ::arg().asNum("processes") > 1 ? forks : -1);
int newgid=0;
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)
{
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";
::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")="";
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<<Logger::Error<<"Exception: "<<ae.reason<<endl;
ret=EXIT_FAILURE;
}
-#ifdef WIN32
- WSACleanup();
-#endif // WIN32
-
return ret;
}
+++ /dev/null
-/*
- 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
-*/
-
-#define WINDOWS_LEAN_AND_MEAN
-#include <windows.h>
-
-
-// Message dll used for logging.
-BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
-{
- return TRUE;
-}
+++ /dev/null
-
-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
-.
-
-
-
-
+++ /dev/null
-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>
-{{{
-}}}
-
-###############################################################################
-
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,
#include <inttypes.h>
#include <string>
#include <stdexcept>
-#if !defined SOLARIS8 && !defined WIN32
-
-#elif defined WIN32
-# include "utility.hh"
-#endif
#include "namespaces.hh"
#include <string>
#include <map>
#include <inttypes.h>
-#if !defined SOLARIS8 && !defined WIN32
-
-#elif defined WIN32
-#include "utility.hh"
-#endif
-
-#ifndef WIN32
#include <sys/un.h>
-#else
-// ?
-struct sockaddr_un {};
-#endif
+
/** this class is used both to send and answer channel commands to the PowerDNS Recursor */
class RecursorControlChannel
#include "logger.hh"
#include "dnsparser.hh"
#include "arguments.hh"
-#ifndef WIN32
#include <sys/resource.h>
#include <sys/time.h>
-#endif
#include "namespaces.hh"
-#include "namespaces.hh"
+
map<string, const uint32_t*> d_get32bitpointers;
map<string, const uint64_t*> d_get64bitpointers;
map<string, function< uint32_t() > > d_get32bitmembers;
return "wiped "+lexical_cast<string>(count)+" records, "+lexical_cast<string>(countNeg)+" negative records\n";
}
-#ifndef WIN32
static uint64_t getSysTimeMsec()
{
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000);
}
-#endif
static uint64_t calculateUptime()
{
addGetStat("uptime", calculateUptime);
-#ifndef WIN32
// addGetStat("query-rate", getQueryRate);
addGetStat("user-msec", getUserTimeMsec);
addGetStat("sys-msec", getSysTimeMsec);
-#endif
}
static void doExitGeneric(bool nicely)
#include <vector>
#include <sys/types.h>
#include "iputils.hh"
-#ifndef WIN32
-# include <netdb.h>
-# include <unistd.h>
-# include <sys/time.h>
-# include <sys/uio.h>
-# include <fcntl.h>
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <arpa/inet.h>
-# undef res_mkquery
-#endif // WIN32
+#include <netdb.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <sys/uio.h>
+#include <fcntl.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#undef res_mkquery
#include "pdnsexception.hh"
#include "dns.hh"
#include <string>
#include <cerrno>
-#ifndef WIN32
-# include <sys/stat.h>
-# include <netdb.h>
-# include <unistd.h>
-# include <sys/time.h>
-# include <sys/socket.h>
-# include <arpa/inet.h>
-# include <netinet/in.h>
-# include <sys/types.h>
-# include <strings.h>
+#include <sys/stat.h>
+#include <netdb.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <sys/types.h>
+#include <strings.h>
-#endif // WIN32
#include "iputils.hh"
#include "pdnsexception.hh"
+++ /dev/null
-/*
- 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 <windows.h>
-
-
-//! A common singleton template class.
-template <class _Ty>
-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 <class _Ty>
-_Ty *Singleton< _Ty >::m_pInstance = NULL;
-
-template <class _Ty>
-long Singleton< _Ty >::m_refCount = 0;
-
-
-#endif // SINGLETON_HH
#include <fstream>
#include "pdns/logger.hh"
#include "misc.hh"
-
-#ifdef WIN32
-# include <io.h>
-# define access _access
-# define F_OK 0
-#else // WIN32
-# include <unistd.h>
-#endif // Unix
+#include <unistd.h>
// Constructor.
SSQLite3::SSQLite3( const std::string & database, bool creat )
#include "iputils.hh"
#include <errno.h>
#include <sys/types.h>
-#ifndef WIN32
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
-#endif
#include <fcntl.h>
#include <stdexcept>
#include <boost/shared_ptr.hpp>
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)
d_ng.addMask( *i );
}
-#ifndef WIN32
signal(SIGPIPE,SIG_IGN);
-#endif // WIN32
for(vector<string>::const_iterator laddr=locals.begin();laddr!=locals.end();++laddr) {
int s=socket(AF_INET,SOCK_STREAM,0);
d_prfds.push_back(pfd);
}
-#if !WIN32 && HAVE_IPV6
+#if HAVE_IPV6
for(vector<string>::const_iterator laddr=locals6.begin();laddr!=locals6.end();++laddr) {
int s=socket(AF_INET6,SOCK_STREAM,0);
d_prfds.push_back(pfd);
}
-#endif // WIN32
+#endif
}
#include <vector>
#include <boost/shared_ptr.hpp>
#include <poll.h>
-
-#ifndef WIN32
-# include <sys/select.h>
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <arpa/inet.h>
-# include <sys/stat.h>
-# include <unistd.h>
-# include <netdb.h>
-# include <sys/uio.h>
-# include <sys/select.h>
-#endif // WIN32
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <netdb.h>
+#include <sys/uio.h>
+#include <sys/select.h>
#include "namespaces.hh"
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) {
L << Logger::Warning << "This version doesn't support dynamic loading (yet)." << endl;
return false;
-#endif // WIN32
-
+#endif
}
void UeberBackend::go(void)
#include <pthread.h>
#include <semaphore.h>
-#ifndef WIN32
#include <sys/un.h>
#include <dlfcn.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
-#endif // WIN32
#include <boost/utility.hpp>
#include "dnspacket.hh"
#include "dnsbackend.hh"
#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;
typedef unsigned long long uint64_t;
#endif
-
-#ifndef WIN32
-# include <arpa/inet.h>
-# include <netinet/in.h>
-# include <sys/socket.h>
-# include <sys/time.h>
-# include <sys/uio.h>
-# include <signal.h>
-# include <pthread.h>
-# include <semaphore.h>
-# include <signal.h>
-# include <errno.h>
-# include <unistd.h>
-#else
-typedef int socklen_t;
-#define _WIN32_WINNT 0x0400
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#include <io.h>
-# define WINDOWS_LEAN_AND_MEAN
-# include <windows.h>
-# include <signal.h>
-# include <map>
-
-#ifndef ETIMEDOUT
-# define ETIMEDOUT WSAETIMEDOUT
-#endif // ETIMEDOUT
-
-# define EINPROGRESS WSAEWOULDBLOCK
-
-# define snprintf _snprintf
-#endif // WIN32
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <sys/uio.h>
+#include <signal.h>
+#include <pthread.h>
+#include <semaphore.h>
+#include <signal.h>
+#include <errno.h>
+#include <unistd.h>
#include <string>
#include "namespaces.hh"
{
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__
sem_value_t m_count;
uint32_t m_nwaiters;
#endif // DARWIN || _AIX || __APPLE__
-#endif // WIN32
protected:
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 );
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
+++ /dev/null
-/*
- 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 <string>
-#include <map>
-#include <sys/types.h>
-#include <pthread.h>
-
-#include <errno.h>
-#include <iostream>
-#include <sstream>
-#include <sys/types.h>
-#include <signal.h>
-
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <boost/algorithm/string.hpp>
-#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<<Logger::Warning<<"Listening on named pipe." << endl;
- d_udp=true;
- }
- else
- d_udp=false;
-
-
-}
-
-void DynListener::go()
-{
- d_ppid=Utility::getpid();
- pthread_create(&d_tid,0,&DynListener::theListenerHelper,this);
-}
-
-void *DynListener::theListenerHelper(void *p)
-{
- DynListener *us=static_cast<DynListener *>(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<string,string> parameters;
-
- for(;;) {
- string line=getLine();
- boost::trim_right(line);
-
- vector<string>parts;
- 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<<Logger::Error<<"Fatal: "<<AE.reason<<endl;
- }
- catch(string &E)
- {
- L<<Logger::Error<<"Fatal: "<<E<<endl;
- }
- catch( ... )
- {
- L<<Logger::Error<<"Fatal: unknown exception occured"<<endl;
- }
-}
-
-
+++ /dev/null
-/*
- 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 <iostream>
-#include <cstdio>
-#include <cstring>
-#include <cstdlib>
-#include <unistd.h>
-#include <errno.h>
-#include <climits>
-#include <string>
-#include <map>
-#include <sys/types.h>
-
-#include <sys/stat.h>
-#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<string>&commands=arg().getCommands();
-
- if(commands.empty()) {
- cerr<<"No command passed"<<endl;
- return 0;
- }
-
- try {
- string command=commands[0];
-
- DynMessenger D( "", s_programname );
-
- string message;
- for(vector<string>::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<commands.size();n++) {
- message+=commands[n];
- message+=" ";
- }
- }
- else if(command=="list") {
- message="SHOW *";
- command="show";
- }
- else if(command=="quit" || command=="QUIT") {
- message="QUIT";
- }
- else if(command=="status" || command=="STATUS") {
- message="STATUS";
- }
- else if(command=="version" || command=="VERSION") {
- message="VERSION";
- }
-
-
- if(D.send(message)<0) {
- cerr<<"Error sending command"<<endl;
- return 1;
- }
-
- string resp=D.receive();
-
- cout<<resp<<endl;
- }
- catch(PDNSException &ae) {
- cerr<<"Fatal error: "<<ae.reason<<endl;
- return 1;
- }
- return 0;
-}
-
-
-
+++ /dev/null
-/*
- 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 "dynmessenger.hh"
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-#include <iostream>
-#include <sys/types.h>
-
-
-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;
-}
-
-
+++ /dev/null
-/*
- 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<<" " <<msg << endl;
- return;
-}
-
-void Logger::toConsole(Urgency u)
-{
- consoleUrgency=u;
-}
-
-
-void Logger::toFile( const string & filename )
-{
- m_pLogFile = fopen( filename.c_str(), "at" );
-}
-
-
-void Logger::toNTLog( void )
-{
- m_eventLogHandle = RegisterEventSource( NULL,
- NTService::instance()->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<<i;
-
- *this<<tmp.str();
-
- return *this;
-}
-
-Logger& Logger::operator<<(unsigned int i)
-{
- ostringstream tmp;
- tmp<<i;
-
- *this<<tmp.str();
-
- return *this;
-}
-
-Logger& Logger::operator<<(unsigned long i)
-{
- ostringstream tmp;
- tmp<<i;
-
- *this<<tmp.str();
-
- return *this;
-}
-
-Logger& Logger::operator<<(unsigned long long i)
-{
- ostringstream tmp;
- tmp<<i;
-
- *this<<tmp.str();
-
- return *this;
-}
-
-
-Logger& Logger::operator<<(long i)
-{
- ostringstream tmp;
- tmp<<i;
-
- *this<<tmp.str();
-
- return *this;
-}
-
-
-Logger& Logger::operator<<( ostream & (blah)(ostream &))
-{
- log(d_strings[0], d_outputurgencies[0]);
-
- d_strings.erase(0);
- d_outputurgencies.erase(0);
-
- return *this;
-}
-
+++ /dev/null
-#include "mtasker.hh"
-#include <stdio.h>
-#include <iostream>
-
-
-/** \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 "<<num<<" launched"<<endl;
-
- MT.waitEvent(num);
- cout<<"Key "<<num<<" was pressed!"<<endl;
-}
-
-
-int main()
-{
- char line[10];
-
- for(int i=0;i<10;++i)
- MT.makeThread(menuHandler,(void *)i);
-
- for(;;) {
- while(MT.schedule()); // do everything we can do
- if(MT.noProcesses()) // exit if no processes are left
- break;
-
- if(!fgets(line,sizeof(line),stdin))
- break;
-
- MT.sendEvent(*line-'0');
- }
-}
-\endcode
-
-\section example2 Canonical multitasking example
-This implements the canonical multitasking example, alternately printing an 'A' and a 'B'. The Linux kernel
- started this way too.
-\code
-void printer(void *p)
-{
- char c=(char)p;
- for(;;) {
- cout<<c<<endl;
- MT.yield();
- }
-
-}
-
-int main()
-{
- MT.makeThread(printer,(void*)'a');
- MT.makeThread(printer,(void*)'b');
-
- for(;;) {
- while(MT.schedule()); // do everything we can do
- if(MT.noProcesses()) // exit if no processes are left
- break;
- }
-}
-\endcode
-
-*/
-
-
-//! puts a thread to sleep waiting until a specified event arrives
-/** Threads can call waitEvent to register that they are waiting on an event with a certain key.
- If so desired, the event can carry data which is returned in val in case that is non-zero.
-
- Furthermore, a timeout can be specified in seconds.
-
- Only one thread can be waiting on a key, results of trying to have more threads
- waiting on the same key are undefined.
-
- \param key Event key to wait for. Needs to match up to a key reported to sendEvent
- \param val If non-zero, the value of the event will be stored in *val
- \param timeout If non-zero, number of seconds to wait for an event.
-
- \return returns -1 in case of error, 0 in case of timeout, 1 in case of an answer
-*/
-template<class EventKey, class EventVal>int MTasker<EventKey,EventVal>::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 */
-
-template<class Key, class Val>void MTasker<Key,Val>::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.
-*/
-template<class EventKey, class EventVal>int MTasker<EventKey,EventVal>::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!"<<endl;
- return 0;
- }
-
- d_waitstatus=Answer;
- if(val)
- d_waitval=*val;
-
- LPVOID userspace=waiter->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
-*/
-template<class Key, class Val>void MTasker<Key,Val>::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
-
-*/
-template<class Key, class Val>bool MTasker<Key,Val>::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<KeyTag>::type waiters_by_ttd_index_t;
- // waiters_by_ttd_index_t& ttdindex=d_waiters.template get<KeyTag>();
- waiters_by_ttd_index_t& ttdindex=boost::multi_index::get<KeyTag>(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
- */
-template<class Key, class Val>bool MTasker<Key,Val>::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
- */
-template<class Key, class Val>unsigned int MTasker<Key,Val>::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
-*/
-template<class Key, class Val>void MTasker<Key,Val>::getEvents(std::vector<Key>& 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.
-*/
-template<class Key, class Val>int MTasker<Key,Val>::getTid()
-{
- return d_tid;
-}
-
-
-template<class Key, class Val>
-VOID WINAPI MTasker<Key,Val>::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);
-}
+++ /dev/null
-/*
- 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 <windows.h>
-
-#include <queue>
-#include <vector>
-#include <map>
-#include <time.h>
-#include <boost/multi_index_container.hpp>
-
-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 EventKey=int, class EventVal=int> class MTasker
-{
-public:
- struct Waiter
- {
- LPVOID context;
- time_t ttd;
- int tid;
- EventKey key;
- };
- typedef multi_index_container<
- Waiter,
- indexed_by <
- ordered_unique<member<Waiter,EventKey,&Waiter::key> >,
- ordered_non_unique<tag<KeyTag>, member<Waiter,time_t,&Waiter::ttd> >
- >
- > waiters_t;
-
- waiters_t d_waiters;
-
-private:
- LPVOID d_kernel;
- std::queue<int> d_runQueue;
- std::queue<int> d_zombiesQueue;
-
-
- std::map<int,LPVOID> 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<EventKey>& 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
-
+++ /dev/null
-/*
- 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 <iostream>
-#include <errno.h>
-#include <map>
-#include <set>
-#include <stdio.h>
-#include <signal.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include "mtasker.hh"
-#include <utility>
-#include "dnspacket.hh"
-#include "statbag.hh"
-#include "arguments.hh"
-#include "syncres.hh"
-#include <fcntl.h>
-#include <fstream>
-#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<b.id)
- return true;
-
- if(a.id==b.id) {
- if(a.remote.sin_addr.s_addr < b.remote.sin_addr.s_addr)
- return true;
- if(a.remote.sin_addr.s_addr == b.remote.sin_addr.s_addr)
- if(a.remote.sin_port < b.remote.sin_port)
- return true;
- }
-
- return false;
-}
-
-MTasker<PacketID,string>* 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<string,set<DNSResourceRecord> > cache_t;
-static cache_t cache;
-int cacheHits, cacheMisses;
-int getCache(const string &qname, const QType& qt, set<DNSResourceRecord>* 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<DNSResourceRecord>& content)
-{
-
- // bogus code to generate root with very low ttl
- /*
- if((0 && qname.empty()) || qname.rfind(".root-servers.net")==1) {
- cout<<"qname: '"<<qname<<"'"<<endl;
- set<DNSResourceRecord> changed;
- for(set<DNSResourceRecord>::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<DNSResourceRecord>::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;
-
- set<DNSResourceRecord>nsset;
- 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'];
- set<DNSResourceRecord>aset;
- 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;
-
- vector<DNSResourceRecord>ret;
- DNSPacket *R=P.replyPacket();
- R->setA(false);
- R->setRA(true);
-
- SyncRes sr;
- if(!quiet)
- L<<Logger::Error<<"["<<MT->getTid()<<"] question for '"<<P.qdomain<<"|"<<P.qtype.getName()<<"' from "<<P.getRemote()<<endl;
-
- sr.setId(MT->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<DNSResourceRecord>::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<<Logger::Error<<"Oops, partial answer sent to "<<P.getRemote()<<" - probably would have trouble receiving our answer anyhow (size="<<R->len<<")"<<endl;
- }
-
- if(!quiet) {
- L<<Logger::Error<<"["<<MT->getTid()<<"] answer to "<<(P.d.rd?"":"non-rd ")<<"question '"<<P.qdomain<<"|"<<P.qtype.getName();
- L<<"': "<<ntohs(R->d.ancount)<<" answers, "<<ntohs(R->d.arcount)<<" additional, took "<<sr.d_outqueries<<" packets, "<<
- sr.d_throttledqueries<<" throttled, rcode="<<res<<endl;
- }
-
- sr.d_outqueries ? cacheMisses++ : cacheHits++;
-
- delete R;
- }
- catch(PDNSException &ae) {
- L<<Logger::Error<<"startDoResolve problem: "<<ae.reason<<endl;
- }
- catch(...) {
- L<<Logger::Error<<"Any other exception in a resolver context"<<endl;
- }
-}
-
-void makeClientSocket()
-{
- d_clientsock=socket(AF_INET, SOCK_DGRAM,0);
- Utility::setCloseOnExec(d_clientsock);
-
- if(d_clientsock<0)
- throw PDNSException("Making a socket for resolver: "+stringerror());
-
- struct sockaddr_in sin;
- memset((char *)&sin,0, sizeof(sin));
-
- sin.sin_family = AF_INET;
- sin.sin_addr.s_addr = INADDR_ANY;
-
- int tries=10;
- while(--tries) {
- uint16_t port=10000+Utility::random()%10000;
- sin.sin_port = htons(port);
-
- if (bind(d_clientsock, (struct sockaddr *)&sin, sizeof(sin)) >= 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<<Logger::Error<<"Setsockopt failed"<<endl;
- exit(1);
- }
-
- listen(d_tcpserversock, 128);
-}
-
-void makeServerSocket()
-{
- d_serversock=socket(AF_INET, SOCK_DGRAM,0);
- Utility::setCloseOnExec(d_serversock);
- if(d_serversock<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") {
- L<<Logger::Warning<<"It is advised to bind to explicit addresses with the --local-address option"<<endl;
- 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_serversock, (struct sockaddr *)&sin, sizeof(sin))<0)
- throw PDNSException("Resolver binding to server socket: "+stringerror());
- L<<Logger::Error<<"Incoming query source port: "<<arg().asNum("local-port")<<endl;
-}
-
-int counter, qcounter;
-bool statsWanted;
-
-void usr1Handler(int)
-{
- statsWanted=true;
-}
-
-
-void doStats(void)
-{
- if(qcounter) {
- L<<Logger::Error<<"stats: "<<qcounter<<" questions, "<<cache.size()<<" cache entries, "<<SyncRes::s_negcache.size()<<" negative entries, "
- <<(int)((cacheHits*100.0)/(cacheHits+cacheMisses))<<"% cache hits";
- L<<Logger::Error<<", outpacket/query ratio "<<(int)(SyncRes::s_outqueries*100.0/SyncRes::s_queries)<<"%";
- L<<Logger::Error<<", "<<(int)(SyncRes::s_throttledqueries*100.0/(SyncRes::s_outqueries+SyncRes::s_throttledqueries))<<"% throttled, "
- <<SyncRes::s_nodelegated<<" no-delegation drops"<<endl;
- }
- statsWanted=false;
-}
-
-void houseKeeping(void *)
-{
- static time_t last_stat, last_rootupdate, last_prune;
-
- if(time(0)-last_stat>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;
- vector<DNSResourceRecord>ret;
-
- sr.setNoCache();
- int res=sr.beginResolve("", QType(QType::NS), ret);
- if(!res) {
- L<<Logger::Error<<"Refreshed . records"<<endl;
- last_rootupdate=time(0);
- }
- else
- L<<Logger::Error<<"Failed to update . records, RCODE="<<res<<endl;
- }
-}
-
-struct TCPConnection
-{
- int fd;
- enum {BYTE0, BYTE1, GETQUESTION} state;
- int qlen;
- int bytesread;
- struct sockaddr_in remote;
- char data[65535];
-};
-
-//! Console handler.
-BOOL WINAPI consoleHandler( DWORD ctrl )
-{
- L << Logger::Error << "Recursor shutting down..." << endl;
- exit( 0 );
-
- // This will never be reached.
- return true;
-}
-
-
-int serviceMain( int argc, char *argv[] )
-{
- try
- {
- makeClientSocket();
- makeServerSocket();
- makeTCPServerSocket();
-
- MT=new MTasker<PacketID,string>(100000);
-
- char data[1500];
- struct sockaddr_in fromaddr;
-
- PacketID pident;
- primeHints();
- L<<Logger::Warning<<"Done priming cache with root hints"<<endl;
-
- vector<TCPConnection> 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<TCPConnection>::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<<Logger::Error<<"Unparseable packet from remote server "<<P.getRemote()<<endl;
- }
- else {
- if(P.d.qr) {
-
- pident.remote=fromaddr;
- pident.id=P.d.id;
- string packet;
- packet.assign(data,d_len);
- MT->sendEvent(pident,&packet);
- }
- else
- L<<Logger::Warning<<"Ignoring question on outgoing socket from "<<P.getRemote()<<endl;
- }
- }
-
- if(FD_ISSET(d_serversock,&readfds)) { // do we have a new question on udp?
- d_len=recvfrom(d_serversock, 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<<Logger::Error<<"Unparseable packet from remote client "<<P.getRemote()<<endl;
- }
- else {
- if(P.d.qr)
- L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
- else {
- ++qcounter;
- P.setSocket(0);
- MT->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<<Logger::Error<<"TCP Remote "<<sockAddrToString(&tc.remote,sizeof(tc.remote))<<" connected"<<endl;
- tcpconnections.push_back(tc);
- }
- }
-
- for(vector<TCPConnection>::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<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected"<<endl;
- Utility::closesocket(i->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<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected after first byte"<<endl;
- Utility::closesocket(i->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<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected while reading question body"<<endl;
- Utility::closesocket(i->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<<Logger::Error<<"Unparseable packet from remote client "<<P.getRemote()<<endl;
- Utility::closesocket(i->fd);
- tcpconnections.erase(i);
- break;
- }
- else {
- P.setSocket(i->fd);
- P.setRemote((struct sockaddr *)&i->remote,sizeof(i->remote));
- if(P.d.qr)
- L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
- else {
- ++qcounter;
- MT->makeThread(startDoResolve,(void*)new DNSPacket(P));
- }
- }
- }
- }
- }
- }
- }
- }
- catch(PDNSException &ae) {
- L<<Logger::Error<<"Exception: "<<ae.reason<<endl;
- }
- catch(std::exception &e) {
- L<<Logger::Error<<"STL Exception: "<<e.what()<<endl;
- }
- catch(...) {
- L<<Logger::Error<<"any other exception in main: "<<endl;
- }
-
-#ifdef WIN32
- WSACleanup();
-#endif // WIN32
-
- return 0;
-}
-
-int main(int argc, char **argv)
-{
- RecursorService recursor;
-
- // Initialize winsock.
- WSAData wsaData;
-
- if ( WSAStartup( MAKEWORD( 2, 0 ), &wsaData ) != 0 )
- {
- cerr << "Could not initialize winsock.dll" << endl;
- return -1;
- }
-
- try {
-
- Utility::srandom(time(0));
- arg().set("soa-minimum-ttl","Don't change")="0";
- arg().set("soa-serial-offset","Don't change")="0";
- arg().set("aaaa-additional-processing","turn on to do AAAA additional processing (slow)")="off";
- arg().set("local-port","port to listen on")="53";
- arg().set("local-address","port to listen on")="0.0.0.0";
- arg().set("trace","if we should output heaps of logging")="off";
- arg().set("daemon","Operate as a daemon")="yes";
- arg().set("quiet","Suppress logging of questions and answers")="off";
- arg().set("delegation-only","Which domains we only accept delegations from")="";
- arg().setCmd("help","Provide a helpful message");
- arg().set("config-dir","Location of configuration directory (recursor.conf)")="./";
- 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" )= "recursor.log";
-
- L.toConsole(Logger::Warning);
- 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());
- }
-
- string configname=arg()["config-dir"]+"/recursor.conf";
- cleanSlashes(configname);
-
- if(!arg().file(configname.c_str()))
- L<<Logger::Warning<<"Unable to parse configuration file '"<<configname<<"'"<<endl;
-
- arg().parse(argc,argv);
-
- if ( arg().mustDo( "register-service" ))
- {
- if ( !recursor.registerService( "The PowerDNS Recursor.", true ))
- {
- cerr << "Could not register service." << endl;
- exit( 99 );
- }
-
- // Exit.
- exit( 0 );
- }
-
- if ( arg().mustDo( "unregister-service" ))
- {
- recursor.unregisterService();
- exit( 0 );
- }
-
- arg().set("delegation-only")=toLower(arg()["delegation-only"]);
-
- if(arg().mustDo("help")) {
- cerr<<"syntax:"<<endl<<endl;
- cerr<<arg().helpstring(arg()["help"])<<endl;
- exit(99);
- }
-
- L.setName("pdns_recursor");
-
- if(arg().mustDo("trace"))
- SyncRes::setLog(true);
-
- if ( arg().mustDo( "use-ntlog" ) && arg().mustDo( "ntservice" ))
- L.toNTLog();
-
- if ( arg().mustDo( "use-logfile" ))
- L.toFile( arg()[ "logfile" ] );
-
- // Register console control handler.
- if ( !arg().mustDo( "ntservice" ))
- SetConsoleCtrlHandler( consoleHandler, true );
-
- RecursorService::instance()->start( argc, argv, arg().mustDo( "ntservice" ));
-
- }
- catch(PDNSException &ae) {
- L<<Logger::Error<<"Exception: "<<ae.reason<<endl;
- }
- catch(std::exception &e) {
- L<<Logger::Error<<"STL Exception: "<<e.what()<<endl;
- }
- catch(...) {
- L<<Logger::Error<<"any other exception in main: "<<endl;
- }
-
- return 0;
-}
+++ /dev/null
-#include "rec_channel.hh"
-#include <cerrno>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <iostream>
-
-#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;
-}
-
+++ /dev/null
-/*
- 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 <windows.h>
-#else
-# include <sys/socket.h>
-# include <netinet/in.h>
-# include <arpa/inet.h>
-# include <sys/time.h>
-# include <sys/wait.h>
-# include <sys/mman.h>
-#endif // WIN32
-
-#include "utility.hh"
-#include <cstdio>
-#include <signal.h>
-#include <cstring>
-#include <cstdlib>
-#include <sys/types.h>
-#include <iostream>
-#include <string>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <errno.h>
-#include <pthread.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <fstream>
-
-#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__<<endl;
- exit(99);
- }
-
-
- if(arg().mustDo("help")) {
- cerr<<"syntax:"<<endl<<endl;
- cerr<<arg().helpstring(arg()["help"])<<endl;
- exit(99);
- }
-
- if(arg().mustDo("config")) {
- cout<<arg().configstring()<<endl;
- exit(99);
- }
-
- if(arg().mustDo("list-modules")) {
- vector<string>modules=BackendMakers().getModules();
- cerr<<"Modules available:"<<endl;
- for(vector<string>::const_iterator i=modules.begin();i!=modules.end();++i)
- cout<<*i<<endl;
-
- exit(99);
- }
- if(!BackendMakers().numLauncheable()) {
- L<<Logger::Error<<"Unable to launch, no backends configured for querying"<<endl;
- exit(99); // this isn't going to fix itself either
- }
-
- if(arg().mustDo("control-console"))
- dl=new DynListener();
- else
- dl=new DynListener(s_programname);
-
- DynListener::registerFunc("SHOW",&DLShowHandler);
- DynListener::registerFunc("RPING",&DLPingHandler);
- DynListener::registerFunc("QUIT",&DLRQuitHandler);
- DynListener::registerFunc("UPTIME",&DLUptimeHandler);
- DynListener::registerFunc("NOTIFY-HOST",&DLNotifyHostHandler);
- DynListener::registerFunc("NOTIFY",&DLNotifyHandler);
- DynListener::registerFunc("RELOAD",&DLReloadHandler);
- DynListener::registerFunc("REDISCOVER",&DLRediscoverHandler);
- DynListener::registerFunc("VERSION",&DLVersionHandler);
- DynListener::registerFunc("PURGE",&DLPurgeHandler);
- DynListener::registerFunc("CCOUNTS",&DLCCHandler);
- DynListener::registerFunc("SET",&DLSettingsHandler);
- DynListener::registerFunc("RETRIEVE",&DLNotifyRetrieveHandler);
-
-
- // reparse, with error checking
- if(!arg().mustDo("no-config"))
- arg().file(configname.c_str());
- arg().parse(argc,argv);
- UeberBackend::go();
- N=new UDPNameserver; // this fails when we are not root, throws exception
-
- if(!arg().mustDo("disable-tcp"))
- TN=new TCPNameserver;
- }
- catch(const ArgException &A) {
- L<<Logger::Error<<"Fatal error: "<<A.reason<<endl;
- exit(1);
- }
-
- declareStats();
- DLOG(L<<Logger::Warning<<"Verbose logging in effect"<<endl);
-
- if ( arg().mustDo( "use-ntlog" ) && arg().mustDo( "ntservice" ))
- L.toNTLog();
-
- if ( arg().mustDo( "use-logfile" ))
- L.toFile( arg()[ "logfile" ] );
-
- L<<Logger::Warning<<"PowerDNS "<<VERSION<<" (C) 2001-2003 PowerDNS.COM BV ("<<__DATE__", "__TIME__<<") starting up"<<endl;
-
- L<<Logger::Warning<<"PowerDNS comes with ABSOLUTELY NO WARRANTY. "
- "This is free software, and you are welcome to redistribute it "
- "according to the terms of the GPL version 2."<<endl;
-
-
- // Register console control handler.
- if ( !arg().mustDo( "ntservice" ))
- SetConsoleCtrlHandler( consoleHandler, true );
-
- PDNSService::instance()->start( argc, argv, arg().mustDo( "ntservice" ));
-
- WSACleanup();
-
- exit(1);
-
- return 0;
-}
-
-
-
+++ /dev/null
-/*
- 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 <iostream>
-#include <mmsystem.h>
-
-// 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;
-}
-
#include <pthread.h>
#include <sstream>
#include <iomanip>
-
-#ifndef WIN32
-# include <unistd.h>
-#endif // WIN32
+#include <unistd.h>
#ifdef HAVE_CONFIG_H
# include <config.h>