| 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" |
|---|
| 54 | StatBag S; |
|---|
| 55 | #endif |
|---|
| 56 | |
|---|
| 57 | |
|---|
| 58 | using namespace boost; |
|---|
| 59 | |
|---|
| 60 | #ifdef __FreeBSD__ // see cvstrac ticket #26 |
|---|
| 61 | #include <pthread.h> |
|---|
| 62 | #include <semaphore.h> |
|---|
| 63 | #endif |
|---|
| 64 | |
|---|
| 65 | MemRecursorCache RC; |
|---|
| 66 | RecursorStats g_stats; |
|---|
| 67 | bool g_quiet; |
|---|
| 68 | NetmaskGroup* g_allowFrom; |
|---|
| 69 | string s_programname="pdns_recursor"; |
|---|
| 70 | |
|---|
| 71 | struct 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__ |
|---|
| 101 | extern "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 | |
|---|
| 116 | ArgvMap &arg() |
|---|
| 117 | { |
|---|
| 118 | static ArgvMap theArg; |
|---|
| 119 | return theArg; |
|---|
| 120 | } |
|---|
| 121 | static int d_clientsock; |
|---|
| 122 | static vector<int> d_udpserversocks; |
|---|
| 123 | |
|---|
| 124 | typedef vector<int> tcpserversocks_t; |
|---|
| 125 | static tcpserversocks_t s_tcpserversocks; |
|---|
| 126 | |
|---|
| 127 | static map<int,PacketID> d_tcpclientreadsocks, d_tcpclientwritesocks; |
|---|
| 128 | |
|---|
| 129 | MTasker<PacketID,string>* MT; |
|---|
| 130 | |
|---|
| 131 | int 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 |
|---|
| 148 | int 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 |
|---|
| 167 | int 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 |
|---|
| 173 | int 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 | |
|---|
| 188 | void 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 | |
|---|
| 203 | static 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 | |
|---|
| 213 | void 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 | |
|---|
| 261 | void 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 | |
|---|
| 387 | RecursorControlChannel s_rcc; |
|---|
| 388 | |
|---|
| 389 | void makeControlChannelSocket() |
|---|
| 390 | { |
|---|
| 391 | s_rcc.listen(::arg()["socket-dir"]+"/pdns_recursor.controlsocket"); |
|---|
| 392 | } |
|---|
| 393 | |
|---|
| 394 | void 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 | |
|---|
| 425 | void 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 | |
|---|
| 469 | void 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 |
|---|
| 506 | void 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 | |
|---|
| 520 | uint64_t counter; |
|---|
| 521 | bool statsWanted; |
|---|
| 522 | |
|---|
| 523 | |
|---|
| 524 | void usr1Handler(int) |
|---|
| 525 | { |
|---|
| 526 | statsWanted=true; |
|---|
| 527 | } |
|---|
| 528 | |
|---|
| 529 | |
|---|
| 530 | |
|---|
| 531 | void usr2Handler(int) |
|---|
| 532 | { |
|---|
| 533 | SyncRes::setLog(true); |
|---|
| 534 | g_quiet=false; |
|---|
| 535 | ::arg().set("quiet")="no"; |
|---|
| 536 | |
|---|
| 537 | } |
|---|
| 538 | |
|---|
| 539 | void 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 | |
|---|
| 557 | static 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 > 60) { |
|---|
| 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 | |
|---|
| 604 | struct TCPConnection |
|---|
| 605 | { |
|---|
| 606 | int fd; |
|---|
| 607 | enum {BYTE0, BYTE1, GETQUESTION} state; |
|---|
| 608 | int qlen; |
|---|
| 609 | int bytesread; |
|---|
| 610 | struct sockaddr_in remote; |
|---|
| 611 | char data[65535]; |
|---|
| 612 | time_t startTime; |
|---|
| 613 | }; |
|---|
| 614 | |
|---|
| 615 | #if 0 |
|---|
| 616 | #include <execinfo.h> |
|---|
| 617 | |
|---|
| 618 | multimap<uint32_t,string> rev; |
|---|
| 619 | for(map<string,uint32_t>::const_iterator i=casesptr->begin(); i!=casesptr->end(); ++i) { |
|---|
| 620 | rev.insert(make_pair(i->second,i->first)); |
|---|
| 621 | } |
|---|
| 622 | for(multimap<uint32_t,string>::const_iterator i=rev.begin(); i!= rev.end(); ++i) |
|---|
| 623 | cout<<i->first<<" times: \n"<<i->second<<"\n"; |
|---|
| 624 | |
|---|
| 625 | cout.flush(); |
|---|
| 626 | |
|---|
| 627 | map<string,uint32_t>* casesptr; |
|---|
| 628 | static string maketrace() |
|---|
| 629 | { |
|---|
| 630 | void *array[20]; //only care about last 17 functions (3 taken with tracing support) |
|---|
| 631 | size_t size; |
|---|
| 632 | char **strings; |
|---|
| 633 | size_t i; |
|---|
| 634 | |
|---|
| 635 | size = backtrace (array, 5); |
|---|
| 636 | strings = backtrace_symbols (array, size); //Need -rdynamic gcc (linker) flag for this to work |
|---|
| 637 | |
|---|
| 638 | string ret; |
|---|
| 639 | |
|---|
| 640 | for (i = 0; i < size; i++) //skip useless functions |
|---|
| 641 | ret+=string(strings[i])+"\n"; |
|---|
| 642 | return ret; |
|---|
| 643 | } |
|---|
| 644 | |
|---|
| 645 | extern "C" { |
|---|
| 646 | |
|---|
| 647 | int gettimeofday (struct timeval *__restrict __tv, |
|---|
| 648 | __timezone_ptr_t __tz) |
|---|
| 649 | { |
|---|
| 650 | static map<string, uint32_t> s_cases; |
|---|
| 651 | casesptr=&s_cases; |
|---|
| 652 | s_cases[maketrace()]++; |
|---|
| 653 | __tv->tv_sec=time(0); |
|---|
| 654 | return 0; |
|---|
| 655 | } |
|---|
| 656 | |
|---|
| 657 | } |
|---|
| 658 | #endif |
|---|
| 659 | |
|---|
| 660 | int main(int argc, char **argv) |
|---|
| 661 | { |
|---|
| 662 | reportBasicTypes(); |
|---|
| 663 | |
|---|
| 664 | int ret = EXIT_SUCCESS; |
|---|
| 665 | #ifdef WIN32 |
|---|
| 666 | WSADATA wsaData; |
|---|
| 667 | WSAStartup( MAKEWORD( 2, 0 ), &wsaData ); |
|---|
| 668 | #endif // WIN32 |
|---|
| 669 | |
|---|
| 670 | try { |
|---|
| 671 | Utility::srandom(time(0)); |
|---|
| 672 | ::arg().set("soa-minimum-ttl","Don't change")="0"; |
|---|
| 673 | ::arg().set("soa-serial-offset","Don't change")="0"; |
|---|
| 674 | ::arg().set("no-shuffle","Don't change")="off"; |
|---|
| 675 | ::arg().set("aaaa-additional-processing","turn on to do AAAA additional processing (slow)")="off"; |
|---|
| 676 | ::arg().set("local-port","port to listen on")="53"; |
|---|
| 677 | ::arg().set("local-address","IP addresses to listen on, separated by spaces or commas")="0.0.0.0"; |
|---|
| 678 | ::arg().set("trace","if we should output heaps of logging")="off"; |
|---|
| 679 | ::arg().set("daemon","Operate as a daemon")="yes"; |
|---|
| 680 | ::arg().set("chroot","switch to chroot jail")=""; |
|---|
| 681 | ::arg().set("setgid","If set, change group id to this gid for more security")=""; |
|---|
| 682 | ::arg().set("setuid","If set, change user id to this uid for more security")=""; |
|---|
| 683 | ::arg().set("quiet","Suppress logging of questions and answers")="true"; |
|---|
| 684 | ::arg().set("config-dir","Location of configuration directory (recursor.conf)")=SYSCONFDIR; |
|---|
| 685 | ::arg().set("socket-dir","Where the controlsocket will live")=LOCALSTATEDIR; |
|---|
| 686 | ::arg().set("delegation-only","Which domains we only accept delegations from")=""; |
|---|
| 687 | ::arg().set("query-local-address","Source IP address for sending queries")="0.0.0.0"; |
|---|
| 688 | ::arg().set("client-tcp-timeout","Timeout in seconds when talking to TCP clients")="2"; |
|---|
| 689 | ::arg().set("max-tcp-clients","Maximum number of simultaneous TCP clients")="128"; |
|---|
| 690 | ::arg().set("hint-file", "If set, load root hints from this file")=""; |
|---|
| 691 | ::arg().set("max-cache-entries", "If set, maximum number of entries in the main cache")="0"; |
|---|
| 692 | ::arg().set("allow-from", "If set, only allow these comma separated netmasks to recurse")=""; |
|---|
| 693 | |
|---|
| 694 | ::arg().setCmd("help","Provide a helpful message"); |
|---|
| 695 | L.toConsole(Logger::Warning); |
|---|
| 696 | ::arg().laxParse(argc,argv); // do a lax parse |
|---|
| 697 | |
|---|
| 698 | string configname=::arg()["config-dir"]+"/recursor.conf"; |
|---|
| 699 | cleanSlashes(configname); |
|---|
| 700 | |
|---|
| 701 | if(!::arg().file(configname.c_str())) |
|---|
| 702 | L<<Logger::Warning<<"Unable to parse configuration file '"<<configname<<"'"<<endl; |
|---|
| 703 | |
|---|
| 704 | ::arg().parse(argc,argv); |
|---|
| 705 | |
|---|
| 706 | ::arg().set("delegation-only")=toLower(::arg()["delegation-only"]); |
|---|
| 707 | |
|---|
| 708 | if(::arg().mustDo("help")) { |
|---|
| 709 | cerr<<"syntax:"<<endl<<endl; |
|---|
| 710 | cerr<<::arg().helpstring(::arg()["help"])<<endl; |
|---|
| 711 | exit(99); |
|---|
| 712 | } |
|---|
| 713 | |
|---|
| 714 | if(!::arg()["allow-from"].empty()) { |
|---|
| 715 | g_allowFrom=new NetmaskGroup; |
|---|
| 716 | vector<string> ips; |
|---|
| 717 | stringtok(ips, ::arg()["allow-from"], ", "); |
|---|
| 718 | for(vector<string>::const_iterator i = ips.begin(); i!= ips.end(); ++i) |
|---|
| 719 | g_allowFrom->addMask(*i); |
|---|
| 720 | } |
|---|
| 721 | |
|---|
| 722 | L.setName("pdns_recursor"); |
|---|
| 723 | |
|---|
| 724 | L<<Logger::Warning<<"PowerDNS recursor "<<VERSION<<" (C) 2001-2006 PowerDNS.COM BV ("<<__DATE__", "__TIME__; |
|---|
| 725 | #ifdef __GNUC__ |
|---|
| 726 | L<<", gcc "__VERSION__; |
|---|
| 727 | #endif // add other compilers here |
|---|
| 728 | L<<") starting up"<<endl; |
|---|
| 729 | |
|---|
| 730 | L<<Logger::Warning<<"Operating in "<<(sizeof(unsigned long)*8) <<" bits mode"<<endl; |
|---|
| 731 | L<<Logger::Warning<<"PowerDNS comes with ABSOLUTELY NO WARRANTY. " |
|---|
| 732 | "This is free software, and you are welcome to redistribute it " |
|---|
| 733 | "according to the terms of the GPL version 2."<<endl; |
|---|
| 734 | |
|---|
| 735 | |
|---|
| 736 | g_quiet=::arg().mustDo("quiet"); |
|---|
| 737 | if(::arg().mustDo("trace")) { |
|---|
| 738 | SyncRes::setLog(true); |
|---|
| 739 | ::arg().set("quiet")="no"; |
|---|
| 740 | g_quiet=false; |
|---|
| 741 | } |
|---|
| 742 | |
|---|
| 743 | makeClientSocket(); |
|---|
| 744 | makeUDPServerSockets(); |
|---|
| 745 | makeTCPServerSockets(); |
|---|
| 746 | makeControlChannelSocket(); |
|---|
| 747 | |
|---|
| 748 | MT=new MTasker<PacketID,string>(100000); |
|---|
| 749 | |
|---|
| 750 | char data[1500]; |
|---|
| 751 | struct sockaddr_in fromaddr; |
|---|
| 752 | |
|---|
| 753 | PacketID pident; |
|---|
| 754 | primeHints(); |
|---|
| 755 | L<<Logger::Warning<<"Done priming cache with root hints"<<endl; |
|---|
| 756 | #ifndef WIN32 |
|---|
| 757 | if(::arg().mustDo("daemon")) { |
|---|
| 758 | L.toConsole(Logger::Critical); |
|---|
| 759 | daemonize(); |
|---|
| 760 | } |
|---|
| 761 | signal(SIGUSR1,usr1Handler); |
|---|
| 762 | signal(SIGUSR2,usr2Handler); |
|---|
| 763 | signal(SIGPIPE,SIG_IGN); |
|---|
| 764 | |
|---|
| 765 | writePid(); |
|---|
| 766 | #endif |
|---|
| 767 | |
|---|
| 768 | int newgid=0; |
|---|
| 769 | if(!::arg()["setgid"].empty()) |
|---|
| 770 | newgid=Utility::makeGidNumeric(::arg()["setgid"]); |
|---|
| 771 | int newuid=0; |
|---|
| 772 | if(!::arg()["setuid"].empty()) |
|---|
| 773 | newuid=Utility::makeUidNumeric(::arg()["setuid"]); |
|---|
| 774 | |
|---|
| 775 | |
|---|
| 776 | if (!::arg()["chroot"].empty()) { |
|---|
| 777 | if (chroot(::arg()["chroot"].c_str())<0) { |
|---|
| 778 | L<<Logger::Error<<"Unable to chroot to '"+::arg()["chroot"]+"': "<<strerror (errno)<<", exiting"<<endl; |
|---|
| 779 | exit(1); |
|---|
| 780 | } |
|---|
| 781 | } |
|---|
| 782 | |
|---|
| 783 | Utility::dropPrivs(newuid, newgid); |
|---|
| 784 | |
|---|
| 785 | vector<TCPConnection> tcpconnections; |
|---|
| 786 | counter=0; |
|---|
| 787 | struct timeval now; |
|---|
| 788 | unsigned int maxTcpClients=::arg().asNum("max-tcp-clients"); |
|---|
| 789 | int tcpLimit=::arg().asNum("client-tcp-timeout"); |
|---|
| 790 | for(;;) { |
|---|
| 791 | while(MT->schedule()); // housekeeping, let threads do their thing |
|---|
| 792 | |
|---|
| 793 | if(!((counter++)%500)) |
|---|
| 794 | MT->makeThread(houseKeeping,0); |
|---|
| 795 | if(statsWanted) { |
|---|
| 796 | doStats(); |
|---|
| 797 | } |
|---|
| 798 | |
|---|
| 799 | Utility::socklen_t addrlen=sizeof(fromaddr); |
|---|
| 800 | int d_len; |
|---|
| 801 | |
|---|
| 802 | struct timeval tv; |
|---|
| 803 | tv.tv_sec=0; |
|---|
| 804 | tv.tv_usec=500000; |
|---|
| 805 | |
|---|
| 806 | fd_set readfds, writefds; |
|---|
| 807 | FD_ZERO( &readfds ); |
|---|
| 808 | FD_ZERO( &writefds ); |
|---|
| 809 | FD_SET( d_clientsock, &readfds ); |
|---|
| 810 | FD_SET( s_rcc.d_fd, &readfds); |
|---|
| 811 | int fdmax=max(d_clientsock, s_rcc.d_fd); |
|---|
| 812 | |
|---|
| 813 | if(!tcpconnections.empty()) |
|---|
| 814 | gettimeofday(&now, 0); |
|---|
| 815 | |
|---|
| 816 | vector<TCPConnection> sweeped; |
|---|
| 817 | |
|---|
| 818 | for(vector<TCPConnection>::iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) { |
|---|
| 819 | if(now.tv_sec < i->startTime + tcpLimit) { |
|---|
| 820 | FD_SET(i->fd, &readfds); |
|---|
| 821 | fdmax=max(fdmax,i->fd); |
|---|
| 822 | sweeped.push_back(*i); |
|---|
| 823 | } |
|---|
| 824 | else { |
|---|
| 825 | L<<Logger::Error<<"TCP timeout from client "<<inet_ntoa(i->remote.sin_addr)<<endl; |
|---|
| 826 | close(i->fd); |
|---|
| 827 | } |
|---|
| 828 | } |
|---|
| 829 | sweeped.swap(tcpconnections); |
|---|
| 830 | |
|---|
| 831 | for(vector<int>::const_iterator i=d_udpserversocks.begin(); i!=d_udpserversocks.end(); ++i) { |
|---|
| 832 | FD_SET( *i, &readfds ); |
|---|
| 833 | fdmax=max(fdmax,*i); |
|---|
| 834 | } |
|---|
| 835 | if(tcpconnections.size() < maxTcpClients) |
|---|
| 836 | for(tcpserversocks_t::const_iterator i=s_tcpserversocks.begin(); i!=s_tcpserversocks.end(); ++i) { |
|---|
| 837 | FD_SET(*i, &readfds ); |
|---|
| 838 | fdmax=max(fdmax,*i); |
|---|
| 839 | } |
|---|
| 840 | |
|---|
| 841 | for(map<int,PacketID>::const_iterator i=d_tcpclientreadsocks.begin(); i!=d_tcpclientreadsocks.end(); ++i) { |
|---|
| 842 | // cerr<<"Adding TCP socket "<<i->first<<" to read select set"<<endl; |
|---|
| 843 | FD_SET( i->first, &readfds ); |
|---|
| 844 | fdmax=max(fdmax,i->first); |
|---|
| 845 | } |
|---|
| 846 | |
|---|
| 847 | for(map<int,PacketID>::const_iterator i=d_tcpclientwritesocks.begin(); i!=d_tcpclientwritesocks.end(); ++i) { |
|---|
| 848 | // cerr<<"Adding TCP socket "<<i->first<<" to write select set"<<endl; |
|---|
| 849 | FD_SET( i->first, &writefds ); |
|---|
| 850 | fdmax=max(fdmax,i->first); |
|---|
| 851 | } |
|---|
| 852 | |
|---|
| 853 | int selret = select( fdmax + 1, &readfds, &writefds, NULL, &tv ); |
|---|
| 854 | gettimeofday(&now, 0); |
|---|
| 855 | if(selret<=0) |
|---|
| 856 | if (selret == -1 && errno!=EINTR) |
|---|
| 857 | throw AhuException("Select returned: "+stringerror()); |
|---|
| 858 | else |
|---|
| 859 | continue; |
|---|
| 860 | |
|---|
| 861 | if(FD_ISSET(s_rcc.d_fd, &readfds)) { |
|---|
| 862 | string remote; |
|---|
| 863 | string msg=s_rcc.recv(&remote); |
|---|
| 864 | RecursorControlParser rcp; |
|---|
| 865 | RecursorControlParser::func_t* command; |
|---|
| 866 | string answer=rcp.getAnswer(msg, &command); |
|---|
| 867 | s_rcc.send(answer, &remote); |
|---|
| 868 | command(); |
|---|
| 869 | } |
|---|
| 870 | |
|---|
| 871 | if(FD_ISSET(d_clientsock,&readfds)) { // do we have a UDP question response? |
|---|
| 872 | while((d_len=recvfrom(d_clientsock, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen)) >= 0) { |
|---|
| 873 | try { |
|---|
| 874 | DNSComboWriter dc(data, d_len, now); |
|---|
| 875 | dc.setRemote((struct sockaddr *)&fromaddr, addrlen); |
|---|
| 876 | |
|---|
| 877 | if(dc.d_mdp.d_header.qr) { |
|---|
| 878 | pident.remote=fromaddr; |
|---|
| 879 | pident.id=dc.d_mdp.d_header.id; |
|---|
| 880 | string packet; |
|---|
| 881 | packet.assign(data, d_len); |
|---|
| 882 | MT->sendEvent(pident, &packet); |
|---|
| 883 | } |
|---|
| 884 | else |
|---|
| 885 | L<<Logger::Warning<<"Ignoring question on outgoing socket from "<<dc.getRemote()<<endl; |
|---|
| 886 | } |
|---|
| 887 | catch(MOADNSException& mde) { |
|---|
| 888 | L<<Logger::Error<<"Unable to parse packet from remote UDP server "<< sockAddrToString((struct sockaddr_in*) &fromaddr, addrlen) <<": "<<mde.what()<<endl; |
|---|
| 889 | } |
|---|
| 890 | } |
|---|
| 891 | } |
|---|
| 892 | |
|---|
| 893 | for(vector<int>::const_iterator i=d_udpserversocks.begin(); i!=d_udpserversocks.end(); ++i) { |
|---|
| 894 | if(FD_ISSET(*i,&readfds)) { // do we have a new question on udp? |
|---|
| 895 | while((d_len=recvfrom(*i, data, sizeof(data), 0, (sockaddr *)&fromaddr, &addrlen)) >= 0) { |
|---|
| 896 | g_stats.queryrate.pulse(now); |
|---|
| 897 | if(g_allowFrom && !g_allowFrom->match(&fromaddr)) { |
|---|
| 898 | g_stats.unauthorizedUDP++; |
|---|
| 899 | continue; |
|---|
| 900 | } |
|---|
| 901 | |
|---|
| 902 | try { |
|---|
| 903 | DNSComboWriter* dc = new DNSComboWriter(data, d_len, now); |
|---|
| 904 | |
|---|
| 905 | dc->setRemote((struct sockaddr *)&fromaddr, addrlen); |
|---|
| 906 | |
|---|
| 907 | if(dc->d_mdp.d_header.qr) |
|---|
| 908 | L<<Logger::Error<<"Ignoring answer on server socket!"<<endl; |
|---|
| 909 | else { |
|---|
| 910 | ++g_stats.qcounter; |
|---|
| 911 | dc->setSocket(*i); |
|---|
| 912 | dc->d_tcp=false; |
|---|
| 913 | MT->makeThread(startDoResolve, (void*) dc); |
|---|
| 914 | } |
|---|
| 915 | } |
|---|
| 916 | catch(MOADNSException& mde) { |
|---|
| 917 | L<<Logger::Error<<"Unable to parse packet from remote udp client "<< sockAddrToString((struct sockaddr_in*) &fromaddr, addrlen) <<": "<<mde.what()<<endl; |
|---|
| 918 | } |
|---|
| 919 | } |
|---|
| 920 | } |
|---|
| 921 | } |
|---|
| 922 | |
|---|
| 923 | for(tcpserversocks_t::const_iterator i=s_tcpserversocks.begin(); i!=s_tcpserversocks.end(); ++i) { |
|---|
| 924 | if(FD_ISSET(*i ,&readfds)) { // do we have a new TCP connection? |
|---|
| 925 | struct sockaddr_in addr; |
|---|
| 926 | socklen_t addrlen=sizeof(addr); |
|---|
| 927 | int newsock=accept(*i, (struct sockaddr*)&addr, &addrlen); |
|---|
| 928 | if(newsock>0) { |
|---|
| 929 | if(g_allowFrom && !g_allowFrom->match(&addr)) { |
|---|
| 930 | g_stats.unauthorizedTCP++; |
|---|
| 931 | close(newsock); |
|---|
| 932 | continue; |
|---|
| 933 | } |
|---|
| 934 | |
|---|
| 935 | Utility::setNonBlocking(newsock); |
|---|
| 936 | TCPConnection tc; |
|---|
| 937 | tc.fd=newsock; |
|---|
| 938 | tc.state=TCPConnection::BYTE0; |
|---|
| 939 | tc.remote=addr; |
|---|
| 940 | tc.startTime=now.tv_sec; |
|---|
| 941 | tcpconnections.push_back(tc); |
|---|
| 942 | } |
|---|
| 943 | } |
|---|
| 944 | } |
|---|
| 945 | |
|---|
| 946 | // have any question answers come in over TCP? |
|---|
| 947 | for(map<int,PacketID>::iterator i=d_tcpclientreadsocks.begin(); i!=d_tcpclientreadsocks.end();) { |
|---|
| 948 | bool haveErased=false; |
|---|
| 949 | if(FD_ISSET(i->first, &readfds)) { // can we receive |
|---|
| 950 | shared_array<char> buffer(new char[i->second.inNeeded]); |
|---|
| 951 | |
|---|
| 952 | int ret=read(i->first, buffer.get(), min(i->second.inNeeded,200)); |
|---|
| 953 | // cerr<<"Read returned "<<ret<<endl; |
|---|
| 954 | if(ret > 0) { |
|---|
| 955 | i->second.inMSG.append(&buffer[0], &buffer[ret]); |
|---|
| 956 | i->second.inNeeded-=ret; |
|---|
| 957 | if(!i->second.inNeeded) { |
|---|
| 958 | // cerr<<"Got entire load of "<<i->second.inMSG.size()<<" bytes"<<endl; |
|---|
| 959 | PacketID pid=i->second; |
|---|
| 960 | string msg=i->second.inMSG; |
|---|
| 961 | |
|---|
| 962 | d_tcpclientreadsocks.erase((i++)); |
|---|
| 963 | haveErased=true; |
|---|
| 964 | MT->sendEvent(pid, &msg); // XXX DODGY |
|---|
| 965 | } |
|---|
| 966 | else { |
|---|
| 967 | // cerr<<"Still have "<<i->second.inNeeded<<" left to go"<<endl; |
|---|
| 968 | } |
|---|
| 969 | } |
|---|
| 970 | else { |
|---|
| 971 | // cerr<<"when reading ret="<<ret<<endl; |
|---|
| 972 | // XXX FIXME I think some stuff needs to happen here - like send an EOF event |
|---|
| 973 | } |
|---|
| 974 | } |
|---|
| 975 | if(!haveErased) |
|---|
| 976 | ++i; |
|---|
| 977 | } |
|---|
| 978 | |
|---|
| 979 | // is there data we can send to remote nameservers over TCP? |
|---|
| 980 | for(map<int,PacketID>::iterator i=d_tcpclientwritesocks.begin(); i!=d_tcpclientwritesocks.end(); ) { |
|---|
| 981 | bool haveErased=false; |
|---|
| 982 | if(FD_ISSET(i->first, &writefds)) { // can we send over TCP |
|---|
| 983 | // cerr<<"Socket "<<i->first<<" available for writing"<<endl; |
|---|
| 984 | int ret=write(i->first, i->second.outMSG.c_str(), i->second.outMSG.size() - i->second.outPos); |
|---|
| 985 | if(ret > 0) { |
|---|
| 986 | i->second.outPos+=ret; |
|---|
| 987 | if(i->second.outPos==i->second.outMSG.size()) { |
|---|
| 988 | // cerr<<"Sent out entire load of "<<i->second.outMSG.size()<<" bytes"<<endl; |
|---|
| 989 | PacketID pid=i->second; |
|---|
| 990 | d_tcpclientwritesocks.erase(i++); // erase! |
|---|
| 991 | haveErased=true; |
|---|
| 992 | MT->sendEvent(pid, 0); |
|---|
| 993 | } |
|---|
| 994 | |
|---|
| 995 | } |
|---|
| 996 | else { |
|---|
| 997 | // cerr<<"ret="<<ret<<" when writing"<<endl; |
|---|
| 998 | // XXX FIXME I think some stuff needs to happen here - like send an EOF event |
|---|
| 999 | } |
|---|
| 1000 | } |
|---|
| 1001 | if(!haveErased) |
|---|
| 1002 | ++i; |
|---|
| 1003 | } |
|---|
| 1004 | |
|---|
| 1005 | // very braindead TCP incoming question parser |
|---|
| 1006 | for(vector<TCPConnection>::iterator i=tcpconnections.begin();i!=tcpconnections.end();++i) { |
|---|
| 1007 | if(FD_ISSET(i->fd, &readfds)) { |
|---|
| 1008 | if(i->state==TCPConnection::BYTE0) { |
|---|
| 1009 | int bytes=read(i->fd,i->data,2); |
|---|
| 1010 | if(bytes==1) |
|---|
| 1011 | i->state=TCPConnection::BYTE1; |
|---|
| 1012 | if(bytes==2) { |
|---|
| 1013 | i->qlen=(i->data[0]<<8)+i->data[1]; |
|---|
| 1014 | i->bytesread=0; |
|---|
| 1015 | i->state=TCPConnection::GETQUESTION; |
|---|
| 1016 | } |
|---|
| 1017 | if(!bytes || bytes < 0) { |
|---|
| 1018 | close(i->fd); |
|---|
| 1019 | tcpconnections.erase(i); |
|---|
| 1020 | break; |
|---|
| 1021 | } |
|---|
| 1022 | } |
|---|
| 1023 | else if(i->state==TCPConnection::BYTE1) { |
|---|
| 1024 | int bytes=read(i->fd,i->data+1,1); |
|---|
| 1025 | if(bytes==1) { |
|---|
| 1026 | i->state=TCPConnection::GETQUESTION; |
|---|
| 1027 | i->qlen=(i->data[0]<<8)+i->data[1]; |
|---|
| 1028 | i->bytesread=0; |
|---|
| 1029 | } |
|---|
| 1030 | if(!bytes || bytes < 0) { |
|---|
| 1031 | L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected after first byte"<<endl; |
|---|
| 1032 | close(i->fd); |
|---|
| 1033 | tcpconnections.erase(i); |
|---|
| 1034 | break; |
|---|
| 1035 | } |
|---|
| 1036 | |
|---|
| 1037 | } |
|---|
| 1038 | else if(i->state==TCPConnection::GETQUESTION) { |
|---|
| 1039 | int bytes=read(i->fd,i->data + i->bytesread,i->qlen - i->bytesread); |
|---|
| 1040 | if(!bytes || bytes < 0) { |
|---|
| 1041 | L<<Logger::Error<<"TCP Remote "<<sockAddrToString(&i->remote,sizeof(i->remote))<<" disconnected while reading question body"<<endl; |
|---|
| 1042 | close(i->fd); |
|---|
| 1043 | tcpconnections.erase(i); |
|---|
| 1044 | break; |
|---|
| 1045 | } |
|---|
| 1046 | i->bytesread+=bytes; |
|---|
| 1047 | if(i->bytesread==i->qlen) { |
|---|
| 1048 | i->state=TCPConnection::BYTE0; |
|---|
| 1049 | DNSComboWriter* dc=0; |
|---|
| 1050 | try { |
|---|
| 1051 | dc=new DNSComboWriter(i->data, i->qlen, now); |
|---|
| 1052 | } |
|---|
| 1053 | catch(MOADNSException &mde) { |
|---|
| 1054 | L<<Logger::Error<<"Unable to parse packet from remote TCP client "<<sockAddrToString(&i->remote,sizeof(i->remote))<<endl; |
|---|
| 1055 | close(i->fd); |
|---|
| 1056 | tcpconnections.erase(i); |
|---|
| 1057 | break; |
|---|
| 1058 | } |
|---|
| 1059 | |
|---|
| 1060 | dc->setSocket(i->fd); |
|---|
| 1061 | dc->d_tcp=true; |
|---|
| 1062 | dc->setRemote((struct sockaddr *)&i->remote,sizeof(i->remote)); |
|---|
| 1063 | if(dc->d_mdp.d_header.qr) |
|---|
| 1064 | L<<Logger::Error<<"Ignoring answer on server socket!"<<endl; |
|---|
| 1065 | else { |
|---|
| 1066 | ++g_stats.qcounter; |
|---|
| 1067 | ++g_stats.tcpqcounter; |
|---|
| 1068 | MT->makeThread(startDoResolve, dc); |
|---|
| 1069 | } |
|---|
| 1070 | } |
|---|
| 1071 | } |
|---|
| 1072 | } |
|---|
| 1073 | } |
|---|
| 1074 | } |
|---|
| 1075 | } |
|---|
| 1076 | catch(AhuException &ae) { |
|---|
| 1077 | L<<Logger::Error<<"Exception: "<<ae.reason<<endl; |
|---|
| 1078 | ret=EXIT_FAILURE; |
|---|
| 1079 | } |
|---|
| 1080 | catch(exception &e) { |
|---|
| 1081 | L<<Logger::Error<<"STL Exception: "<<e.what()<<endl; |
|---|
| 1082 | ret=EXIT_FAILURE; |
|---|
| 1083 | } |
|---|
| 1084 | catch(...) { |
|---|
| 1085 | L<<Logger::Error<<"any other exception in main: "<<endl; |
|---|
| 1086 | ret=EXIT_FAILURE; |
|---|
| 1087 | } |
|---|
| 1088 | |
|---|
| 1089 | #ifdef WIN32 |
|---|
| 1090 | WSACleanup(); |
|---|
| 1091 | #endif // WIN32 |
|---|
| 1092 | |
|---|
| 1093 | return ret; |
|---|
| 1094 | } |
|---|