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

Revision 190, 17.9 KB (checked in by ahu, 10 years ago)

pdns_recursor static build fix, docs

  • 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) 2002  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 as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18*/
19
20#include "utility.hh"
21#include <iostream>
22#include <errno.h>
23#include <map>
24#include <set>
25#ifndef WIN32
26#include <netdb.h>
27#endif // WIN32
28#include <stdio.h>
29#include <signal.h>
30#include <stdlib.h>
31#include <unistd.h>
32#include "mtasker.hh"
33#include <utility>
34#include "dnspacket.hh"
35#include "statbag.hh"
36#include "arguments.hh"
37#include "syncres.hh"
38#include <fcntl.h>
39#include <fstream>
40
41string s_programname="pdns_recursor";
42
43#ifndef WIN32
44extern "C" {
45  int sem_init(sem_t*, int, unsigned int){return 0;}
46  int sem_wait(sem_t*){return 0;}
47  int sem_trywait(sem_t*){return 0;}
48  int sem_post(sem_t*){return 0;}
49  int sem_getvalue(sem_t*, int*){return 0;}
50  pthread_t pthread_self(void){return (pthread_t) 0;}
51  int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr){ return 0; }
52  int pthread_mutex_lock(pthread_mutex_t *mutex){ return 0; }
53  int pthread_mutex_unlock(pthread_mutex_t *mutex) { return 0; }
54
55}
56#endif // WIN32
57
58StatBag S;
59ArgvMap &arg()
60{
61  static ArgvMap theArg;
62  return theArg;
63}
64int d_clientsock;
65int d_serversock;
66int d_tcpserversock;
67
68struct PacketID
69{
70  u_int16_t id;
71  struct sockaddr_in remote;
72};
73
74bool operator<(const PacketID& a, const PacketID& b)
75{
76  if(a.id<b.id)
77    return true;
78
79  if(a.id==b.id) {
80    if(a.remote.sin_addr.s_addr < b.remote.sin_addr.s_addr)
81      return true;
82    if(a.remote.sin_addr.s_addr == b.remote.sin_addr.s_addr)
83      if(a.remote.sin_port < b.remote.sin_port)
84        return true;
85  }
86
87  return false;
88}
89
90MTasker<PacketID,string>* MT;
91
92/* these two functions are used by LWRes */
93int asendto(const char *data, int len, int flags, struct sockaddr *toaddr, int addrlen, int id) 
94{
95  return sendto(d_clientsock, data, len, flags, toaddr, addrlen);
96}
97
98int arecvfrom(char *data, int len, int flags, struct sockaddr *toaddr, Utility::socklen_t *addrlen, int *d_len, int id)
99{
100  PacketID pident;
101  pident.id=id;
102  memcpy(&pident.remote,toaddr,sizeof(pident.remote));
103
104  string packet;
105  if(!MT->waitEvent(pident,&packet,1)) { // timeout
106    return 0; 
107  }
108
109  *d_len=packet.size();
110  memcpy(data,packet.c_str(),min(len,*d_len));
111
112  return 1;
113}
114
115typedef map<string,set<DNSResourceRecord> > cache_t;
116static cache_t cache;
117int cacheHits, cacheMisses;
118int getCache(const string &qname, const QType& qt, set<DNSResourceRecord>* res)
119{
120  cache_t::const_iterator j=cache.find(toLower(qname)+"|"+qt.getName());
121  if(j!=cache.end() && j->first==toLower(qname)+"|"+qt.getName() && j->second.begin()->ttl>(unsigned int)time(0)) {
122    if(res)
123      *res=j->second;
124
125    return (unsigned int)j->second.begin()->ttl-time(0);
126  }
127
128  return -1;
129}
130
131void replaceCache(const string &qname, const QType& qt,  const set<DNSResourceRecord>& content)
132{
133  cache[toLower(qname)+"|"+qt.getName()]=content;
134}
135
136void doPrune(void)
137{
138  unsigned int names=0, records=0;
139
140  for(cache_t::iterator j=cache.begin();j!=cache.end();){
141    for(set<DNSResourceRecord>::iterator k=j->second.begin();k!=j->second.end();) 
142      if((unsigned int)k->ttl < (unsigned int)time(0)) {
143        j->second.erase(k++);
144        records++;
145      }
146      else
147        ++k;
148
149    if(j->second.empty()) { // everything is gone
150      cache.erase(j++);
151      names++;
152
153    }
154    else {
155      ++j;
156    }
157  }
158}
159
160
161static void writePid(void)
162{
163  string fname=arg()["socket-dir"]+"/"+s_programname+".pid";
164  ofstream of(fname.c_str());
165  if(of)
166    of<<getpid()<<endl;
167  else
168    L<<Logger::Error<<"Requested to write pid for "<<getpid()<<" to "<<fname<<" failed: "<<strerror(errno)<<endl;
169}
170
171void init(void)
172{
173  // prime root cache
174  static char*ips[]={"198.41.0.4", "128.9.0.107", "192.33.4.12", "128.8.10.90", "192.203.230.10", "192.5.5.241", "192.112.36.4", "128.63.2.53", 
175                     "192.36.148.17","192.58.128.30", "193.0.14.129", "198.32.64.12", "202.12.27.33"};
176  DNSResourceRecord arr, nsrr;
177  arr.qtype=QType::A;
178  arr.ttl=time(0)+3600000;
179  nsrr.qtype=QType::NS;
180  nsrr.ttl=time(0)+3600000;
181 
182  set<DNSResourceRecord>nsset;
183  for(char c='a';c<='m';++c) {
184    static char templ[40];
185    strncpy(templ,"a.root-servers.net", sizeof(templ) - 1);
186    *templ=c;
187    arr.qname=nsrr.content=templ;
188    arr.content=ips[c-'a'];
189    set<DNSResourceRecord>aset;
190    aset.insert(arr);
191    replaceCache(string(templ),QType(QType::A),aset);
192
193    nsset.insert(nsrr);
194  }
195  replaceCache("",QType(QType::NS),nsset);
196}
197
198void startDoResolve(void *p)
199{
200  try {
201    bool quiet=arg().mustDo("quiet");
202    DNSPacket P=*(DNSPacket *)p;
203
204    delete (DNSPacket *)p;
205
206    vector<DNSResourceRecord>ret;
207    DNSPacket *R=P.replyPacket();
208    R->setA(false);
209    R->setRA(true);
210
211    SyncRes sr;
212    if(!quiet)
213      L<<Logger::Error<<"["<<MT->getTid()<<"] question for '"<<P.qdomain<<"|"<<P.qtype.getName()<<"' from "<<P.getRemote()<<endl;
214
215    sr.setId(MT->getTid());
216    if(!P.d.rd)
217      sr.setCacheOnly();
218
219    int res=sr.beginResolve(P.qdomain, P.qtype, ret);
220    if(res<0)
221      R->setRcode(RCode::ServFail);
222    else {
223      R->setRcode(res);
224      for(vector<DNSResourceRecord>::const_iterator i=ret.begin();i!=ret.end();++i)
225        R->addRecord(*i);
226    }
227
228    const char *buffer=R->getData();
229    if(!R->getSocket())
230      sendto(d_serversock,buffer,R->len,0,(struct sockaddr *)(R->remote),R->d_socklen);
231    else {
232      char buf[2];
233      buf[0]=R->len/256;
234      buf[1]=R->len%256;
235      if(write(R->getSocket(),buf,2)!=2 || write(R->getSocket(),buffer,R->len)!=R->len)
236        L<<Logger::Error<<"Oops, partial answer sent to "<<P.getRemote()<<" - probably would have trouble receiving our answer anyhow (size="<<R->len<<")"<<endl;
237    }
238
239    if(!quiet) {
240      L<<Logger::Error<<"["<<MT->getTid()<<"] answer to "<<(P.d.rd?"":"non-rd ")<<"question '"<<P.qdomain<<"|"<<P.qtype.getName();
241      L<<"': "<<ntohs(R->d.ancount)<<" answers, "<<ntohs(R->d.arcount)<<" additional, took "<<sr.d_outqueries<<" packets, "<<
242        sr.d_throttledqueries<<" throttled, rcode="<<res<<endl;
243    }
244   
245    sr.d_outqueries ? cacheMisses++ : cacheHits++;
246
247    delete R;
248  }
249  catch(AhuException &ae) {
250    L<<Logger::Error<<"startDoResolve problem: "<<ae.reason<<endl;
251  }
252  catch(...) {
253    L<<Logger::Error<<"Any other exception in a resolver context"<<endl;
254  }
255}
256
257void makeClientSocket()
258{
259  d_clientsock=socket(AF_INET, SOCK_DGRAM,0);
260  if(d_clientsock<0) 
261    throw AhuException("Making a socket for resolver: "+stringerror());
262 
263  struct sockaddr_in sin;
264  memset((char *)&sin,0, sizeof(sin));
265 
266  sin.sin_family = AF_INET;
267  sin.sin_addr.s_addr = INADDR_ANY;
268 
269  int tries=10;
270  while(--tries) {
271    u_int16_t port=10000+Utility::random()%10000;
272    sin.sin_port = htons(port); 
273   
274    if (bind(d_clientsock, (struct sockaddr *)&sin, sizeof(sin)) >= 0) 
275      break;
276   
277  }
278  if(!tries)
279    throw AhuException("Resolver binding to local socket: "+stringerror());
280}
281
282void makeTCPServerSocket()
283{
284  d_tcpserversock=socket(AF_INET, SOCK_STREAM,0);
285  if(d_tcpserversock<0) 
286    throw AhuException("Making a server socket for resolver: "+stringerror());
287 
288  struct sockaddr_in sin;
289  memset((char *)&sin,0, sizeof(sin));
290 
291  sin.sin_family = AF_INET;
292
293  if(arg()["local-address"]=="0.0.0.0") {
294    sin.sin_addr.s_addr = INADDR_ANY;
295  }
296  else {
297    if(!IpToU32(arg()["local-address"], &sin.sin_addr.s_addr))
298      throw AhuException("Unable to resolve local address"); 
299  }
300
301  sin.sin_port = htons(arg().asNum("local-port")); 
302   
303  if (bind(d_tcpserversock, (struct sockaddr *)&sin, sizeof(sin))<0) 
304    throw AhuException("TCP Resolver binding to server socket: "+stringerror());
305 
306  int tmp=1;
307  if(setsockopt(d_tcpserversock,SOL_SOCKET,SO_REUSEADDR,(char*)&tmp,sizeof tmp)<0) {
308    L<<Logger::Error<<"Setsockopt failed"<<endl;
309    exit(1); 
310  }
311
312  listen(d_tcpserversock, 128);
313}
314
315void makeServerSocket()
316{
317  d_serversock=socket(AF_INET, SOCK_DGRAM,0);
318  if(d_serversock<0) 
319    throw AhuException("Making a server socket for resolver: "+stringerror());
320 
321  struct sockaddr_in sin;
322  memset((char *)&sin,0, sizeof(sin));
323 
324  sin.sin_family = AF_INET;
325
326  if(arg()["local-address"]=="0.0.0.0") {
327    L<<Logger::Warning<<"It is advised to bind to explicit addresses with the --local-address option"<<endl;
328    sin.sin_addr.s_addr = INADDR_ANY;
329  }
330  else {
331   
332    if(!IpToU32(arg()["local-address"], &sin.sin_addr.s_addr))
333      throw AhuException("Unable to resolve local address"); 
334
335  }
336
337  sin.sin_port = htons(arg().asNum("local-port")); 
338   
339  if (bind(d_serversock, (struct sockaddr *)&sin, sizeof(sin))<0) 
340    throw AhuException("Resolver binding to server socket: "+stringerror());
341  L<<Logger::Error<<"Incoming query source port: "<<arg().asNum("local-port")<<endl;
342}
343
344
345#ifndef WIN32
346void daemonize(void)
347{
348  if(fork())
349    exit(0); // bye bye
350 
351  setsid(); 
352
353  // cleanup open fds, but skip sockets
354  close(0);
355  close(1);
356  close(2);
357
358}
359#endif
360
361int counter, qcounter;
362bool statsWanted;
363
364void usr1Handler(int)
365{
366  statsWanted=true;
367}
368
369
370void doStats(void)
371{
372  if(qcounter) {
373    L<<Logger::Error<<"stats: "<<qcounter<<" questions, "<<cache.size()<<" cache entries, "<<SyncRes::s_negcache.size()<<" negative entries, "
374     <<(int)((cacheHits*100.0)/(cacheHits+cacheMisses))<<"% cache hits";
375    L<<Logger::Error<<", outpacket/query ratio "<<(int)(SyncRes::s_outqueries*100.0/SyncRes::s_queries)<<"%";
376    L<<Logger::Error<<", "<<(int)(SyncRes::s_throttledqueries*100.0/(SyncRes::s_outqueries+SyncRes::s_throttledqueries))<<"% throttled, "
377     <<SyncRes::s_nodelegated<<" no-delegation drops"<<endl;
378  }
379  statsWanted=false;
380}
381
382void houseKeeping(void *)
383{
384  static time_t last_stat, last_rootupdate, last_prune;
385
386  if(time(0)-last_stat>30) { 
387    doPrune();
388    last_prune=time(0);
389  }
390  if(time(0)-last_stat>1800) { 
391    doStats();
392    last_stat=time(0);
393  }
394  if(time(0)-last_rootupdate>7200) {
395    SyncRes sr;
396    vector<DNSResourceRecord>ret;
397
398    sr.setNoCache();
399    int res=sr.beginResolve("", QType(QType::NS), ret);
400    if(!res) {
401      L<<Logger::Error<<"Refreshed . records"<<endl;
402      last_rootupdate=time(0);
403    }
404    else
405      L<<Logger::Error<<"Failed to update . records, RCODE="<<res<<endl;
406  }
407}
408
409struct TCPConnection
410{
411  int fd;
412  enum {BYTE0, BYTE1, GETQUESTION} state;
413  int qlen;
414  int bytesread;
415  struct sockaddr_in remote;
416  char data[65535];
417};
418
419int main(int argc, char **argv) 
420{
421#ifdef WIN32
422    WSADATA wsaData;
423    WSAStartup( MAKEWORD( 2, 0 ), &wsaData );
424#endif // WIN32
425
426  try {
427    Utility::srandom(time(0));
428    arg().set("soa-minimum-ttl","Don't change")="0";
429    arg().set("soa-serial-offset","Don't change")="0";
430    arg().set("aaaa-additional-processing","turn on to do AAAA additional processing (slow)")="off";
431    arg().set("local-port","port to listen on")="53";
432    arg().set("local-address","port to listen on")="0.0.0.0";
433    arg().set("trace","if we should output heaps of logging")="off";
434    arg().set("daemon","Operate as a daemon")="yes";
435    arg().set("quiet","Suppress logging of questions and answers")="off";
436    arg().set("config-dir","Location of configuration directory (recursor.conf)")=SYSCONFDIR;
437    arg().set("socket-dir","Where the controlsocket will live")=LOCALSTATEDIR;
438    arg().set("delegation-only","Which domains we only accept delegations from")="";
439    arg().setCmd("help","Provide a helpful message");
440    L.toConsole(Logger::Warning);
441    arg().laxParse(argc,argv); // do a lax parse
442
443    string configname=arg()["config-dir"]+"/recursor.conf";
444    cleanSlashes(configname);
445
446    if(!arg().file(configname.c_str())) 
447      L<<Logger::Warning<<"Unable to parse configuration file '"<<configname<<"'"<<endl;
448
449    arg().parse(argc,argv);
450
451    arg().set("delegation-only")=toLower(arg()["delegation-only"]);
452
453    if(arg().mustDo("help")) {
454      cerr<<"syntax:"<<endl<<endl;
455      cerr<<arg().helpstring(arg()["help"])<<endl;
456      exit(99);
457    }
458
459    L.setName("pdns_recursor");
460
461    if(arg().mustDo("trace"))
462      SyncRes::setLog(true);
463   
464    makeClientSocket();
465    makeServerSocket();
466    makeTCPServerSocket();
467       
468    MT=new MTasker<PacketID,string>(100000);
469
470    char data[1500];
471    struct sockaddr_in fromaddr;
472   
473    PacketID pident;
474    init();   
475    L<<Logger::Warning<<"Done priming cache with root hints"<<endl;
476#ifndef WIN32
477    if(arg().mustDo("daemon")) {
478      L.toConsole(Logger::Critical);
479      daemonize();
480    }
481    signal(SIGUSR1,usr1Handler);
482
483    writePid();
484#endif
485
486    vector<TCPConnection> tcpconnections;
487    for(;;) {
488      while(MT->schedule()); // housekeeping, let threads do their thing
489     
490      if(!((counter++)%100)) 
491        MT->makeThread(houseKeeping,0);
492      if(statsWanted)
493        doStats();
494
495      Utility::socklen_t addrlen=sizeof(fromaddr);
496      int d_len;
497      DNSPacket P;
498     
499      struct timeval tv;
500      tv.tv_sec=0;
501      tv.tv_usec=500000;
502     
503      fd_set readfds;
504      FD_ZERO( &readfds );
505      FD_SET( d_clientsock, &readfds );
506      FD_SET( d_serversock, &readfds );
507      FD_SET( d_tcpserversock, &readfds );
508      int fdmax=max(d_tcpserversock,max(d_clientsock,d_serversock));
509      for(vector<TCPConnection>::const_iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) {
510        FD_SET(i->fd, &readfds);
511        fdmax=max(fdmax,i->fd);
512      }
513
514
515      /* this should listen on a TCP port as well for new connections,  */
516      int selret = select(  fdmax + 1, &readfds, NULL, NULL, &tv );
517      if(selret<=0) 
518        if (selret == -1 && errno!=EINTR) 
519          throw AhuException("Select returned: "+stringerror());
520        else
521          continue;
522
523      if(FD_ISSET(d_clientsock,&readfds)) { // do we have a question response?
524        d_len=recvfrom(d_clientsock, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen);   
525        if(d_len<0) 
526          continue;
527       
528        P.setRemote((struct sockaddr *)&fromaddr, addrlen);
529        if(P.parse(data,d_len)<0) {
530          L<<Logger::Error<<"Unparseable packet from remote server "<<P.getRemote()<<endl;
531        }
532        else { 
533          if(P.d.qr) {
534
535            pident.remote=fromaddr;
536            pident.id=P.d.id;
537            string packet;
538            packet.assign(data,d_len);
539            MT->sendEvent(pident,&packet);
540          }
541          else 
542            L<<Logger::Warning<<"Ignoring question on outgoing socket from "<<P.getRemote()<<endl;
543        }
544      }
545     
546      if(FD_ISSET(d_serversock,&readfds)) { // do we have a new question on udp?
547        d_len=recvfrom(d_serversock, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen);   
548        if(d_len<0) 
549          continue;
550        P.setRemote((struct sockaddr *)&fromaddr, addrlen);
551        if(P.parse(data,d_len)<0) {
552          L<<Logger::Error<<"Unparseable packet from remote client "<<P.getRemote()<<endl;
553        }
554        else { 
555          if(P.d.qr)
556            L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
557          else {
558            ++qcounter;
559            P.setSocket(0);
560            MT->makeThread(startDoResolve,(void*)new DNSPacket(P));
561
562          }
563        }
564      }
565
566      if(FD_ISSET(d_tcpserversock,&readfds)) { // do we have a new TCP connection
567        struct sockaddr_in addr;
568        socklen_t addrlen=sizeof(addr);
569        int newsock=accept(d_tcpserversock, (struct sockaddr*)&addr, &addrlen);
570        Utility::setNonBlocking(newsock);
571       
572        if(newsock>0) {
573          TCPConnection tc;
574          tc.fd=newsock;
575          tc.state=TCPConnection::BYTE0;
576          tc.remote=addr;
577          L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&tc.remote,sizeof(tc.remote))<<" connected"<<endl;
578          tcpconnections.push_back(tc);
579        }
580      }
581
582      for(vector<TCPConnection>::iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) {
583        if(FD_ISSET(i->fd, &readfds)) {
584          if(i->state==TCPConnection::BYTE0) {
585            int bytes=read(i->fd,i->data,2);
586            if(bytes==1)
587              i->state=TCPConnection::BYTE1;
588            if(bytes==2) { 
589              i->qlen=(i->data[0]<<8)+i->data[1];
590              i->bytesread=0;
591              i->state=TCPConnection::GETQUESTION;
592            }
593            if(!bytes || bytes < 0) {
594              L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected"<<endl;
595              close(i->fd);
596              tcpconnections.erase(i);
597              break;
598            }
599          }
600          else if(i->state==TCPConnection::BYTE1) {
601            int bytes=read(i->fd,i->data+1,1);
602            if(bytes==1) {
603              i->state=TCPConnection::GETQUESTION;
604              i->qlen=(i->data[0]<<8)+i->data[1];
605              i->bytesread=0;
606            }
607            if(!bytes || bytes < 0) {
608              L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected after first byte"<<endl;
609              close(i->fd);
610              tcpconnections.erase(i);
611              break;
612            }
613           
614          }
615          else if(i->state==TCPConnection::GETQUESTION) {
616            int bytes=read(i->fd,i->data + i->bytesread,i->qlen - i->bytesread);
617            if(!bytes || bytes < 0) {
618              L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected while reading question body"<<endl;
619              close(i->fd);
620              tcpconnections.erase(i);
621              break;
622            }
623            i->bytesread+=bytes;
624            if(i->bytesread==i->qlen) {
625              i->state=TCPConnection::BYTE0;
626
627              if(P.parse(i->data,i->qlen)<0) {
628                L<<Logger::Error<<"Unparseable packet from remote client "<<P.getRemote()<<endl;
629                close(i->fd);
630                tcpconnections.erase(i);
631                break;
632              }
633              else { 
634                P.setSocket(i->fd);
635                P.setRemote((struct sockaddr *)&i->remote,sizeof(i->remote));
636                if(P.d.qr)
637                  L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
638                else {
639                  ++qcounter;
640                  MT->makeThread(startDoResolve,(void*)new DNSPacket(P));
641                }
642              }
643            }
644          }
645        }
646      }
647    }
648  }
649  catch(AhuException &ae) {
650    L<<Logger::Error<<"Exception: "<<ae.reason<<endl;
651  }
652  catch(exception &e) {
653    L<<Logger::Error<<"STL Exception: "<<e.what()<<endl;
654  }
655  catch(...) {
656    L<<Logger::Error<<"any other exception in main: "<<endl;
657  }
658 
659#ifdef WIN32
660  WSACleanup();
661#endif // WIN32
662
663  return 0;
664}
Note: See TracBrowser for help on using the browser.