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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines