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.7 by pcg, Thu Mar 3 16:54:34 2005 UTC vs.
Revision 1.48 by pcg, Tue Jul 28 00:42:14 2009 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines