]> git.ipfire.org Git - thirdparty/pdns.git/blame - pdns/dnsproxy.cc
Logging: have a global g_log
[thirdparty/pdns.git] / pdns / dnsproxy.cc
CommitLineData
12c86877 1/*
12471842
PL
2 * This file is part of PowerDNS or dnsdist.
3 * Copyright -- PowerDNS.COM B.V. and its contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License as
7 * published by the Free Software Foundation.
8 *
9 * In addition, for the avoidance of any doubt, permission is granted to
10 * link this program with OpenSSL and to (re)distribute the binaries
11 * produced as the result of such linking.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 */
870a0fe4
AT
22#ifdef HAVE_CONFIG_H
23#include "config.h"
24#endif
379ab445 25#include "packetcache.hh"
b636533b 26#include "utility.hh"
12c86877 27#include "dnsproxy.hh"
5c409fa2 28#include "pdnsexception.hh"
12c86877
BH
29#include <sys/types.h>
30#include <errno.h>
31#include "dns.hh"
32#include "logger.hh"
33#include "statbag.hh"
d2116c15 34#include "dns_random.hh"
c4e084f2 35#include "stubresolver.hh"
c4e084f2 36#include "arguments.hh"
12c86877
BH
37
38extern StatBag S;
12c86877
BH
39
40DNSProxy::DNSProxy(const string &remote)
41{
12c86877
BH
42 pthread_mutex_init(&d_lock,0);
43 d_resanswers=S.getPointer("recursing-answers");
44 d_resquestions=S.getPointer("recursing-questions");
45 d_udpanswers=S.getPointer("udp-answers");
2b78726c
PL
46
47 vector<string> addresses;
48 stringtok(addresses, remote, " ,\t");
40c9a111
RG
49 d_remote = ComboAddress(addresses[0], 53);
50
51 if((d_sock=socket(d_remote.sin4.sin_family, SOCK_DGRAM,0))<0) {
3f81d239 52 throw PDNSException(string("socket: ")+strerror(errno));
40c9a111
RG
53 }
54
c0cc6559 55 ComboAddress local;
40c9a111 56 if(d_remote.sin4.sin_family==AF_INET) {
c0cc6559 57 local = ComboAddress("0.0.0.0");
40c9a111
RG
58 }
59 else {
c0cc6559 60 local = ComboAddress("::");
40c9a111 61 }
c0cc6559 62
40c9a111 63 unsigned int n=0;
12c86877 64 for(;n<10;n++) {
d2116c15 65 local.sin4.sin_port = htons(10000+dns_random(50000));
12c86877 66
c0cc6559 67 if(::bind(d_sock, (struct sockaddr *)&local, local.getSocklen()) >= 0)
12c86877
BH
68 break;
69 }
70 if(n==10) {
3897b9e1 71 closesocket(d_sock);
12c86877 72 d_sock=-1;
3f81d239 73 throw PDNSException(string("binding dnsproxy socket: ")+strerror(errno));
12c86877
BH
74 }
75
40c9a111
RG
76 if(connect(d_sock, (sockaddr *)&d_remote, d_remote.getSocklen())<0) {
77 throw PDNSException("Unable to UDP connect to remote nameserver "+d_remote.toStringWithPort()+": "+stringerror());
78 }
12c86877 79
d2116c15 80 d_xor=dns_random(0xffff);
e6a9dde5 81 g_log<<Logger::Error<<"DNS Proxy launched, local port "<<ntohs(local.sin4.sin_port)<<", remote "<<d_remote.toStringWithPort()<<endl;
12c86877
BH
82}
83
84void DNSProxy::go()
85{
86 pthread_t tid;
87 pthread_create(&tid,0,&launchhelper,this);
88}
89
d59b894d 90//! look up qname aname with r->qtype, plonk it in the answer section of 'r' with name target
561434a6 91bool DNSProxy::completePacket(DNSPacket *r, const DNSName& target,const DNSName& aname)
d59b894d 92{
c4e084f2 93 if(r->d_tcp) {
c4e084f2
PD
94 vector<DNSZoneRecord> ips;
95 int ret1 = 0, ret2 = 0;
96
97 if(r->qtype == QType::A || r->qtype == QType::ANY)
98 ret1 = stubDoResolve(target, QType::A, ips);
99 if(r->qtype == QType::AAAA || r->qtype == QType::ANY)
100 ret2 = stubDoResolve(target, QType::AAAA, ips);
101
102 if(ret1 != RCode::NoError || ret2 != RCode::NoError) {
e6a9dde5 103 g_log<<Logger::Error<<"Error resolving for ALIAS "<<target<<", returning SERVFAIL"<<endl;
c4e084f2
PD
104 }
105
106 for (auto &ip : ips)
107 {
108 ip.dr.d_name = target;
109 r->addRecord(ip);
110 }
111
112 uint16_t len=htons(r->getString().length());
113 string buffer((const char*)&len, 2);
114 buffer.append(r->getString());
115 writen2WithTimeout(r->getSocket(), buffer.c_str(), buffer.length(), ::arg().asNum("tcp-idle-timeout"));
116
117 return true;
118 }
119
d59b894d 120 uint16_t id;
121 {
122 Lock l(&d_lock);
123 id=getID_locked();
124
125 ConntrackEntry ce;
126 ce.id = r->d.id;
127 ce.remote = r->d_remote;
128 ce.outsock = r->getSocket();
129 ce.created = time( NULL );
130 ce.qtype = r->qtype.getCode();
561434a6 131 ce.qname = target;
d59b894d 132 ce.anyLocal = r->d_anyLocal;
133 ce.complete = r;
134 ce.aname=aname;
135 d_conntrack[id]=ce;
136 }
137
138 vector<uint8_t> packet;
139 DNSPacketWriter pw(packet, target, r->qtype.getCode());
140 pw.getHeader()->rd=true;
141 pw.getHeader()->id=id ^ d_xor;
142
143 if(send(d_sock,&packet[0], packet.size() , 0)<0) { // zoom
e6a9dde5 144 g_log<<Logger::Error<<"Unable to send a packet to our recursing backend: "<<stringerror()<<endl;
d59b894d 145 }
146
147 return true;
148
149}
150
151
12c86877
BH
152/** This finds us an unused or stale ID. Does not actually clean the contents */
153int DNSProxy::getID_locked()
154{
155 map_t::iterator i;
156 for(int n=0;;++n) {
157 i=d_conntrack.find(n);
158 if(i==d_conntrack.end()) {
159 return n;
160 }
161 else if(i->second.created<time(0)-60) {
d59b894d 162 if(i->second.created) {
e6a9dde5 163 g_log<<Logger::Warning<<"Recursive query for remote "<<
85db02c5 164 i->second.remote.toStringWithPort()<<" with internal id "<<n<<
4957a608 165 " was not answered by backend within timeout, reusing id"<<endl;
d59b894d 166 delete i->second.complete;
bb6e54fe 167 S.inc("recursion-unanswered");
d59b894d 168 }
12c86877
BH
169 return n;
170 }
171 }
172}
173
174void DNSProxy::mainloop(void)
175{
176 try {
177 char buffer[1500];
a683e8bd 178 ssize_t len;
12c86877 179
65d8e171
KN
180 struct msghdr msgh;
181 struct iovec iov;
182 char cbuf[256];
40c9a111 183 ComboAddress fromaddr;
65d8e171 184
12c86877 185 for(;;) {
40c9a111
RG
186 socklen_t fromaddrSize = sizeof(fromaddr);
187 len=recvfrom(d_sock, buffer, sizeof(buffer),0, (struct sockaddr*) &fromaddr, &fromaddrSize); // answer from our backend
a683e8bd 188 if(len<(ssize_t)sizeof(dnsheader)) {
4957a608 189 if(len<0)
e6a9dde5 190 g_log<<Logger::Error<<"Error receiving packet from recursor backend: "<<stringerror()<<endl;
4957a608 191 else if(len==0)
e6a9dde5 192 g_log<<Logger::Error<<"Error receiving packet from recursor backend, EOF"<<endl;
4957a608 193 else
e6a9dde5 194 g_log<<Logger::Error<<"Short packet from recursor backend, "<<len<<" bytes"<<endl;
4957a608
BH
195
196 continue;
12c86877 197 }
40c9a111 198 if (fromaddr != d_remote) {
e6a9dde5 199 g_log<<Logger::Error<<"Got answer from unexpected host "<<fromaddr.toStringWithPort()<<" instead of our recursor backend "<<d_remote.toStringWithPort()<<endl;
40c9a111
RG
200 continue;
201 }
12c86877
BH
202 (*d_resanswers)++;
203 (*d_udpanswers)++;
88c1bc50 204 dnsheader d;
caa6eefa 205 memcpy(&d,buffer,sizeof(d));
12c86877 206 {
4957a608 207 Lock l(&d_lock);
bf549564 208#if BYTE_ORDER == BIG_ENDIAN
4957a608
BH
209 // this is needed because spoof ID down below does not respect the native byteorder
210 d.id = ( 256 * (uint16_t)buffer[1] ) + (uint16_t)buffer[0];
a899e13a 211#endif
4957a608
BH
212 map_t::iterator i=d_conntrack.find(d.id^d_xor);
213 if(i==d_conntrack.end()) {
e6a9dde5 214 g_log<<Logger::Error<<"Discarding untracked packet from recursor backend with id "<<(d.id^d_xor)<<
abc1d928 215 ". Conntrack table size="<<d_conntrack.size()<<endl;
4957a608
BH
216 continue;
217 }
218 else if(i->second.created==0) {
e6a9dde5 219 g_log<<Logger::Error<<"Received packet from recursor backend with id "<<(d.id^d_xor)<<" which is a duplicate"<<endl;
4957a608
BH
220 continue;
221 }
d59b894d 222
4957a608
BH
223 d.id=i->second.id;
224 memcpy(buffer,&d,sizeof(d)); // commit spoofed id
225
27c0050c 226 DNSPacket p(false),q(false);
a683e8bd
RG
227 p.parse(buffer,(size_t)len);
228 q.parse(buffer,(size_t)len);
7de6b0d5
BH
229
230 if(p.qtype.getCode() != i->second.qtype || p.qdomain != i->second.qname) {
e6a9dde5 231 g_log<<Logger::Error<<"Discarding packet from recursor backend with id "<<(d.id^d_xor)<<
c348fec2 232 ", qname or qtype mismatch ("<<p.qtype.getCode()<<" v " <<i->second.qtype<<", "<<p.qdomain<<" v "<<i->second.qname<<")"<<endl;
7de6b0d5
BH
233 continue;
234 }
f5310162 235
65d8e171
KN
236 /* Set up iov and msgh structures. */
237 memset(&msgh, 0, sizeof(struct msghdr));
d59b894d 238 string reply; // needs to be alive at time of sendmsg!
239 if(i->second.complete) {
240
27c0050c 241 MOADNSParser mdp(false, p.getString());
d59b894d 242 // cerr<<"Got completion, "<<mdp.d_answers.size()<<" answers, rcode: "<<mdp.d_header.rcode<<endl;
243 for(MOADNSParser::answers_t::const_iterator j=mdp.d_answers.begin(); j!=mdp.d_answers.end(); ++j) {
244 // cerr<<"comp: "<<(int)j->first.d_place-1<<" "<<j->first.d_label<<" " << DNSRecordContent::NumberToType(j->first.d_type)<<" "<<j->first.d_content->getZoneRepresentation()<<endl;
e693ff5a 245 if(j->first.d_place == DNSResourceRecord::ANSWER || (j->first.d_place == DNSResourceRecord::AUTHORITY && j->first.d_type == QType::SOA)) {
d59b894d 246
65d2032b 247 if(j->first.d_type == i->second.qtype || (i->second.qtype == QType::ANY && (j->first.d_type == QType::A || j->first.d_type == QType::AAAA))) {
90ba52e0 248 DNSZoneRecord dzr;
249 dzr.dr.d_name=i->second.aname;
250 dzr.dr.d_type = j->first.d_type;
251 dzr.dr.d_ttl=j->first.d_ttl;
252 dzr.dr.d_place= j->first.d_place;
253 dzr.dr.d_content=j->first.d_content;
254 i->second.complete->addRecord(dzr);
d59b894d 255 }
256 }
257 }
258 i->second.complete->setRcode(mdp.d_header.rcode);
259 reply=i->second.complete->getString();
260 iov.iov_base = (void*)reply.c_str();
261 iov.iov_len = reply.length();
262 delete i->second.complete;
263 i->second.complete=0;
264 }
265 else {
266 iov.iov_base = buffer;
267 iov.iov_len = len;
268 }
65d8e171
KN
269 msgh.msg_iov = &iov;
270 msgh.msg_iovlen = 1;
271 msgh.msg_name = (struct sockaddr*)&i->second.remote;
272 msgh.msg_namelen = i->second.remote.getSocklen();
3eae691f 273 msgh.msg_control=NULL;
65d8e171
KN
274
275 if(i->second.anyLocal) {
fbe2a2e0 276 addCMsgSrcAddr(&msgh, cbuf, i->second.anyLocal.get_ptr(), 0);
f5310162 277 }
76511d0d 278 if(sendmsg(i->second.outsock, &msgh, 0) < 0)
e6a9dde5 279 g_log<<Logger::Warning<<"dnsproxy.cc: Error sending reply with sendmsg (socket="<<i->second.outsock<<"): "<<strerror(errno)<<endl;
4957a608 280
4957a608 281 i->second.created=0;
12c86877
BH
282 }
283 }
284 }
3f81d239 285 catch(PDNSException &ae) {
e6a9dde5 286 g_log<<Logger::Error<<"Fatal error in DNS proxy: "<<ae.reason<<endl;
12c86877 287 }
adc10f99 288 catch(std::exception &e) {
e6a9dde5 289 g_log<<Logger::Error<<"Communicator thread died because of STL error: "<<e.what()<<endl;
12c86877
BH
290 }
291 catch( ... )
292 {
e6a9dde5 293 g_log << Logger::Error << "Caught unknown exception." << endl;
12c86877 294 }
e6a9dde5 295 g_log<<Logger::Error<<"Exiting because DNS proxy failed"<<endl;
5bd2ea7b 296 _exit(1);
12c86877 297}
732d9faa
AT
298
299DNSProxy::~DNSProxy() {
a7b68ae7
RG
300 if (d_sock>-1) {
301 try {
302 closesocket(d_sock);
303 }
304 catch(const PDNSException& e) {
305 }
306 }
307
732d9faa
AT
308 d_sock=-1;
309}