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.50 by root, Sun Mar 6 13:49:50 2011 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines