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

Revision 670, 33.2 KB (checked in by ahu, 7 years ago)

1) make everyting intrinsically case-insensitive
2) clear up . oddness, removing all calls to toLowerCanonic

  • 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 - 2006  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17*/
18
19#include "utility.hh"
20#include <iostream>
21#include <errno.h>
22#include <map>
23#include <set>
24#ifndef WIN32
25#include <netdb.h>
26#endif // WIN32
27#include "recursor_cache.hh"
28#include <stdio.h>
29#include <signal.h>
30#include <stdlib.h>
31#include <unistd.h>
32#include <netinet/tcp.h>
33#include "mtasker.hh"
34#include <utility>
35#include "arguments.hh"
36#include "syncres.hh"
37#include <fcntl.h>
38#include <fstream>
39#include "sstuff.hh"
40#include <boost/tuple/tuple.hpp>
41#include <boost/tuple/tuple_comparison.hpp>
42#include <boost/shared_array.hpp>
43#include <boost/lexical_cast.hpp>
44#include "dnsparser.hh"
45#include "dnswriter.hh"
46#include "dnsrecords.hh"
47#include "zoneparser-tng.hh"
48#include "rec_channel.hh"
49#include "logger.hh"
50#include "iputils.hh"
51
52#ifndef RECURSOR
53#include "statbag.hh"
54StatBag S;
55#endif
56
57
58using namespace boost;
59
60#ifdef __FreeBSD__           // see cvstrac ticket #26
61#include <pthread.h>
62#include <semaphore.h>
63#endif
64
65MemRecursorCache RC;
66RecursorStats g_stats;
67bool g_quiet;
68NetmaskGroup* g_allowFrom;
69string s_programname="pdns_recursor";
70
71struct DNSComboWriter {
72  DNSComboWriter(const char* data, uint16_t len, const struct timeval& now) : d_mdp(data, len), d_now(now), d_tcp(false), d_socket(-1)
73  {}
74  MOADNSParser d_mdp;
75  void setRemote(struct sockaddr* sa, socklen_t len)
76  {
77    memcpy((void *)d_remote, (void *)sa, len);
78    d_socklen=len;
79  }
80
81  void setSocket(int sock)
82  {
83    d_socket=sock;
84  }
85
86  string getRemote() const
87  {
88    return sockAddrToString((struct sockaddr_in *)d_remote, d_socklen);
89  }
90
91  struct timeval d_now;
92  char d_remote[sizeof(sockaddr_in6)];
93  socklen_t d_socklen;
94  bool d_tcp;
95  int d_socket;
96};
97
98
99#ifndef WIN32
100#ifndef __FreeBSD__
101extern "C" {
102  int sem_init(sem_t*, int, unsigned int){return 0;}
103  int sem_wait(sem_t*){return 0;}
104  int sem_trywait(sem_t*){return 0;}
105  int sem_post(sem_t*){return 0;}
106  int sem_getvalue(sem_t*, int*){return 0;}
107  pthread_t pthread_self(void){return (pthread_t) 0;}
108  int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr){ return 0; }
109  int pthread_mutex_lock(pthread_mutex_t *mutex){ return 0; }
110  int pthread_mutex_unlock(pthread_mutex_t *mutex) { return 0; }
111  int pthread_mutex_destroy(pthread_mutex_t *mutex) { return 0; }
112}
113#endif // __FreeBSD__
114#endif // WIN32
115
116ArgvMap &arg()
117{
118  static ArgvMap theArg;
119  return theArg;
120}
121static int d_clientsock;
122static vector<int> d_udpserversocks;
123
124typedef vector<int> tcpserversocks_t;
125static tcpserversocks_t s_tcpserversocks;
126
127static map<int,PacketID> d_tcpclientreadsocks, d_tcpclientwritesocks;
128
129MTasker<PacketID,string>* MT;
130
131int asendtcp(const string& data, Socket* sock) 
132{
133  PacketID pident;
134  pident.sock=sock;
135  pident.outMSG=data;
136  string packet;
137
138  d_tcpclientwritesocks[sock->getHandle()]=pident;
139
140  int ret=MT->waitEvent(pident,&packet,1);
141  if(!ret || ret==-1) { // timeout
142    d_tcpclientwritesocks.erase(sock->getHandle());
143  }
144  return ret;
145}
146
147// -1 is error, 0 is timeout, 1 is success
148int arecvtcp(string& data, int len, Socket* sock) 
149{
150  data="";
151  PacketID pident;
152  pident.sock=sock;
153  pident.inNeeded=len;
154
155  d_tcpclientreadsocks[sock->getHandle()]=pident;
156
157  int ret=MT->waitEvent(pident,&data,1);
158  if(!ret || ret==-1) { // timeout
159    d_tcpclientreadsocks.erase(sock->getHandle());
160  }
161  return ret;
162}
163
164
165/* these two functions are used by LWRes */
166// -1 is error, > 1 is success
167int asendto(const char *data, int len, int flags, struct sockaddr *toaddr, int addrlen, int id) 
168{
169  return sendto(d_clientsock, data, len, flags, toaddr, addrlen);
170}
171
172// -1 is error, 0 is timeout, 1 is success
173int arecvfrom(char *data, int len, int flags, struct sockaddr *toaddr, Utility::socklen_t *addrlen, int *d_len, int id)
174{
175  PacketID pident;
176  pident.id=id;
177  memcpy(&pident.remote, toaddr, sizeof(pident.remote));
178
179  string packet;
180  int ret=MT->waitEvent(pident, &packet, 1);
181  if(ret > 0) {
182    *d_len=packet.size();
183    memcpy(data,packet.c_str(),min(len,*d_len));
184  }
185  return ret;
186}
187
188void setReceiveBuffer(int fd, uint32_t size)
189{
190  uint32_t psize=0;
191  socklen_t len=sizeof(psize);
192 
193  if(!getsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&psize, &len) && psize > size) {
194    L<<Logger::Error<<"Not decreasing socket buffer size from "<<psize<<" to "<<size<<endl;
195    return; 
196  }
197
198  if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&size, sizeof(size)) < 0 )
199    L<<Logger::Error<<"Warning: unable to raise socket buffer size to "<<size<<": "<<strerror(errno)<<endl;
200}
201
202
203static void writePid(void)
204{
205  string fname=::arg()["socket-dir"]+"/"+s_programname+".pid";
206  ofstream of(fname.c_str());
207  if(of)
208    of<< getpid() <<endl;
209  else
210    L<<Logger::Error<<"Requested to write pid for "<<getpid()<<" to "<<fname<<" failed: "<<strerror(errno)<<endl;
211}
212
213void primeHints(void)
214{
215  // prime root cache
216  set<DNSResourceRecord>nsset;
217
218  if(::arg()["hint-file"].empty()) {
219    static 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", "192.112.36.4", "128.63.2.53", 
220                       "192.36.148.17","192.58.128.30", "193.0.14.129", "198.32.64.12", "202.12.27.33"};
221    DNSResourceRecord arr, nsrr;
222    arr.qtype=QType::A;
223    arr.ttl=time(0)+3600000;
224    nsrr.qtype=QType::NS;
225    nsrr.ttl=time(0)+3600000;
226   
227    for(char c='a';c<='m';++c) {
228      static char templ[40];
229      strncpy(templ,"a.root-servers.net.", sizeof(templ) - 1);
230      *templ=c;
231      arr.qname=nsrr.content=templ;
232      arr.content=ips[c-'a'];
233      set<DNSResourceRecord> aset;
234      aset.insert(arr);
235      RC.replace(string(templ), QType(QType::A), aset);
236     
237      nsset.insert(nsrr);
238    }
239  }
240  else {
241    ZoneParserTNG zpt(::arg()["hint-file"]);
242    DNSResourceRecord rr;
243    set<DNSResourceRecord> aset;
244
245    while(zpt.get(rr)) {
246      rr.ttl+=time(0);
247      if(rr.qtype.getCode()==QType::A) {
248        set<DNSResourceRecord> aset;
249        aset.insert(rr);
250        RC.replace(rr.qname, QType(QType::A), aset);
251      }
252      if(rr.qtype.getCode()==QType::NS) {
253        rr.content=toLower(rr.content);
254        nsset.insert(rr);
255      }
256    }
257  }
258  RC.replace(".", QType(QType::NS), nsset); // and stuff in the cache
259}
260
261void startDoResolve(void *p)
262{
263  try {
264    DNSComboWriter* dc=(DNSComboWriter *)p;
265
266    uint16_t maxudpsize=512;
267    MOADNSParser::EDNSOpts edo;
268    if(dc->d_mdp.getEDNSOpts(&edo)) {
269      maxudpsize=edo.d_packetsize;
270    }
271
272    vector<DNSResourceRecord> ret;
273   
274    vector<uint8_t> packet;
275    DNSPacketWriter pw(packet, dc->d_mdp.d_qname, dc->d_mdp.d_qtype, dc->d_mdp.d_qclass);
276
277    pw.getHeader()->aa=0;
278    pw.getHeader()->ra=1;
279    pw.getHeader()->qr=1;
280    pw.getHeader()->id=dc->d_mdp.d_header.id;
281    pw.getHeader()->rd=dc->d_mdp.d_header.rd;
282
283    //    MT->setTitle("udp question for "+P.qdomain+"|"+P.qtype.getName());
284    SyncRes sr(dc->d_now);
285    if(!g_quiet)
286      L<<Logger::Error<<"["<<MT->getTid()<<"] " << (dc->d_tcp ? "TCP " : "") << "question for '"<<dc->d_mdp.d_qname<<"|"
287       <<DNSRecordContent::NumberToType(dc->d_mdp.d_qtype)<<"' from "<<dc->getRemote()<<endl;
288
289    sr.setId(MT->getTid());
290    if(!dc->d_mdp.d_header.rd)
291      sr.setCacheOnly();
292
293    int res=sr.beginResolve(dc->d_mdp.d_qname, QType(dc->d_mdp.d_qtype), ret);
294    if(res<0) {
295      pw.getHeader()->rcode=RCode::ServFail;
296      // no commit here, because no record
297      g_stats.servFails++;
298    }
299    else {
300      pw.getHeader()->rcode=res;
301      switch(res) {
302      case RCode::ServFail:
303        g_stats.servFails++;
304        break;
305      case RCode::NXDomain:
306        g_stats.nxDomains++;
307        break;
308      case RCode::NoError:
309        g_stats.noErrors++;
310        break;
311      }
312     
313      if(ret.size()) {
314        shuffle(ret);
315        for(vector<DNSResourceRecord>::const_iterator i=ret.begin();i!=ret.end();++i) {
316          pw.startRecord(i->qname, i->qtype.getCode(), i->ttl, 1, (DNSPacketWriter::Place)i->d_place);
317          shared_ptr<DNSRecordContent> drc(DNSRecordContent::mastermake(i->qtype.getCode(), 1, i->content)); 
318          drc->toPacket(pw);
319          if(!dc->d_tcp && pw.size() > maxudpsize) {
320            pw.rollback();
321            if(i->d_place==DNSResourceRecord::ANSWER)  // only truncate if we actually omitted parts of the answer
322              pw.getHeader()->tc=1;
323            goto sendit; // need to jump over pw.commit
324          }
325        }
326        pw.commit();
327      }
328    }
329  sendit:;
330    if(!dc->d_tcp) {
331      sendto(dc->d_socket, &*packet.begin(), packet.size(), 0, (struct sockaddr *)(dc->d_remote), dc->d_socklen);
332    }
333    else {
334      char buf[2];
335      buf[0]=packet.size()/256;
336      buf[1]=packet.size()%256;
337
338      struct iovec iov[2];
339
340      iov[0].iov_base=(void*)buf;              iov[0].iov_len=2;
341      iov[1].iov_base=(void*)&*packet.begin(); iov[1].iov_len = packet.size();
342
343      int ret=writev(dc->d_socket, iov, 2);
344
345      if(ret <= 0 ) 
346        L<<Logger::Error<<"Error writing TCP answer to "<<dc->getRemote()<<": "<< (ret ? strerror(errno) : "EOF") <<endl;
347      else if((unsigned int)ret != 2 + packet.size())
348        L<<Logger::Error<<"Oops, partial answer sent to "<<dc->getRemote()<<" - probably would have trouble receiving our answer anyhow (size="<<packet.size()<<")"<<endl;
349    }
350
351    //    MT->setTitle("DONE! udp question for "+P.qdomain+"|"+P.qtype.getName());
352    if(!g_quiet) {
353      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);
354      L<<"': "<<ntohs(pw.getHeader()->ancount)<<" answers, "<<ntohs(pw.getHeader()->arcount)<<" additional, took "<<sr.d_outqueries<<" packets, "<<
355        sr.d_throttledqueries<<" throttled, "<<sr.d_timeouts<<" timeouts, "<<sr.d_tcpoutqueries<<" tcp connections, rcode="<<res<<endl;
356    }
357   
358    sr.d_outqueries ? RC.cacheMisses++ : RC.cacheHits++; 
359    float spent=makeFloat(sr.d_now-dc->d_now);
360    if(spent < 0.001)
361      g_stats.answers0_1++;
362    else if(spent < 0.010)
363      g_stats.answers1_10++;
364    else if(spent < 0.1)
365      g_stats.answers10_100++;
366    else if(spent < 1.0)
367      g_stats.answers100_1000++;
368    else
369      g_stats.answersSlow++;
370
371    uint64_t newLat=(uint64_t)(spent*1000000);
372    if(newLat < 1000000)  // outliers of several minutes exist..
373      g_stats.avgLatencyUsec=(uint64_t)((1-0.0001)*g_stats.avgLatencyUsec + 0.0001*newLat);
374    delete dc;
375  }
376  catch(AhuException &ae) {
377    L<<Logger::Error<<"startDoResolve problem: "<<ae.reason<<endl;
378  }
379  catch(exception& e) {
380    L<<Logger::Error<<"STL error: "<<e.what()<<endl;
381  }
382  catch(...) {
383    L<<Logger::Error<<"Any other exception in a resolver context"<<endl;
384  }
385}
386
387RecursorControlChannel s_rcc;
388
389void makeControlChannelSocket()
390{
391  s_rcc.listen(::arg()["socket-dir"]+"/pdns_recursor.controlsocket");
392}
393
394void makeClientSocket()
395{
396  d_clientsock=socket(AF_INET, SOCK_DGRAM,0);
397  if(d_clientsock<0) 
398    throw AhuException("Making a socket for resolver: "+stringerror());
399  setReceiveBuffer(d_clientsock, 200000); 
400  struct sockaddr_in sin;
401  memset((char *)&sin,0, sizeof(sin));
402 
403  sin.sin_family = AF_INET;
404
405  if(!IpToU32(::arg()["query-local-address"], &sin.sin_addr.s_addr))
406    throw AhuException("Unable to resolve local address '"+ ::arg()["query-local-address"] +"'"); 
407
408  int tries=10;
409  while(--tries) {
410    uint16_t port=10000+Utility::random()%10000;
411    sin.sin_port = htons(port); 
412   
413    if (::bind(d_clientsock, (struct sockaddr *)&sin, sizeof(sin)) >= 0) 
414      break;
415   
416  }
417  if(!tries)
418    throw AhuException("Resolver binding to local socket: "+stringerror());
419
420  Utility::setNonBlocking(d_clientsock);
421
422  L<<Logger::Error<<"Sending UDP queries from "<<inet_ntoa(sin.sin_addr)<<":"<< ntohs(sin.sin_port)  <<endl;
423}
424
425void makeTCPServerSockets()
426{
427  vector<string>locals;
428  stringtok(locals,::arg()["local-address"]," ,");
429
430  if(locals.empty())
431    throw AhuException("No local address specified");
432 
433  for(vector<string>::const_iterator i=locals.begin();i!=locals.end();++i) {
434    int fd=socket(AF_INET, SOCK_STREAM,0);
435    if(fd<0) 
436      throw AhuException("Making a server socket for resolver: "+stringerror());
437 
438    struct sockaddr_in sin;
439    memset((char *)&sin,0, sizeof(sin));
440   
441    sin.sin_family = AF_INET;
442    if(!IpToU32(*i, &sin.sin_addr.s_addr))
443      throw AhuException("Unable to resolve local address '"+ *i +"'"); 
444
445    int tmp=1;
446    if(setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char*)&tmp,sizeof tmp)<0) {
447      L<<Logger::Error<<"Setsockopt failed for TCP listening socket"<<endl;
448      exit(1);
449    }
450   
451#ifdef TCP_DEFER_ACCEPT
452    if(setsockopt(fd,SOL_TCP,TCP_DEFER_ACCEPT,(char*)&tmp,sizeof tmp) >= 0) {
453      L<<Logger::Error<<"Enabled TCP data-ready filter for (slight) DoS protection"<<endl;
454    }
455#endif
456
457    sin.sin_port = htons(::arg().asNum("local-port")); 
458   
459    if (::bind(fd, (struct sockaddr *)&sin, sizeof(sin))<0) 
460      throw AhuException("Binding TCP server socket for "+*i+": "+stringerror());
461   
462    Utility::setNonBlocking(fd);
463    listen(fd, 128);
464    s_tcpserversocks.push_back(fd);
465    L<<Logger::Error<<"Listening for TCP queries on "<<inet_ntoa(sin.sin_addr)<<":"<<::arg().asNum("local-port")<<endl;
466  }
467}
468
469void makeUDPServerSockets()
470{
471  vector<string>locals;
472  stringtok(locals,::arg()["local-address"]," ,");
473
474  if(locals.empty())
475    throw AhuException("No local address specified");
476 
477  if(::arg()["local-address"]=="0.0.0.0") {
478    L<<Logger::Warning<<"It is advised to bind to explicit addresses with the --local-address option"<<endl;
479  }
480
481  for(vector<string>::const_iterator i=locals.begin();i!=locals.end();++i) {
482    int fd=socket(AF_INET, SOCK_DGRAM,0);
483    if(fd<0) 
484      throw AhuException("Making a server socket for resolver: "+stringerror());
485    setReceiveBuffer(fd, 200000);
486    struct sockaddr_in sin;
487    memset((char *)&sin,0, sizeof(sin));
488   
489    sin.sin_family = AF_INET;
490    if(!IpToU32(*i, &sin.sin_addr.s_addr))
491      throw AhuException("Unable to resolve local address '"+ *i +"'"); 
492   
493    sin.sin_port = htons(::arg().asNum("local-port")); 
494   
495    if (::bind(fd, (struct sockaddr *)&sin, sizeof(sin))<0) 
496      throw AhuException("Resolver binding to server socket for "+*i+": "+stringerror());
497   
498    Utility::setNonBlocking(fd);
499    d_udpserversocks.push_back(fd);
500    L<<Logger::Error<<"Listening for UDP queries on "<<inet_ntoa(sin.sin_addr)<<":"<<::arg().asNum("local-port")<<endl;
501  }
502}
503
504
505#ifndef WIN32
506void daemonize(void)
507{
508  if(fork())
509    exit(0); // bye bye
510 
511  setsid(); 
512
513  // cleanup open fds, but skip sockets
514  close(0);
515  close(1);
516  close(2);
517}
518#endif
519
520uint64_t counter;
521bool statsWanted;
522
523
524void usr1Handler(int)
525{
526  statsWanted=true;
527}
528
529
530
531void usr2Handler(int)
532{
533  SyncRes::setLog(true);
534  g_quiet=false;
535  ::arg().set("quiet")="no";
536
537}
538
539void doStats(void)
540{
541  if(g_stats.qcounter) {
542    L<<Logger::Error<<"stats: "<<g_stats.qcounter<<" questions, "<<RC.size()<<" cache entries, "<<SyncRes::s_negcache.size()<<" negative entries, "
543     <<(int)((RC.cacheHits*100.0)/(RC.cacheHits+RC.cacheMisses))<<"% cache hits"<<endl;
544    L<<Logger::Error<<"stats: throttle map: "<<SyncRes::s_throttle.size()<<", ns speeds: "
545     <<SyncRes::s_nsSpeeds.size()<<endl; // ", bytes: "<<RC.bytes()<<endl;
546    L<<Logger::Error<<"stats: outpacket/query ratio "<<(int)(SyncRes::s_outqueries*100.0/SyncRes::s_queries)<<"%";
547    L<<Logger::Error<<", "<<(int)(SyncRes::s_throttledqueries*100.0/(SyncRes::s_outqueries+SyncRes::s_throttledqueries))<<"% throttled, "
548     <<SyncRes::s_nodelegated<<" no-delegation drops"<<endl;
549    L<<Logger::Error<<"stats: "<<SyncRes::s_tcpoutqueries<<" outgoing tcp connections, "<<MT->numProcesses()<<" queries running, "<<SyncRes::s_outgoingtimeouts<<" outgoing timeouts"<<endl;
550  }
551  else if(statsWanted) 
552    L<<Logger::Error<<"stats: no stats yet!"<<endl;
553
554  statsWanted=false;
555}
556
557static void houseKeeping(void *)
558{
559  static time_t last_stat, last_rootupdate, last_prune;
560  struct timeval now;
561  gettimeofday(&now, 0);
562
563  if(now.tv_sec - last_prune > 300) { 
564    DTime dt;
565    dt.setTimeval(now);
566    RC.doPrune();
567   
568    typedef SyncRes::negcache_t::nth_index<1>::type negcache_by_ttd_index_t;
569    negcache_by_ttd_index_t& ttdindex=boost::multi_index::get<1>(SyncRes::s_negcache);
570
571    negcache_by_ttd_index_t::iterator i=ttdindex.lower_bound(now.tv_sec);
572    ttdindex.erase(ttdindex.begin(), i);
573
574    time_t limit=now.tv_sec-300;
575    for(SyncRes::nsspeeds_t::iterator i = SyncRes::s_nsSpeeds.begin() ; i!= SyncRes::s_nsSpeeds.end(); )
576      if(i->second.stale(limit))
577        SyncRes::s_nsSpeeds.erase(i++);
578      else
579        ++i;
580
581    //   cerr<<"Pruned "<<pruned<<" records, left "<<SyncRes::s_negcache.size()<<"\n";
582//    cout<<"Prune took "<<dt.udiff()<<"usec\n";
583    last_prune=time(0);
584  }
585  if(now.tv_sec - last_stat>1800) { 
586    doStats();
587    last_stat=time(0);
588  }
589  if(now.tv_sec -last_rootupdate>7200) {
590    SyncRes sr(now);
591    vector<DNSResourceRecord> ret;
592
593    sr.setNoCache();
594    int res=sr.beginResolve(".", QType(QType::NS), ret);
595    if(!res) {
596      L<<Logger::Error<<"Refreshed . records"<<endl;
597      last_rootupdate=now.tv_sec;
598    }
599    else
600      L<<Logger::Error<<"Failed to update . records, RCODE="<<res<<endl;
601  }
602}
603
604map<uint32_t, uint32_t> g_tcpClientCounts;
605struct TCPConnection
606{
607  int fd;
608  enum {BYTE0, BYTE1, GETQUESTION} state;
609  int qlen;
610  int bytesread;
611  struct sockaddr_in remote;
612  char data[65535];
613  time_t startTime;
614
615  void closeAndCleanup()
616  {
617    close(fd);
618    if(!g_tcpClientCounts[remote.sin_addr.s_addr]--) 
619      g_tcpClientCounts.erase(remote.sin_addr.s_addr);
620  }
621};
622
623#if 0
624#include <execinfo.h>
625
626  multimap<uint32_t,string> rev;
627  for(map<string,uint32_t>::const_iterator i=casesptr->begin(); i!=casesptr->end(); ++i) {
628    rev.insert(make_pair(i->second,i->first));
629  }
630  for(multimap<uint32_t,string>::const_iterator i=rev.begin(); i!= rev.end(); ++i)
631    cout<<i->first<<" times: \n"<<i->second<<"\n";
632
633  cout.flush();
634
635map<string,uint32_t>* casesptr;
636static string maketrace()
637{
638  void *array[20]; //only care about last 17 functions (3 taken with tracing support)
639  size_t size;
640  char **strings;
641  size_t i;
642
643  size = backtrace (array, 5);
644  strings = backtrace_symbols (array, size); //Need -rdynamic gcc (linker) flag for this to work
645
646  string ret;
647
648  for (i = 0; i < size; i++) //skip useless functions
649    ret+=string(strings[i])+"\n";
650  return ret;
651}
652
653extern "C" {
654
655int gettimeofday (struct timeval *__restrict __tv,
656                  __timezone_ptr_t __tz)
657{
658  static map<string, uint32_t> s_cases;
659  casesptr=&s_cases;
660  s_cases[maketrace()]++;
661  __tv->tv_sec=time(0);
662  return 0;
663}
664
665}
666#endif
667
668int main(int argc, char **argv) 
669{
670  reportBasicTypes();
671
672  int ret = EXIT_SUCCESS;
673#ifdef WIN32
674    WSADATA wsaData;
675    WSAStartup( MAKEWORD( 2, 0 ), &wsaData );
676#endif // WIN32
677
678  try {
679    Utility::srandom(time(0));
680    ::arg().set("soa-minimum-ttl","Don't change")="0";
681    ::arg().set("soa-serial-offset","Don't change")="0";
682    ::arg().set("no-shuffle","Don't change")="off";
683    ::arg().set("aaaa-additional-processing","turn on to do AAAA additional processing (slow)")="off";
684    ::arg().set("local-port","port to listen on")="53";
685    ::arg().set("local-address","IP addresses to listen on, separated by spaces or commas")="0.0.0.0";
686    ::arg().set("trace","if we should output heaps of logging")="off";
687    ::arg().set("daemon","Operate as a daemon")="yes";
688    ::arg().set("chroot","switch to chroot jail")="";
689    ::arg().set("setgid","If set, change group id to this gid for more security")="";
690    ::arg().set("setuid","If set, change user id to this uid for more security")="";
691    ::arg().set("quiet","Suppress logging of questions and answers")="true";
692    ::arg().set("config-dir","Location of configuration directory (recursor.conf)")=SYSCONFDIR;
693    ::arg().set("socket-dir","Where the controlsocket will live")=LOCALSTATEDIR;
694    ::arg().set("delegation-only","Which domains we only accept delegations from")="";
695    ::arg().set("query-local-address","Source IP address for sending queries")="0.0.0.0";
696    ::arg().set("client-tcp-timeout","Timeout in seconds when talking to TCP clients")="2";
697    ::arg().set("max-tcp-clients","Maximum number of simultaneous TCP clients")="128";
698    ::arg().set("hint-file", "If set, load root hints from this file")="";
699    ::arg().set("max-cache-entries", "If set, maximum number of entries in the main cache")="0";
700    ::arg().set("allow-from", "If set, only allow these comma separated netmasks to recurse")="";
701    ::arg().set("max-tcp-per-client", "If set, maximum number of TCP sessions per client (IP address)")="0";
702
703    ::arg().setCmd("help","Provide a helpful message");
704    L.toConsole(Logger::Warning);
705    ::arg().laxParse(argc,argv); // do a lax parse
706
707    string configname=::arg()["config-dir"]+"/recursor.conf";
708    cleanSlashes(configname);
709
710    if(!::arg().file(configname.c_str())) 
711      L<<Logger::Warning<<"Unable to parse configuration file '"<<configname<<"'"<<endl;
712
713    ::arg().parse(argc,argv);
714
715    ::arg().set("delegation-only")=toLower(::arg()["delegation-only"]);
716
717    if(::arg().mustDo("help")) {
718      cerr<<"syntax:"<<endl<<endl;
719      cerr<<::arg().helpstring(::arg()["help"])<<endl;
720      exit(99);
721    }
722
723    if(!::arg()["allow-from"].empty()) {
724      g_allowFrom=new NetmaskGroup;
725      vector<string> ips;
726      stringtok(ips, ::arg()["allow-from"], ", ");
727      for(vector<string>::const_iterator i = ips.begin(); i!= ips.end(); ++i)
728        g_allowFrom->addMask(*i);
729    }
730
731    L.setName("pdns_recursor");
732
733    L<<Logger::Warning<<"PowerDNS recursor "<<VERSION<<" (C) 2001-2006 PowerDNS.COM BV ("<<__DATE__", "__TIME__;
734#ifdef __GNUC__
735    L<<", gcc "__VERSION__;
736#endif // add other compilers here
737    L<<") starting up"<<endl;
738
739    L<<Logger::Warning<<"Operating in "<<(sizeof(unsigned long)*8) <<" bits mode"<<endl;
740  L<<Logger::Warning<<"PowerDNS comes with ABSOLUTELY NO WARRANTY. "
741    "This is free software, and you are welcome to redistribute it "
742    "according to the terms of the GPL version 2."<<endl;
743
744
745  g_quiet=::arg().mustDo("quiet");
746  if(::arg().mustDo("trace")) {
747      SyncRes::setLog(true);
748      ::arg().set("quiet")="no";
749      g_quiet=false;
750  }
751
752    makeClientSocket();
753    makeUDPServerSockets();
754    makeTCPServerSockets();
755    makeControlChannelSocket();
756   
757    MT=new MTasker<PacketID,string>(100000);
758
759    char data[1500];
760    struct sockaddr_in fromaddr;
761   
762    PacketID pident;
763    primeHints();   
764    L<<Logger::Warning<<"Done priming cache with root hints"<<endl;
765#ifndef WIN32
766    if(::arg().mustDo("daemon")) {
767      L.toConsole(Logger::Critical);
768      daemonize();
769    }
770    signal(SIGUSR1,usr1Handler);
771    signal(SIGUSR2,usr2Handler);
772    signal(SIGPIPE,SIG_IGN);
773
774    writePid();
775#endif
776
777    int newgid=0;
778    if(!::arg()["setgid"].empty())
779      newgid=Utility::makeGidNumeric(::arg()["setgid"]);
780    int newuid=0;
781    if(!::arg()["setuid"].empty())
782      newuid=Utility::makeUidNumeric(::arg()["setuid"]);
783
784
785    if (!::arg()["chroot"].empty()) {
786        if (chroot(::arg()["chroot"].c_str())<0) {
787            L<<Logger::Error<<"Unable to chroot to '"+::arg()["chroot"]+"': "<<strerror (errno)<<", exiting"<<endl;
788            exit(1);
789        }
790    }
791
792    Utility::dropPrivs(newuid, newgid);
793
794    vector<TCPConnection> tcpconnections;
795    counter=0;
796    struct timeval now;
797    unsigned int maxTcpClients=::arg().asNum("max-tcp-clients");
798    int tcpTimeout=::arg().asNum("client-tcp-timeout");
799
800    unsigned int maxTCPPerClient=::arg().asNum("max-tcp-per-client");
801
802    for(;;) {
803      while(MT->schedule()); // housekeeping, let threads do their thing
804     
805      if(!((counter++)%500)) 
806        MT->makeThread(houseKeeping,0);
807      if(statsWanted) {
808        doStats();
809      }
810
811      Utility::socklen_t addrlen=sizeof(fromaddr);
812      int d_len;
813     
814      struct timeval tv;
815      tv.tv_sec=0;
816      tv.tv_usec=500000;
817     
818      fd_set readfds, writefds;
819      FD_ZERO( &readfds );
820      FD_ZERO( &writefds );
821      FD_SET( d_clientsock, &readfds );
822      FD_SET( s_rcc.d_fd, &readfds);
823      int fdmax=max(d_clientsock, s_rcc.d_fd);
824
825      if(!tcpconnections.empty())
826        gettimeofday(&now, 0);
827
828      vector<TCPConnection> sweeped;
829
830      for(vector<TCPConnection>::iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) {
831        if(now.tv_sec < i->startTime + tcpTimeout) {
832          FD_SET(i->fd, &readfds);
833          fdmax=max(fdmax,i->fd);
834          sweeped.push_back(*i);
835        }
836        else {
837          L<<Logger::Error<<"TCP timeout from client "<<inet_ntoa(i->remote.sin_addr)<<endl;
838          i->closeAndCleanup();
839        }
840      }
841      sweeped.swap(tcpconnections);
842
843      for(vector<int>::const_iterator i=d_udpserversocks.begin(); i!=d_udpserversocks.end(); ++i) {
844        FD_SET( *i, &readfds );
845        fdmax=max(fdmax,*i);
846      }
847      if(tcpconnections.size() < maxTcpClients) 
848        for(tcpserversocks_t::const_iterator i=s_tcpserversocks.begin(); i!=s_tcpserversocks.end(); ++i) {
849          FD_SET(*i, &readfds );
850          fdmax=max(fdmax,*i);
851        }
852
853      for(map<int,PacketID>::const_iterator i=d_tcpclientreadsocks.begin(); i!=d_tcpclientreadsocks.end(); ++i) {
854        // cerr<<"Adding TCP socket "<<i->first<<" to read select set"<<endl;
855        FD_SET( i->first, &readfds );
856        fdmax=max(fdmax,i->first);
857      }
858
859      for(map<int,PacketID>::const_iterator i=d_tcpclientwritesocks.begin(); i!=d_tcpclientwritesocks.end(); ++i) {
860        // cerr<<"Adding TCP socket "<<i->first<<" to write select set"<<endl;
861        FD_SET( i->first, &writefds );
862        fdmax=max(fdmax,i->first);
863      }
864
865      int selret = select(  fdmax + 1, &readfds, &writefds, NULL, &tv );
866      gettimeofday(&now, 0);
867      if(selret<=0) 
868        if (selret == -1 && errno!=EINTR) 
869          throw AhuException("Select returned: "+stringerror());
870        else
871          continue;
872
873      if(FD_ISSET(s_rcc.d_fd, &readfds)) {
874        string remote;
875        string msg=s_rcc.recv(&remote);
876        RecursorControlParser rcp;
877        RecursorControlParser::func_t* command;
878        string answer=rcp.getAnswer(msg, &command);
879        s_rcc.send(answer, &remote);
880        command();
881      }
882
883      if(FD_ISSET(d_clientsock,&readfds)) { // do we have a UDP question response?
884        while((d_len=recvfrom(d_clientsock, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen)) >= 0) {
885        try {
886            DNSComboWriter dc(data, d_len, now);
887            dc.setRemote((struct sockaddr *)&fromaddr, addrlen);
888
889            if(dc.d_mdp.d_header.qr) {
890              pident.remote=fromaddr;
891              pident.id=dc.d_mdp.d_header.id;
892              string packet;
893              packet.assign(data, d_len);
894              MT->sendEvent(pident, &packet);
895            }
896            else 
897              L<<Logger::Warning<<"Ignoring question on outgoing socket from "<<dc.getRemote()<<endl;
898          }
899          catch(MOADNSException& mde) {
900            L<<Logger::Error<<"Unable to parse packet from remote UDP server "<< sockAddrToString((struct sockaddr_in*) &fromaddr, addrlen) <<": "<<mde.what()<<endl;
901          }
902        }
903      }
904     
905      for(vector<int>::const_iterator i=d_udpserversocks.begin(); i!=d_udpserversocks.end(); ++i) {
906        if(FD_ISSET(*i,&readfds)) { // do we have a new question on udp?
907          while((d_len=recvfrom(*i, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen)) >= 0) {
908            g_stats.queryrate.pulse(now);
909            if(g_allowFrom && !g_allowFrom->match(&fromaddr)) {
910              g_stats.unauthorizedUDP++;
911              continue;
912            }
913
914            try {
915              DNSComboWriter* dc = new DNSComboWriter(data, d_len, now);
916
917              dc->setRemote((struct sockaddr *)&fromaddr, addrlen);
918
919              if(dc->d_mdp.d_header.qr)
920                L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
921              else {
922                ++g_stats.qcounter;
923                dc->setSocket(*i);
924                dc->d_tcp=false;
925                MT->makeThread(startDoResolve, (void*) dc);
926              }
927            }
928            catch(MOADNSException& mde) {
929              L<<Logger::Error<<"Unable to parse packet from remote udp client "<< sockAddrToString((struct sockaddr_in*) &fromaddr, addrlen) <<": "<<mde.what()<<endl;
930            }
931          }
932        }
933      }
934
935      for(tcpserversocks_t::const_iterator i=s_tcpserversocks.begin(); i!=s_tcpserversocks.end(); ++i) { 
936        if(FD_ISSET(*i ,&readfds)) { // do we have a new TCP connection?
937          struct sockaddr_in addr;
938          socklen_t addrlen=sizeof(addr);
939          int newsock=accept(*i, (struct sockaddr*)&addr, &addrlen);
940          if(newsock>0) {
941            if(g_allowFrom && !g_allowFrom->match(&addr)) {
942              g_stats.unauthorizedTCP++;
943              close(newsock);
944              continue;
945            }
946
947            if(maxTCPPerClient && g_tcpClientCounts.count(addr.sin_addr.s_addr) && g_tcpClientCounts[addr.sin_addr.s_addr] >= maxTCPPerClient) {
948              g_stats.tcpClientOverflow++;
949              close(newsock); // don't call TCPConnection::closeAndCleanup here - did not enter it in the counts yet!
950              continue;
951            }
952            g_tcpClientCounts[addr.sin_addr.s_addr]++;
953            Utility::setNonBlocking(newsock);
954            TCPConnection tc;
955            tc.fd=newsock;
956            tc.state=TCPConnection::BYTE0;
957            tc.remote=addr;
958            tc.startTime=now.tv_sec;
959            tcpconnections.push_back(tc);
960          }
961        }
962      }
963
964      // have any question answers come in over TCP?
965      for(map<int,PacketID>::iterator i=d_tcpclientreadsocks.begin(); i!=d_tcpclientreadsocks.end();) { 
966        bool haveErased=false;
967        if(FD_ISSET(i->first, &readfds)) { // can we receive
968          shared_array<char> buffer(new char[i->second.inNeeded]);
969
970          int ret=read(i->first, buffer.get(), min(i->second.inNeeded,200));
971          // cerr<<"Read returned "<<ret<<endl;
972          if(ret > 0) {
973            i->second.inMSG.append(&buffer[0], &buffer[ret]);
974            i->second.inNeeded-=ret;
975            if(!i->second.inNeeded) {
976              // cerr<<"Got entire load of "<<i->second.inMSG.size()<<" bytes"<<endl;
977              PacketID pid=i->second;
978              string msg=i->second.inMSG;
979             
980              d_tcpclientreadsocks.erase((i++));
981              haveErased=true;
982              MT->sendEvent(pid, &msg);   // XXX DODGY
983            }
984            else {
985              // cerr<<"Still have "<<i->second.inNeeded<<" left to go"<<endl;
986            }
987          }
988          else {
989            //      cerr<<"when reading ret="<<ret<<endl;
990            // XXX FIXME I think some stuff needs to happen here - like send an EOF event
991          }
992        }
993        if(!haveErased)
994          ++i;
995      }
996     
997      // is there data we can send to remote nameservers over TCP?
998      for(map<int,PacketID>::iterator i=d_tcpclientwritesocks.begin(); i!=d_tcpclientwritesocks.end(); ) { 
999        bool haveErased=false;
1000        if(FD_ISSET(i->first, &writefds)) { // can we send over TCP
1001          // cerr<<"Socket "<<i->first<<" available for writing"<<endl;
1002          int ret=write(i->first, i->second.outMSG.c_str(), i->second.outMSG.size() - i->second.outPos);
1003          if(ret > 0) {
1004            i->second.outPos+=ret;
1005            if(i->second.outPos==i->second.outMSG.size()) {
1006              // cerr<<"Sent out entire load of "<<i->second.outMSG.size()<<" bytes"<<endl;
1007              PacketID pid=i->second;
1008              d_tcpclientwritesocks.erase(i++);   // erase!
1009              haveErased=true;
1010              MT->sendEvent(pid, 0);
1011            }
1012
1013          }
1014          else { 
1015            //      cerr<<"ret="<<ret<<" when writing"<<endl;
1016            // XXX FIXME I think some stuff needs to happen here - like send an EOF event
1017          }
1018        }
1019        if(!haveErased)
1020          ++i;
1021      }
1022     
1023      // very braindead TCP incoming question parser
1024      for(vector<TCPConnection>::iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) {
1025        if(FD_ISSET(i->fd, &readfds)) {
1026          if(i->state==TCPConnection::BYTE0) {
1027            int bytes=read(i->fd,i->data,2);
1028            if(bytes==1)
1029              i->state=TCPConnection::BYTE1;
1030            if(bytes==2) { 
1031              i->qlen=(i->data[0]<<8)+i->data[1];
1032              i->bytesread=0;
1033              i->state=TCPConnection::GETQUESTION;
1034            }
1035            if(!bytes || bytes < 0) {
1036              i->closeAndCleanup();
1037              tcpconnections.erase(i);
1038              break;
1039            }
1040          }
1041          else if(i->state==TCPConnection::BYTE1) {
1042            int bytes=read(i->fd,i->data+1,1);
1043            if(bytes==1) {
1044              i->state=TCPConnection::GETQUESTION;
1045              i->qlen=(i->data[0]<<8)+i->data[1];
1046              i->bytesread=0;
1047            }
1048            if(!bytes || bytes < 0) {
1049              L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected after first byte"<<endl;
1050              i->closeAndCleanup();
1051              tcpconnections.erase(i);
1052              break;
1053            }
1054           
1055          }
1056          else if(i->state==TCPConnection::GETQUESTION) {
1057            int bytes=read(i->fd,i->data + i->bytesread,i->qlen - i->bytesread);
1058            if(!bytes || bytes < 0) {
1059              L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected while reading question body"<<endl;
1060              i->closeAndCleanup();
1061              tcpconnections.erase(i);
1062              break;
1063            }
1064            i->bytesread+=bytes;
1065            if(i->bytesread==i->qlen) {
1066              i->state=TCPConnection::BYTE0;
1067              DNSComboWriter* dc=0;
1068              try {
1069                dc=new DNSComboWriter(i->data, i->qlen, now);
1070              }
1071              catch(MOADNSException &mde) {
1072                L<<Logger::Error<<"Unable to parse packet from remote TCP client "<<sockAddrToString(&i->remote,sizeof(i->remote))<<endl;
1073                i->closeAndCleanup();
1074                tcpconnections.erase(i);
1075                break;
1076              }
1077
1078              dc->setSocket(i->fd);
1079              dc->d_tcp=true;
1080              dc->setRemote((struct sockaddr *)&i->remote,sizeof(i->remote));
1081              if(dc->d_mdp.d_header.qr)
1082                L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
1083              else {
1084                ++g_stats.qcounter;
1085                ++g_stats.tcpqcounter;
1086                MT->makeThread(startDoResolve, dc);
1087              }
1088            }
1089          }
1090        }
1091      }
1092    }
1093  }
1094  catch(AhuException &ae) {
1095    L<<Logger::Error<<"Exception: "<<ae.reason<<endl;
1096    ret=EXIT_FAILURE;
1097  }
1098  catch(exception &e) {
1099    L<<Logger::Error<<"STL Exception: "<<e.what()<<endl;
1100    ret=EXIT_FAILURE;
1101  }
1102  catch(...) {
1103    L<<Logger::Error<<"any other exception in main: "<<endl;
1104    ret=EXIT_FAILURE;
1105  }
1106 
1107#ifdef WIN32
1108  WSACleanup();
1109#endif // WIN32
1110
1111  return ret;
1112}
Note: See TracBrowser for help on using the browser.