root/trunk/pdns/pdns/pdns_recursor.cc @ 1276

Revision 1276, 62.9 KB (checked in by ahu, 5 years ago)

third batch of std::exception

  • Property svn:eol-style set to native
  • Property svn:keywords set to author date id revision
Line 
1/*
2    PowerDNS Versatile Database Driven Nameserver
3    Copyright (C) 2003 - 2008  PowerDNS.COM BV
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License version 2
7    as published by the Free Software Foundation
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17*/
18
19#ifndef WIN32
20# include <netdb.h>
21# include <unistd.h>
22#else
23 #include "ntservice.hh"
24 #include "recursorservice.hh"
25#endif // WIN32
26
27#include "utility.hh"
28#include "dns_random.hh"
29#include <iostream>
30#include <errno.h>
31#include <map>
32#include <set>
33#include "recursor_cache.hh"
34#include <stdio.h>
35#include <signal.h>
36#include <stdlib.h>
37
38#include "mtasker.hh"
39#include <utility>
40#include "arguments.hh"
41#include "syncres.hh"
42#include <fcntl.h>
43#include <fstream>
44#include "sstuff.hh"
45#include <boost/tuple/tuple.hpp>
46#include <boost/tuple/tuple_comparison.hpp>
47#include <boost/shared_array.hpp>
48#include <boost/lexical_cast.hpp>
49#include <boost/function.hpp>
50#include <boost/algorithm/string.hpp>
51#include "dnsparser.hh"
52#include "dnswriter.hh"
53#include "dnsrecords.hh"
54#include "zoneparser-tng.hh"
55#include "rec_channel.hh"
56#include "logger.hh"
57#include "iputils.hh"
58#include "mplexer.hh"
59#include "config.h"
60#include "lua-pdns-recursor.hh"
61
62#ifndef RECURSOR
63#include "statbag.hh"
64StatBag S;
65#endif
66
67FDMultiplexer* g_fdm;
68unsigned int g_maxTCPPerClient;
69bool g_logCommonErrors;
70shared_ptr<PowerDNSLua> g_pdl;
71using namespace boost;
72
73#ifdef __FreeBSD__           // see cvstrac ticket #26
74#include <pthread.h>
75#include <semaphore.h>
76#endif
77
78MemRecursorCache RC;
79RecursorStats g_stats;
80bool g_quiet;
81NetmaskGroup* g_allowFrom;
82NetmaskGroup* g_dontQuery;
83string s_programname="pdns_recursor";
84typedef vector<int> g_tcpListenSockets_t;
85g_tcpListenSockets_t g_tcpListenSockets;
86int g_tcpTimeout;
87
88struct DNSComboWriter {
89  DNSComboWriter(const char* data, uint16_t len, const struct timeval& now) : d_mdp(data, len), d_now(now), d_tcp(false), d_socket(-1)
90  {}
91  MOADNSParser d_mdp;
92  void setRemote(ComboAddress* sa)
93  {
94    d_remote=*sa;
95  }
96
97  void setSocket(int sock)
98  {
99    d_socket=sock;
100  }
101
102  string getRemote() const
103  {
104    return d_remote.toString();
105  }
106
107  struct timeval d_now;
108  ComboAddress d_remote;
109  bool d_tcp;
110  int d_socket;
111};
112
113
114#ifndef WIN32
115#ifndef __FreeBSD__
116extern "C" {
117  int sem_init(sem_t*, int, unsigned int){return 0;}
118  int sem_wait(sem_t*){return 0;}
119  int sem_trywait(sem_t*){return 0;}
120  int sem_post(sem_t*){return 0;}
121  int sem_getvalue(sem_t*, int*){return 0;}
122  pthread_t pthread_self(void){return (pthread_t) 0;}
123  int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr){ return 0; }
124  int pthread_mutex_lock(pthread_mutex_t *mutex){ return 0; }
125  int pthread_mutex_unlock(pthread_mutex_t *mutex) { return 0; }
126  int pthread_mutex_destroy(pthread_mutex_t *mutex) { return 0; }
127}
128#endif // __FreeBSD__
129#endif // WIN32
130
131ArgvMap &arg()
132{
133  static ArgvMap theArg;
134  return theArg;
135}
136
137struct timeval g_now;
138typedef vector<int> tcpserversocks_t;
139
140MT_t* MT; // the big MTasker
141
142void handleTCPClientWritable(int fd, FDMultiplexer::funcparam_t& var);
143
144// -1 is error, 0 is timeout, 1 is success
145int asendtcp(const string& data, Socket* sock) 
146{
147  PacketID pident;
148  pident.sock=sock;
149  pident.outMSG=data;
150 
151  g_fdm->addWriteFD(sock->getHandle(), handleTCPClientWritable, pident);
152  string packet;
153
154  int ret=MT->waitEvent(pident, &packet, 1);
155
156  if(!ret || ret==-1) { // timeout
157    g_fdm->removeWriteFD(sock->getHandle());
158  }
159  else if(packet.size() !=data.size()) { // main loop tells us what it sent out, or empty in case of an error
160    return -1;
161  }
162  return ret;
163}
164
165void handleTCPClientReadable(int fd, FDMultiplexer::funcparam_t& var);
166
167// -1 is error, 0 is timeout, 1 is success
168int arecvtcp(string& data, int len, Socket* sock) 
169{
170  data.clear();
171  PacketID pident;
172  pident.sock=sock;
173  pident.inNeeded=len;
174  g_fdm->addReadFD(sock->getHandle(), handleTCPClientReadable, pident);
175
176  int ret=MT->waitEvent(pident,&data,1);
177  if(!ret || ret==-1) { // timeout
178    g_fdm->removeReadFD(sock->getHandle());
179  }
180  else if(data.empty()) {// error, EOF or other
181    return -1;
182  }
183
184  return ret;
185}
186
187
188void handleUDPServerResponse(int fd, FDMultiplexer::funcparam_t&);
189
190// you can ask this class for a UDP socket to send a query from
191// this socket is not yours, don't even think about deleting it
192// but after you call 'returnSocket' on it, don't assume anything anymore
193class UDPClientSocks
194{
195  unsigned int d_numsocks;
196  unsigned int d_maxsocks;
197
198public:
199  UDPClientSocks() : d_numsocks(0), d_maxsocks(5000)
200  {
201  }
202
203  typedef set<int> socks_t;
204  socks_t d_socks;
205
206  // returning -1 means: temporary OS error (ie, out of files), -2 means OS error
207  int getSocket(const ComboAddress& toaddr, int* fd)
208  {
209    *fd=makeClientSocket(toaddr.sin4.sin_family);
210    if(*fd < 0) // temporary error - receive exception otherwise
211      return -1;
212
213    if(connect(*fd, (struct sockaddr*)(&toaddr), toaddr.getSocklen()) < 0) {
214      int err = errno;
215      //      returnSocket(*fd);
216      Utility::closesocket(*fd);
217      if(err==ENETUNREACH) // Seth "My Interfaces Are Like A Yo Yo" Arnold special
218        return -2;
219      return -1;
220    }
221
222    d_socks.insert(*fd);
223    d_numsocks++;
224    return 0;
225  }
226
227  void returnSocket(int fd)
228  {
229    socks_t::iterator i=d_socks.find(fd);
230    if(i==d_socks.end()) {
231      throw AhuException("Trying to return a socket (fd="+lexical_cast<string>(fd)+") not in the pool");
232    }
233    returnSocket(i);
234  }
235
236  // return a socket to the pool, or simply erase it
237  void returnSocket(socks_t::iterator& i)
238  {
239    if(i==d_socks.end()) {
240      throw AhuException("Trying to return a socket not in the pool");
241    }
242    try {
243      g_fdm->removeReadFD(*i);
244    }
245    catch(FDMultiplexerException& e) {
246      // we sometimes return a socket that has not yet been assigned to g_fdm
247    }
248    Utility::closesocket(*i);
249   
250    d_socks.erase(i++);
251    --d_numsocks;
252  }
253
254  // returns -1 for errors which might go away, throws for ones that won't
255  int makeClientSocket(int family)
256  {
257    int ret=(int)socket(family, SOCK_DGRAM, 0);
258    if(ret < 0 && errno==EMFILE) // this is not a catastrophic error
259      return ret;
260   
261    if(ret<0) 
262      throw AhuException("Making a socket for resolver: "+stringerror());
263   
264    static optional<ComboAddress> sin4;
265    if(!sin4) {
266      sin4=ComboAddress(::arg()["query-local-address"]);
267    }
268    static optional<ComboAddress> sin6;
269    if(!sin6) {
270      if(!::arg()["query-local-address6"].empty())
271        sin6=ComboAddress(::arg()["query-local-address6"]);
272    }
273   
274    int tries=10;
275    while(--tries) {
276      uint16_t port=1025+dns_random(64510);
277      if(tries==1)  // fall back to kernel 'random'
278        port=0;
279     
280      if(family==AF_INET) {
281        sin4->sin4.sin_port = htons(port); 
282       
283        if (::bind(ret, (struct sockaddr *)&*sin4, sin4->getSocklen()) >= 0) 
284          break;
285      }
286      else {
287        sin6->sin6.sin6_port = htons(port); 
288       
289        if (::bind(ret, (struct sockaddr *)&*sin6, sin6->getSocklen()) >= 0) 
290          break;
291      }
292    }
293    if(!tries)
294      throw AhuException("Resolver binding to local query client socket: "+stringerror());
295   
296    Utility::setNonBlocking(ret);
297    return ret;
298  }
299
300
301} g_udpclientsocks;
302
303
304/* these two functions are used by LWRes */
305// -2 is OS error, -1 is error that depends on the remote, > 0 is success
306int asendto(const char *data, int len, int flags, 
307            const ComboAddress& toaddr, uint16_t id, const string& domain, uint16_t qtype, int* fd) 
308{
309
310  PacketID pident;
311  pident.domain = domain;
312  pident.remote = toaddr;
313  pident.type = qtype;
314
315  // see if there is an existing outstanding request we can chain on to, using partial equivalence function
316  pair<MT_t::waiters_t::iterator, MT_t::waiters_t::iterator> chain=MT->d_waiters.equal_range(pident, PacketIDBirthdayCompare());
317
318  for(; chain.first != chain.second; chain.first++) {
319    if(chain.first->key.fd > -1) { // don't chain onto existing chained waiter!
320      cerr<<"Orig: "<<pident.domain<<", "<<pident.remote.toString()<<", id="<<id<<endl;
321      cerr<<"Had hit: "<< chain.first->key.domain<<", "<<chain.first->key.remote.toString()<<", id="<<chain.first->key.id
322          <<", count="<<chain.first->key.chain.size()<<", origfd: "<<chain.first->key.fd<<endl;
323     
324      chain.first->key.chain.insert(id); // we can chain
325      *fd=-1;                            // gets used in waitEvent / sendEvent later on
326      return 1;
327    }
328  }
329
330  int ret=g_udpclientsocks.getSocket(toaddr, fd);
331  if(ret < 0)
332    return ret;
333
334  pident.fd=*fd;
335  pident.id=id;
336 
337  g_fdm->addReadFD(*fd, handleUDPServerResponse, pident);
338  ret=send(*fd, data, len, 0);
339  if(ret < 0)
340    g_udpclientsocks.returnSocket(*fd);
341  return ret;
342}
343
344// -1 is error, 0 is timeout, 1 is success
345int arecvfrom(char *data, int len, int flags, const ComboAddress& fromaddr, int *d_len, 
346              uint16_t id, const string& domain, uint16_t qtype, int fd, unsigned int now)
347{
348  static optional<unsigned int> nearMissLimit;
349  if(!nearMissLimit) 
350    nearMissLimit=::arg().asNum("spoof-nearmiss-max");
351
352  PacketID pident;
353  pident.fd=fd;
354  pident.id=id;
355  pident.domain=domain;
356  pident.type = qtype;
357  pident.remote=fromaddr;
358
359  string packet;
360  int ret=MT->waitEvent(pident, &packet, 1, now);
361
362  if(ret > 0) {
363    if(packet.empty()) // means "error"
364      return -1; 
365
366    *d_len=(int)packet.size();
367    memcpy(data,packet.c_str(),min(len,*d_len));
368    if(*nearMissLimit && pident.nearMisses > *nearMissLimit) {
369      L<<Logger::Error<<"Too many ("<<pident.nearMisses<<" > "<<*nearMissLimit<<") bogus answers for '"<<domain<<"' from "<<fromaddr.toString()<<", assuming spoof attempt."<<endl;
370      g_stats.spoofCount++;
371      return -1;
372    }
373  }
374  else {
375    if(fd >= 0)
376      g_udpclientsocks.returnSocket(fd);
377  }
378  return ret;
379}
380
381void setBuffer(int fd, int optname, uint32_t size)
382{
383  uint32_t psize=0;
384  socklen_t len=sizeof(psize);
385 
386  if(!getsockopt(fd, SOL_SOCKET, optname, (char*)&psize, &len) && psize > size) {
387    L<<Logger::Error<<"Not decreasing socket buffer size from "<<psize<<" to "<<size<<endl;
388    return; 
389  }
390
391  if (setsockopt(fd, SOL_SOCKET, optname, (char*)&size, sizeof(size)) < 0 )
392    L<<Logger::Error<<"Warning: unable to raise socket buffer size to "<<size<<": "<<strerror(errno)<<endl;
393}
394
395
396static void setReceiveBuffer(int fd, uint32_t size)
397{
398  setBuffer(fd, SO_RCVBUF, size);
399}
400
401static void setSendBuffer(int fd, uint32_t size)
402{
403  setBuffer(fd, SO_SNDBUF, size);
404}
405
406string s_pidfname;
407static void writePid(void)
408{
409  ofstream of(s_pidfname.c_str(), ios_base::app);
410  if(of)
411    of<< Utility::getpid() <<endl;
412  else
413    L<<Logger::Error<<"Requested to write pid for "<<Utility::getpid()<<" to "<<s_pidfname<<" failed: "<<strerror(errno)<<endl;
414}
415
416void primeHints(void)
417{
418  // prime root cache
419  set<DNSResourceRecord>nsset;
420
421  if(::arg()["hint-file"].empty()) {
422    static const char*ips[]={"198.41.0.4", "192.228.79.201", "192.33.4.12", "128.8.10.90", "192.203.230.10", "192.5.5.241", 
423                             "192.112.36.4", "128.63.2.53",
424                             "192.36.148.17","192.58.128.30", "193.0.14.129", "199.7.83.42", "202.12.27.33"};
425    static const char *ip6s[]={
426      "2001:503:ba3e::2:30", NULL, NULL, NULL, NULL,
427      "2001:500:2f::f", NULL, "2001:500:1::803f:235", NULL,
428      "2001:503:c27::2:30", NULL, NULL, NULL
429    };
430    DNSResourceRecord arr, aaaarr, nsrr;
431    arr.qtype=QType::A;
432    aaaarr.qtype=QType::AAAA;
433    nsrr.qtype=QType::NS;
434    arr.ttl=aaaarr.ttl=nsrr.ttl=time(0)+3600000;
435   
436    for(char c='a';c<='m';++c) {
437      static char templ[40];
438      strncpy(templ,"a.root-servers.net.", sizeof(templ) - 1);
439      *templ=c;
440      aaaarr.qname=arr.qname=nsrr.content=templ;
441      arr.content=ips[c-'a'];
442      set<DNSResourceRecord> aset;
443      aset.insert(arr);
444      RC.replace(time(0), string(templ), QType(QType::A), aset, true); // auth, nuke it all
445      if (ip6s[c-'a'] != NULL) {
446        aaaarr.content=ip6s[c-'a'];
447
448        set<DNSResourceRecord> aaaaset;
449        aaaaset.insert(aaaarr);
450        RC.replace(time(0), string(templ), QType(QType::AAAA), aaaaset, true);
451      }
452     
453      nsset.insert(nsrr);
454    }
455  }
456  else {
457    ZoneParserTNG zpt(::arg()["hint-file"]);
458    DNSResourceRecord rr;
459
460    while(zpt.get(rr)) {
461      rr.ttl+=time(0);
462      if(rr.qtype.getCode()==QType::A) {
463        set<DNSResourceRecord> aset;
464        aset.insert(rr);
465        RC.replace(time(0), rr.qname, QType(QType::A), aset, true); // auth, etc see above
466      } else if(rr.qtype.getCode()==QType::AAAA) {
467        set<DNSResourceRecord> aaaaset;
468        aaaaset.insert(rr);
469        RC.replace(time(0), rr.qname, QType(QType::AAAA), aaaaset, true);
470      } else if(rr.qtype.getCode()==QType::NS) {
471        rr.content=toLower(rr.content);
472        nsset.insert(rr);
473      }
474    }
475  }
476  RC.replace(time(0),".", QType(QType::NS), nsset, true); // and stuff in the cache (auth)
477}
478
479map<ComboAddress, uint32_t> g_tcpClientCounts;
480
481struct TCPConnection
482{
483  int fd;
484  enum stateenum {BYTE0, BYTE1, GETQUESTION, DONE} state;
485  int qlen;
486  int bytesread;
487  ComboAddress remote;
488  char data[65535];
489  time_t startTime;
490
491  static void closeAndCleanup(int fd, const ComboAddress& remote) 
492  {
493    Utility::closesocket(fd);
494    if(!g_tcpClientCounts[remote]--) 
495      g_tcpClientCounts.erase(remote);
496    s_currentConnections--;
497  }
498  void closeAndCleanup()
499  {
500    closeAndCleanup(fd, remote);
501  }
502  static unsigned int s_currentConnections; //!< total number of current TCP connections
503};
504
505unsigned int TCPConnection::s_currentConnections; 
506void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var);
507
508void startDoResolve(void *p)
509{
510  DNSComboWriter* dc=(DNSComboWriter *)p;
511
512  try {
513    uint16_t maxudpsize=512;
514    EDNSOpts edo;
515    if(getEDNSOpts(dc->d_mdp, &edo)) {
516      maxudpsize=max(edo.d_packetsize, (uint16_t)1280);
517    }
518   
519    vector<DNSResourceRecord> ret;
520    vector<uint8_t> packet;
521
522    DNSPacketWriter pw(packet, dc->d_mdp.d_qname, dc->d_mdp.d_qtype, dc->d_mdp.d_qclass); 
523
524    pw.getHeader()->aa=0;
525    pw.getHeader()->ra=1;
526    pw.getHeader()->qr=1;
527    pw.getHeader()->id=dc->d_mdp.d_header.id;
528    pw.getHeader()->rd=dc->d_mdp.d_header.rd;
529
530    SyncRes sr(dc->d_now);
531    if(!g_quiet)
532      L<<Logger::Error<<"["<<MT->getTid()<<"] " << (dc->d_tcp ? "TCP " : "") << "question for '"<<dc->d_mdp.d_qname<<"|"
533       <<DNSRecordContent::NumberToType(dc->d_mdp.d_qtype)<<"' from "<<dc->getRemote()<<endl;
534
535    sr.setId(MT->getTid());
536    if(!dc->d_mdp.d_header.rd)
537      sr.setCacheOnly();
538
539    int res;
540
541    if(!g_pdl.get() || !g_pdl->preresolve(dc->d_remote, dc->d_mdp.d_qname, QType(dc->d_mdp.d_qtype), ret, res)) {
542       res = sr.beginResolve(dc->d_mdp.d_qname, QType(dc->d_mdp.d_qtype), dc->d_mdp.d_qclass, ret);
543
544       if(g_pdl.get()) {
545         if(res == RCode::NXDomain)
546           g_pdl->nxdomain(dc->d_remote, dc->d_mdp.d_qname, QType(dc->d_mdp.d_qtype), ret, res);
547       }
548    }
549
550    if(res<0) {
551      pw.getHeader()->rcode=RCode::ServFail;
552      // no commit here, because no record
553      g_stats.servFails++;
554    }
555    else {
556      pw.getHeader()->rcode=res;
557      switch(res) {
558      case RCode::ServFail:
559        g_stats.servFails++;
560        break;
561      case RCode::NXDomain:
562        g_stats.nxDomains++;
563        break;
564      case RCode::NoError:
565        g_stats.noErrors++;
566        break;
567      }
568     
569      if(ret.size()) {
570        shuffle(ret);
571       
572        for(vector<DNSResourceRecord>::const_iterator i=ret.begin(); i!=ret.end(); ++i) {
573          pw.startRecord(i->qname, i->qtype.getCode(), i->ttl, i->qclass, (DNSPacketWriter::Place)i->d_place); 
574         
575          if(i->qtype.getCode() == QType::A) { // blast out A record w/o doing whole dnswriter thing
576            uint32_t ip=0;
577            IpToU32(i->content, &ip);
578            pw.xfr32BitInt(htonl(ip));
579          } else {
580            shared_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(i->qtype.getCode(), i->qclass, i->content)); 
581            drc->toPacket(pw);
582          }
583          if(!dc->d_tcp && pw.size() > maxudpsize) {
584            pw.rollback();
585            if(i->d_place==DNSResourceRecord::ANSWER)  // only truncate if we actually omitted parts of the answer
586              pw.getHeader()->tc=1;
587            goto sendit; // need to jump over pw.commit
588          }
589        }
590
591        pw.commit();
592      }
593    }
594  sendit:;
595    if(!dc->d_tcp) {
596      sendto(dc->d_socket, (const char*)&*packet.begin(), packet.size(), 0, (struct sockaddr *)(&dc->d_remote), dc->d_remote.getSocklen());
597    }
598    else {
599      char buf[2];
600      buf[0]=packet.size()/256;
601      buf[1]=packet.size()%256;
602
603      Utility::iovec iov[2];
604
605      iov[0].iov_base=(void*)buf;              iov[0].iov_len=2;
606      iov[1].iov_base=(void*)&*packet.begin(); iov[1].iov_len = packet.size();
607
608      int ret=Utility::writev(dc->d_socket, iov, 2);
609      bool hadError=true;
610
611      if(ret == 0) 
612        L<<Logger::Error<<"EOF writing TCP answer to "<<dc->getRemote()<<endl;
613      else if(ret < 0 ) 
614        L<<Logger::Error<<"Error writing TCP answer to "<<dc->getRemote()<<": "<< strerror(errno) <<endl;
615      else if((unsigned int)ret != 2 + packet.size())
616        L<<Logger::Error<<"Oops, partial answer sent to "<<dc->getRemote()<<" for "<<dc->d_mdp.d_qname<<" (size="<< (2 + packet.size()) <<", sent "<<ret<<")"<<endl;
617      else
618        hadError=false;
619     
620      // update tcp connection status, either by closing or moving to 'BYTE0'
621
622      if(hadError) {
623        g_fdm->removeReadFD(dc->d_socket);
624        TCPConnection::closeAndCleanup(dc->d_socket, dc->d_remote);
625      }
626      else {
627        TCPConnection tc;
628        tc.fd=dc->d_socket;
629        tc.state=TCPConnection::BYTE0;
630        tc.remote=dc->d_remote;
631        Utility::gettimeofday(&g_now, 0); // needs to be updated
632        tc.startTime=g_now.tv_sec;
633        g_fdm->addReadFD(tc.fd, handleRunningTCPQuestion, tc);
634        g_fdm->setReadTTD(tc.fd, g_now, g_tcpTimeout);
635      }
636    }
637   
638    if(!g_quiet) {
639      L<<Logger::Error<<"["<<MT->getTid()<<"] answer to "<<(dc->d_mdp.d_header.rd?"":"non-rd ")<<"question '"<<dc->d_mdp.d_qname<<"|"<<DNSRecordContent::NumberToType(dc->d_mdp.d_qtype);
640      L<<"': "<<ntohs(pw.getHeader()->ancount)<<" answers, "<<ntohs(pw.getHeader()->arcount)<<" additional, took "<<sr.d_outqueries<<" packets, "<<
641        sr.d_throttledqueries<<" throttled, "<<sr.d_timeouts<<" timeouts, "<<sr.d_tcpoutqueries<<" tcp connections, rcode="<<res<<endl;
642    }
643
644    sr.d_outqueries ? RC.cacheMisses++ : RC.cacheHits++; 
645    float spent=makeFloat(sr.d_now-dc->d_now);
646    if(spent < 0.001)
647      g_stats.answers0_1++;
648    else if(spent < 0.010)
649      g_stats.answers1_10++;
650    else if(spent < 0.1)
651      g_stats.answers10_100++;
652    else if(spent < 1.0)
653      g_stats.answers100_1000++;
654    else
655      g_stats.answersSlow++;
656
657    uint64_t newLat=(uint64_t)(spent*1000000);
658    if(newLat < 1000000)  // outliers of several minutes exist..
659      g_stats.avgLatencyUsec=(uint64_t)((1-0.0001)*g_stats.avgLatencyUsec + 0.0001*newLat);
660
661    delete dc;
662  }
663  catch(AhuException &ae) {
664    L<<Logger::Error<<"startDoResolve problem: "<<ae.reason<<endl;
665  }
666  catch(MOADNSException& e) {
667    L<<Logger::Error<<"DNS parser error: "<<dc->d_mdp.d_qname<<", "<<e.what()<<endl;
668  }
669  catch(std::exception& e) {
670    L<<Logger::Error<<"STL error: "<<e.what()<<endl;
671  }
672  catch(...) {
673    L<<Logger::Error<<"Any other exception in a resolver context"<<endl;
674  }
675}
676
677RecursorControlChannel s_rcc;
678
679void makeControlChannelSocket()
680{
681  string sockname=::arg()["socket-dir"]+"/pdns_recursor.controlsocket";
682  if(::arg().mustDo("fork")) {
683    sockname+="."+lexical_cast<string>(Utility::getpid());
684    L<<Logger::Warning<<"Forked control socket name: "<<sockname<<endl;
685  }
686  s_rcc.listen(sockname);
687}
688
689void handleRunningTCPQuestion(int fd, FDMultiplexer::funcparam_t& var)
690{
691  TCPConnection* conn=any_cast<TCPConnection>(&var);
692
693  if(conn->state==TCPConnection::BYTE0) {
694    int bytes=recv(conn->fd, conn->data, 2, 0);
695    if(bytes==1)
696      conn->state=TCPConnection::BYTE1;
697    if(bytes==2) { 
698      conn->qlen=(((unsigned char)conn->data[0]) << 8)+ (unsigned char)conn->data[1];
699      conn->bytesread=0;
700      conn->state=TCPConnection::GETQUESTION;
701    }
702    if(!bytes || bytes < 0) {
703      TCPConnection tmp(*conn); 
704      g_fdm->removeReadFD(fd);
705      tmp.closeAndCleanup();
706      return;
707    }
708  }
709  else if(conn->state==TCPConnection::BYTE1) {
710    int bytes=recv(conn->fd, conn->data+1, 1, 0);
711    if(bytes==1) {
712      conn->state=TCPConnection::GETQUESTION;
713      conn->qlen=(((unsigned char)conn->data[0]) << 8)+ (unsigned char)conn->data[1];
714      conn->bytesread=0;
715    }
716    if(!bytes || bytes < 0) {
717      if(g_logCommonErrors)
718        L<<Logger::Error<<"TCP client "<< conn->remote.toString() <<" disconnected after first byte"<<endl;
719      TCPConnection tmp(*conn); 
720      g_fdm->removeReadFD(fd);
721      tmp.closeAndCleanup();  // conn loses validity here..
722      return;
723    }
724  }
725  else if(conn->state==TCPConnection::GETQUESTION) {
726    int bytes=recv(conn->fd, conn->data + conn->bytesread, conn->qlen - conn->bytesread, 0);
727    if(!bytes || bytes < 0) {
728      L<<Logger::Error<<"TCP client "<< conn->remote.toString() <<" disconnected while reading question body"<<endl;
729      TCPConnection tmp(*conn);
730      g_fdm->removeReadFD(fd);
731      tmp.closeAndCleanup();  // conn loses validity here..
732
733      return;
734    }
735    conn->bytesread+=bytes;
736    if(conn->bytesread==conn->qlen) {
737      TCPConnection tconn(*conn); 
738      g_fdm->removeReadFD(fd); // should no longer awake ourselves when there is data to read
739
740      DNSComboWriter* dc=0;
741      try {
742        dc=new DNSComboWriter(tconn.data, tconn.qlen, g_now);
743      }
744      catch(MOADNSException &mde) {
745        g_stats.clientParseError++; 
746        if(g_logCommonErrors)
747          L<<Logger::Error<<"Unable to parse packet from TCP client "<< tconn.remote.toString() <<endl;
748        tconn.closeAndCleanup();
749        return;
750      }
751     
752      dc->setSocket(tconn.fd);
753      dc->d_tcp=true;
754      dc->setRemote(&tconn.remote);
755      if(dc->d_mdp.d_header.qr) {
756        delete dc;
757        L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
758        tconn.closeAndCleanup();
759        return;
760      }
761      else {
762        ++g_stats.qcounter;
763        ++g_stats.tcpqcounter;
764        MT->makeThread(startDoResolve, dc); // deletes dc
765        return;
766      }
767    }
768  }
769}
770
771//! Handle new incoming TCP connection
772void handleNewTCPQuestion(int fd, FDMultiplexer::funcparam_t& )
773{
774  ComboAddress addr;
775  socklen_t addrlen=sizeof(addr);
776  int newsock=(int)accept(fd, (struct sockaddr*)&addr, &addrlen);
777  if(newsock>0) {
778    g_stats.addRemote(addr);
779    if(g_allowFrom && !g_allowFrom->match(&addr)) {
780      if(!g_quiet) 
781        L<<Logger::Error<<"["<<MT->getTid()<<"] dropping TCP query from "<<addr.toString()<<", address not matched by allow-from"<<endl;
782
783      g_stats.unauthorizedTCP++;
784      Utility::closesocket(newsock);
785      return;
786    }
787   
788    if(g_maxTCPPerClient && g_tcpClientCounts.count(addr) && g_tcpClientCounts[addr] >= g_maxTCPPerClient) {
789      g_stats.tcpClientOverflow++;
790      Utility::closesocket(newsock); // don't call TCPConnection::closeAndCleanup here - did not enter it in the counts yet!
791      return;
792    }
793    g_tcpClientCounts[addr]++;
794    Utility::setNonBlocking(newsock);
795    TCPConnection tc;
796    tc.fd=newsock;
797    tc.state=TCPConnection::BYTE0;
798    tc.remote=addr;
799    tc.startTime=g_now.tv_sec;
800    TCPConnection::s_currentConnections++;
801    g_fdm->addReadFD(tc.fd, handleRunningTCPQuestion, tc);
802
803    struct timeval now;
804    Utility::gettimeofday(&now, 0);
805    g_fdm->setReadTTD(tc.fd, now, g_tcpTimeout);
806  }
807}
808 
809void questionExpand(const char* packet, uint16_t len, char* qname, int maxlen, uint16_t& type)
810{
811  type=0;
812  const unsigned char* end=(const unsigned char*)packet+len;
813  unsigned char* lbegin=(unsigned char*)packet+12;
814  unsigned char* pos=lbegin;
815  unsigned char labellen;
816
817  // 3www4ds9a2nl0
818  char *dst=qname;
819  char* lend=dst + maxlen;
820 
821  if(!*pos)
822    *dst++='.';
823
824  while((labellen=*pos++) && pos < end) { // "scan and copy"
825    if(dst >= lend)
826      throw runtime_error("Label length exceeded destination length");
827    for(;labellen;--labellen)
828      *dst++ = *pos++;
829    *dst++='.';
830  }
831  *dst=0;
832
833  if(pos + labellen + 2 <= end)  // is this correct XXX FIXME?
834    type=(*pos)*256 + *(pos+1);
835
836
837  //  cerr<<"Returning: '"<< string(tmp+1, pos) <<"'\n";
838}
839
840string questionExpand(const char* packet, uint16_t len, uint16_t& type)
841{
842  char tmp[512];
843  questionExpand(packet, len, tmp, sizeof(tmp), type);
844  return tmp;
845}
846
847void handleNewUDPQuestion(int fd, FDMultiplexer::funcparam_t& var)
848{
849  //  static HTimer s_timer("udp new question processing");
850  //  HTimerSentinel hts=s_timer.getSentinel();
851  int len;
852  char data[1500];
853  ComboAddress fromaddr;
854  socklen_t addrlen=sizeof(fromaddr);
855  //  uint64_t tsc1, tsc2;
856
857  if((len=recvfrom(fd, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen)) >= 0) {
858    //    RDTSC(tsc1);     
859    g_stats.addRemote(fromaddr);
860
861    if(g_allowFrom && !g_allowFrom->match(&fromaddr)) {
862      if(!g_quiet) 
863        L<<Logger::Error<<"["<<MT->getTid()<<"] dropping UDP query from "<<fromaddr.toString()<<", address not matched by allow-from"<<endl;
864
865      g_stats.unauthorizedUDP++;
866      return;
867    }
868    try {
869      dnsheader* dh=(dnsheader*)data;
870     
871      if(dh->qr) {
872        if(g_logCommonErrors)
873          L<<Logger::Error<<"Ignoring answer from "<<fromaddr.toString()<<" on server socket!"<<endl;
874      }
875      else {
876        ++g_stats.qcounter;
877#if 0
878        uint16_t type;
879        char qname[256];
880        try {
881           questionExpand(data, len, qname, sizeof(qname), type); 
882        }
883        catch(std::exception &e)
884        {
885           throw MOADNSException(e.what());
886        }
887       
888        // must all be same length answers right now!
889        if((type==QType::A || type==QType::AAAA) && dh->arcount==0 && dh->ancount==0 && dh->nscount ==0 && ntohs(dh->qdcount)==1 ) {
890          char *record[10];
891          uint16_t rlen[10];
892          uint32_t ttd[10];
893          int count;
894          if((count=RC.getDirect(g_now.tv_sec, qname, QType(type), ttd, record, rlen))) {
895            if(len + count*(sizeof(dnsrecordheader) + 2 + rlen[0]) > 512)
896              goto slow;
897
898            random_shuffle(record, &record[count]);
899            dh->qr=1;
900            dh->ra=1;
901            dh->ancount=ntohs(count);
902            for(int n=0; n < count ; ++n) {
903              memcpy(data+len, "\xc0\x0c", 2); // answer label pointer
904              len+=2;
905              struct dnsrecordheader drh;
906              drh.d_type=htons(type);
907              drh.d_class=htons(1);
908              drh.d_ttl=htonl(ttd[n] - g_now.tv_sec);
909              drh.d_clen=htons(rlen[n]);
910              memcpy(data+len, &drh, sizeof(drh));
911              len+=sizeof(drh);
912              memcpy(data+len, record[n], rlen[n]);
913              len+=rlen[n];
914            }
915            RDTSC(tsc2);           
916            g_stats.shunted++;
917            sendto(fd, data, len, 0, (struct sockaddr *)(&fromaddr), fromaddr.getSocklen());
918//          cerr<<"shunted: " << (tsc2-tsc1) / 3000.0 << endl;
919            return;
920          }
921        }
922        else {
923          if(type!=QType::A && type!=QType::AAAA)
924            g_stats.noShuntWrongType++;
925          else
926            g_stats.noShuntWrongQuestion++;
927        }
928      slow:
929#endif
930        DNSComboWriter* dc = new DNSComboWriter(data, len, g_now);
931        dc->setSocket(fd);
932        dc->setRemote(&fromaddr);
933
934        dc->d_tcp=false;
935
936        MT->makeThread(startDoResolve, (void*) dc); // deletes dc
937      }
938    }
939    catch(MOADNSException& mde) {
940      g_stats.clientParseError++; 
941      if(g_logCommonErrors)
942        L<<Logger::Error<<"Unable to parse packet from remote UDP client "<<fromaddr.toString() <<": "<<mde.what()<<endl;
943    }
944  }
945}
946
947typedef vector<pair<int, function< void(int, any&) > > > deferredAdd_t;
948deferredAdd_t deferredAdd;
949
950void makeTCPServerSockets()
951{
952  int fd;
953  vector<string>locals;
954  stringtok(locals,::arg()["local-address"]," ,");
955
956  if(locals.empty())
957    throw AhuException("No local address specified");
958 
959  for(vector<string>::const_iterator i=locals.begin();i!=locals.end();++i) {
960    ServiceTuple st;
961    st.port=::arg().asNum("local-port");
962    parseService(*i, st);
963   
964    ComboAddress sin;
965
966    memset((char *)&sin,0, sizeof(sin));
967    sin.sin4.sin_family = AF_INET;
968    if(!IpToU32(st.host, (uint32_t*)&sin.sin4.sin_addr.s_addr)) {
969      sin.sin6.sin6_family = AF_INET6;
970      if(Utility::inet_pton(AF_INET6, st.host.c_str(), &sin.sin6.sin6_addr) <= 0)
971        throw AhuException("Unable to resolve local address for TCP server on '"+ st.host +"'"); 
972    }
973
974    fd=socket(sin.sin6.sin6_family, SOCK_STREAM, 0);
975    if(fd<0) 
976      throw AhuException("Making a TCP server socket for resolver: "+stringerror());
977
978    int tmp=1;
979    if(setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char*)&tmp,sizeof tmp)<0) {
980      L<<Logger::Error<<"Setsockopt failed for TCP listening socket"<<endl;
981      exit(1);
982    }
983   
984#ifdef TCP_DEFER_ACCEPT
985    if(setsockopt(fd, SOL_TCP,TCP_DEFER_ACCEPT,(char*)&tmp,sizeof tmp) >= 0) {
986      if(i==locals.begin())
987        L<<Logger::Error<<"Enabled TCP data-ready filter for (slight) DoS protection"<<endl;
988    }
989#endif
990
991    sin.sin4.sin_port = htons(st.port);
992    int socklen=sin.sin4.sin_family==AF_INET ? sizeof(sin.sin4) : sizeof(sin.sin6);
993    if (::bind(fd, (struct sockaddr *)&sin, socklen )<0) 
994      throw AhuException("Binding TCP server socket for "+ st.host +": "+stringerror());
995   
996    Utility::setNonBlocking(fd);
997    setSendBuffer(fd, 65000);
998    listen(fd, 128);
999    deferredAdd.push_back(make_pair(fd, handleNewTCPQuestion));
1000    g_tcpListenSockets.push_back(fd);
1001
1002    if(sin.sin4.sin_family == AF_INET) 
1003      L<<Logger::Error<<"Listening for TCP queries on "<< sin.toString() <<":"<<st.port<<endl;
1004    else
1005      L<<Logger::Error<<"Listening for TCP queries on ["<< sin.toString() <<"]:"<<st.port<<endl;
1006  }
1007}
1008
1009void makeUDPServerSockets()
1010{
1011  vector<string>locals;
1012  stringtok(locals,::arg()["local-address"]," ,");
1013
1014  if(locals.empty())
1015    throw AhuException("No local address specified");
1016 
1017  if(::arg()["local-address"]=="0.0.0.0") {
1018    L<<Logger::Warning<<"It is advised to bind to explicit addresses with the --local-address option"<<endl;
1019  }
1020
1021  for(vector<string>::const_iterator i=locals.begin();i!=locals.end();++i) {
1022    ServiceTuple st;
1023    st.port=::arg().asNum("local-port");
1024    parseService(*i, st);
1025
1026    ComboAddress sin;
1027
1028    memset(&sin, 0, sizeof(sin));
1029    sin.sin4.sin_family = AF_INET;
1030    if(!IpToU32(st.host.c_str() , (uint32_t*)&sin.sin4.sin_addr.s_addr)) {
1031      sin.sin6.sin6_family = AF_INET6;
1032      if(Utility::inet_pton(AF_INET6, st.host.c_str(), &sin.sin6.sin6_addr) <= 0)
1033        throw AhuException("Unable to resolve local address for UDP server on '"+ st.host +"'"); 
1034    }
1035   
1036    int fd=socket(sin.sin4.sin_family, SOCK_DGRAM,0);
1037    if(fd < 0) {
1038      throw AhuException("Making a UDP server socket for resolver: "+netstringerror());
1039    }
1040
1041    setReceiveBuffer(fd, 200000);
1042    sin.sin4.sin_port = htons(st.port);
1043
1044    int socklen=sin.sin4.sin_family==AF_INET ? sizeof(sin.sin4) : sizeof(sin.sin6);
1045    if (::bind(fd, (struct sockaddr *)&sin, socklen)<0) 
1046      throw AhuException("Resolver binding to server socket on port "+ lexical_cast<string>(st.port) +" for "+ st.host+": "+stringerror());
1047   
1048    Utility::setNonBlocking(fd);
1049    //    g_fdm->addReadFD(fd, handleNewUDPQuestion);
1050    deferredAdd.push_back(make_pair(fd, handleNewUDPQuestion));
1051
1052    if(sin.sin4.sin_family == AF_INET) 
1053      L<<Logger::Error<<"Listening for UDP queries on "<< sin.toString() <<":"<<st.port<<endl;
1054    else
1055      L<<Logger::Error<<"Listening for UDP queries on ["<< sin.toString() <<"]:"<<st.port<<endl;
1056  }
1057}
1058
1059
1060#ifndef WIN32
1061void daemonize(void)
1062{
1063  if(fork())
1064    exit(0); // bye bye
1065 
1066  setsid(); 
1067
1068  int i=open("/dev/null",O_RDWR); /* open stdin */
1069  if(i < 0) 
1070    L<<Logger::Critical<<"Unable to open /dev/null: "<<stringerror()<<endl;
1071  else {
1072    dup2(i,0); /* stdin */
1073    dup2(i,1); /* stderr */
1074    dup2(i,2); /* stderr */
1075    close(i);
1076  }
1077}
1078#endif
1079
1080uint64_t counter;
1081bool statsWanted;
1082
1083
1084void usr1Handler(int)
1085{
1086  statsWanted=true;
1087}
1088
1089
1090
1091void usr2Handler(int)
1092{
1093  SyncRes::setLog(true);
1094  g_quiet=false;
1095  ::arg().set("quiet")="no";
1096
1097}
1098
1099void doStats(void)
1100{
1101  if(g_stats.qcounter && (RC.cacheHits + RC.cacheMisses) && SyncRes::s_queries && SyncRes::s_outqueries) {
1102    L<<Logger::Warning<<"stats: "<<g_stats.qcounter<<" questions, "<<RC.size()<<" cache entries, "<<SyncRes::s_negcache.size()<<" negative entries, "
1103     <<(int)((RC.cacheHits*100.0)/(RC.cacheHits+RC.cacheMisses))<<"% cache hits"<<endl;
1104    L<<Logger::Warning<<"stats: throttle map: "<<SyncRes::s_throttle.size()<<", ns speeds: "
1105     <<SyncRes::s_nsSpeeds.size()<<endl; // ", bytes: "<<RC.bytes()<<endl;
1106    L<<Logger::Warning<<"stats: outpacket/query ratio "<<(int)(SyncRes::s_outqueries*100.0/SyncRes::s_queries)<<"%";
1107    L<<Logger::Warning<<", "<<(int)(SyncRes::s_throttledqueries*100.0/(SyncRes::s_outqueries+SyncRes::s_throttledqueries))<<"% throttled, "
1108     <<SyncRes::s_nodelegated<<" no-delegation drops"<<endl;
1109    L<<Logger::Warning<<"stats: "<<SyncRes::s_tcpoutqueries<<" outgoing tcp connections, "<<MT->numProcesses()<<" queries running, "<<SyncRes::s_outgoingtimeouts<<" outgoing timeouts"<<endl;
1110  }
1111  else if(statsWanted) 
1112    L<<Logger::Warning<<"stats: no stats yet!"<<endl;
1113
1114  //  HTimer::listAll();
1115
1116  statsWanted=false;
1117}
1118
1119static void houseKeeping(void *)
1120try
1121{
1122  static time_t last_stat, last_rootupdate, last_prune;
1123  struct timeval now;
1124  Utility::gettimeofday(&now, 0);
1125
1126  if(now.tv_sec - last_prune > 300) { 
1127    DTime dt;
1128    dt.setTimeval(now);
1129    RC.doPrune();
1130   
1131    typedef SyncRes::negcache_t::nth_index<1>::type negcache_by_ttd_index_t;
1132    negcache_by_ttd_index_t& ttdindex=boost::multi_index::get<1>(SyncRes::s_negcache);
1133
1134    negcache_by_ttd_index_t::iterator i=ttdindex.lower_bound(now.tv_sec);
1135    ttdindex.erase(ttdindex.begin(), i);
1136
1137    time_t limit=now.tv_sec-300;
1138    for(SyncRes::nsspeeds_t::iterator i = SyncRes::s_nsSpeeds.begin() ; i!= SyncRes::s_nsSpeeds.end(); )
1139      if(i->second.stale(limit))
1140        SyncRes::s_nsSpeeds.erase(i++);
1141      else
1142        ++i;
1143
1144    //   cerr<<"Pruned "<<pruned<<" records, left "<<SyncRes::s_negcache.size()<<"\n";
1145//    cout<<"Prune took "<<dt.udiff()<<"usec\n";
1146    last_prune=time(0);
1147  }
1148  if(now.tv_sec - last_stat>1800) { 
1149    doStats();
1150    last_stat=time(0);
1151  }
1152  if(now.tv_sec - last_rootupdate > 7200) {
1153    SyncRes sr(now);
1154    sr.setDoEDNS0(true);
1155    vector<DNSResourceRecord> ret;
1156
1157    sr.setNoCache();
1158    int res=sr.beginResolve(".", QType(QType::NS), 1, ret);
1159    if(!res) {
1160      L<<Logger::Warning<<"Refreshed . records"<<endl;
1161      last_rootupdate=now.tv_sec;
1162    }
1163    else
1164      L<<Logger::Error<<"Failed to update . records, RCODE="<<res<<endl;
1165  }
1166}
1167catch(AhuException& ae)
1168{
1169  L<<Logger::Error<<"Fatal error: "<<ae.reason<<endl;
1170  throw;
1171}
1172;
1173
1174
1175void handleRCC(int fd, FDMultiplexer::funcparam_t& var)
1176{
1177  string remote;
1178  string msg=s_rcc.recv(&remote);
1179  RecursorControlParser rcp;
1180  RecursorControlParser::func_t* command;
1181  string answer=rcp.getAnswer(msg, &command);
1182  try {
1183    s_rcc.send(answer, &remote);
1184    command();
1185  }
1186  catch(std::exception& e) {
1187    L<<Logger::Error<<"Error dealing with control socket request: "<<e.what()<<endl;
1188  }
1189  catch(AhuException& ae) {
1190    L<<Logger::Error<<"Error dealing with control socket request: "<<ae.reason<<endl;
1191  }
1192}
1193
1194void handleTCPClientReadable(int fd, FDMultiplexer::funcparam_t& var)
1195{
1196  PacketID* pident=any_cast<PacketID>(&var);
1197  //  cerr<<"handleTCPClientReadable called for fd "<<fd<<", pident->inNeeded: "<<pident->inNeeded<<", "<<pident->sock->getHandle()<<endl;
1198
1199  shared_array<char> buffer(new char[pident->inNeeded]);
1200
1201  int ret=recv(fd, buffer.get(), pident->inNeeded,0);
1202  if(ret > 0) {
1203    pident->inMSG.append(&buffer[0], &buffer[ret]);
1204    pident->inNeeded-=ret;
1205    if(!pident->inNeeded) {
1206      //      cerr<<"Got entire load of "<<pident->inMSG.size()<<" bytes"<<endl;
1207      PacketID pid=*pident;
1208      string msg=pident->inMSG;
1209     
1210      g_fdm->removeReadFD(fd);
1211      MT->sendEvent(pid, &msg); 
1212    }
1213    else {
1214      //      cerr<<"Still have "<<pident->inNeeded<<" left to go"<<endl;
1215    }
1216  }
1217  else {
1218    PacketID tmp=*pident;
1219    g_fdm->removeReadFD(fd); // pident might now be invalid (it isn't, but still)
1220    string empty;
1221    MT->sendEvent(tmp, &empty); // this conveys error status
1222  }
1223}
1224
1225void handleTCPClientWritable(int fd, FDMultiplexer::funcparam_t& var)
1226{
1227  PacketID* pid=any_cast<PacketID>(&var);
1228  int ret=send(fd, pid->outMSG.c_str() + pid->outPos, pid->outMSG.size() - pid->outPos,0);
1229  if(ret > 0) {
1230    pid->outPos+=ret;
1231    if(pid->outPos==pid->outMSG.size()) {
1232      PacketID tmp=*pid;
1233      g_fdm->removeWriteFD(fd);
1234      MT->sendEvent(tmp, &tmp.outMSG);  // send back what we sent to convey everything is ok
1235    }
1236  }
1237  else {  // error or EOF
1238    PacketID tmp(*pid);
1239    g_fdm->removeWriteFD(fd);
1240    string sent;
1241    MT->sendEvent(tmp, &sent);         // we convey error status by sending empty string
1242  }
1243}
1244
1245// resend event to everybody chained onto it
1246void doResends(MT_t::waiters_t::iterator& iter, PacketID resend, const string& content)
1247{
1248
1249  if(iter->key.chain.empty())
1250    return;
1251
1252  cerr<<"doResends called!\n";
1253  for(PacketID::chain_t::iterator i=iter->key.chain.begin(); i != iter->key.chain.end() ; ++i) {
1254    resend.fd=-1;
1255    resend.id=*i;
1256    cerr<<"\tResending "<<content.size()<<" bytes for fd="<<resend.fd<<" and id="<<resend.id<<endl;
1257
1258    MT->sendEvent(resend, &content);
1259    g_stats.chainResends++;
1260  }
1261}
1262
1263void handleUDPServerResponse(int fd, FDMultiplexer::funcparam_t& var)
1264{
1265  //  static HTimer s_timer("udp server response processing");
1266
1267  PacketID pid=any_cast<PacketID>(var);
1268  int len;
1269  char data[1500];
1270  ComboAddress fromaddr;
1271  socklen_t addrlen=sizeof(fromaddr);
1272
1273  len=recvfrom(fd, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen);
1274  //  HTimerSentinel hts=s_timer.getSentinel();
1275  if(len < (int)sizeof(dnsheader)) {
1276    if(len < 0)
1277      ; //      cerr<<"Error on fd "<<fd<<": "<<stringerror()<<"\n";
1278    else {
1279      g_stats.serverParseError++; 
1280      if(g_logCommonErrors)
1281        L<<Logger::Error<<"Unable to parse packet from remote UDP server "<< sockAddrToString((struct sockaddr_in*) &fromaddr) <<
1282          ": packet smalller than DNS header"<<endl;
1283    }
1284
1285    g_udpclientsocks.returnSocket(fd);
1286    string empty;
1287
1288    MT_t::waiters_t::iterator iter=MT->d_waiters.find(pid);
1289    if(iter != MT->d_waiters.end()) 
1290      doResends(iter, pid, empty);
1291   
1292    MT->sendEvent(pid, &empty); // this denotes error (does lookup again.. at least L1 will be hot)
1293    return;
1294  } 
1295
1296  dnsheader dh;
1297  memcpy(&dh, data, sizeof(dh));
1298 
1299  if(!dh.qdcount) // UPC, Nominum?
1300    return;
1301 
1302  if(dh.qr) {
1303    PacketID pident;
1304    pident.remote=fromaddr;
1305    pident.id=dh.id;
1306    pident.fd=fd;
1307    pident.domain=questionExpand(data, len, pident.type); // don't copy this from above - we need to do the actual read
1308    string packet;
1309    packet.assign(data, len);
1310
1311    MT_t::waiters_t::iterator iter=MT->d_waiters.find(pident);
1312    if(iter != MT->d_waiters.end()) {
1313      doResends(iter, pident, packet);
1314    }
1315
1316    //    s_timer.stop();
1317    if(!MT->sendEvent(pident, &packet)) {
1318      //      s_timer.start();
1319//      if(g_logCommonErrors)
1320//        L<<Logger::Warning<<"Discarding unexpected packet from "<<fromaddr.toString()<<": "<<pident.type<<endl;
1321      g_stats.unexpectedCount++;
1322     
1323      for(MT_t::waiters_t::iterator mthread=MT->d_waiters.begin(); mthread!=MT->d_waiters.end(); ++mthread) {
1324        if(pident.fd==mthread->key.fd && mthread->key.remote==pident.remote &&  mthread->key.type == pident.type &&
1325           !Utility::strcasecmp(pident.domain.c_str(), mthread->key.domain.c_str())) {
1326          mthread->key.nearMisses++;
1327        }
1328      }
1329    }
1330    else if(fd >= 0) {
1331      //      s_timer.start();
1332      g_udpclientsocks.returnSocket(fd);
1333    }
1334  }
1335  else
1336    L<<Logger::Warning<<"Ignoring question on outgoing socket from "<< sockAddrToString((struct sockaddr_in*) &fromaddr)  <<endl;
1337}
1338
1339FDMultiplexer* getMultiplexer()
1340{
1341  FDMultiplexer* ret;
1342  for(FDMultiplexer::FDMultiplexermap_t::const_iterator i = FDMultiplexer::getMultiplexerMap().begin();
1343      i != FDMultiplexer::getMultiplexerMap().end(); ++i) {
1344    try {
1345      ret=i->second();
1346      L<<Logger::Error<<"Enabled '"<<ret->getName()<<"' multiplexer"<<endl;
1347      return ret;
1348    }
1349    catch(FDMultiplexerException &fe) {
1350      L<<Logger::Error<<"Non-fatal error initializing possible multiplexer ("<<fe.what()<<"), falling back"<<endl;
1351    }
1352    catch(...) {
1353      L<<Logger::Error<<"Non-fatal error initializing possible multiplexer"<<endl;
1354    }
1355  }
1356  L<<Logger::Error<<"No working multiplexer found!"<<endl;
1357  exit(1);
1358}
1359
1360static void makeNameToIPZone(const string& hostname, const string& ip)
1361{
1362  SyncRes::AuthDomain ad;
1363  DNSResourceRecord rr;
1364  rr.qname=toCanonic("", hostname);
1365  rr.d_place=DNSResourceRecord::ANSWER;
1366  rr.ttl=86400;
1367  rr.qtype=QType::SOA;
1368  rr.content="localhost. root 1 604800 86400 2419200 604800";
1369 
1370  ad.d_records.insert(rr);
1371
1372  rr.qtype=QType::NS;
1373  rr.content="localhost.";
1374
1375  ad.d_records.insert(rr);
1376 
1377  rr.qtype=QType::A;
1378  rr.content=ip;
1379  ad.d_records.insert(rr);
1380 
1381  if(SyncRes::s_domainmap.count(rr.qname)) {
1382    L<<Logger::Warning<<"Hosts file will not overwrite zone '"<<rr.qname<<"' already loaded"<<endl;
1383  }
1384  else {
1385    L<<Logger::Warning<<"Inserting forward zone '"<<rr.qname<<"' based on hosts file"<<endl;
1386    SyncRes::s_domainmap[rr.qname]=ad;
1387  }
1388}
1389
1390//! parts[0] must be an IP address, the rest must be host names
1391static void makeIPToNamesZone(const vector<string>& parts) 
1392{
1393  string address=parts[0];
1394  vector<string> ipparts;
1395  stringtok(ipparts, address,".");
1396 
1397  SyncRes::AuthDomain ad;
1398  DNSResourceRecord rr;
1399  for(int n=ipparts.size()-1; n>=0 ; --n) {
1400    rr.qname.append(ipparts[n]);
1401    rr.qname.append(1,'.');
1402  }
1403  rr.qname.append("in-addr.arpa.");
1404
1405  rr.d_place=DNSResourceRecord::ANSWER;
1406  rr.ttl=86400;
1407  rr.qtype=QType::SOA;
1408  rr.content="localhost. root. 1 604800 86400 2419200 604800";
1409 
1410  ad.d_records.insert(rr);
1411
1412  rr.qtype=QType::NS;
1413  rr.content="localhost.";
1414
1415  ad.d_records.insert(rr);
1416  rr.qtype=QType::PTR;
1417
1418  if(ipparts.size()==4)  // otherwise this is a partial zone
1419    for(unsigned int n=1; n < parts.size(); ++n) {
1420      rr.content=toCanonic("", parts[n]);
1421      ad.d_records.insert(rr);
1422    }
1423
1424  if(SyncRes::s_domainmap.count(rr.qname)) {
1425    L<<Logger::Warning<<"Will not overwrite zone '"<<rr.qname<<"' already loaded"<<endl;
1426  }
1427  else {
1428    if(ipparts.size()==4)
1429      L<<Logger::Warning<<"Inserting reverse zone '"<<rr.qname<<"' based on hosts file"<<endl;
1430    SyncRes::s_domainmap[rr.qname]=ad;
1431  }
1432}
1433
1434
1435void parseAuthAndForwards();
1436
1437void convertServersForAD(const std::string& input, SyncRes::AuthDomain& ad, const char* sepa, bool verbose=true)
1438{
1439  vector<string> servers;
1440  stringtok(servers, input, sepa);
1441  ad.d_servers.clear();
1442  for(vector<string>::const_iterator iter = servers.begin(); iter != servers.end(); ++iter) {
1443    if(verbose && iter != servers.begin()) 
1444      L<<", ";
1445    pair<string,string> ipport=splitField(*iter, ':');
1446    ComboAddress addr(ipport.first, ipport.second.empty() ? 53 : lexical_cast<uint16_t>(ipport.second));
1447    if(verbose)
1448      L<<addr.toStringWithPort();
1449    ad.d_servers.push_back(addr);
1450  }
1451  if(verbose)
1452    L<<endl;
1453}
1454
1455string reloadAuthAndForwards()
1456{
1457  SyncRes::domainmap_t original=SyncRes::s_domainmap;
1458 
1459  try {
1460    L<<Logger::Warning<<"Reloading zones, purging data from cache"<<endl;
1461 
1462    for(SyncRes::domainmap_t::const_iterator i = SyncRes::s_domainmap.begin(); i != SyncRes::s_domainmap.end(); ++i) {
1463      for(SyncRes::AuthDomain::records_t::const_iterator j = i->second.d_records.begin(); j != i->second.d_records.end(); ++j) 
1464        RC.doWipeCache(j->qname);
1465    }
1466
1467    string configname=::arg()["config-dir"]+"/recursor.conf";
1468    cleanSlashes(configname);
1469   
1470    if(!::arg().preParseFile(configname.c_str(), "forward-zones")) 
1471      L<<Logger::Warning<<"Unable to re-parse configuration file '"<<configname<<"'"<<endl;
1472   
1473    ::arg().preParseFile(configname.c_str(), "auth-zones");
1474    ::arg().preParseFile(configname.c_str(), "export-etc-hosts");
1475    ::arg().preParseFile(configname.c_str(), "serve-rfc1918");
1476   
1477    parseAuthAndForwards();
1478   
1479    // purge again - new zones need to blank out the cache
1480    for(SyncRes::domainmap_t::const_iterator i = SyncRes::s_domainmap.begin(); i != SyncRes::s_domainmap.end(); ++i) {
1481      for(SyncRes::AuthDomain::records_t::const_iterator j = i->second.d_records.begin(); j != i->second.d_records.end(); ++j) 
1482        RC.doWipeCache(j->qname);
1483    }
1484
1485    // this is pretty blunt
1486    SyncRes::s_negcache.clear(); 
1487    return "ok\n";
1488  }
1489  catch(std::exception& e) {
1490    L<<Logger::Error<<"Had error reloading zones, keeping original data: "<<e.what()<<endl;
1491  }
1492  catch(AhuException& ae) {
1493    L<<Logger::Error<<"Encountered error reloading zones, keeping original data: "<<ae.reason<<endl;
1494  }
1495  catch(...) {
1496    L<<Logger::Error<<"Encountered unknown error reloading zones, keeping original data"<<endl;
1497  }
1498  SyncRes::s_domainmap.swap(original);
1499  return "reloading failed, see log\n";
1500}
1501
1502void parseAuthAndForwards()
1503{
1504  SyncRes::s_domainmap.clear(); // this makes us idempotent
1505
1506  TXTRecordContent::report();
1507  OPTRecordContent::report();
1508
1509  typedef vector<string> parts_t;
1510  parts_t parts; 
1511  for(int n=0; n < 2 ; ++n ) {
1512    parts.clear();
1513    stringtok(parts, ::arg()[n ? "forward-zones" : "auth-zones"], ",\t\n\r");
1514    for(parts_t::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) {
1515      SyncRes::AuthDomain ad;
1516      pair<string,string> headers=splitField(*iter, '=');
1517      trim(headers.first);
1518      trim(headers.second);
1519      headers.first=toCanonic("", headers.first);
1520      if(n==0) {
1521        L<<Logger::Error<<"Parsing authoritative data for zone '"<<headers.first<<"' from file '"<<headers.second<<"'"<<endl;
1522        ZoneParserTNG zpt(headers.second, headers.first);
1523        DNSResourceRecord rr;
1524        while(zpt.get(rr)) {
1525          try {
1526            string tmp=DNSRR2String(rr);
1527            rr=String2DNSRR(rr.qname, rr.qtype, tmp, rr.ttl);
1528          }
1529          catch(std::exception &e) {
1530            throw AhuException("Error parsing record '"+rr.qname+"' of type "+rr.qtype.getName()+" in zone '"+headers.first+"' from file '"+headers.second+"': "+e.what());
1531          }
1532          catch(...) {
1533            throw AhuException("Error parsing record '"+rr.qname+"' of type "+rr.qtype.getName()+" in zone '"+headers.first+"' from file '"+headers.second+"'");
1534          }
1535
1536          ad.d_records.insert(rr);
1537
1538        }
1539      }
1540      else {
1541        L<<Logger::Error<<"Redirecting queries for zone '"<<headers.first<<"' to: ";
1542        convertServersForAD(headers.second, ad, ";");
1543      }
1544     
1545      SyncRes::s_domainmap[headers.first]=ad;
1546    }
1547  }
1548 
1549  if(!::arg()["forward-zones-file"].empty()) {
1550    L<<Logger::Warning<<"Reading zone forwarding information from '"<<::arg()["forward-zones-file"]<<"'"<<endl;
1551    SyncRes::AuthDomain ad;
1552    FILE *rfp=fopen(::arg()["forward-zones-file"].c_str(), "r");
1553
1554    if(!rfp)
1555      throw AhuException("Error opening forward-zones-file '"+::arg()["forward-zones-file"]+"': "+stringerror());
1556
1557    shared_ptr<FILE> fp=shared_ptr<FILE>(rfp, fclose);
1558   
1559    char line[1024];
1560    int linenum=0;
1561    uint64_t before = SyncRes::s_domainmap.size();
1562    while(linenum++, fgets(line, sizeof(line)-1, fp.get())) {
1563      string domain, instructions;
1564      tie(domain, instructions)=splitField(line, '=');
1565      trim(domain);
1566      trim(instructions);
1567
1568      if(domain.empty()) 
1569        throw AhuException("Error parsing line "+lexical_cast<string>(linenum)+" of " +::arg()["forward-zones-file"]);
1570
1571      try {
1572        convertServersForAD(instructions, ad, ",; ", false);
1573      }
1574      catch(...) {
1575        throw AhuException("Conversion error parsing line "+lexical_cast<string>(linenum)+" of " +::arg()["forward-zones-file"]);
1576      }
1577
1578      SyncRes::s_domainmap[toCanonic("", domain)]=ad;
1579    }
1580    L<<Logger::Warning<<"Done parsing " << SyncRes::s_domainmap.size() - before<<" forwarding instructions from file '"<<::arg()["forward-zones-file"]<<"'"<<endl;
1581  }
1582
1583  if(::arg().mustDo("export-etc-hosts")) {
1584    string line;
1585    string fname;
1586   
1587    ifstream ifs("/etc/hosts");
1588    if(!ifs) {
1589      L<<Logger::Warning<<"Could not open /etc/hosts for reading"<<endl;
1590      return;
1591    }
1592   
1593    string::size_type pos;
1594    while(getline(ifs,line)) {
1595      pos=line.find('#');
1596      if(pos!=string::npos)
1597        line.resize(pos);
1598      trim(line);
1599      if(line.empty())
1600        continue;
1601      parts.clear();
1602      stringtok(parts, line, "\t\r\n ");
1603      if(parts[0].find(':')!=string::npos)
1604        continue;
1605     
1606      for(unsigned int n=1; n < parts.size(); ++n)
1607        makeNameToIPZone(parts[n], parts[0]);
1608      makeIPToNamesZone(parts);
1609    }
1610  }
1611  if(::arg().mustDo("serve-rfc1918")) {
1612    L<<Logger::Warning<<"Inserting rfc 1918 private space zones"<<endl;
1613    parts.clear();
1614    parts.push_back("127");
1615    makeIPToNamesZone(parts);
1616    parts[0]="10";
1617    makeIPToNamesZone(parts);
1618
1619    parts[0]="192.168";
1620    makeIPToNamesZone(parts);
1621    for(int n=16; n < 32; n++) {
1622      parts[0]="172."+lexical_cast<string>(n);
1623      makeIPToNamesZone(parts);
1624    }
1625  }
1626}
1627
1628string doReloadLuaScript(vector<string>::const_iterator begin, vector<string>::const_iterator end)
1629{
1630  string fname=::arg()["lua-dns-script"];
1631  try {
1632    if(begin==end) {
1633      if(!fname.empty()) 
1634        g_pdl = shared_ptr<PowerDNSLua>(new PowerDNSLua(fname));
1635      else
1636        throw runtime_error("Asked to relead lua scripts, but no name passed and no default ('lua-dns-script') defined");
1637    }
1638    else {
1639      fname=*begin;
1640      if(fname.empty()) {
1641        g_pdl.reset();
1642        L<<Logger::Error<<"Unloaded current lua script"<<endl;
1643        return "unloaded current lua script\n";
1644      }
1645      else {
1646        g_pdl = shared_ptr<PowerDNSLua>(new PowerDNSLua(fname));
1647        ::arg().set("lua-dns-script")=fname;
1648      }
1649    }
1650  }
1651  catch(std::exception& e) {
1652    L<<Logger::Error<<"Retaining current script, error from '"<<fname<<"': "<< e.what() <<endl;
1653    return string("Retaining current script, error from '"+fname+"': "+string(e.what())+"\n");
1654  }
1655  L<<Logger::Warning<<"(Re)loaded lua script from '"<<fname<<"'"<<endl;
1656  return "ok - loaded script from '"+fname+"'\n";
1657}
1658
1659
1660
1661int serviceMain(int argc, char*argv[])
1662{
1663  L.setName("pdns_recursor");
1664
1665  L.setLoglevel((Logger::Urgency)(6)); // info and up
1666
1667  if(!::arg()["logging-facility"].empty()) {
1668    boost::optional<int> val=logFacilityToLOG(::arg().asNum("logging-facility") );
1669    if(val)
1670      theL().setFacility(*val);
1671    else
1672      L<<Logger::Error<<"Unknown logging facility "<<::arg().asNum("logging-facility") <<endl;
1673  }
1674
1675  L<<Logger::Warning<<"PowerDNS recursor "<<VERSION<<" (C) 2001-2008 PowerDNS.COM BV ("<<__DATE__", "__TIME__;
1676#ifdef __GNUC__
1677  L<<", gcc "__VERSION__;
1678#endif // add other compilers here
1679#ifdef _MSC_VER
1680  L<<", MSVC "<<_MSC_VER;
1681#endif
1682  L<<") starting up"<<endl;
1683 
1684  L<<Logger::Warning<<"PowerDNS comes with ABSOLUTELY NO WARRANTY. "
1685    "This is free software, and you are welcome to redistribute it "
1686    "according to the terms of the GPL version 2."<<endl;
1687 
1688  L<<Logger::Warning<<"Operating in "<<(sizeof(unsigned long)*8) <<" bits mode"<<endl;
1689 
1690  seedRandom(::arg()["entropy-source"]);
1691
1692  if(!::arg()["allow-from-file"].empty()) {
1693    string line;
1694    g_allowFrom=new NetmaskGroup;
1695    ifstream ifs(::arg()["allow-from-file"].c_str());
1696    if(!ifs) {
1697        throw AhuException("Could not open '"+::arg()["allow-from-file"]+"': "+stringerror());
1698    }
1699
1700    string::size_type pos;
1701    while(getline(ifs,line)) {
1702      pos=line.find('#');
1703      if(pos!=string::npos)
1704        line.resize(pos);
1705      trim(line);
1706      if(line.empty())
1707        continue;
1708
1709      g_allowFrom->addMask(line);
1710    }
1711    L<<Logger::Warning<<"Done parsing " << g_allowFrom->size() <<" allow-from ranges from file '"<<::arg()["allow-from-file"]<<"' - overriding 'allow-from' setting"<<endl;
1712  }
1713  else if(!::arg()["allow-from"].empty()) {
1714    g_allowFrom=new NetmaskGroup;
1715    vector<string> ips;
1716    stringtok(ips, ::arg()["allow-from"], ", ");
1717    L<<Logger::Warning<<"Only allowing queries from: ";
1718    for(vector<string>::const_iterator i = ips.begin(); i!= ips.end(); ++i) {
1719      g_allowFrom->addMask(*i);
1720      if(i!=ips.begin())
1721        L<<Logger::Warning<<", ";
1722      L<<Logger::Warning<<*i;
1723    }
1724    L<<Logger::Warning<<endl;
1725  }
1726  else if(::arg()["local-address"]!="127.0.0.1" && ::arg().asNum("local-port")==53)
1727    L<<Logger::Error<<"WARNING: Allowing queries from all IP addresses - this can be a security risk!"<<endl;
1728 
1729
1730  if(!::arg()["dont-query"].empty()) {
1731    g_dontQuery=new NetmaskGroup;
1732    vector<string> ips;
1733    stringtok(ips, ::arg()["dont-query"], ", ");
1734    L<<Logger::Warning<<"Will not send queries to: ";
1735    for(vector<string>::const_iterator i = ips.begin(); i!= ips.end(); ++i) {
1736      g_dontQuery->addMask(*i);
1737      if(i!=ips.begin())
1738        L<<Logger::Warning<<", ";
1739      L<<Logger::Warning<<*i;
1740    }
1741    L<<Logger::Warning<<endl;
1742  }
1743
1744  g_quiet=::arg().mustDo("quiet");
1745  if(::arg().mustDo("trace")) {
1746    SyncRes::setLog(true);
1747    ::arg().set("quiet")="no";
1748    g_quiet=false;
1749  }
1750
1751  RC.d_followRFC2181=::arg().mustDo("auth-can-lower-ttl");
1752 
1753  if(!::arg()["query-local-address6"].empty()) {
1754    SyncRes::s_doIPv6=true;
1755    L<<Logger::Error<<"Enabling IPv6 transport for outgoing queries"<<endl;
1756  }
1757 
1758  SyncRes::s_maxnegttl=::arg().asNum("max-negative-ttl");
1759  SyncRes::s_serverID=::arg()["server-id"];
1760  if(SyncRes::s_serverID.empty()) {
1761    char tmp[128];
1762    gethostname(tmp, sizeof(tmp)-1);
1763    SyncRes::s_serverID=tmp;
1764  }
1765 
1766  parseAuthAndForwards();
1767
1768  try {
1769    if(!::arg()["lua-dns-script"].empty()) {
1770      g_pdl = shared_ptr<PowerDNSLua>(new PowerDNSLua(::arg()["lua-dns-script"]));
1771      L<<Logger::Warning<<"Loaded 'lua' script from '"<<::arg()["lua-dns-script"]<<"'"<<endl;
1772    }
1773   
1774  }
1775  catch(std::exception &e) {
1776    L<<Logger::Error<<"Failed to load 'lua' script from '"<<::arg()["lua-dns-script"]<<"': "<<e.what()<<endl;
1777    exit(99);
1778  }
1779
1780 
1781  g_stats.remotes.resize(::arg().asNum("remotes-ringbuffer-entries"));
1782  if(!g_stats.remotes.empty())
1783    memset(&g_stats.remotes[0], 0, g_stats.remotes.size() * sizeof(RecursorStats::remotes_t::value_type));
1784  g_logCommonErrors=::arg().mustDo("log-common-errors");
1785 
1786  makeUDPServerSockets();
1787  makeTCPServerSockets();
1788
1789  s_pidfname=::arg()["socket-dir"]+"/"+s_programname+".pid";
1790  if(!s_pidfname.empty())
1791    unlink(s_pidfname.c_str()); // remove possible old pid file
1792 
1793#ifndef WIN32
1794  if(::arg().mustDo("fork")) {
1795    fork();
1796    L<<Logger::Warning<<"This is forked pid "<<getpid()<<endl;
1797  }
1798#endif
1799 
1800  MT=new MTasker<PacketID,string>(::arg().asNum("stack-size"));
1801  PacketID pident;
1802  primeHints();   
1803  L<<Logger::Warning<<"Done priming cache with root hints"<<endl;
1804#ifndef WIN32
1805  if(::arg().mustDo("daemon")) {
1806    L<<Logger::Warning<<"Calling daemonize, going to background"<<endl;
1807    L.toConsole(Logger::Critical);
1808    daemonize();
1809  }
1810  signal(SIGUSR1,usr1Handler);
1811  signal(SIGUSR2,usr2Handler);
1812  signal(SIGPIPE,SIG_IGN);
1813  writePid();
1814#endif
1815  makeControlChannelSocket();       
1816  g_fdm=getMultiplexer();
1817 
1818  for(deferredAdd_t::const_iterator i=deferredAdd.begin(); i!=deferredAdd.end(); ++i) 
1819    g_fdm->addReadFD(i->first, i->second);
1820 
1821  int newgid=0;
1822  if(!::arg()["setgid"].empty())
1823    newgid=Utility::makeGidNumeric(::arg()["setgid"]);
1824  int newuid=0;
1825  if(!::arg()["setuid"].empty())
1826    newuid=Utility::makeUidNumeric(::arg()["setuid"]);
1827 
1828#ifndef WIN32
1829  if (!::arg()["chroot"].empty()) {
1830    if (chroot(::arg()["chroot"].c_str())<0 || chdir("/") < 0) {
1831      L<<Logger::Error<<"Unable to chroot to '"+::arg()["chroot"]+"': "<<strerror (errno)<<", exiting"<<endl;
1832      exit(1);
1833    }
1834  }
1835 
1836  Utility::dropPrivs(newuid, newgid);
1837  g_fdm->addReadFD(s_rcc.d_fd, handleRCC); // control channel
1838#endif
1839 
1840  counter=0;
1841  unsigned int maxTcpClients=::arg().asNum("max-tcp-clients");
1842  g_tcpTimeout=::arg().asNum("client-tcp-timeout");
1843 
1844  g_maxTCPPerClient=::arg().asNum("max-tcp-per-client");
1845 
1846 
1847  bool listenOnTCP(true);
1848 
1849  for(;;) {
1850    while(MT->schedule(g_now.tv_sec)); // housekeeping, let threads do their thing
1851     
1852    if(!(counter%500)) {
1853      MT->makeThread(houseKeeping,0);
1854    }
1855
1856    if(!(counter%55)) {
1857      typedef vector<pair<int, FDMultiplexer::funcparam_t> > expired_t;
1858      expired_t expired=g_fdm->getTimeouts(g_now);
1859       
1860      for(expired_t::iterator i=expired.begin() ; i != expired.end(); ++i) {
1861        TCPConnection conn=any_cast<TCPConnection>(i->second);
1862        if(g_logCommonErrors)
1863          L<<Logger::Warning<<"Timeout from remote TCP client "<< conn.remote.toString() <<endl;
1864        g_fdm->removeReadFD(i->first);
1865        conn.closeAndCleanup();
1866      }
1867    }
1868     
1869    counter++;
1870
1871    if(statsWanted) {
1872      doStats();
1873    }
1874
1875    Utility::gettimeofday(&g_now, 0);
1876    g_fdm->run(&g_now);
1877    Utility::gettimeofday(&g_now, 0);
1878
1879    if(listenOnTCP) {
1880      if(TCPConnection::s_currentConnections > maxTcpClients) {  // shutdown
1881        for(g_tcpListenSockets_t::iterator i=g_tcpListenSockets.begin(); i != g_tcpListenSockets.end(); ++i)
1882          g_fdm->removeReadFD(*i);
1883        listenOnTCP=false;
1884      }
1885    }
1886    else {
1887      if(TCPConnection::s_currentConnections <= maxTcpClients) {  // reenable
1888        for(g_tcpListenSockets_t::iterator i=g_tcpListenSockets.begin(); i != g_tcpListenSockets.end(); ++i)
1889          g_fdm->addReadFD(*i, handleNewTCPQuestion);
1890        listenOnTCP=true;
1891      }
1892    }
1893  }
1894}
1895#ifdef WIN32
1896void doWindowsServiceArguments(RecursorService& recursor)
1897{
1898  if(::arg().mustDo( "register-service" )) {
1899    if ( !recursor.registerService( "The PowerDNS Recursor.", true )) {
1900      cerr << "Could not register service." << endl;
1901      exit( 99 );
1902    }
1903   
1904    exit( 0 );
1905  }
1906
1907  if ( ::arg().mustDo( "unregister-service" )) {
1908    recursor.unregisterService();
1909    exit( 0 );
1910  }
1911}
1912#endif
1913
1914
1915int main(int argc, char **argv) 
1916{
1917  //  HTimer mtimer("main");
1918  //  mtimer.start();
1919
1920
1921  g_stats.startupTime=time(0);
1922  reportBasicTypes();
1923
1924  int ret = EXIT_SUCCESS;
1925#ifdef WIN32
1926  RecursorService service;
1927  WSADATA wsaData;
1928  if(WSAStartup( MAKEWORD( 2, 2 ), &wsaData )) {
1929    cerr<<"Unable to initialize winsock\n";
1930    exit(1);
1931  }
1932#endif // WIN32
1933
1934  try {
1935    ::arg().set("stack-size","stack size per mthread")="200000";
1936    ::arg().set("soa-minimum-ttl","Don't change")="0";
1937    ::arg().set("soa-serial-offset","Don't change")="0";
1938    ::arg().set("no-shuffle","Don't change")="off";
1939    ::arg().set("aaaa-additional-processing","turn on to do AAAA additional processing (slow)")="off";
1940    ::arg().set("local-port","port to listen on")="53";
1941    ::arg().set("local-address","IP addresses to listen on, separated by spaces or commas. Also accepts ports.")="127.0.0.1";
1942    ::arg().set("trace","if we should output heaps of logging")="off";
1943    ::arg().set("daemon","Operate as a daemon")="yes";
1944    ::arg().set("log-common-errors","If we should log rather common errors")="yes";
1945    ::arg().set("chroot","switch to chroot jail")="";
1946    ::arg().set("setgid","If set, change group id to this gid for more security")="";
1947    ::arg().set("setuid","If set, change user id to this uid for more security")="";
1948#ifdef WIN32
1949    ::arg().set("quiet","Suppress logging of questions and answers")="off";
1950    ::arg().setSwitch( "register-service", "Register the service" )= "no";
1951    ::arg().setSwitch( "unregister-service", "Unregister the service" )= "no";
1952    ::arg().setSwitch( "ntservice", "Run as service" )= "no";
1953    ::arg().setSwitch( "use-ntlog", "Use the NT logging facilities" )= "yes"; 
1954    ::arg().setSwitch( "use-logfile", "Use a log file" )= "no"; 
1955    ::arg().setSwitch( "logfile", "Filename of the log file" )= "recursor.log"; 
1956#else
1957    ::arg().set("quiet","Suppress logging of questions and answers")="";
1958    ::arg().set("logging-facility","Facility to log messages as. 0 corresponds to local0")="";
1959#endif
1960    ::arg().set("config-dir","Location of configuration directory (recursor.conf)")=SYSCONFDIR;
1961#ifndef WIN32
1962    ::arg().set("socket-owner","Owner of socket")="";
1963    ::arg().set("socket-group","Group of socket")="";
1964    ::arg().set("socket-mode", "Permissions for socket")="";
1965#endif
1966   
1967    ::arg().set("socket-dir","Where the controlsocket will live")=LOCALSTATEDIR;
1968    ::arg().set("delegation-only","Which domains we only accept delegations from")="";
1969    ::arg().set("query-local-address","Source IP address for sending queries")="0.0.0.0";
1970    ::arg().set("query-local-address6","Source IPv6 address for sending queries")="";
1971    ::arg().set("client-tcp-timeout","Timeout in seconds when talking to TCP clients")="2";
1972    ::arg().set("max-tcp-clients","Maximum number of simultaneous TCP clients")="128";
1973    ::arg().set("hint-file", "If set, load root hints from this file")="";
1974    ::arg().set("max-cache-entries", "If set, maximum number of entries in the main cache")="0";
1975    ::arg().set("max-negative-ttl", "maximum number of seconds to keep a negative cached entry in memory")="3600";
1976    ::arg().set("server-id", "Returned when queried for 'server.id' TXT or NSID, defaults to hostname")="";
1977    ::arg().set("remotes-ringbuffer-entries", "maximum number of packets to store statistics for")="0";
1978    ::arg().set("version-string", "string reported on version.pdns or version.bind")="PowerDNS Recursor "VERSION" $Id$";
1979    ::arg().set("allow-from", "If set, only allow these comma separated netmasks to recurse")="127.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, ::1/128, fe80::/10";
1980    ::arg().set("allow-from-file", "If set, load allowed netmasks from this file")="";
1981    ::arg().set("entropy-source", "If set, read entropy from this file")="/dev/urandom";
1982    ::arg().set("dont-query", "If set, do not query these netmasks for DNS data")="127.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, ::1/128, fe80::/10";
1983    ::arg().set("max-tcp-per-client", "If set, maximum number of TCP sessions per client (IP address)")="0";
1984    ::arg().set("fork", "If set, fork the daemon for possible double performance")="no";
1985    ::arg().set("spoof-nearmiss-max", "If non-zero, assume spoofing after this many near misses")="20";
1986    ::arg().set("single-socket", "If set, only use a single socket for outgoing queries")="off";
1987    ::arg().set("auth-zones", "Zones for which we have authoritative data, comma separated domain=file pairs ")="";
1988    ::arg().set("forward-zones", "Zones for which we forward queries, comma separated domain=ip pairs")="";
1989    ::arg().set("forward-zones-file", "File with domain=ip pairs for forwarding")="";
1990    ::arg().set("export-etc-hosts", "If we should serve up contents from /etc/hosts")="off";
1991    ::arg().set("serve-rfc1918", "If we should be authoritative for RFC 1918 private IP space")="";
1992    ::arg().set("auth-can-lower-ttl", "If we follow RFC 2181 to the letter, an authoritative server can lower the TTL of NS records")="off";
1993    ::arg().set("lua-dns-script", "Filename containing an optional 'lua' script that will be used to modify dns answers")="";
1994    ::arg().setSwitch( "ignore-rd-bit", "Assume each packet requires recursion, for compatability" )= "off"; 
1995
1996    ::arg().setCmd("help","Provide a helpful message");
1997    ::arg().setCmd("version","Print version string ("VERSION")");
1998    ::arg().setCmd("config","Output blank configuration");
1999    L.toConsole(Logger::Info);
2000    ::arg().laxParse(argc,argv); // do a lax parse
2001
2002    string configname=::arg()["config-dir"]+"/recursor.conf";
2003    cleanSlashes(configname);
2004
2005    if(!::arg().file(configname.c_str())) 
2006      L<<Logger::Warning<<"Unable to parse configuration file '"<<configname<<"'"<<endl;
2007
2008    ::arg().parse(argc,argv);
2009
2010    ::arg().set("delegation-only")=toLower(::arg()["delegation-only"]);
2011
2012    if(::arg().mustDo("help")) {
2013      cerr<<"syntax:"<<endl<<endl;
2014      cerr<<::arg().helpstring(::arg()["help"])<<endl;
2015      exit(99);
2016    }
2017    if(::arg().mustDo("version")) {
2018      cerr<<"version: "VERSION<<endl;
2019      exit(99);
2020    }
2021
2022    if(::arg().mustDo("config")) {
2023      cout<<::arg().configstring()<<endl;
2024      exit(0);
2025    }
2026
2027
2028#ifndef WIN32
2029    serviceMain(argc, argv);
2030#else
2031    doWindowsServiceArguments(service);
2032        L.toNTLog();
2033    RecursorService::instance()->start( argc, argv, ::arg().mustDo( "ntservice" )); 
2034#endif
2035
2036  }
2037  catch(AhuException &ae) {
2038    L<<Logger::Error<<"Exception: "<<ae.reason<<endl;
2039    ret=EXIT_FAILURE;
2040  }
2041  catch(std::exception &e) {
2042    L<<Logger::Error<<"STL Exception: "<<e.what()<<endl;
2043    ret=EXIT_FAILURE;
2044  }
2045  catch(...) {
2046    L<<Logger::Error<<"any other exception in main: "<<endl;
2047    ret=EXIT_FAILURE;
2048  }
2049 
2050#ifdef WIN32
2051  WSACleanup();
2052#endif // WIN32
2053
2054  return ret;
2055}
Note: See TracBrowser for help on using the browser.