ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/vpn_dns.C
(Generate patch)

Comparing gvpe/src/vpn_dns.C (file contents):
Revision 1.6 by pcg, Thu Mar 3 08:38:32 2005 UTC vs.
Revision 1.48 by pcg, Tue Jul 28 00:42:14 2009 UTC

1/* 1/*
2 vpn_dns.C -- handle the dns tunnel part of the protocol. 2 vpn_dns.C -- handle the dns tunnel part of the protocol.
3 Copyright (C) 2003-2004 Marc Lehmann <pcg@goof.com> 3 Copyright (C) 2003-2008 Marc Lehmann <gvpe@schmorp.de>
4 4
5 This file is part of GVPE.
6
5 This program is free software; you can redistribute it and/or modify 7 GVPE is free software; you can redistribute it and/or modify it
6 it under the terms of the GNU General Public License as published by 8 under the terms of the GNU General Public License as published by the
7 the Free Software Foundation; either version 2 of the License, or 9 Free Software Foundation; either version 3 of the License, or (at your
8 (at your option) any later version. 10 option) any later version.
9 11
10 This program is distributed in the hope that it will be useful, 12 This program is distributed in the hope that it will be useful, but
11 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 GNU General Public License for more details. 15 Public License for more details.
14 16
15 You should have received a copy of the GNU General Public License 17 You should have received a copy of the GNU General Public License along
16 along with this program; if not, write to the Free Software 18 with this program; if not, see <http://www.gnu.org/licenses/>.
17 Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19
20 Additional permission under GNU GPL version 3 section 7
21
22 If you modify this Program, or any covered work, by linking or
23 combining it with the OpenSSL project's OpenSSL library (or a modified
24 version of that library), containing parts covered by the terms of the
25 OpenSSL or SSLeay licenses, the licensors of this Program grant you
26 additional permission to convey the resulting work. Corresponding
27 Source for a non-source form of such a combination shall include the
28 source code for the parts of OpenSSL used as well as that of the
29 covered work.
18*/ 30*/
31
32// TODO: EDNS0 option to increase dns mtu?
33// TODO: re-write dns packet parsing/creation using a safe mem-buffer
34// to ensure no buffer overflows or similar problems.
19 35
20#include "config.h" 36#include "config.h"
21 37
22#if ENABLE_DNS 38#if ENABLE_DNS
23 39
24// dns processing is EXTREMELY ugly. For obvious(?) reasons. 40// dns processing is EXTREMELY ugly. For obvious(?) reasons.
25// it's a hack, use only in emergency situations please. 41// it's a hack, use only in emergency situations please.
26 42
27#include <cstring> 43#include <cstring>
44#include <cassert>
28 45
29#include <sys/types.h> 46#include <sys/types.h>
30#include <sys/socket.h> 47#include <sys/socket.h>
31#include <sys/wait.h> 48#include <sys/wait.h>
32#include <sys/uio.h> 49#include <sys/uio.h>
35#include <unistd.h> 52#include <unistd.h>
36#include <fcntl.h> 53#include <fcntl.h>
37 54
38#include <map> 55#include <map>
39 56
57#include <cstdio> /* bug in libgmp: gmp.h relies on cstdio being included */
58#include <gmp.h>
59
40#include "netcompat.h" 60#include "netcompat.h"
41 61
42#include "vpn.h" 62#include "vpn.h"
43 63
44#define MIN_RETRY 1. 64#define MAX_POLL_INTERVAL 5. // how often to poll minimally when the server has no data
45#define MAX_RETRY 60. 65#define ACTIVITY_INTERVAL 5.
46 66
47#define MAX_OUTSTANDING 40 // max. outstanding requests 67#define INITIAL_TIMEOUT 0.1 // retry timeouts
68#define INITIAL_SYN_TIMEOUT 2. // retry timeout for initial syn
69
70#define MAX_SEND_INTERVAL 2. // optimistic?
71
48#define MAX_WINDOW 100 // max. for MAX_OUTSTANDING 72#define MAX_WINDOW 1000 // max. for MAX_OUTSTANDING, and backlog
49#define MAX_RATE 1000 // requests/s
50#define MAX_BACKLOG (10*1024) // size of protocol backlog, must be > MAXSIZE 73#define MAX_BACKLOG (64*1024) // size of gvpe protocol backlog (bytes), must be > MAXSIZE
51 74
52#define MAX_DOMAIN_SIZE 220 // 255 is legal limit, but bind doesn't compress well 75#define MAX_DOMAIN_SIZE 240 // 255 is legal limit, but bind doesn't compress well
53// 240 leaves about 4 bytes of server reply data 76// 240 leaves about 4 bytes of server reply data
54// every two request byte sless give room for one reply byte 77// every request byte less give room for two reply bytes
55 78
56// seqno has 12 bits, but the lower bit is always left as zero
57// as bind caches ttl=0 records and we have to generate
58// sequence numbers that always differ case-insensitively
59#define SEQNO_MASK 0x07ff 79#define SEQNO_MASK 0x3fff
60 80#define SEQNO_EQ(a,b) ( 0 == ( ((a) ^ (b)) & SEQNO_MASK) )
61/*
62
63protocol, in shorthand :)
64
65client -> server <req> ANY?
66server -> client <req> TXT <rep>
67
68<req> is dns64-encoded <client-id:12><recv-seqno:10>[<send-seqno:10><data>]
69<rep> is dns64-encoded <0:12><recv-seqno:10>[<send-seqno:10><data>]
70
71if <client-id> is zero, the connection will be configured:
72
73<0:12><0:4>client-id:12><default-ttl:8><max-size:16><flags:16>
74
75*/
76 81
77#define MAX_LBL_SIZE 63 82#define MAX_LBL_SIZE 63
78#define MAX_PKT_SIZE 512 83#define MAX_PKT_SIZE 512
79 84
85#define RR_TYPE_A 1
86#define RR_TYPE_NULL 10
80#define RR_TYPE_TXT 16 87#define RR_TYPE_TXT 16
88#define RR_TYPE_AAAA 28
81#define RR_TYPE_ANY 255 89#define RR_TYPE_ANY 255
90
82#define RR_CLASS_IN 1 91#define RR_CLASS_IN 1
83 92
84// the "_" is not valid but widely accepted (all octets should be supported, but let's be conservative) 93#define CMD_IP_1 207
85struct dns64 94#define CMD_IP_2 46
86{ 95#define CMD_IP_3 236
87 static const char encode_chars[64 + 1]; 96#define CMD_IP_RST 29
88 static s8 decode_chars[256]; 97#define CMD_IP_SYN 113
98#define CMD_IP_REJ 32
89 99
90 static int encode_len (int bytes) { return (bytes * 8 + 5) / 6; } 100// works for cmaps up to 255 (not 256!)
91 static int decode_len (int bytes) { return (bytes * 6) / 8; } 101struct charmap
102{
103 enum { INVALID = (u8)255 };
104
105 char encode [256]; // index => char
106 u8 decode [256]; // char => index
107 unsigned int size;
108
109 charmap (const char *cmap);
110};
111
112charmap::charmap (const char *cmap)
113{
114 char *enc = encode;
115 u8 *dec = decode;
116
117 memset (enc, (char) 0, 256);
118 memset (dec, (char)INVALID, 256);
119
120 for (size = 0; cmap [size]; size++)
121 {
122 enc [size] = cmap [size];
123 dec [(u8)enc [size]] = size;
124 }
125
126 assert (size < 256);
127}
128
129#define MAX_DEC_LEN 500
130#define MAX_ENC_LEN (MAX_DEC_LEN * 2)
131#define MAX_LIMBS ((MAX_DEC_LEN * 8 + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS)
132
133// ugly. minimum base is 16(!)
134struct basecoder
135{
136 charmap cmap;
137 unsigned int enc_len [MAX_DEC_LEN];
138 unsigned int dec_len [MAX_ENC_LEN];
139
140 unsigned int encode_len (unsigned int len);
141 unsigned int decode_len (unsigned int len);
142
92 static int encode (char *dst, u8 *src, int len); 143 unsigned int encode (char *dst, u8 *src, unsigned int len);
93 static int decode (u8 *dst, char *src, int len); 144 unsigned int decode (u8 *dst, char *src, unsigned int len);
94 145
95 dns64 (); 146 basecoder (const char *cmap);
96} dns64; 147};
97 148
98// the following sequence has been crafted to 149basecoder::basecoder (const char *cmap)
99// a) look somewhat random 150: cmap (cmap)
100// b) the even (and odd) indices never share the same character as upper/lowercase
101const char dns64::encode_chars[64 + 1] = "_-dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI";
102s8 dns64::decode_chars[256];
103
104dns64::dns64 ()
105{ 151{
106 for (int i = 0; i < 64; i++) 152 for (unsigned int len = 0; len < MAX_DEC_LEN; ++len)
107 decode_chars [encode_chars [i]] = i + 1; 153 {
108} 154 u8 src [MAX_DEC_LEN];
155 u8 dst [MAX_ENC_LEN];
109 156
110int dns64::encode (char *dst, u8 *src, int len) 157 memset (src, 255, len);
158
159 mp_limb_t m [MAX_LIMBS];
160 mp_size_t n;
161
162 n = mpn_set_str (m, src, len, 256);
163 n = mpn_get_str (dst, this->cmap.size, m, n);
164
165 for (int i = 0; !dst [i]; ++i)
166 n--;
167
168 enc_len [len] = n;
169 dec_len [n] = len;
170 }
171}
172
173unsigned int basecoder::encode_len (unsigned int len)
111{ 174{
112 // slow, but easy to debug 175 return enc_len [len];
113 char *beg = dst; 176}
114 unsigned int accum, bits = 0; 177
178unsigned int basecoder::decode_len (unsigned int len)
179{
180 while (len && !dec_len [len])
181 --len;
182
183 return dec_len [len];
184}
185
186unsigned int basecoder::encode (char *dst, u8 *src, unsigned int len)
187{
188 if (!len || len > MAX_DEC_LEN)
189 return 0;
190
191 int elen = encode_len (len);
192
193 mp_limb_t m [MAX_LIMBS];
194 mp_size_t n;
195
196 u8 dst_ [MAX_ENC_LEN];
197
198 n = mpn_set_str (m, src, len, 256);
199 n = mpn_get_str (dst_, cmap.size, m, n);
200
201 int plen = elen; // for padding
202
203 while (n < plen)
204 {
205 *dst++ = cmap.encode [0];
206 plen--;
207 }
208
209 for (unsigned int i = n - plen; i < n; ++i)
210 *dst++ = cmap.encode [dst_ [i]];
211
212 return elen;
213}
214
215unsigned int basecoder::decode (u8 *dst, char *src, unsigned int len)
216{
217 if (!len || len > MAX_ENC_LEN)
218 return 0;
219
220 u8 src_ [MAX_ENC_LEN];
221 unsigned int elen = 0;
115 222
116 while (len--) 223 while (len--)
117 { 224 {
118 accum <<= 8; 225 u8 val = cmap.decode [(u8)*src++];
119 accum |= *src++;
120 bits += 8;
121 226
122 while (bits >= 6) 227 if (val != charmap::INVALID)
123 { 228 src_ [elen++] = val;
124 *dst++ = encode_chars [(accum >> (bits - 6)) & 63]; 229 }
125 bits -= 6; 230
126 } 231 int dlen = decode_len (elen);
232
233 mp_limb_t m [MAX_LIMBS];
234 mp_size_t n;
235
236 u8 dst_ [MAX_DEC_LEN];
237
238 n = mpn_set_str (m, src_, elen, cmap.size);
239 n = mpn_get_str (dst_, 256, m, n);
240
241 if (n < dlen)
127 } 242 {
243 memset (dst, 0, dlen - n);
244 memcpy (dst + dlen - n, dst_, n);
245 }
246 else
247 memcpy (dst, dst_ + n - dlen, dlen);
128 248
129 if (bits) 249 return dlen;
130 *dst++ = encode_chars [(accum << (6 - bits)) & 63];
131
132 return dst - beg;
133} 250}
134 251
135int dns64::decode (u8 *dst, char *src, int len) 252#if 0
136{ 253struct test { test (); } test;
137 // slow, but easy to debug
138 u8 *beg = dst;
139 unsigned int accum, bits = 0;
140 254
141 while (len--) 255test::test ()
256{
257 basecoder cdc ("0123456789abcdefghijklmnopqrstuvwxyz");
258
259 u8 in[] = "0123456789abcdefghijklmnopqrstuvwxyz";
260 static char enc[200];
261 static u8 dec[200];
262
263 for (int i = 1; i < 20; i++)
142 { 264 {
143 s8 chr = decode_chars [(u8)*src++]; 265 int elen = cdc.encode (enc, in, i);
266 int dlen = cdc.decode (dec, enc, elen);
144 267
145 if (!chr) 268 printf ("%d>%d>%d (%s>%s)\n", i, elen, dlen, enc, dec);
146 continue;
147
148 accum <<= 6;
149 accum |= chr - 1;
150 bits += 6;
151
152 while (bits >= 8)
153 {
154 *dst++ = accum >> (bits - 8);
155 bits -= 8;
156 }
157 } 269 }
270 abort ();
271}
272#endif
158 273
159 return dst - beg; 274//static basecoder cdc64 ("_dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI-");
275//static basecoder cdc63 ("_dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI");
276static basecoder cdc62 ("dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI");
277//static basecoder cdc36 ("dphzr06qmjkb34tsvl81xaef92wgyo57ucni"); // unused as of yet
278static basecoder cdc26 ("dPhZrQmJkBtSvLxAeFwGyO");
279
280/////////////////////////////////////////////////////////////////////////////
281
282#define HDRSIZE 6
283
284inline void encode_header (char *data, int clientid, int seqno, int retry = 0)
285{
286 seqno &= SEQNO_MASK;
287
288 u8 hdr[3] = {
289 clientid,
290 (seqno >> 8) | (retry << 6),
291 seqno,
292 };
293
294 assert (clientid < 256);
295
296 cdc26.encode (data, hdr, 3);
297}
298
299inline void decode_header (char *data, int &clientid, int &seqno)
300{
301 u8 hdr[3];
302
303 cdc26.decode (hdr, data, HDRSIZE);
304
305 clientid = hdr[0];
306 seqno = ((hdr[1] << 8) | hdr[2]) & SEQNO_MASK;
160} 307}
161 308
162///////////////////////////////////////////////////////////////////////////// 309/////////////////////////////////////////////////////////////////////////////
163 310
164struct byte_stream 311struct byte_stream
193} 340}
194 341
195void byte_stream::remove (int count) 342void byte_stream::remove (int count)
196{ 343{
197 if (count > fill) 344 if (count > fill)
198 abort (); 345 assert (count <= fill);
199 346
200 memmove (data, data + count, fill -= count); 347 memmove (data, data + count, fill -= count);
201} 348}
202 349
203bool byte_stream::put (u8 *data, unsigned int datalen) 350bool byte_stream::put (u8 *data, unsigned int datalen)
216 return false; 363 return false;
217 364
218 data [fill++] = pkt->len >> 8; 365 data [fill++] = pkt->len >> 8;
219 data [fill++] = pkt->len; 366 data [fill++] = pkt->len;
220 367
221 memcpy (data + fill, &((*pkt)[0]), pkt->len); fill += pkt->len; 368 memcpy (data + fill, pkt->at (0), pkt->len); fill += pkt->len;
222 369
223 return true; 370 return true;
224} 371}
225 372
226vpn_packet *byte_stream::get () 373vpn_packet *byte_stream::get ()
227{ 374{
375 unsigned int len;
376
377 for (;;)
378 {
228 int len = (data [0] << 8) | data [1]; 379 len = (data [0] << 8) | data [1];
229 380
230 if (len > MAXSIZE && fill >= 2) 381 if (len <= MAXSIZE || fill < 2)
231 abort (); // TODO handle this gracefully, connection reset 382 break;
232 383
384 // TODO: handle this better than skipping, e.g. by reset
385 slog (L_DEBUG, _("DNS: corrupted packet stream skipping a byte..."));
386 remove (1);
387 }
388
233 if (fill < len + 2) 389 if (fill < len + 2)
234 return 0; 390 return 0;
235 391
236 vpn_packet *pkt = new vpn_packet; 392 vpn_packet *pkt = new vpn_packet;
237 393
238 pkt->len = len; 394 pkt->len = len;
239 memcpy (&((*pkt)[0]), data + 2, len); 395 memcpy (pkt->at (0), data + 2, len);
240 remove (len + 2); 396 remove (len + 2);
241 397
242 return pkt; 398 return pkt;
243} 399}
244 400
245///////////////////////////////////////////////////////////////////////////// 401/////////////////////////////////////////////////////////////////////////////
246 402
247#define FLAG_QUERY ( 0 << 15) 403#define FLAG_QUERY ( 0 << 15)
248#define FLAG_RESPONSE ( 1 << 15) 404#define FLAG_RESPONSE ( 1 << 15)
249#define FLAG_OP_MASK (15 << 14) 405#define FLAG_OP_MASK (15 << 11)
250#define FLAG_OP_QUERY ( 0 << 11) 406#define FLAG_OP_QUERY ( 0 << 11)
251#define FLAG_AA ( 1 << 10) 407#define FLAG_AA ( 1 << 10)
252#define FLAG_TC ( 1 << 9) 408#define FLAG_TC ( 1 << 9)
253#define FLAG_RD ( 1 << 8) 409#define FLAG_RD ( 1 << 8)
254#define FLAG_RA ( 1 << 7) 410#define FLAG_RA ( 1 << 7)
261#define FLAG_RCODE_REFUSED ( 5 << 0) 417#define FLAG_RCODE_REFUSED ( 5 << 0)
262 418
263#define DEFAULT_CLIENT_FLAGS (FLAG_QUERY | FLAG_OP_QUERY | FLAG_RD) 419#define DEFAULT_CLIENT_FLAGS (FLAG_QUERY | FLAG_OP_QUERY | FLAG_RD)
264#define DEFAULT_SERVER_FLAGS (FLAG_RESPONSE | FLAG_OP_QUERY | FLAG_AA | FLAG_RD | FLAG_RA) 420#define DEFAULT_SERVER_FLAGS (FLAG_RESPONSE | FLAG_OP_QUERY | FLAG_AA | FLAG_RD | FLAG_RA)
265 421
422struct dns_cfg
423{
424 static int next_uid;
425
426 u8 id1, id2, id3, id4;
427
428 u8 version;
429 u8 flags;
430 u8 rrtype;
431 u8 def_ttl;
432
433 u16 client;
434 u16 uid; // to make request unique
435
436 u16 max_size;
437 u8 seq_cdc;
438 u8 req_cdc;
439
440 u8 rep_cdc;
441 u8 delay; // time in 0.01s units that the server may delay replying packets
442 u8 r3, r4;
443
444 u8 r5, r6, r7, r8;
445
446 void reset (int clientid);
447 bool valid ();
448};
449
450int dns_cfg::next_uid;
451
452void dns_cfg::reset (int clientid)
453{
454 id1 = 'G';
455 id2 = 'V';
456 id3 = 'P';
457 id4 = 'E';
458
459 version = 1;
460
461 rrtype = RR_TYPE_TXT;
462 flags = 0;
463 def_ttl = 0;
464 seq_cdc = 26;
465 req_cdc = 62;
466 rep_cdc = 0;
467 max_size = htons (MAX_PKT_SIZE);
468 client = htons (clientid);
469 uid = next_uid++;
470 delay = 0;
471
472 r3 = r4 = 0;
473 r4 = r5 = r6 = r7 = 0;
474}
475
476bool dns_cfg::valid ()
477{
478 // although the protocol itself allows for some configurability,
479 // only the following encoding/decoding settings are implemented.
480 return id1 == 'G'
481 && id2 == 'V'
482 && id3 == 'P'
483 && id4 == 'E'
484 && seq_cdc == 26
485 && req_cdc == 62
486 && rep_cdc == 0
487 && version == 1;
488}
489
266struct dns_packet : net_packet 490struct dns_packet : net_packet
267{ 491{
268 u16 id; 492 u16 id;
269 u16 flags; // QR:1 Opcode:4 AA:1 TC:1 RD:1 RA:1 Z:3 RCODE:4 493 u16 flags; // QR:1 Opcode:4 AA:1 TC:1 RD:1 RA:1 Z:3 RCODE:4
270 u16 qdcount, ancount, nscount, arcount; 494 u16 qdcount, ancount, nscount, arcount;
271 495
272 u8 data[MAXSIZE - 6 * 2]; 496 u8 data [MAXSIZE - 6 * 2];
273 497
274 int decode_label (char *data, int size, int &offs); 498 int decode_label (char *data, int size, int &offs);
275}; 499};
276 500
277int dns_packet::decode_label (char *data, int size, int &offs) 501int dns_packet::decode_label (char *data, int size, int &offs)
308 return data - orig; 532 return data - orig;
309} 533}
310 534
311///////////////////////////////////////////////////////////////////////////// 535/////////////////////////////////////////////////////////////////////////////
312 536
313struct dns_req
314{
315 dns_packet *pkt;
316 tstamp next;
317 int retry;
318 connection *conn;
319 int seqno;
320
321 dns_req (connection *c);
322 void gen_stream_req (int seqno, byte_stream *stream);
323};
324
325static u16 dns_id = 12098; // TODO: should be per-vpn 537static u16 dns_id = 0; // TODO: should be per-vpn
326 538
327static u16 next_id () 539static u16 next_id ()
328{ 540{
541 if (!dns_id)
542 dns_id = time (0);
543
329 // the simplest lsfr with periodicity 65535 i could find 544 // the simplest lsfr with periodicity 65535 i could find
330 dns_id = (dns_id << 1) 545 dns_id = (dns_id << 1)
331 | (((dns_id >> 1) 546 | (((dns_id >> 1)
332 ^ (dns_id >> 2) 547 ^ (dns_id >> 2)
333 ^ (dns_id >> 4) 548 ^ (dns_id >> 4)
334 ^ (dns_id >> 15)) & 1); 549 ^ (dns_id >> 15)) & 1);
335 550
336 return dns_id; 551 return dns_id;
337} 552}
338 553
339dns_req::dns_req (connection *c) 554struct dns_rcv;
340: conn (c) 555struct dns_snd;
556
557struct dns_connection
341{ 558{
342 next = 0; 559 connection *c;
560 struct vpn *vpn;
561
562 dns_cfg cfg;
563
564 bool established;
565
566 tstamp last_received;
567 tstamp last_sent;
568 double min_latency;
569 double poll_interval, send_interval;
570
571 vector<dns_rcv *> rcvpq;
572
573 byte_stream rcvdq; int rcvseq; int repseq;
574 byte_stream snddq; int sndseq;
575
576 inline void time_cb (ev::timer &w, int revents); ev::timer tw;
577 void receive_rep (dns_rcv *r);
578
579 dns_connection (connection *c);
580 ~dns_connection ();
581};
582
583struct dns_snd
584{
585 dns_packet *pkt;
586 tstamp timeout, sent;
587 int retry;
588 struct dns_connection *dns;
589 int seqno;
590 bool stdhdr;
591
592 void gen_stream_req (int seqno, byte_stream &stream);
593 void gen_syn_req ();
594
595 dns_snd (dns_connection *dns);
596 ~dns_snd ();
597};
598
599dns_snd::dns_snd (dns_connection *dns)
600: dns (dns)
601{
602 timeout = 0;
343 retry = 0; 603 retry = 0;
604 seqno = 0;
605 sent = ev_now ();
606 stdhdr = false;
344 607
345 pkt = new dns_packet; 608 pkt = new dns_packet;
346 609
347 pkt->id = next_id (); 610 pkt->id = next_id ();
348} 611}
349 612
613dns_snd::~dns_snd ()
614{
615 delete pkt;
616}
617
618static void append_domain (dns_packet &pkt, int &offs, const char *domain)
619{
620 // add tunnel domain
621 for (;;)
622 {
623 const char *end = strchr (domain, '.');
624
625 if (!end)
626 end = domain + strlen (domain);
627
628 int len = end - domain;
629
630 pkt [offs++] = len;
631 memcpy (pkt.at (offs), domain, len);
632 offs += len;
633
634 if (!*end)
635 break;
636
637 domain = end + 1;
638 }
639}
640
350void dns_req::gen_stream_req (int seqno, byte_stream *stream) 641void dns_snd::gen_stream_req (int seqno, byte_stream &stream)
351{ 642{
643 stdhdr = true;
352 this->seqno = seqno; 644 this->seqno = seqno;
645
646 timeout = ev_now () + INITIAL_TIMEOUT;
353 647
354 pkt->flags = htons (DEFAULT_CLIENT_FLAGS); 648 pkt->flags = htons (DEFAULT_CLIENT_FLAGS);
355 pkt->qdcount = htons (1); 649 pkt->qdcount = htons (1);
356 650
357 int offs = 6*2; 651 int offs = 6*2;
358 int dlen = MAX_DOMAIN_SIZE - strlen (THISNODE->domain) - 2; 652 int dlen = MAX_DOMAIN_SIZE - (strlen (dns->c->conf->domain) + 2);
359 // MAX_DOMAIN_SIZE is technically 255, but bind doesn't compress responses well, 653 // MAX_DOMAIN_SIZE is technically 255, but bind doesn't compress responses well,
360 // so we need to have space for 2*MAX_DOMAIN_SIZE + header + extra 654 // so we need to have space for 2*MAX_DOMAIN_SIZE + header + extra
361 655
362 u8 data[256]; //TODO
363
364 data[0] = THISNODE->id; //TODO
365 data[1] = seqno >> 7; //TODO
366 data[2] = seqno << 1; //TODO
367
368 int datalen = dns64::decode_len (dlen - (dlen + MAX_LBL_SIZE - 1) / MAX_LBL_SIZE) - 3;
369
370 if (datalen > stream->size ())
371 datalen = stream->size ();
372
373 char enc[256], *encp = enc; 656 char enc[256], *encp = enc;
374 657 encode_header (enc, THISNODE->id, seqno);
375 memcpy (data + 3, stream->begin (), datalen); 658
376 int enclen = dns64::encode (enc, data, datalen + 3); 659 int datalen = cdc62.decode_len (dlen - (dlen + MAX_LBL_SIZE - 1) / MAX_LBL_SIZE - HDRSIZE);
660
661 if (datalen > stream.size ())
662 datalen = stream.size ();
663
664 int enclen = cdc62.encode (enc + HDRSIZE, stream.begin (), datalen) + HDRSIZE;
377 stream->remove (datalen); 665 stream.remove (datalen);
378 666
379 while (enclen) 667 while (enclen)
380 { 668 {
381 int lbllen = enclen < MAX_LBL_SIZE ? enclen : MAX_LBL_SIZE; 669 int lbllen = enclen < MAX_LBL_SIZE ? enclen : MAX_LBL_SIZE;
382 670
387 encp += lbllen; 675 encp += lbllen;
388 676
389 enclen -= lbllen; 677 enclen -= lbllen;
390 } 678 }
391 679
392 const char *suffix = THISNODE->domain; 680 append_domain (*pkt, offs, dns->c->conf->domain);
393
394 // add tunnel domain
395 for (;;)
396 {
397 const char *end = strchr (suffix, '.');
398
399 if (!end)
400 end = suffix + strlen (suffix);
401
402 int len = end - suffix;
403
404 (*pkt)[offs++] = len;
405 memcpy (&((*pkt)[offs]), suffix, len);
406 offs += len;
407
408 if (!*end)
409 break;
410
411 suffix = end + 1;
412 }
413 681
414 (*pkt)[offs++] = 0; 682 (*pkt)[offs++] = 0;
415 (*pkt)[offs++] = RR_TYPE_ANY >> 8; (*pkt)[offs++] = RR_TYPE_ANY; 683 (*pkt)[offs++] = RR_TYPE_ANY >> 8; (*pkt)[offs++] = RR_TYPE_ANY;
684 (*pkt)[offs++] = RR_CLASS_IN >> 8; (*pkt)[offs++] = RR_CLASS_IN;
685
686 pkt->len = offs;
687}
688
689void dns_snd::gen_syn_req ()
690{
691 timeout = ev_now () + INITIAL_SYN_TIMEOUT;
692
693 pkt->flags = htons (DEFAULT_CLIENT_FLAGS);
694 pkt->qdcount = htons (1);
695
696 int offs = 6 * 2;
697
698 int elen = cdc26.encode ((char *)pkt->at (offs + 1), (u8 *)&dns->cfg, sizeof (dns_cfg));
699
700 assert (elen <= MAX_LBL_SIZE);
701
702 (*pkt)[offs] = elen;
703 offs += elen + 1;
704 append_domain (*pkt, offs, dns->c->conf->domain);
705
706 (*pkt)[offs++] = 0;
707 (*pkt)[offs++] = RR_TYPE_A >> 8; (*pkt)[offs++] = RR_TYPE_A;
416 (*pkt)[offs++] = RR_CLASS_IN >> 8; (*pkt)[offs++] = RR_CLASS_IN; 708 (*pkt)[offs++] = RR_CLASS_IN >> 8; (*pkt)[offs++] = RR_CLASS_IN;
417 709
418 pkt->len = offs; 710 pkt->len = offs;
419} 711}
420 712
439{ 731{
440 delete pkt; 732 delete pkt;
441} 733}
442 734
443///////////////////////////////////////////////////////////////////////////// 735/////////////////////////////////////////////////////////////////////////////
444 736
445struct dns_cfg 737dns_connection::dns_connection (connection *c)
738: c (c)
739, rcvdq (MAX_BACKLOG * 2)
740, snddq (MAX_BACKLOG)
446{ 741{
447 u8 id1, id2, id3; 742 tw.set<dns_connection, &dns_connection::time_cb> (this);
448 u8 def_ttl;
449 u8 unused1;
450 u16 max_size;
451 u8 flags1, flags2;
452};
453 743
744 vpn = c->vpn;
745
746 established = false;
747
748 rcvseq = repseq = sndseq = 0;
749
750 last_sent = last_received = 0;
751 poll_interval = 0.5; // starting here
752 send_interval = 0.5; // starting rate
753 min_latency = INITIAL_TIMEOUT;
754}
755
756dns_connection::~dns_connection ()
757{
758 for (vector<dns_rcv *>::iterator i = rcvpq.begin ();
759 i != rcvpq.end ();
760 ++i)
761 delete *i;
762}
763
454void connection::dnsv4_receive_rep (struct dns_rcv *r) 764void dns_connection::receive_rep (dns_rcv *r)
455{ 765{
766 if (r->datalen)
767 {
768 last_received = ev_now ();
769 tw ();
770
771 poll_interval = send_interval;
772 }
773 else
774 {
775 poll_interval *= 1.5;
776
777 if (poll_interval > MAX_POLL_INTERVAL)
778 poll_interval = MAX_POLL_INTERVAL;
779 }
780
456 dns_rcvpq.push_back (r); 781 rcvpq.push_back (r);
457 782
458 redo: 783 redo:
459 784
785 // find next packet
460 for (vector<dns_rcv *>::iterator i = dns_rcvpq.begin (); 786 for (vector<dns_rcv *>::iterator i = rcvpq.end (); i-- != rcvpq.begin (); )
461 i != dns_rcvpq.end ();
462 ++i)
463 if (dns_rcvseq == (*i)->seqno) 787 if (SEQNO_EQ (rcvseq, (*i)->seqno))
464 { 788 {
789 //printf ("seqno eq %x %x\n", rcvseq, (*i)->seqno);//D
790 // enter the packet into our input stream
465 dns_rcv *r = *i; 791 r = *i;
466 792
793 // remove the oldest packet, look forward, as it's oldest first
794 for (vector<dns_rcv *>::iterator j = rcvpq.begin (); j != rcvpq.end (); ++j)
795 if (SEQNO_EQ ((*j)->seqno, rcvseq - MAX_WINDOW))
796 {
797 //printf ("seqno RR %x %x\n", (*j)->seqno, rcvseq - MAX_WINDOW);//D
798 delete *j;
799 rcvpq.erase (j);
800 break;
801 }
802
467 dns_rcvseq = (dns_rcvseq + 1) & SEQNO_MASK; 803 rcvseq = (rcvseq + 1) & SEQNO_MASK;
468 804
469 if (!dns_snddq && !dns_rcvdq) 805 if (!rcvdq.put (r->data, r->datalen))
470 { 806 {
471 dns_rcvdq = new byte_stream (MAX_BACKLOG * 2); 807 slog (L_ERR, "DNS: !rcvdq.put (r->data, r->datalen)");
472 dns_snddq = new byte_stream (MAX_BACKLOG); 808 abort (); // MUST never overflow, can be caused by data corruption, TODO
473
474 dns_si.set (::conf.dns_forw_host, ::conf.dns_forw_port, PROT_DNSv4);
475 } 809 }
476 810
477 if (!dns_rcvdq->put (r->data, r->datalen))
478 abort (); // MUST never overflow, can be caused by data corruption, TODO
479
480 while (vpn_packet *pkt = dns_rcvdq->get ()) 811 while (vpn_packet *pkt = rcvdq.get ())
481 { 812 {
482 sockinfo si; 813 sockinfo si;
483 si.host = 0; si.port = 0; si.prot = PROT_DNSv4; 814 si.host = htonl (c->conf->id); si.port = 0; si.prot = PROT_DNSv4;
484 815
485 vpn->recv_vpn_packet (pkt, si); 816 vpn->recv_vpn_packet (pkt, si);
817
818 delete pkt;
486 } 819 }
487 } 820
488 else if ((u32)(*i)->seqno - (u32)dns_rcvseq + MAX_WINDOW > MAX_WINDOW * 2) 821 // check for further packets
489 {
490 //D
491 //abort();
492 printf ("%d erasing %d (%d)\n", THISNODE->id, (u32)(*i)->seqno, dns_rcvseq);
493 dns_rcvpq.erase (i);
494 goto redo; 822 goto redo;
495 } 823 }
496} 824}
497 825
498dns_packet * 826void
499vpn::dnsv4_server (dns_packet *pkt) 827vpn::dnsv4_server (dns_packet &pkt)
500{ 828{
501 u16 flags = ntohs (pkt->flags); 829 u16 flags = ntohs (pkt.flags);
502 830
503 //memcpy (&((*rep)[0]), &((*pkt)[0]), pkt->len);
504 int offs = 6 * 2; // skip header 831 int offs = 6 * 2; // skip header
505 832
506 pkt->flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_FORMERR); 833 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_FORMERR);
507 834
508 if (!(flags & (FLAG_RESPONSE | FLAG_OP_MASK | FLAG_TC)) 835 if (0 == (flags & (FLAG_RESPONSE | FLAG_OP_MASK))
509 && pkt->qdcount == htons (1)) 836 && pkt.qdcount == htons (1))
510 { 837 {
511 char qname[MAXSIZE]; 838 char qname [MAXSIZE];
512 int qlen = pkt->decode_label ((char *)qname, MAXSIZE - offs, offs); 839 int qlen = pkt.decode_label ((char *)qname, MAXSIZE - offs, offs);
513 840
514 u16 qtype = (*pkt) [offs++] << 8; qtype |= (*pkt) [offs++]; 841 u16 qtype = pkt [offs++] << 8; qtype |= pkt [offs++];
515 u16 qclass = (*pkt) [offs++] << 8; qclass |= (*pkt) [offs++]; 842 u16 qclass = pkt [offs++] << 8; qclass |= pkt [offs++];
516 843
517 pkt->qdcount = htons (1); 844 pkt.qdcount = htons (1);
518 pkt->ancount = 0; 845 pkt.ancount = 0;
519 pkt->nscount = 0; // should be self, as other nameservers reply like this 846 pkt.nscount = 0; // should be self, as other nameservers reply like this
520 pkt->arcount = 0; // a record for self, as other nameservers reply like this 847 pkt.arcount = 0; // a record for self, as other nameservers reply like this
521 848
522 pkt->flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_NXDOMAIN); 849 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_SERVFAIL);
523 850
524 int dlen = strlen (THISNODE->domain); 851 int dlen = strlen (THISNODE->domain);
525 852
526 if (qclass == RR_CLASS_IN 853 if (qclass == RR_CLASS_IN
527 && (qtype == RR_TYPE_ANY || qtype == RR_TYPE_TXT)
528 && qlen > dlen + 1 854 && qlen > dlen + 1
529 && !memcmp (qname + qlen - dlen - 1, THISNODE->domain, dlen)) 855 && !memcmp (qname + qlen - (dlen + 1), THISNODE->domain, dlen))
530 { 856 {
531 // correct class, domain: parse 857 // now generate reply
532 u8 data[MAXSIZE]; 858 pkt.ancount = htons (1); // one answer RR
533 int datalen = dns64::decode (data, qname, qlen - dlen - 1); 859 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_OK);
534 860
535 int client = data[0]; 861 if ((qtype == RR_TYPE_ANY
536 int seqno = ((data[1] << 7) | (data[2] >> 1)) & SEQNO_MASK; 862 || qtype == RR_TYPE_TXT
537 863 || qtype == RR_TYPE_NULL)
538 if (0 < client && client <= conns.size ()) 864 && qlen > dlen + 1 + HDRSIZE)
539 { 865 {
866 // correct class, domain: parse
867 int client, seqno;
868 decode_header (qname, client, seqno);
869
870 u8 data[MAXSIZE];
871 int datalen = cdc62.decode (data, qname + HDRSIZE, qlen - (dlen + 1 + HDRSIZE));
872
873 if (0 < client && client <= conns.size ())
874 {
540 connection *c = conns [client - 1]; 875 connection *c = conns [client - 1];
876 dns_connection *dns = c->dns;
877 dns_rcv *rcv;
541 878
542 redo: 879 if (dns)
543
544 for (vector<dns_rcv *>::iterator i = c->dns_rcvpq.begin ();
545 i != c->dns_rcvpq.end ();
546 ++i) 880 {
881 for (vector<dns_rcv *>::iterator i = dns->rcvpq.end (); i-- != dns->rcvpq.begin (); )
547 if ((*i)->seqno == seqno) 882 if (SEQNO_EQ ((*i)->seqno, seqno))
883 {
884 // already seen that request: simply reply with the cached reply
885 dns_rcv *r = *i;
886
887 slog (L_DEBUG, "DNS: duplicate packet received ID %d, SEQ %d", htons (r->pkt->id), seqno);
888
889 // refresh header & id, as the retry count could have changed
890 memcpy (r->pkt->at (6 * 2 + 1), pkt.at (6 * 2 + 1), HDRSIZE);
891 r->pkt->id = pkt.id;
892
893 memcpy (pkt.at (0), r->pkt->at (0), offs = r->pkt->len);
894
895 goto duplicate_request;
896 }
897
898 // new packet, queue
899 rcv = new dns_rcv (seqno, data, datalen);
900 dns->receive_rep (rcv);
901 }
902
548 { 903 {
549 // already seen that request: simply reply with the cached reply 904 pkt [offs++] = 0xc0; pkt [offs++] = 6 * 2; // refer to name in query section
550 dns_rcv *r = *i;
551 905
552 printf ("DUPLICATE %d\n", htons (r->pkt->id));//D 906 int rtype = dns ? dns->cfg.rrtype : RR_TYPE_A;
907 pkt [offs++] = rtype >> 8; pkt [offs++] = rtype; // type
908 pkt [offs++] = RR_CLASS_IN >> 8; pkt [offs++] = RR_CLASS_IN; // class
909 pkt [offs++] = 0; pkt [offs++] = 0;
910 pkt [offs++] = 0; pkt [offs++] = dns ? dns->cfg.def_ttl : 0; // TTL
553 911
912 int rdlen_offs = offs += 2;
913
914 if (dns)
915 {
916 int dlen = ntohs (dns->cfg.max_size) - offs;
917
918 // bind doesn't compress well, so reduce further by one label length
919 dlen -= qlen;
920
921 // only put data into in-order sequence packets, if
922 // we receive out-of-order packets we generate empty
923 // replies
924 //printf ("%d - %d & %x (=%d) < %d\n", seqno, dns->repseq, SEQNO_MASK, (seqno - dns->repseq) & SEQNO_MASK, MAX_WINDOW);//D
925 if (((seqno - dns->repseq) & SEQNO_MASK) <= MAX_WINDOW)
926 {
927 dns->repseq = seqno;
928
929 while (dlen > 1 && !dns->snddq.empty ())
930 {
931 int txtlen = dlen <= 255 ? dlen - 1 : 255;
932
933 if (txtlen > dns->snddq.size ())
934 txtlen = dns->snddq.size ();
935
936 pkt[offs++] = txtlen;
937 memcpy (pkt.at (offs), dns->snddq.begin (), txtlen);
938 offs += txtlen;
939 dns->snddq.remove (txtlen);
940
941 dlen -= txtlen + 1;
942 }
943 }
944
945 // avoid completely empty TXT rdata
946 if (offs == rdlen_offs)
947 pkt[offs++] = 0;
948
949 slog (L_NOISE, "DNS: snddq %d", dns->snddq.size ());
950 }
951 else
952 {
953 // send RST
954 pkt [offs++] = CMD_IP_1; pkt [offs++] = CMD_IP_2; pkt [offs++] = CMD_IP_3;
955 pkt [offs++] = CMD_IP_RST;
956 }
957
958 int rdlen = offs - rdlen_offs;
959
960 pkt [rdlen_offs - 2] = rdlen >> 8;
961 pkt [rdlen_offs - 1] = rdlen;
962
963 if (dns)
964 {
965 // now update dns_rcv copy
554 offs = r->pkt->len; 966 rcv->pkt->len = offs;
555 memcpy (pkt->at (0), r->pkt->at (0), offs); 967 memcpy (rcv->pkt->at (0), pkt.at (0), offs);
556 goto duplicate_request; 968 }
557 } 969 }
558 970
559 // new packet, queue 971 duplicate_request: ;
560 dns_rcv *rcv = new dns_rcv (seqno, data + 3, datalen - 3); 972 }
561 c->dnsv4_receive_rep (rcv); 973 else
562
563 // now generate reply
564 pkt->ancount = htons (1); // one answer RR
565 pkt->flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_OK); 974 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_FORMERR);
975 }
976 else if (qtype == RR_TYPE_A
977 && qlen > dlen + 1 + cdc26.encode_len (sizeof (dns_cfg)))
978 {
979 dns_cfg cfg;
980 cdc26.decode ((u8 *)&cfg, qname, cdc26.encode_len (sizeof (dns_cfg)));
981 int client = ntohs (cfg.client);
566 982
567 (*pkt) [offs++] = 0xc0;
568 (*pkt) [offs++] = 6 * 2; // same as in query section 983 pkt [offs++] = 0xc0; pkt [offs++] = 6 * 2; // refer to name in query section
569 984
570 (*pkt) [offs++] = RR_TYPE_TXT >> 8; (*pkt) [offs++] = RR_TYPE_TXT; 985 pkt [offs++] = RR_TYPE_A >> 8; pkt [offs++] = RR_TYPE_A; // type
571 (*pkt) [offs++] = RR_CLASS_IN >> 8; (*pkt) [offs++] = RR_CLASS_IN; 986 pkt [offs++] = RR_CLASS_IN >> 8; pkt [offs++] = RR_CLASS_IN; // class
572
573 (*pkt) [offs++] = 0; (*pkt) [offs++] = 0; 987 pkt [offs++] = 0; pkt [offs++] = 0;
574 (*pkt) [offs++] = 0; (*pkt) [offs++] = 0; // TTL 988 pkt [offs++] = 0; pkt [offs++] = cfg.def_ttl; // TTL
989 pkt [offs++] = 0; pkt [offs++] = 4; // rdlength
575 990
576 int dlen = MAX_PKT_SIZE - offs - 2; 991 slog (L_INFO, _("DNS: client %d connects"), client);
577 992
578 // bind doesn't compress well, so reduce further by one label length 993 pkt [offs++] = CMD_IP_1; pkt [offs++] = CMD_IP_2; pkt [offs++] = CMD_IP_3;
579 dlen -= qlen; 994 pkt [offs++] = CMD_IP_REJ;
580 995
581 int rdlen_offs = offs += 2; 996 if (0 < client && client <= conns.size ())
582
583 while (c->dns_snddq
584 && !c->dns_snddq->empty ()
585 && dlen > 1)
586 { 997 {
587 int txtlen = dlen <= 255 ? dlen - 1 : 255; 998 connection *c = conns [client - 1];
588 999
589 if (txtlen > c->dns_snddq->size ()) 1000 if (cfg.valid ())
590 txtlen = c->dns_snddq->size (); 1001 {
1002 pkt [offs - 1] = CMD_IP_SYN;
591 1003
592 (*pkt)[offs++] = txtlen; 1004 delete c->dns;
593 memcpy (pkt->at (offs), c->dns_snddq->begin (), txtlen); 1005 c->dns = new dns_connection (c);
594 offs += txtlen; 1006 c->dns->cfg = cfg;
595 c->dns_snddq->remove (txtlen); 1007 }
596
597 dlen -= txtlen + 1;
598 } 1008 }
599
600 // avoid empty TXT rdata
601 if (offs == rdlen_offs)
602 (*pkt)[offs++] = 0;
603
604 int rdlen = offs - rdlen_offs;
605
606 (*pkt) [rdlen_offs - 2] = rdlen >> 8;
607 (*pkt) [rdlen_offs - 1] = rdlen;
608
609 // now update dns_rcv copy
610 rcv->pkt->len = offs;
611 memcpy (rcv->pkt->at (0), pkt->at (0), offs);
612
613 duplicate_request: ;
614 } 1009 }
615 else
616 pkt->flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_FORMERR);
617 } 1010 }
618 1011
619 pkt->len = offs; 1012 pkt.len = offs;
620 } 1013 }
621
622 return pkt;
623} 1014}
624 1015
625void 1016void
626vpn::dnsv4_client (dns_packet *pkt) 1017vpn::dnsv4_client (dns_packet &pkt)
627{ 1018{
628 u16 flags = ntohs (pkt->flags); 1019 u16 flags = ntohs (pkt.flags);
629 int offs = 6 * 2; // skip header 1020 int offs = 6 * 2; // skip header
630 1021
631 pkt->qdcount = ntohs (pkt->qdcount); 1022 pkt.qdcount = ntohs (pkt.qdcount);
632 pkt->ancount = ntohs (pkt->ancount); 1023 pkt.ancount = ntohs (pkt.ancount);
633 1024
634 // go through our request list and find the corresponding request 1025 // go through our request list and find the corresponding request
635 for (vector<dns_req *>::iterator i = dns_sndpq.begin (); 1026 for (vector<dns_snd *>::iterator i = dns_sndpq.begin ();
636 i != dns_sndpq.end (); 1027 i != dns_sndpq.end ();
637 ++i) 1028 ++i)
638 if ((*i)->pkt->id == pkt->id) 1029 if ((*i)->pkt->id == pkt.id)
639 { 1030 {
1031 dns_connection *dns = (*i)->dns;
640 connection *c = (*i)->conn; 1032 connection *c = dns->c;
641 int seqno = (*i)->seqno; 1033 int seqno = (*i)->seqno;
642 u8 data[MAXSIZE], *datap = data; 1034 u8 data[MAXSIZE], *datap = data;
1035 //printf ("rcv pkt %x\n", seqno);//D
1036
1037 if ((*i)->retry)
1038 {
1039 dns->send_interval *= 1.01;
1040 if (dns->send_interval > MAX_SEND_INTERVAL)
1041 dns->send_interval = MAX_SEND_INTERVAL;
1042 }
1043 else
1044 {
1045#if 0
1046 dns->send_interval *= 0.999;
1047#endif
1048 // the latency surely puts an upper bound on
1049 // the minimum send interval
1050 double latency = ev_now () - (*i)->sent;
1051
1052 if (latency < dns->min_latency)
1053 dns->min_latency = latency;
1054
1055 if (dns->send_interval > dns->min_latency * conf.dns_overlap_factor)
1056 dns->send_interval = dns->min_latency * conf.dns_overlap_factor;
1057
1058 if (dns->send_interval < conf.dns_send_interval)
1059 dns->send_interval = conf.dns_send_interval;
1060 }
643 1061
644 delete *i; 1062 delete *i;
645 dns_sndpq.erase (i); 1063 dns_sndpq.erase (i);
646 1064
647 if (flags & (FLAG_RESPONSE | FLAG_OP_MASK | FLAG_TC)) 1065 if (flags & FLAG_RESPONSE && !(flags & FLAG_OP_MASK))
648 { 1066 {
649 char qname[MAXSIZE]; 1067 char qname[MAXSIZE];
650 1068
651 while (pkt->qdcount-- && offs < MAXSIZE - 4) 1069 while (pkt.qdcount-- && offs < MAXSIZE - 4)
652 { 1070 {
653 int qlen = pkt->decode_label ((char *)qname, MAXSIZE - offs, offs); 1071 int qlen = pkt.decode_label ((char *)qname, MAXSIZE - offs, offs);
654 offs += 4; // skip qtype, qclass 1072 offs += 4; // skip qtype, qclass
655 } 1073 }
656 1074
657 while (pkt->ancount-- && offs < MAXSIZE - 10) 1075 while (pkt.ancount-- && offs < MAXSIZE - 10 && datap)
658 { 1076 {
659 pkt->decode_label ((char *)qname, MAXSIZE - offs, offs); 1077 int qlen = pkt.decode_label ((char *)qname, MAXSIZE - offs, offs);
660 1078
661 u16 qtype = (*pkt) [offs++] << 8; qtype |= (*pkt) [offs++]; 1079 u16 qtype = pkt [offs++] << 8; qtype |= pkt [offs++];
662 u16 qclass = (*pkt) [offs++] << 8; qclass |= (*pkt) [offs++]; 1080 u16 qclass = pkt [offs++] << 8; qclass |= pkt [offs++];
663 u32 ttl = (*pkt) [offs++] << 24; 1081 u32 ttl = pkt [offs++] << 24;
664 ttl |= (*pkt) [offs++] << 16; 1082 ttl |= pkt [offs++] << 16;
665 ttl |= (*pkt) [offs++] << 8; 1083 ttl |= pkt [offs++] << 8;
666 ttl |= (*pkt) [offs++]; 1084 ttl |= pkt [offs++];
667
668 u16 rdlen = (*pkt) [offs++] << 8; rdlen |= (*pkt) [offs++]; 1085 u16 rdlen = pkt [offs++] << 8; rdlen |= pkt [offs++];
669 1086
670 if (rdlen <= MAXSIZE - offs) 1087 if (qtype == RR_TYPE_NULL || qtype == RR_TYPE_TXT)
671 { 1088 {
672 // decode bytes, finally 1089 if (rdlen <= MAXSIZE - offs)
673
674 while (rdlen)
675 { 1090 {
1091 // decode bytes, finally
1092
1093 while (rdlen)
1094 {
676 int txtlen = (*pkt) [offs++]; 1095 int txtlen = pkt [offs++];
677 1096
678 assert (txtlen + offs < MAXSIZE - 1); 1097 assert (txtlen + offs < MAXSIZE - 1);
679 1098
680 memcpy (datap, pkt->at (offs), txtlen); 1099 memcpy (datap, pkt.at (offs), txtlen);
681 datap += txtlen; offs += txtlen; 1100 datap += txtlen; offs += txtlen;
682 1101
683 rdlen -= txtlen + 1; 1102 rdlen -= txtlen + 1;
1103 }
684 } 1104 }
685
686 } 1105 }
1106 else if (qtype == RR_TYPE_A)
1107 {
1108 u8 ip [4];
687 1109
1110 ip [0] = pkt [offs++];
1111 ip [1] = pkt [offs++];
1112 ip [2] = pkt [offs++];
1113 ip [3] = pkt [offs++];
1114
1115 if (ip [0] == CMD_IP_1
1116 && ip [1] == CMD_IP_2
1117 && ip [2] == CMD_IP_3)
1118 {
1119 slog (L_TRACE, _("DNS: got tunnel meta command %02x"), ip [3]);
1120
1121 if (ip [3] == CMD_IP_RST)
1122 {
1123 slog (L_DEBUG, _("DNS: got tunnel RST request"));
1124
1125 delete dns; c->dns = 0;
1126
1127 return;
1128 }
1129 else if (ip [3] == CMD_IP_SYN)
1130 {
1131 slog (L_DEBUG, _("DNS: got tunnel SYN reply, server likes us."));
1132 dns->established = true;
1133 }
1134 else if (ip [3] == CMD_IP_REJ)
1135 {
1136 slog (L_DEBUG, _("DNS: got tunnel REJ reply, server does not like us, aborting."));
1137 abort ();
1138 }
1139 else
1140 slog (L_INFO, _("DNS: got unknown meta command %02x"), ip [3]);
1141 }
1142 else
1143 slog (L_INFO, _("DNS: got spurious a record %d.%d.%d.%d"),
1144 ip [0], ip [1], ip [2], ip [3]);
1145
1146 return;
1147 }
1148
1149 int client, rseqno;
1150 decode_header (qname, client, rseqno);
1151
1152 if (client != THISNODE->id)
1153 {
1154 slog (L_INFO, _("DNS: got dns tunnel response with wrong clientid, ignoring"));
1155 datap = 0;
1156 }
1157 else if (rseqno != seqno)
1158 {
1159 slog (L_DEBUG, _("DNS: got dns tunnel response with wrong seqno, badly caching nameserver?"));
1160 datap = 0;
1161 }
688 } 1162 }
689 } 1163 }
690 1164
691 // todo: pkt now used 1165 // todo: pkt now used
1166 if (datap)
692 c->dnsv4_receive_rep (new dns_rcv (seqno, data, datap - data)); 1167 dns->receive_rep (new dns_rcv (seqno, data, datap - data));
693 1168
694 break; 1169 break;
695 } 1170 }
696
697 delete pkt;
698} 1171}
699 1172
700void 1173void
701vpn::dnsv4_ev (io_watcher &w, short revents) 1174vpn::dnsv4_ev (ev::io &w, int revents)
702{ 1175{
703 if (revents & EVENT_READ) 1176 if (revents & EV_READ)
704 { 1177 {
705 dns_packet *pkt = new dns_packet; 1178 dns_packet *pkt = new dns_packet;
706 struct sockaddr_in sa; 1179 struct sockaddr_in sa;
707 socklen_t sa_len = sizeof (sa); 1180 socklen_t sa_len = sizeof (sa);
708 1181
709 pkt->len = recvfrom (w.fd, &((*pkt)[0]), MAXSIZE, 0, (sockaddr *)&sa, &sa_len); 1182 pkt->len = recvfrom (w.fd, pkt->at (0), MAXSIZE, 0, (sockaddr *)&sa, &sa_len);
710 1183
711 if (pkt->len > 0) 1184 if (pkt->len > 0)
712 { 1185 {
713 if (pkt->flags & htons (FLAG_TC)) 1186 if (ntohs (pkt->flags) & FLAG_RESPONSE)
1187 dnsv4_client (*pkt);
1188 else
714 { 1189 {
715 slog (L_WARN, _("DNS request/response truncated, check protocol settings.")); 1190 dnsv4_server (*pkt);
716 //TODO connection reset 1191 sendto (w.fd, pkt->at (0), pkt->len, 0, (sockaddr *)&sa, sa_len);
717 } 1192 }
718 1193
719 if (THISNODE->dns_port) 1194 delete pkt;
720 {
721 pkt = dnsv4_server (pkt);
722 sendto (w.fd, &((*pkt)[0]), pkt->len, 0, (sockaddr *)&sa, sa_len);
723 }
724 else
725 dnsv4_client (pkt);
726 } 1195 }
727 } 1196 }
728} 1197}
729 1198
730bool 1199bool
731connection::send_dnsv4_packet (vpn_packet *pkt, const sockinfo &si, int tos) 1200vpn::send_dnsv4_packet (vpn_packet *pkt, const sockinfo &si, int tos)
732{ 1201{
733 // never initialized 1202 int client = ntohl (si.host);
734 if (!dns_snddq && !dns_rcvdq)
735 {
736 dns_rcvdq = new byte_stream (MAX_BACKLOG * 2);
737 dns_snddq = new byte_stream (MAX_BACKLOG);
738 1203
739 //dns_rcvseq = dns_sndseq = 0; 1204 assert (0 < client && client <= conns.size ());
740 1205
741 dns_si.set (::conf.dns_forw_host, ::conf.dns_forw_port, PROT_DNSv4); 1206 connection *c = conns [client - 1];
742 } 1207
1208 if (!c->dns)
1209 c->dns = new dns_connection (c);
743 1210
744 if (!dns_snddq->put (pkt)) 1211 if (c->dns->snddq.put (pkt))
745 return false; 1212 c->dns->tw ();
746 1213
747 // start timer if neccessary 1214 // always return true even if the buffer overflows
748 if (!THISNODE->dns_port && !dnsv4_tw.active)
749 dnsv4_cb (dnsv4_tw);
750
751 return true; 1215 return true;
752} 1216}
753 1217
754void 1218void
755connection::dnsv4_cb (time_watcher &w) 1219connection::dnsv4_reset_connection ()
756{ 1220{
1221 //delete dns; dns = 0; //TODO
1222}
1223
1224#define NEXT(w) do { if (next > (w)) next = w; } while (0)
1225
1226void
1227dns_connection::time_cb (ev::timer &w, int revents)
1228{
1229 // servers have to be polled
1230 if (THISNODE->dns_port)
1231 return;
1232
757 // check for timeouts and (re)transmit 1233 // check for timeouts and (re)transmit
758 tstamp next = NOW + 60; 1234 tstamp next = ev::now () + poll_interval;
759 dns_req *send = 0; 1235 dns_snd *send = 0;
760 1236
761 for (vector<dns_req *>::iterator i = vpn->dns_sndpq.begin (); 1237 for (vector<dns_snd *>::iterator i = vpn->dns_sndpq.begin ();
762 i != vpn->dns_sndpq.end (); 1238 i != vpn->dns_sndpq.end ();
763 ++i) 1239 ++i)
764 { 1240 {
765 dns_req *r = *i; 1241 dns_snd *r = *i;
766 1242
767 if (r->next <= NOW) 1243 if (r->timeout <= ev_now ())
768 { 1244 {
769 if (!send) 1245 if (!send)
770 { 1246 {
771 send = r; 1247 send = r;
772 1248
773 if (r->retry)//D
774 printf ("req %d, retry %d\n", r->pkt->id, r->retry);
775 r->retry++; 1249 r->retry++;
776 r->next = NOW + r->retry; 1250 r->timeout = ev_now () + (r->retry * min_latency * conf.dns_timeout_factor);
1251 //printf ("RETRY %x (%d, %f)\n", r->seqno, r->retry, r->timeout - ev_now ());//D
1252
1253 // the following code changes the query section a bit, forcing
1254 // the forwarder to generate a new request
1255 if (r->stdhdr)
1256 encode_header ((char *)r->pkt->at (6 * 2 + 1), THISNODE->id, r->seqno, r->retry);
777 } 1257 }
778 } 1258 }
779 1259 else
780 if (r->next < next) 1260 NEXT (r->timeout);
781 next = r->next;
782 } 1261 }
783 1262
784 if (!send 1263 if (!send)
785 && vpn->dns_sndpq.size () < MAX_OUTSTANDING)
786 { 1264 {
1265 // generate a new packet, if wise
1266
1267 if (!established)
1268 {
1269 if (vpn->dns_sndpq.empty ())
1270 {
787 send = new dns_req (this); 1271 send = new dns_snd (this);
1272
1273 cfg.reset (THISNODE->id);
1274 send->gen_syn_req ();
1275 }
1276 }
1277 else if (vpn->dns_sndpq.size () < conf.dns_max_outstanding
1278 && !SEQNO_EQ (rcvseq, sndseq - (MAX_WINDOW - 1)))
1279 {
1280 if (last_sent + send_interval <= ev_now ())
1281 {
1282 //printf ("sending data request etc.\n"); //D
1283 if (!snddq.empty () || last_received + 1. > ev_now ())
1284 {
1285 poll_interval = send_interval;
1286 NEXT (ev_now () + send_interval);
1287 }
1288
1289 send = new dns_snd (this);
788 send->gen_stream_req (dns_sndseq, dns_snddq); 1290 send->gen_stream_req (sndseq, snddq);
1291 send->timeout = ev_now () + min_latency * conf.dns_timeout_factor;
1292 //printf ("SEND %x (%f)\n", send->seqno, send->timeout - ev_now (), min_latency, conf.dns_timeout_factor);//D
1293
1294 sndseq = (sndseq + 1) & SEQNO_MASK;
1295 }
1296 else
1297 NEXT (last_sent + send_interval);
1298 }
1299
1300 if (send)
789 vpn->dns_sndpq.push_back (send); 1301 vpn->dns_sndpq.push_back (send);
790
791 dns_sndseq = (dns_sndseq + 1) & SEQNO_MASK;
792 } 1302 }
793
794 tstamp min_next = NOW + (1. / (tstamp)MAX_RATE);
795 1303
796 if (send) 1304 if (send)
797 { 1305 {
798 dns_packet *pkt = send->pkt; 1306 last_sent = ev_now ();
799 1307 sendto (vpn->dnsv4_fd,
800 next = min_next; 1308 send->pkt->at (0), send->pkt->len, 0,
801 1309 vpn->dns_forwarder.sav4 (), vpn->dns_forwarder.salenv4 ());
802 sendto (vpn->dnsv4_fd, &((*pkt)[0]), pkt->len, 0, dns_si.sav4 (), dns_si.salenv4 ());
803 } 1310 }
804 else if (next < min_next)
805 next = min_next;
806 1311
807 w.start (next); 1312 slog (L_NOISE, "DNS: pi %f si %f N %f (%d:%d %d)",
1313 poll_interval, send_interval, next - ev_now (),
1314 vpn->dns_sndpq.size (), snddq.size (),
1315 rcvpq.size ());
1316
1317 // TODO: no idea when this happens, but when next < ev_now (), we have a problem
1318 // doesn't seem to happen anymore
1319 if (next < ev_now () + 0.001)
1320 next = ev_now () + 0.1;
1321
1322 w.start (next - ev_now ());
808} 1323}
809 1324
810#endif 1325#endif
811 1326

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines