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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines