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

Revision 672, 33.6 KB (checked in by ahu, 7 years ago)

implement very simple SMP support

  • 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  string sockname=::arg()["socket-dir"]+"/pdns_recursor.controlsocket";
392  if(::arg().mustDo("fork")) {
393    sockname+="."+lexical_cast<string>(getpid());
394    L<<Logger::Warning<<"Forked control socket name: "<<sockname<<endl;
395  }
396  s_rcc.listen(sockname);
397}
398
399void makeClientSocket()
400{
401  d_clientsock=socket(AF_INET, SOCK_DGRAM,0);
402  if(d_clientsock<0) 
403    throw AhuException("Making a socket for resolver: "+stringerror());
404  setReceiveBuffer(d_clientsock, 200000); 
405  struct sockaddr_in sin;
406  memset((char *)&sin,0, sizeof(sin));
407 
408  sin.sin_family = AF_INET;
409
410  if(!IpToU32(::arg()["query-local-address"], &sin.sin_addr.s_addr))
411    throw AhuException("Unable to resolve local address '"+ ::arg()["query-local-address"] +"'"); 
412
413  int tries=10;
414  while(--tries) {
415    uint16_t port=10000+Utility::random()%10000;
416    sin.sin_port = htons(port); 
417   
418    if (::bind(d_clientsock, (struct sockaddr *)&sin, sizeof(sin)) >= 0) 
419      break;
420   
421  }
422  if(!tries)
423    throw AhuException("Resolver binding to local socket: "+stringerror());
424
425  Utility::setNonBlocking(d_clientsock);
426
427  L<<Logger::Error<<"Sending UDP queries from "<<inet_ntoa(sin.sin_addr)<<":"<< ntohs(sin.sin_port)  <<endl;
428}
429
430void makeTCPServerSockets()
431{
432  vector<string>locals;
433  stringtok(locals,::arg()["local-address"]," ,");
434
435  if(locals.empty())
436    throw AhuException("No local address specified");
437 
438  for(vector<string>::const_iterator i=locals.begin();i!=locals.end();++i) {
439    int fd=socket(AF_INET, SOCK_STREAM,0);
440    if(fd<0) 
441      throw AhuException("Making a server socket for resolver: "+stringerror());
442 
443    struct sockaddr_in sin;
444    memset((char *)&sin,0, sizeof(sin));
445   
446    sin.sin_family = AF_INET;
447    if(!IpToU32(*i, &sin.sin_addr.s_addr))
448      throw AhuException("Unable to resolve local address '"+ *i +"'"); 
449
450    int tmp=1;
451    if(setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,(char*)&tmp,sizeof tmp)<0) {
452      L<<Logger::Error<<"Setsockopt failed for TCP listening socket"<<endl;
453      exit(1);
454    }
455   
456#ifdef TCP_DEFER_ACCEPT
457    if(setsockopt(fd,SOL_TCP,TCP_DEFER_ACCEPT,(char*)&tmp,sizeof tmp) >= 0) {
458      L<<Logger::Error<<"Enabled TCP data-ready filter for (slight) DoS protection"<<endl;
459    }
460#endif
461
462    sin.sin_port = htons(::arg().asNum("local-port")); 
463   
464    if (::bind(fd, (struct sockaddr *)&sin, sizeof(sin))<0) 
465      throw AhuException("Binding TCP server socket for "+*i+": "+stringerror());
466   
467    Utility::setNonBlocking(fd);
468    listen(fd, 128);
469    s_tcpserversocks.push_back(fd);
470    L<<Logger::Error<<"Listening for TCP queries on "<<inet_ntoa(sin.sin_addr)<<":"<<::arg().asNum("local-port")<<endl;
471  }
472}
473
474void makeUDPServerSockets()
475{
476  vector<string>locals;
477  stringtok(locals,::arg()["local-address"]," ,");
478
479  if(locals.empty())
480    throw AhuException("No local address specified");
481 
482  if(::arg()["local-address"]=="0.0.0.0") {
483    L<<Logger::Warning<<"It is advised to bind to explicit addresses with the --local-address option"<<endl;
484  }
485
486  for(vector<string>::const_iterator i=locals.begin();i!=locals.end();++i) {
487    int fd=socket(AF_INET, SOCK_DGRAM,0);
488    if(fd<0) 
489      throw AhuException("Making a server socket for resolver: "+stringerror());
490    setReceiveBuffer(fd, 200000);
491    struct sockaddr_in sin;
492    memset((char *)&sin,0, sizeof(sin));
493   
494    sin.sin_family = AF_INET;
495    if(!IpToU32(*i, &sin.sin_addr.s_addr))
496      throw AhuException("Unable to resolve local address '"+ *i +"'"); 
497   
498    sin.sin_port = htons(::arg().asNum("local-port")); 
499   
500    if (::bind(fd, (struct sockaddr *)&sin, sizeof(sin))<0) 
501      throw AhuException("Resolver binding to server socket for "+*i+": "+stringerror());
502   
503    Utility::setNonBlocking(fd);
504    d_udpserversocks.push_back(fd);
505    L<<Logger::Error<<"Listening for UDP queries on "<<inet_ntoa(sin.sin_addr)<<":"<<::arg().asNum("local-port")<<endl;
506  }
507}
508
509
510#ifndef WIN32
511void daemonize(void)
512{
513  if(fork())
514    exit(0); // bye bye
515 
516  setsid(); 
517
518  // cleanup open fds, but skip sockets
519  close(0);
520  close(1);
521  close(2);
522}
523#endif
524
525uint64_t counter;
526bool statsWanted;
527
528
529void usr1Handler(int)
530{
531  statsWanted=true;
532}
533
534
535
536void usr2Handler(int)
537{
538  SyncRes::setLog(true);
539  g_quiet=false;
540  ::arg().set("quiet")="no";
541
542}
543
544void doStats(void)
545{
546  if(g_stats.qcounter) {
547    L<<Logger::Error<<"stats: "<<g_stats.qcounter<<" questions, "<<RC.size()<<" cache entries, "<<SyncRes::s_negcache.size()<<" negative entries, "
548     <<(int)((RC.cacheHits*100.0)/(RC.cacheHits+RC.cacheMisses))<<"% cache hits"<<endl;
549    L<<Logger::Error<<"stats: throttle map: "<<SyncRes::s_throttle.size()<<", ns speeds: "
550     <<SyncRes::s_nsSpeeds.size()<<endl; // ", bytes: "<<RC.bytes()<<endl;
551    L<<Logger::Error<<"stats: outpacket/query ratio "<<(int)(SyncRes::s_outqueries*100.0/SyncRes::s_queries)<<"%";
552    L<<Logger::Error<<", "<<(int)(SyncRes::s_throttledqueries*100.0/(SyncRes::s_outqueries+SyncRes::s_throttledqueries))<<"% throttled, "
553     <<SyncRes::s_nodelegated<<" no-delegation drops"<<endl;
554    L<<Logger::Error<<"stats: "<<SyncRes::s_tcpoutqueries<<" outgoing tcp connections, "<<MT->numProcesses()<<" queries running, "<<SyncRes::s_outgoingtimeouts<<" outgoing timeouts"<<endl;
555  }
556  else if(statsWanted) 
557    L<<Logger::Error<<"stats: no stats yet!"<<endl;
558
559  statsWanted=false;
560}
561
562static void houseKeeping(void *)
563{
564  static time_t last_stat, last_rootupdate, last_prune;
565  struct timeval now;
566  gettimeofday(&now, 0);
567
568  if(now.tv_sec - last_prune > 300) { 
569    DTime dt;
570    dt.setTimeval(now);
571    RC.doPrune();
572   
573    typedef SyncRes::negcache_t::nth_index<1>::type negcache_by_ttd_index_t;
574    negcache_by_ttd_index_t& ttdindex=boost::multi_index::get<1>(SyncRes::s_negcache);
575
576    negcache_by_ttd_index_t::iterator i=ttdindex.lower_bound(now.tv_sec);
577    ttdindex.erase(ttdindex.begin(), i);
578
579    time_t limit=now.tv_sec-300;
580    for(SyncRes::nsspeeds_t::iterator i = SyncRes::s_nsSpeeds.begin() ; i!= SyncRes::s_nsSpeeds.end(); )
581      if(i->second.stale(limit))
582        SyncRes::s_nsSpeeds.erase(i++);
583      else
584        ++i;
585
586    //   cerr<<"Pruned "<<pruned<<" records, left "<<SyncRes::s_negcache.size()<<"\n";
587//    cout<<"Prune took "<<dt.udiff()<<"usec\n";
588    last_prune=time(0);
589  }
590  if(now.tv_sec - last_stat>1800) { 
591    doStats();
592    last_stat=time(0);
593  }
594  if(now.tv_sec -last_rootupdate>7200) {
595    SyncRes sr(now);
596    vector<DNSResourceRecord> ret;
597
598    sr.setNoCache();
599    int res=sr.beginResolve(".", QType(QType::NS), ret);
600    if(!res) {
601      L<<Logger::Error<<"Refreshed . records"<<endl;
602      last_rootupdate=now.tv_sec;
603    }
604    else
605      L<<Logger::Error<<"Failed to update . records, RCODE="<<res<<endl;
606  }
607}
608
609map<uint32_t, uint32_t> g_tcpClientCounts;
610struct TCPConnection
611{
612  int fd;
613  enum {BYTE0, BYTE1, GETQUESTION} state;
614  int qlen;
615  int bytesread;
616  struct sockaddr_in remote;
617  char data[65535];
618  time_t startTime;
619
620  void closeAndCleanup()
621  {
622    close(fd);
623    if(!g_tcpClientCounts[remote.sin_addr.s_addr]--) 
624      g_tcpClientCounts.erase(remote.sin_addr.s_addr);
625  }
626};
627
628#if 0
629#include <execinfo.h>
630
631  multimap<uint32_t,string> rev;
632  for(map<string,uint32_t>::const_iterator i=casesptr->begin(); i!=casesptr->end(); ++i) {
633    rev.insert(make_pair(i->second,i->first));
634  }
635  for(multimap<uint32_t,string>::const_iterator i=rev.begin(); i!= rev.end(); ++i)
636    cout<<i->first<<" times: \n"<<i->second<<"\n";
637
638  cout.flush();
639
640map<string,uint32_t>* casesptr;
641static string maketrace()
642{
643  void *array[20]; //only care about last 17 functions (3 taken with tracing support)
644  size_t size;
645  char **strings;
646  size_t i;
647
648  size = backtrace (array, 5);
649  strings = backtrace_symbols (array, size); //Need -rdynamic gcc (linker) flag for this to work
650
651  string ret;
652
653  for (i = 0; i < size; i++) //skip useless functions
654    ret+=string(strings[i])+"\n";
655  return ret;
656}
657
658extern "C" {
659
660int gettimeofday (struct timeval *__restrict __tv,
661                  __timezone_ptr_t __tz)
662{
663  static map<string, uint32_t> s_cases;
664  casesptr=&s_cases;
665  s_cases[maketrace()]++;
666  __tv->tv_sec=time(0);
667  return 0;
668}
669
670}
671#endif
672
673int main(int argc, char **argv) 
674{
675  reportBasicTypes();
676
677  int ret = EXIT_SUCCESS;
678#ifdef WIN32
679    WSADATA wsaData;
680    WSAStartup( MAKEWORD( 2, 0 ), &wsaData );
681#endif // WIN32
682
683  try {
684    Utility::srandom(time(0));
685    ::arg().set("soa-minimum-ttl","Don't change")="0";
686    ::arg().set("soa-serial-offset","Don't change")="0";
687    ::arg().set("no-shuffle","Don't change")="off";
688    ::arg().set("aaaa-additional-processing","turn on to do AAAA additional processing (slow)")="off";
689    ::arg().set("local-port","port to listen on")="53";
690    ::arg().set("local-address","IP addresses to listen on, separated by spaces or commas")="0.0.0.0";
691    ::arg().set("trace","if we should output heaps of logging")="off";
692    ::arg().set("daemon","Operate as a daemon")="yes";
693    ::arg().set("chroot","switch to chroot jail")="";
694    ::arg().set("setgid","If set, change group id to this gid for more security")="";
695    ::arg().set("setuid","If set, change user id to this uid for more security")="";
696    ::arg().set("quiet","Suppress logging of questions and answers")="true";
697    ::arg().set("config-dir","Location of configuration directory (recursor.conf)")=SYSCONFDIR;
698    ::arg().set("socket-dir","Where the controlsocket will live")=LOCALSTATEDIR;
699    ::arg().set("delegation-only","Which domains we only accept delegations from")="";
700    ::arg().set("query-local-address","Source IP address for sending queries")="0.0.0.0";
701    ::arg().set("client-tcp-timeout","Timeout in seconds when talking to TCP clients")="2";
702    ::arg().set("max-tcp-clients","Maximum number of simultaneous TCP clients")="128";
703    ::arg().set("hint-file", "If set, load root hints from this file")="";
704    ::arg().set("max-cache-entries", "If set, maximum number of entries in the main cache")="0";
705    ::arg().set("allow-from", "If set, only allow these comma separated netmasks to recurse")="";
706    ::arg().set("max-tcp-per-client", "If set, maximum number of TCP sessions per client (IP address)")="0";
707    ::arg().set("fork", "If set, fork the daemon for possible double performance")="no";
708
709    ::arg().setCmd("help","Provide a helpful message");
710    L.toConsole(Logger::Warning);
711    ::arg().laxParse(argc,argv); // do a lax parse
712
713    string configname=::arg()["config-dir"]+"/recursor.conf";
714    cleanSlashes(configname);
715
716    if(!::arg().file(configname.c_str())) 
717      L<<Logger::Warning<<"Unable to parse configuration file '"<<configname<<"'"<<endl;
718
719    ::arg().parse(argc,argv);
720
721    ::arg().set("delegation-only")=toLower(::arg()["delegation-only"]);
722
723    if(::arg().mustDo("help")) {
724      cerr<<"syntax:"<<endl<<endl;
725      cerr<<::arg().helpstring(::arg()["help"])<<endl;
726      exit(99);
727    }
728
729    if(!::arg()["allow-from"].empty()) {
730      g_allowFrom=new NetmaskGroup;
731      vector<string> ips;
732      stringtok(ips, ::arg()["allow-from"], ", ");
733      for(vector<string>::const_iterator i = ips.begin(); i!= ips.end(); ++i)
734        g_allowFrom->addMask(*i);
735    }
736
737    L.setName("pdns_recursor");
738
739    L<<Logger::Warning<<"PowerDNS recursor "<<VERSION<<" (C) 2001-2006 PowerDNS.COM BV ("<<__DATE__", "__TIME__;
740#ifdef __GNUC__
741    L<<", gcc "__VERSION__;
742#endif // add other compilers here
743    L<<") starting up"<<endl;
744
745    L<<Logger::Warning<<"Operating in "<<(sizeof(unsigned long)*8) <<" bits mode"<<endl;
746  L<<Logger::Warning<<"PowerDNS comes with ABSOLUTELY NO WARRANTY. "
747    "This is free software, and you are welcome to redistribute it "
748    "according to the terms of the GPL version 2."<<endl;
749
750
751  g_quiet=::arg().mustDo("quiet");
752  if(::arg().mustDo("trace")) {
753      SyncRes::setLog(true);
754      ::arg().set("quiet")="no";
755      g_quiet=false;
756  }
757
758    makeUDPServerSockets();
759    makeTCPServerSockets();
760
761    if(::arg().mustDo("fork")) {
762      fork();
763      L<<Logger::Warning<<"This is forked pid "<<getpid()<<endl;
764    }
765    makeClientSocket();
766
767    makeControlChannelSocket();
768   
769    MT=new MTasker<PacketID,string>(100000);
770
771    char data[1500];
772    struct sockaddr_in fromaddr;
773   
774    PacketID pident;
775    primeHints();   
776    L<<Logger::Warning<<"Done priming cache with root hints"<<endl;
777#ifndef WIN32
778    if(::arg().mustDo("daemon")) {
779      L.toConsole(Logger::Critical);
780      daemonize();
781    }
782    signal(SIGUSR1,usr1Handler);
783    signal(SIGUSR2,usr2Handler);
784    signal(SIGPIPE,SIG_IGN);
785
786    writePid();
787#endif
788
789    int newgid=0;
790    if(!::arg()["setgid"].empty())
791      newgid=Utility::makeGidNumeric(::arg()["setgid"]);
792    int newuid=0;
793    if(!::arg()["setuid"].empty())
794      newuid=Utility::makeUidNumeric(::arg()["setuid"]);
795
796
797    if (!::arg()["chroot"].empty()) {
798        if (chroot(::arg()["chroot"].c_str())<0) {
799            L<<Logger::Error<<"Unable to chroot to '"+::arg()["chroot"]+"': "<<strerror (errno)<<", exiting"<<endl;
800            exit(1);
801        }
802    }
803
804    Utility::dropPrivs(newuid, newgid);
805
806    vector<TCPConnection> tcpconnections;
807    counter=0;
808    struct timeval now;
809    unsigned int maxTcpClients=::arg().asNum("max-tcp-clients");
810    int tcpTimeout=::arg().asNum("client-tcp-timeout");
811
812    unsigned int maxTCPPerClient=::arg().asNum("max-tcp-per-client");
813
814    for(;;) {
815      while(MT->schedule()); // housekeeping, let threads do their thing
816     
817      if(!((counter++)%500)) 
818        MT->makeThread(houseKeeping,0);
819      if(statsWanted) {
820        doStats();
821      }
822
823      Utility::socklen_t addrlen=sizeof(fromaddr);
824      int d_len;
825     
826      struct timeval tv;
827      tv.tv_sec=0;
828      tv.tv_usec=500000;
829     
830      fd_set readfds, writefds;
831      FD_ZERO( &readfds );
832      FD_ZERO( &writefds );
833      FD_SET( d_clientsock, &readfds );
834      FD_SET( s_rcc.d_fd, &readfds);
835      int fdmax=max(d_clientsock, s_rcc.d_fd);
836
837      if(!tcpconnections.empty())
838        gettimeofday(&now, 0);
839
840      vector<TCPConnection> sweeped;
841
842      for(vector<TCPConnection>::iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) {
843        if(now.tv_sec < i->startTime + tcpTimeout) {
844          FD_SET(i->fd, &readfds);
845          fdmax=max(fdmax,i->fd);
846          sweeped.push_back(*i);
847        }
848        else {
849          L<<Logger::Error<<"TCP timeout from client "<<inet_ntoa(i->remote.sin_addr)<<endl;
850          i->closeAndCleanup();
851        }
852      }
853      sweeped.swap(tcpconnections);
854
855      for(vector<int>::const_iterator i=d_udpserversocks.begin(); i!=d_udpserversocks.end(); ++i) {
856        FD_SET( *i, &readfds );
857        fdmax=max(fdmax,*i);
858      }
859      if(tcpconnections.size() < maxTcpClients) 
860        for(tcpserversocks_t::const_iterator i=s_tcpserversocks.begin(); i!=s_tcpserversocks.end(); ++i) {
861          FD_SET(*i, &readfds );
862          fdmax=max(fdmax,*i);
863        }
864
865      for(map<int,PacketID>::const_iterator i=d_tcpclientreadsocks.begin(); i!=d_tcpclientreadsocks.end(); ++i) {
866        // cerr<<"Adding TCP socket "<<i->first<<" to read select set"<<endl;
867        FD_SET( i->first, &readfds );
868        fdmax=max(fdmax,i->first);
869      }
870
871      for(map<int,PacketID>::const_iterator i=d_tcpclientwritesocks.begin(); i!=d_tcpclientwritesocks.end(); ++i) {
872        // cerr<<"Adding TCP socket "<<i->first<<" to write select set"<<endl;
873        FD_SET( i->first, &writefds );
874        fdmax=max(fdmax,i->first);
875      }
876
877      int selret = select(  fdmax + 1, &readfds, &writefds, NULL, &tv );
878      gettimeofday(&now, 0);
879      if(selret<=0) 
880        if (selret == -1 && errno!=EINTR) 
881          throw AhuException("Select returned: "+stringerror());
882        else
883          continue;
884
885      if(FD_ISSET(s_rcc.d_fd, &readfds)) {
886        string remote;
887        string msg=s_rcc.recv(&remote);
888        RecursorControlParser rcp;
889        RecursorControlParser::func_t* command;
890        string answer=rcp.getAnswer(msg, &command);
891        s_rcc.send(answer, &remote);
892        command();
893      }
894
895      if(FD_ISSET(d_clientsock,&readfds)) { // do we have a UDP question response?
896        while((d_len=recvfrom(d_clientsock, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen)) >= 0) {
897        try {
898            DNSComboWriter dc(data, d_len, now);
899            dc.setRemote((struct sockaddr *)&fromaddr, addrlen);
900
901            if(dc.d_mdp.d_header.qr) {
902              pident.remote=fromaddr;
903              pident.id=dc.d_mdp.d_header.id;
904              string packet;
905              packet.assign(data, d_len);
906              MT->sendEvent(pident, &packet);
907            }
908            else 
909              L<<Logger::Warning<<"Ignoring question on outgoing socket from "<<dc.getRemote()<<endl;
910          }
911          catch(MOADNSException& mde) {
912            L<<Logger::Error<<"Unable to parse packet from remote UDP server "<< sockAddrToString((struct sockaddr_in*) &fromaddr, addrlen) <<": "<<mde.what()<<endl;
913          }
914        }
915      }
916     
917      for(vector<int>::const_iterator i=d_udpserversocks.begin(); i!=d_udpserversocks.end(); ++i) {
918        if(FD_ISSET(*i,&readfds)) { // do we have a new question on udp?
919          while((d_len=recvfrom(*i, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen)) >= 0) {
920            g_stats.queryrate.pulse(now);
921            if(g_allowFrom && !g_allowFrom->match(&fromaddr)) {
922              g_stats.unauthorizedUDP++;
923              continue;
924            }
925
926            try {
927              DNSComboWriter* dc = new DNSComboWriter(data, d_len, now);
928
929              dc->setRemote((struct sockaddr *)&fromaddr, addrlen);
930
931              if(dc->d_mdp.d_header.qr)
932                L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
933              else {
934                ++g_stats.qcounter;
935                dc->setSocket(*i);
936                dc->d_tcp=false;
937                MT->makeThread(startDoResolve, (void*) dc);
938              }
939            }
940            catch(MOADNSException& mde) {
941              L<<Logger::Error<<"Unable to parse packet from remote udp client "<< sockAddrToString((struct sockaddr_in*) &fromaddr, addrlen) <<": "<<mde.what()<<endl;
942            }
943          }
944        }
945      }
946
947      for(tcpserversocks_t::const_iterator i=s_tcpserversocks.begin(); i!=s_tcpserversocks.end(); ++i) { 
948        if(FD_ISSET(*i ,&readfds)) { // do we have a new TCP connection?
949          struct sockaddr_in addr;
950          socklen_t addrlen=sizeof(addr);
951          int newsock=accept(*i, (struct sockaddr*)&addr, &addrlen);
952          if(newsock>0) {
953            if(g_allowFrom && !g_allowFrom->match(&addr)) {
954              g_stats.unauthorizedTCP++;
955              close(newsock);
956              continue;
957            }
958
959            if(maxTCPPerClient && g_tcpClientCounts.count(addr.sin_addr.s_addr) && g_tcpClientCounts[addr.sin_addr.s_addr] >= maxTCPPerClient) {
960              g_stats.tcpClientOverflow++;
961              close(newsock); // don't call TCPConnection::closeAndCleanup here - did not enter it in the counts yet!
962              continue;
963            }
964            g_tcpClientCounts[addr.sin_addr.s_addr]++;
965            Utility::setNonBlocking(newsock);
966            TCPConnection tc;
967            tc.fd=newsock;
968            tc.state=TCPConnection::BYTE0;
969            tc.remote=addr;
970            tc.startTime=now.tv_sec;
971            tcpconnections.push_back(tc);
972          }
973        }
974      }
975
976      // have any question answers come in over TCP?
977      for(map<int,PacketID>::iterator i=d_tcpclientreadsocks.begin(); i!=d_tcpclientreadsocks.end();) { 
978        bool haveErased=false;
979        if(FD_ISSET(i->first, &readfds)) { // can we receive
980          shared_array<char> buffer(new char[i->second.inNeeded]);
981
982          int ret=read(i->first, buffer.get(), min(i->second.inNeeded,200));
983          // cerr<<"Read returned "<<ret<<endl;
984          if(ret > 0) {
985            i->second.inMSG.append(&buffer[0], &buffer[ret]);
986            i->second.inNeeded-=ret;
987            if(!i->second.inNeeded) {
988              // cerr<<"Got entire load of "<<i->second.inMSG.size()<<" bytes"<<endl;
989              PacketID pid=i->second;
990              string msg=i->second.inMSG;
991             
992              d_tcpclientreadsocks.erase((i++));
993              haveErased=true;
994              MT->sendEvent(pid, &msg);   // XXX DODGY
995            }
996            else {
997              // cerr<<"Still have "<<i->second.inNeeded<<" left to go"<<endl;
998            }
999          }
1000          else {
1001            //      cerr<<"when reading ret="<<ret<<endl;
1002            // XXX FIXME I think some stuff needs to happen here - like send an EOF event
1003          }
1004        }
1005        if(!haveErased)
1006          ++i;
1007      }
1008     
1009      // is there data we can send to remote nameservers over TCP?
1010      for(map<int,PacketID>::iterator i=d_tcpclientwritesocks.begin(); i!=d_tcpclientwritesocks.end(); ) { 
1011        bool haveErased=false;
1012        if(FD_ISSET(i->first, &writefds)) { // can we send over TCP
1013          // cerr<<"Socket "<<i->first<<" available for writing"<<endl;
1014          int ret=write(i->first, i->second.outMSG.c_str(), i->second.outMSG.size() - i->second.outPos);
1015          if(ret > 0) {
1016            i->second.outPos+=ret;
1017            if(i->second.outPos==i->second.outMSG.size()) {
1018              // cerr<<"Sent out entire load of "<<i->second.outMSG.size()<<" bytes"<<endl;
1019              PacketID pid=i->second;
1020              d_tcpclientwritesocks.erase(i++);   // erase!
1021              haveErased=true;
1022              MT->sendEvent(pid, 0);
1023            }
1024
1025          }
1026          else { 
1027            //      cerr<<"ret="<<ret<<" when writing"<<endl;
1028            // XXX FIXME I think some stuff needs to happen here - like send an EOF event
1029          }
1030        }
1031        if(!haveErased)
1032          ++i;
1033      }
1034     
1035      // very braindead TCP incoming question parser
1036      for(vector<TCPConnection>::iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) {
1037        if(FD_ISSET(i->fd, &readfds)) {
1038          if(i->state==TCPConnection::BYTE0) {
1039            int bytes=read(i->fd,i->data,2);
1040            if(bytes==1)
1041              i->state=TCPConnection::BYTE1;
1042            if(bytes==2) { 
1043              i->qlen=(i->data[0]<<8)+i->data[1];
1044              i->bytesread=0;
1045              i->state=TCPConnection::GETQUESTION;
1046            }
1047            if(!bytes || bytes < 0) {
1048              i->closeAndCleanup();
1049              tcpconnections.erase(i);
1050              break;
1051            }
1052          }
1053          else if(i->state==TCPConnection::BYTE1) {
1054            int bytes=read(i->fd,i->data+1,1);
1055            if(bytes==1) {
1056              i->state=TCPConnection::GETQUESTION;
1057              i->qlen=(i->data[0]<<8)+i->data[1];
1058              i->bytesread=0;
1059            }
1060            if(!bytes || bytes < 0) {
1061              L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected after first byte"<<endl;
1062              i->closeAndCleanup();
1063              tcpconnections.erase(i);
1064              break;
1065            }
1066           
1067          }
1068          else if(i->state==TCPConnection::GETQUESTION) {
1069            int bytes=read(i->fd,i->data + i->bytesread,i->qlen - i->bytesread);
1070            if(!bytes || bytes < 0) {
1071              L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected while reading question body"<<endl;
1072              i->closeAndCleanup();
1073              tcpconnections.erase(i);
1074              break;
1075            }
1076            i->bytesread+=bytes;
1077            if(i->bytesread==i->qlen) {
1078              i->state=TCPConnection::BYTE0;
1079              DNSComboWriter* dc=0;
1080              try {
1081                dc=new DNSComboWriter(i->data, i->qlen, now);
1082              }
1083              catch(MOADNSException &mde) {
1084                L<<Logger::Error<<"Unable to parse packet from remote TCP client "<<sockAddrToString(&i->remote,sizeof(i->remote))<<endl;
1085                i->closeAndCleanup();
1086                tcpconnections.erase(i);
1087                break;
1088              }
1089
1090              dc->setSocket(i->fd);
1091              dc->d_tcp=true;
1092              dc->setRemote((struct sockaddr *)&i->remote,sizeof(i->remote));
1093              if(dc->d_mdp.d_header.qr)
1094                L<<Logger::Error<<"Ignoring answer on server socket!"<<endl;
1095              else {
1096                ++g_stats.qcounter;
1097                ++g_stats.tcpqcounter;
1098                MT->makeThread(startDoResolve, dc);
1099              }
1100            }
1101          }
1102        }
1103      }
1104    }
1105  }
1106  catch(AhuException &ae) {
1107    L<<Logger::Error<<"Exception: "<<ae.reason<<endl;
1108    ret=EXIT_FAILURE;
1109  }
1110  catch(exception &e) {
1111    L<<Logger::Error<<"STL Exception: "<<e.what()<<endl;
1112    ret=EXIT_FAILURE;
1113  }
1114  catch(...) {
1115    L<<Logger::Error<<"any other exception in main: "<<endl;
1116    ret=EXIT_FAILURE;
1117  }
1118 
1119#ifdef WIN32
1120  WSACleanup();
1121#endif // WIN32
1122
1123  return ret;
1124}
Note: See TracBrowser for help on using the browser.