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.30 by pcg, Mon Mar 14 17:40:01 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
52#define INITIAL_TIMEOUT 0.1 // retry timeouts
53#define INITIAL_SYN_TIMEOUT 10. // retry timeout for initial syn
54
55#define MIN_SEND_INTERVAL 0.001 // wait at least this time between sending requests
56#define MAX_SEND_INTERVAL 2. // optimistic?
57
58#define LATENCY_FACTOR 0.5 // RTT * LATENCY_FACTOR == sending rate
47#define MAX_OUTSTANDING 40 // max. outstanding requests 59#define MAX_OUTSTANDING 2 // max. outstanding requests
48#define MAX_WINDOW 100 // max. for MAX_OUTSTANDING 60#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 61#define MAX_BACKLOG (100*1024) // size of gvpe protocol backlog (bytes), must be > MAXSIZE
51 62
52#define MAX_DOMAIN_SIZE 220 // 255 is legal limit, but bind doesn't compress well 63#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 64// 240 leaves about 4 bytes of server reply data
54// every two request byte sless give room for one reply byte 65// every two request bytes less give room for one reply byte
55 66
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 67#define SEQNO_MASK 0x3fff
60 68#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 69
77#define MAX_LBL_SIZE 63 70#define MAX_LBL_SIZE 63
78#define MAX_PKT_SIZE 512 71#define MAX_PKT_SIZE 512
79 72
73#define RR_TYPE_A 1
74#define RR_TYPE_NULL 10
80#define RR_TYPE_TXT 16 75#define RR_TYPE_TXT 16
81#define RR_TYPE_ANY 255 76#define RR_TYPE_ANY 255
77
82#define RR_CLASS_IN 1 78#define RR_CLASS_IN 1
83 79
84// the "_" is not valid but widely accepted (all octets should be supported, but let's be conservative) 80#define CMD_IP_1 207
85struct dns64 81#define CMD_IP_2 46
86{ 82#define CMD_IP_3 236
87 static const char encode_chars[64 + 1]; 83#define CMD_IP_RST 29
88 static s8 decode_chars[256]; 84#define CMD_IP_SYN 113
85#define CMD_IP_REJ 32
89 86
90 static int encode_len (int bytes) { return (bytes * 8 + 5) / 6; } 87// works for cmaps up to 255 (not 256!)
91 static int decode_len (int bytes) { return (bytes * 6) / 8; } 88struct charmap
89{
90 enum { INVALID = (u8)255 };
91
92 char encode [256]; // index => char
93 u8 decode [256]; // char => index
94 unsigned int size;
95
96 charmap (const char *cmap);
97};
98
99charmap::charmap (const char *cmap)
100{
101 char *enc = encode;
102 u8 *dec = decode;
103
104 memset (enc, (char) 0, 256);
105 memset (dec, (char)INVALID, 256);
106
107 for (size = 0; cmap [size]; size++)
108 {
109 enc [size] = cmap [size];
110 dec [(u8)enc [size]] = size;
111 }
112
113 assert (size < 256);
114}
115
116#define MAX_DEC_LEN 500
117#define MAX_ENC_LEN (MAX_DEC_LEN * 2)
118#define MAX_LIMBS ((MAX_DEC_LEN * 8 + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS)
119
120// ugly. minimum base is 16(!)
121struct basecoder
122{
123 charmap cmap;
124 unsigned int enc_len [MAX_DEC_LEN];
125 unsigned int dec_len [MAX_ENC_LEN];
126
127 unsigned int encode_len (unsigned int len);
128 unsigned int decode_len (unsigned int len);
129
92 static int encode (char *dst, u8 *src, int len); 130 unsigned int encode (char *dst, u8 *src, unsigned int len);
93 static int decode (u8 *dst, char *src, int len); 131 unsigned int decode (u8 *dst, char *src, unsigned int len);
94 132
95 dns64 (); 133 basecoder (const char *cmap);
96} dns64; 134};
97 135
98// the following sequence has been crafted to 136basecoder::basecoder (const char *cmap)
99// a) look somewhat random 137: 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{ 138{
106 for (int i = 0; i < 64; i++) 139 for (unsigned int len = 0; len < MAX_DEC_LEN; ++len)
107 decode_chars [encode_chars [i]] = i + 1; 140 {
108} 141 u8 src [MAX_DEC_LEN];
142 u8 dst [MAX_ENC_LEN];
109 143
110int dns64::encode (char *dst, u8 *src, int len) 144 memset (src, 255, len);
145
146 mp_limb_t m [MAX_LIMBS];
147 mp_size_t n;
148
149 n = mpn_set_str (m, src, len, 256);
150 n = mpn_get_str (dst, this->cmap.size, m, n);
151
152 for (int i = 0; !dst [i]; ++i)
153 n--;
154
155 enc_len [len] = n;
156 dec_len [n] = len;
157 }
158}
159
160unsigned int basecoder::encode_len (unsigned int len)
111{ 161{
112 // slow, but easy to debug 162 return enc_len [len];
113 char *beg = dst; 163}
114 unsigned int accum, bits = 0; 164
165unsigned int basecoder::decode_len (unsigned int len)
166{
167 while (len && !dec_len [len])
168 --len;
169
170 return dec_len [len];
171}
172
173unsigned int basecoder::encode (char *dst, u8 *src, unsigned int len)
174{
175 if (!len || len > MAX_DEC_LEN)
176 return 0;
177
178 int elen = encode_len (len);
179
180 mp_limb_t m [MAX_LIMBS];
181 mp_size_t n;
182
183 u8 dst_ [MAX_ENC_LEN];
184
185 n = mpn_set_str (m, src, len, 256);
186 n = mpn_get_str (dst_, cmap.size, m, n);
187
188 int plen = elen; // for padding
189
190 while (n < plen)
191 {
192 *dst++ = cmap.encode [0];
193 plen--;
194 }
195
196 for (unsigned int i = n - plen; i < n; ++i)
197 *dst++ = cmap.encode [dst_ [i]];
198
199 return elen;
200}
201
202unsigned int basecoder::decode (u8 *dst, char *src, unsigned int len)
203{
204 if (!len || len > MAX_ENC_LEN)
205 return 0;
206
207 u8 src_ [MAX_ENC_LEN];
208 unsigned int elen = 0;
115 209
116 while (len--) 210 while (len--)
117 { 211 {
118 accum <<= 8; 212 u8 val = cmap.decode [(u8)*src++];
119 accum |= *src++;
120 bits += 8;
121 213
122 while (bits >= 6) 214 if (val != charmap::INVALID)
123 { 215 src_ [elen++] = val;
124 *dst++ = encode_chars [(accum >> (bits - 6)) & 63]; 216 }
125 bits -= 6; 217
126 } 218 int dlen = decode_len (elen);
219
220 mp_limb_t m [MAX_LIMBS];
221 mp_size_t n;
222
223 u8 dst_ [MAX_DEC_LEN];
224
225 n = mpn_set_str (m, src_, elen, cmap.size);
226 n = mpn_get_str (dst_, 256, m, n);
227
228 if (n < dlen)
127 } 229 {
230 memset (dst, 0, dlen - n);
231 memcpy (dst + dlen - n, dst_, n);
232 }
233 else
234 memcpy (dst, dst_ + n - dlen, dlen);
128 235
129 if (bits) 236 return dlen;
130 *dst++ = encode_chars [(accum << (6 - bits)) & 63];
131
132 return dst - beg;
133} 237}
134 238
135int dns64::decode (u8 *dst, char *src, int len) 239#if 0
136{ 240struct test { test (); } test;
137 // slow, but easy to debug
138 u8 *beg = dst;
139 unsigned int accum, bits = 0;
140 241
141 while (len--) 242test::test ()
243{
244 basecoder cdc ("0123456789abcdefghijklmnopqrstuvwxyz");
245
246 u8 in[] = "0123456789abcdefghijklmnopqrstuvwxyz";
247 static char enc[200];
248 static u8 dec[200];
249
250 for (int i = 1; i < 20; i++)
142 { 251 {
143 s8 chr = decode_chars [(u8)*src++]; 252 int elen = cdc.encode (enc, in, i);
253 int dlen = cdc.decode (dec, enc, elen);
144 254
145 if (!chr) 255 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 } 256 }
257 abort ();
258}
259#endif
158 260
159 return dst - beg; 261//static basecoder cdc64 ("_dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI-");
262//static basecoder cdc63 ("_dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI");
263static basecoder cdc62 ("dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI");
264//static basecoder cdc36 ("dphzr06qmjkb34tsvl81xaef92wgyo57ucni"); // unused as of yet
265static basecoder cdc26 ("dPhZrQmJkBtSvLxAeFwGyO");
266
267/////////////////////////////////////////////////////////////////////////////
268
269#define HDRSIZE 6
270
271inline void encode_header (char *data, int clientid, int seqno, int retry = 0)
272{
273 seqno &= SEQNO_MASK;
274
275 u8 hdr[3] = {
276 clientid,
277 (seqno >> 8) | (retry << 6),
278 seqno,
279 };
280
281 assert (clientid < 256);
282
283 cdc26.encode (data, hdr, 3);
284}
285
286inline void decode_header (char *data, int &clientid, int &seqno)
287{
288 u8 hdr[3];
289
290 cdc26.decode (hdr, data, HDRSIZE);
291
292 clientid = hdr[0];
293 seqno = ((hdr[1] << 8) | hdr[2]) & SEQNO_MASK;
160} 294}
161 295
162///////////////////////////////////////////////////////////////////////////// 296/////////////////////////////////////////////////////////////////////////////
163 297
164struct byte_stream 298struct byte_stream
193} 327}
194 328
195void byte_stream::remove (int count) 329void byte_stream::remove (int count)
196{ 330{
197 if (count > fill) 331 if (count > fill)
198 abort (); 332 assert (count <= fill);
199 333
200 memmove (data, data + count, fill -= count); 334 memmove (data, data + count, fill -= count);
201} 335}
202 336
203bool byte_stream::put (u8 *data, unsigned int datalen) 337bool byte_stream::put (u8 *data, unsigned int datalen)
216 return false; 350 return false;
217 351
218 data [fill++] = pkt->len >> 8; 352 data [fill++] = pkt->len >> 8;
219 data [fill++] = pkt->len; 353 data [fill++] = pkt->len;
220 354
221 memcpy (data + fill, &((*pkt)[0]), pkt->len); fill += pkt->len; 355 memcpy (data + fill, pkt->at (0), pkt->len); fill += pkt->len;
222 356
223 return true; 357 return true;
224} 358}
225 359
226vpn_packet *byte_stream::get () 360vpn_packet *byte_stream::get ()
227{ 361{
362 unsigned int len;
363
364 for (;;)
365 {
228 int len = (data [0] << 8) | data [1]; 366 len = (data [0] << 8) | data [1];
229 367
230 if (len > MAXSIZE && fill >= 2) 368 if (len <= MAXSIZE || fill < 2)
231 abort (); // TODO handle this gracefully, connection reset 369 break;
232 370
371 // TODO: handle this better than skipping, e.g. by reset
372 slog (L_DEBUG, _("DNS: corrupted packet stream skipping a byte..."));
373 remove (1);
374 }
375
233 if (fill < len + 2) 376 if (fill < len + 2)
234 return 0; 377 return 0;
235 378
236 vpn_packet *pkt = new vpn_packet; 379 vpn_packet *pkt = new vpn_packet;
237 380
238 pkt->len = len; 381 pkt->len = len;
239 memcpy (&((*pkt)[0]), data + 2, len); 382 memcpy (pkt->at (0), data + 2, len);
240 remove (len + 2); 383 remove (len + 2);
241 384
242 return pkt; 385 return pkt;
243} 386}
244 387
245///////////////////////////////////////////////////////////////////////////// 388/////////////////////////////////////////////////////////////////////////////
246 389
247#define FLAG_QUERY ( 0 << 15) 390#define FLAG_QUERY ( 0 << 15)
248#define FLAG_RESPONSE ( 1 << 15) 391#define FLAG_RESPONSE ( 1 << 15)
249#define FLAG_OP_MASK (15 << 14) 392#define FLAG_OP_MASK (15 << 11)
250#define FLAG_OP_QUERY ( 0 << 11) 393#define FLAG_OP_QUERY ( 0 << 11)
251#define FLAG_AA ( 1 << 10) 394#define FLAG_AA ( 1 << 10)
252#define FLAG_TC ( 1 << 9) 395#define FLAG_TC ( 1 << 9)
253#define FLAG_RD ( 1 << 8) 396#define FLAG_RD ( 1 << 8)
254#define FLAG_RA ( 1 << 7) 397#define FLAG_RA ( 1 << 7)
261#define FLAG_RCODE_REFUSED ( 5 << 0) 404#define FLAG_RCODE_REFUSED ( 5 << 0)
262 405
263#define DEFAULT_CLIENT_FLAGS (FLAG_QUERY | FLAG_OP_QUERY | FLAG_RD) 406#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) 407#define DEFAULT_SERVER_FLAGS (FLAG_RESPONSE | FLAG_OP_QUERY | FLAG_AA | FLAG_RD | FLAG_RA)
265 408
409struct dns_cfg
410{
411 static int next_uid;
412
413 u8 id1, id2, id3, id4;
414
415 u8 version;
416 u8 flags;
417 u8 rrtype;
418 u8 def_ttl;
419
420 u16 client;
421 u16 uid; // to make request unique
422
423 u16 max_size;
424 u8 seq_cdc;
425 u8 req_cdc;
426
427 u8 rep_cdc;
428 u8 delay; // time in 0.01s units that the server may delay replying packets
429 u8 r3, r4;
430
431 u8 r5, r6, r7, r8;
432
433 void reset (int clientid);
434 bool valid ();
435};
436
437int dns_cfg::next_uid;
438
439void dns_cfg::reset (int clientid)
440{
441 id1 = 'G';
442 id2 = 'V';
443 id3 = 'P';
444 id4 = 'E';
445
446 version = 1;
447
448 rrtype = RR_TYPE_TXT;
449 flags = 0;
450 def_ttl = 0;
451 seq_cdc = 26;
452 req_cdc = 62;
453 rep_cdc = 0;
454 max_size = htons (MAX_PKT_SIZE);
455 client = htons (clientid);
456 uid = next_uid++;
457 delay = 0;
458
459 r3 = r4 = 0;
460 r4 = r5 = r6 = r7 = 0;
461}
462
463bool dns_cfg::valid ()
464{
465 return id1 == 'G'
466 && id2 == 'V'
467 && id3 == 'P'
468 && id4 == 'E'
469 && seq_cdc == 26
470 && req_cdc == 62
471 && rep_cdc == 0
472 && version == 1;
473}
474
266struct dns_packet : net_packet 475struct dns_packet : net_packet
267{ 476{
268 u16 id; 477 u16 id;
269 u16 flags; // QR:1 Opcode:4 AA:1 TC:1 RD:1 RA:1 Z:3 RCODE:4 478 u16 flags; // QR:1 Opcode:4 AA:1 TC:1 RD:1 RA:1 Z:3 RCODE:4
270 u16 qdcount, ancount, nscount, arcount; 479 u16 qdcount, ancount, nscount, arcount;
271 480
272 u8 data[MAXSIZE - 6 * 2]; 481 u8 data [MAXSIZE - 6 * 2];
273 482
274 int decode_label (char *data, int size, int &offs); 483 int decode_label (char *data, int size, int &offs);
275}; 484};
276 485
277int dns_packet::decode_label (char *data, int size, int &offs) 486int dns_packet::decode_label (char *data, int size, int &offs)
308 return data - orig; 517 return data - orig;
309} 518}
310 519
311///////////////////////////////////////////////////////////////////////////// 520/////////////////////////////////////////////////////////////////////////////
312 521
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 522static u16 dns_id = 0; // TODO: should be per-vpn
326 523
327static u16 next_id () 524static u16 next_id ()
328{ 525{
526 if (!dns_id)
527 dns_id = time (0);
528
329 // the simplest lsfr with periodicity 65535 i could find 529 // the simplest lsfr with periodicity 65535 i could find
330 dns_id = (dns_id << 1) 530 dns_id = (dns_id << 1)
331 | (((dns_id >> 1) 531 | (((dns_id >> 1)
332 ^ (dns_id >> 2) 532 ^ (dns_id >> 2)
333 ^ (dns_id >> 4) 533 ^ (dns_id >> 4)
334 ^ (dns_id >> 15)) & 1); 534 ^ (dns_id >> 15)) & 1);
335 535
336 return dns_id; 536 return dns_id;
337} 537}
338 538
339dns_req::dns_req (connection *c) 539struct dns_rcv;
340: conn (c) 540struct dns_snd;
541
542struct dns_connection
341{ 543{
342 next = 0; 544 connection *c;
545 struct vpn *vpn;
546
547 dns_cfg cfg;
548
549 bool established;
550
551 tstamp last_received;
552 tstamp last_sent;
553 double min_latency;
554 double poll_interval, send_interval;
555
556 vector<dns_rcv *> rcvpq;
557
558 byte_stream rcvdq; int rcvseq;
559 byte_stream snddq; int sndseq;
560
561 void time_cb (time_watcher &w); time_watcher tw;
562 void receive_rep (dns_rcv *r);
563
564 dns_connection (connection *c);
565 ~dns_connection ();
566};
567
568struct dns_snd
569{
570 dns_packet *pkt;
571 tstamp timeout, sent;
572 int retry;
573 struct dns_connection *dns;
574 int seqno;
575 bool stdhdr;
576
577 void gen_stream_req (int seqno, byte_stream &stream);
578 void gen_syn_req ();
579
580 dns_snd (dns_connection *dns);
581 ~dns_snd ();
582};
583
584dns_snd::dns_snd (dns_connection *dns)
585: dns (dns)
586{
587 timeout = 0;
343 retry = 0; 588 retry = 0;
589 seqno = 0;
590 sent = NOW;
591 stdhdr = false;
344 592
345 pkt = new dns_packet; 593 pkt = new dns_packet;
346 594
347 pkt->id = next_id (); 595 pkt->id = next_id ();
348} 596}
349 597
598dns_snd::~dns_snd ()
599{
600 delete pkt;
601}
602
603static void append_domain (dns_packet &pkt, int &offs, const char *domain)
604{
605 // add tunnel domain
606 for (;;)
607 {
608 const char *end = strchr (domain, '.');
609
610 if (!end)
611 end = domain + strlen (domain);
612
613 int len = end - domain;
614
615 pkt [offs++] = len;
616 memcpy (pkt.at (offs), domain, len);
617 offs += len;
618
619 if (!*end)
620 break;
621
622 domain = end + 1;
623 }
624}
625
350void dns_req::gen_stream_req (int seqno, byte_stream *stream) 626void dns_snd::gen_stream_req (int seqno, byte_stream &stream)
351{ 627{
628 stdhdr = true;
352 this->seqno = seqno; 629 this->seqno = seqno;
630
631 timeout = NOW + INITIAL_TIMEOUT;
353 632
354 pkt->flags = htons (DEFAULT_CLIENT_FLAGS); 633 pkt->flags = htons (DEFAULT_CLIENT_FLAGS);
355 pkt->qdcount = htons (1); 634 pkt->qdcount = htons (1);
356 635
357 int offs = 6*2; 636 int offs = 6*2;
358 int dlen = MAX_DOMAIN_SIZE - strlen (THISNODE->domain) - 2; 637 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, 638 // 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 639 // so we need to have space for 2*MAX_DOMAIN_SIZE + header + extra
361 640
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; 641 char enc[256], *encp = enc;
374 642 encode_header (enc, THISNODE->id, seqno);
375 memcpy (data + 3, stream->begin (), datalen); 643
376 int enclen = dns64::encode (enc, data, datalen + 3); 644 int datalen = cdc62.decode_len (dlen - (dlen + MAX_LBL_SIZE - 1) / MAX_LBL_SIZE - HDRSIZE);
645
646 if (datalen > stream.size ())
647 datalen = stream.size ();
648
649 int enclen = cdc62.encode (enc + HDRSIZE, stream.begin (), datalen) + HDRSIZE;
377 stream->remove (datalen); 650 stream.remove (datalen);
378 651
379 while (enclen) 652 while (enclen)
380 { 653 {
381 int lbllen = enclen < MAX_LBL_SIZE ? enclen : MAX_LBL_SIZE; 654 int lbllen = enclen < MAX_LBL_SIZE ? enclen : MAX_LBL_SIZE;
382 655
387 encp += lbllen; 660 encp += lbllen;
388 661
389 enclen -= lbllen; 662 enclen -= lbllen;
390 } 663 }
391 664
392 const char *suffix = THISNODE->domain; 665 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 666
414 (*pkt)[offs++] = 0; 667 (*pkt)[offs++] = 0;
415 (*pkt)[offs++] = RR_TYPE_ANY >> 8; (*pkt)[offs++] = RR_TYPE_ANY; 668 (*pkt)[offs++] = RR_TYPE_ANY >> 8; (*pkt)[offs++] = RR_TYPE_ANY;
669 (*pkt)[offs++] = RR_CLASS_IN >> 8; (*pkt)[offs++] = RR_CLASS_IN;
670
671 pkt->len = offs;
672}
673
674void dns_snd::gen_syn_req ()
675{
676 timeout = NOW + INITIAL_SYN_TIMEOUT;
677
678 pkt->flags = htons (DEFAULT_CLIENT_FLAGS);
679 pkt->qdcount = htons (1);
680
681 int offs = 6 * 2;
682
683 int elen = cdc26.encode ((char *)pkt->at (offs + 1), (u8 *)&dns->cfg, sizeof (dns_cfg));
684
685 assert (elen <= MAX_LBL_SIZE);
686
687 (*pkt)[offs] = elen;
688 offs += elen + 1;
689 append_domain (*pkt, offs, dns->c->conf->domain);
690
691 (*pkt)[offs++] = 0;
692 (*pkt)[offs++] = RR_TYPE_A >> 8; (*pkt)[offs++] = RR_TYPE_A;
416 (*pkt)[offs++] = RR_CLASS_IN >> 8; (*pkt)[offs++] = RR_CLASS_IN; 693 (*pkt)[offs++] = RR_CLASS_IN >> 8; (*pkt)[offs++] = RR_CLASS_IN;
417 694
418 pkt->len = offs; 695 pkt->len = offs;
419} 696}
420 697
439{ 716{
440 delete pkt; 717 delete pkt;
441} 718}
442 719
443///////////////////////////////////////////////////////////////////////////// 720/////////////////////////////////////////////////////////////////////////////
444 721
445struct dns_cfg 722dns_connection::dns_connection (connection *c)
723: c (c)
724, rcvdq (MAX_BACKLOG * 2)
725, snddq (MAX_BACKLOG * 2)
726, tw (this, &dns_connection::time_cb)
446{ 727{
447 u8 id1, id2, id3; 728 vpn = c->vpn;
448 u8 def_ttl;
449 u8 unused1;
450 u16 max_size;
451 u8 flags1, flags2;
452};
453 729
730 established = false;
731
732 rcvseq = sndseq = 0;
733
734 last_sent = last_received = 0;
735 poll_interval = 0.5; // starting here
736 send_interval = 0.5; // starting rate
737 min_latency = INITIAL_TIMEOUT;
738}
739
740dns_connection::~dns_connection ()
741{
742 for (vector<dns_rcv *>::iterator i = rcvpq.begin ();
743 i != rcvpq.end ();
744 ++i)
745 delete *i;
746}
747
454void connection::dnsv4_receive_rep (struct dns_rcv *r) 748void dns_connection::receive_rep (dns_rcv *r)
455{ 749{
750 if (r->datalen)
751 {
752 last_received = NOW;
753 tw.trigger ();
754
755 poll_interval = send_interval;
756 }
757 else
758 {
759 poll_interval *= 1.5;
760
761 if (poll_interval > MAX_POLL_INTERVAL)
762 poll_interval = MAX_POLL_INTERVAL;
763 }
764
456 dns_rcvpq.push_back (r); 765 rcvpq.push_back (r);
457 766
458 redo: 767 redo:
459 768
769 // find next packet
460 for (vector<dns_rcv *>::iterator i = dns_rcvpq.begin (); 770 for (vector<dns_rcv *>::iterator i = rcvpq.end (); i-- != rcvpq.begin (); )
461 i != dns_rcvpq.end ();
462 ++i)
463 if (dns_rcvseq == (*i)->seqno) 771 if (SEQNO_EQ (rcvseq, (*i)->seqno))
464 { 772 {
773 // enter the packet into our input stream
465 dns_rcv *r = *i; 774 r = *i;
466 775
776 // remove the oldest packet, look forward, as it's oldest first
777 for (vector<dns_rcv *>::iterator j = rcvpq.begin (); j != rcvpq.end (); ++j)
778 if (SEQNO_EQ ((*j)->seqno, rcvseq - MAX_WINDOW))
779 {
780 delete *j;
781 rcvpq.erase (j);
782 break;
783 }
784
467 dns_rcvseq = (dns_rcvseq + 1) & SEQNO_MASK; 785 rcvseq = (rcvseq + 1) & SEQNO_MASK;
468 786
469 if (!dns_snddq && !dns_rcvdq) 787 if (!rcvdq.put (r->data, r->datalen))
470 { 788 {
471 dns_rcvdq = new byte_stream (MAX_BACKLOG * 2); 789 slog (L_ERR, "DNS: !rcvdq.put (r->data, r->datalen)");
472 dns_snddq = new byte_stream (MAX_BACKLOG); 790 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 } 791 }
476 792
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 ()) 793 while (vpn_packet *pkt = rcvdq.get ())
481 { 794 {
482 sockinfo si; 795 sockinfo si;
483 si.host = 0; si.port = 0; si.prot = PROT_DNSv4; 796 si.host = 0x01010101; si.port = htons (c->conf->id); si.prot = PROT_DNSv4;
484 797
485 vpn->recv_vpn_packet (pkt, si); 798 vpn->recv_vpn_packet (pkt, si);
799
800 delete pkt;
486 } 801 }
487 } 802
488 else if ((u32)(*i)->seqno - (u32)dns_rcvseq + MAX_WINDOW > MAX_WINDOW * 2) 803 // 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; 804 goto redo;
495 } 805 }
496} 806}
497 807
498dns_packet * 808void
499vpn::dnsv4_server (dns_packet *pkt) 809vpn::dnsv4_server (dns_packet &pkt)
500{ 810{
501 u16 flags = ntohs (pkt->flags); 811 u16 flags = ntohs (pkt.flags);
502 812
503 //memcpy (&((*rep)[0]), &((*pkt)[0]), pkt->len);
504 int offs = 6 * 2; // skip header 813 int offs = 6 * 2; // skip header
505 814
506 pkt->flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_FORMERR); 815 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_FORMERR);
507 816
508 if (!(flags & (FLAG_RESPONSE | FLAG_OP_MASK | FLAG_TC)) 817 if (0 == (flags & (FLAG_RESPONSE | FLAG_OP_MASK))
509 && pkt->qdcount == htons (1)) 818 && pkt.qdcount == htons (1))
510 { 819 {
511 char qname[MAXSIZE]; 820 char qname [MAXSIZE];
512 int qlen = pkt->decode_label ((char *)qname, MAXSIZE - offs, offs); 821 int qlen = pkt.decode_label ((char *)qname, MAXSIZE - offs, offs);
513 822
514 u16 qtype = (*pkt) [offs++] << 8; qtype |= (*pkt) [offs++]; 823 u16 qtype = pkt [offs++] << 8; qtype |= pkt [offs++];
515 u16 qclass = (*pkt) [offs++] << 8; qclass |= (*pkt) [offs++]; 824 u16 qclass = pkt [offs++] << 8; qclass |= pkt [offs++];
516 825
517 pkt->qdcount = htons (1); 826 pkt.qdcount = htons (1);
518 pkt->ancount = 0; 827 pkt.ancount = 0;
519 pkt->nscount = 0; // should be self, as other nameservers reply like this 828 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 829 pkt.arcount = 0; // a record for self, as other nameservers reply like this
521 830
522 pkt->flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_NXDOMAIN); 831 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_SERVFAIL);
523 832
524 int dlen = strlen (THISNODE->domain); 833 int dlen = strlen (THISNODE->domain);
525 834
526 if (qclass == RR_CLASS_IN 835 if (qclass == RR_CLASS_IN
527 && (qtype == RR_TYPE_ANY || qtype == RR_TYPE_TXT)
528 && qlen > dlen + 1 836 && qlen > dlen + 1
529 && !memcmp (qname + qlen - dlen - 1, THISNODE->domain, dlen)) 837 && !memcmp (qname + qlen - (dlen + 1), THISNODE->domain, dlen))
530 { 838 {
531 // correct class, domain: parse 839 // now generate reply
532 u8 data[MAXSIZE]; 840 pkt.ancount = htons (1); // one answer RR
533 int datalen = dns64::decode (data, qname, qlen - dlen - 1); 841 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_OK);
534 842
535 int client = data[0]; 843 if ((qtype == RR_TYPE_ANY
536 int seqno = ((data[1] << 7) | (data[2] >> 1)) & SEQNO_MASK; 844 || qtype == RR_TYPE_TXT
537 845 || qtype == RR_TYPE_NULL)
538 if (0 < client && client <= conns.size ()) 846 && qlen > dlen + 1 + HDRSIZE)
539 { 847 {
848 // correct class, domain: parse
849 int client, seqno;
850 decode_header (qname, client, seqno);
851
852 u8 data[MAXSIZE];
853 int datalen = cdc62.decode (data, qname + HDRSIZE, qlen - (dlen + 1 + HDRSIZE));
854
855 if (0 < client && client <= conns.size ())
856 {
540 connection *c = conns [client - 1]; 857 connection *c = conns [client - 1];
858 dns_connection *dns = c->dns;
859 dns_rcv *rcv;
860 bool in_seq;
541 861
542 redo: 862 if (dns)
543
544 for (vector<dns_rcv *>::iterator i = c->dns_rcvpq.begin ();
545 i != c->dns_rcvpq.end ();
546 ++i) 863 {
864 for (vector<dns_rcv *>::iterator i = dns->rcvpq.end (); i-- != dns->rcvpq.begin (); )
547 if ((*i)->seqno == seqno) 865 if (SEQNO_EQ ((*i)->seqno, seqno))
866 {
867 // already seen that request: simply reply with the cached reply
868 dns_rcv *r = *i;
869
870 slog (L_DEBUG, "DNS: duplicate packet received ID %d, SEQ %d", htons (r->pkt->id), seqno);
871
872 // refresh header & id, as the retry count could have changed
873 memcpy (r->pkt->at (6 * 2 + 1), pkt.at (6 * 2 + 1), HDRSIZE);
874 r->pkt->id = pkt.id;
875
876 memcpy (pkt.at (0), r->pkt->at (0), offs = r->pkt->len);
877
878 goto duplicate_request;
879 }
880
881 in_seq = dns->rcvseq == seqno;
882
883 // new packet, queue
884 rcv = new dns_rcv (seqno, data, datalen);
885 dns->receive_rep (rcv);
886 }
887
548 { 888 {
549 // already seen that request: simply reply with the cached reply 889 pkt [offs++] = 0xc0; pkt [offs++] = 6 * 2; // refer to name in query section
550 dns_rcv *r = *i;
551 890
552 printf ("DUPLICATE %d\n", htons (r->pkt->id));//D 891 int rtype = dns ? dns->cfg.rrtype : RR_TYPE_A;
892 pkt [offs++] = rtype >> 8; pkt [offs++] = rtype; // type
893 pkt [offs++] = RR_CLASS_IN >> 8; pkt [offs++] = RR_CLASS_IN; // class
894 pkt [offs++] = 0; pkt [offs++] = 0;
895 pkt [offs++] = 0; pkt [offs++] = dns ? dns->cfg.def_ttl : 0; // TTL
553 896
897 int rdlen_offs = offs += 2;
898
899 if (dns)
900 {
901 int dlen = ntohs (dns->cfg.max_size) - offs;
902
903 // bind doesn't compress well, so reduce further by one label length
904 dlen -= qlen;
905
906 // only put data into in-order sequence packets, if
907 // we receive out-of-order packets we generate empty
908 // replies
909 while (dlen > 1 && !dns->snddq.empty () && in_seq)
910 {
911 int txtlen = dlen <= 255 ? dlen - 1 : 255;
912
913 if (txtlen > dns->snddq.size ())
914 txtlen = dns->snddq.size ();
915
916 pkt[offs++] = txtlen;
917 memcpy (pkt.at (offs), dns->snddq.begin (), txtlen);
918 offs += txtlen;
919 dns->snddq.remove (txtlen);
920
921 dlen -= txtlen + 1;
922 }
923
924 // avoid 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 * LATENCY_FACTOR)
1034 dns->send_interval = dns->min_latency * LATENCY_FACTOR;
1035
1036 if (dns->send_interval < MIN_SEND_INTERVAL)
1037 dns->send_interval = MIN_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 = ntohs (si.port);
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 return false;
746 1191
747 // start timer if neccessary 1192 c->dns->tw.trigger ();
748 if (!THISNODE->dns_port && !dnsv4_tw.active)
749 dnsv4_cb (dnsv4_tw);
750 1193
751 return true; 1194 return true;
752} 1195}
753 1196
754void 1197void
1198connection::dnsv4_reset_connection ()
1199{
1200 //delete dns; dns = 0; //TODO
1201}
1202
1203#define NEXT(w) do { if (next > (w)) next = w; } while (0)
1204
1205void
755connection::dnsv4_cb (time_watcher &w) 1206dns_connection::time_cb (time_watcher &w)
756{ 1207{
1208 // servers have to be polled
1209 if (THISNODE->dns_port)
1210 return;
1211
757 // check for timeouts and (re)transmit 1212 // check for timeouts and (re)transmit
758 tstamp next = NOW + 60; 1213 tstamp next = NOW + poll_interval;
759 dns_req *send = 0; 1214 dns_snd *send = 0;
760 1215
761 for (vector<dns_req *>::iterator i = vpn->dns_sndpq.begin (); 1216 for (vector<dns_snd *>::iterator i = vpn->dns_sndpq.begin ();
762 i != vpn->dns_sndpq.end (); 1217 i != vpn->dns_sndpq.end ();
763 ++i) 1218 ++i)
764 { 1219 {
765 dns_req *r = *i; 1220 dns_snd *r = *i;
766 1221
767 if (r->next <= NOW) 1222 if (r->timeout <= NOW)
768 { 1223 {
769 if (!send) 1224 if (!send)
770 { 1225 {
771 send = r; 1226 send = r;
772 1227
773 if (r->retry)//D
774 printf ("req %d, retry %d\n", r->pkt->id, r->retry);
775 r->retry++; 1228 r->retry++;
776 r->next = NOW + r->retry; 1229 r->timeout = NOW + (r->retry * min_latency * 8.);
1230
1231 // the following code changes the query section a bit, forcing
1232 // the forwarder to generate a new request
1233 if (r->stdhdr)
1234 {
1235 //printf ("reencoded header for ID %d retry %d:%d:%d (%p)\n", htons (r->pkt->id), THISNODE->id, r->seqno, r->retry);
1236 //encode_header ((char *)r->pkt->at (6 * 2 + 1), THISNODE->id, r->seqno, r->retry);
1237 }
777 } 1238 }
778 } 1239 }
779 1240 else
780 if (r->next < next) 1241 NEXT (r->timeout);
781 next = r->next;
782 } 1242 }
783 1243
784 if (!send 1244 if (!send)
1245 {
1246 // generate a new packet, if wise
1247
1248 if (!established)
1249 {
1250 if (vpn->dns_sndpq.empty ())
1251 {
1252 send = new dns_snd (this);
1253
1254 cfg.reset (THISNODE->id);
1255 send->gen_syn_req ();
1256 }
1257 }
785 && vpn->dns_sndpq.size () < MAX_OUTSTANDING) 1258 else if (vpn->dns_sndpq.size () < MAX_OUTSTANDING
786 { 1259 && !SEQNO_EQ (rcvseq, sndseq - (MAX_WINDOW - 1)))
1260 {
1261 if (last_sent + send_interval <= NOW)
1262 {
1263 //printf ("sending data request etc.\n"); //D
1264 if (!snddq.empty () || last_received + 1. > NOW)
1265 {
1266 poll_interval = send_interval;
1267 NEXT (NOW + send_interval);
1268 }
1269
787 send = new dns_req (this); 1270 send = new dns_snd (this);
788 send->gen_stream_req (dns_sndseq, dns_snddq); 1271 send->gen_stream_req (sndseq, snddq);
1272 send->timeout = NOW + min_latency * 8.;
1273
1274 sndseq = (sndseq + 1) & SEQNO_MASK;
1275 }
1276 else
1277 NEXT (last_sent + send_interval);
1278 }
1279
1280 if (send)
789 vpn->dns_sndpq.push_back (send); 1281 vpn->dns_sndpq.push_back (send);
790
791 dns_sndseq = (dns_sndseq + 1) & SEQNO_MASK;
792 } 1282 }
793
794 tstamp min_next = NOW + (1. / (tstamp)MAX_RATE);
795 1283
796 if (send) 1284 if (send)
797 { 1285 {
798 dns_packet *pkt = send->pkt; 1286 last_sent = NOW;
799 1287 sendto (vpn->dnsv4_fd,
800 next = min_next; 1288 send->pkt->at (0), send->pkt->len, 0,
801 1289 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 } 1290 }
804 else if (next < min_next) 1291
805 next = min_next; 1292 slog (L_NOISE, "DNS: pi %f si %f N %f (%d:%d %d)",
1293 poll_interval, send_interval, next - NOW,
1294 vpn->dns_sndpq.size (), snddq.size (),
1295 rcvpq.size ());
1296
1297 // TODO: no idea when this happens, but when next < NOW, we have a problem
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