fix typo in pt.po headers
[debian/iodine.git] / src / iodined.c
1 /*
2  * Copyright (c) 2006-2014 Erik Ekman <yarrick@kryo.se>,
3  * 2006-2009 Bjorn Andersson <flex@kryo.se>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 #include <stdio.h>
19 #include <stdint.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <strings.h>
23 #include <signal.h>
24 #include <unistd.h>
25 #include <sys/param.h>
26 #include <sys/time.h>
27 #include <fcntl.h>
28 #include <time.h>
29 #include <zlib.h>
30
31 #include "common.h"
32
33 #ifdef WINDOWS32
34 #include "windows.h"
35 #include <winsock2.h>
36 #else
37 #include <arpa/nameser.h>
38 #ifdef DARWIN
39 #define BIND_8_COMPAT
40 #include <arpa/nameser_compat.h>
41 #endif
42 #define _XPG4_2
43 #include <netinet/in_systm.h>
44 #include <netinet/ip.h>
45 #include <grp.h>
46 #include <sys/uio.h>
47 #include <pwd.h>
48 #include <netdb.h>
49 #include <syslog.h>
50 #endif
51
52 #include "dns.h"
53 #include "encoding.h"
54 #include "base32.h"
55 #include "base64.h"
56 #include "base64u.h"
57 #include "base128.h"
58 #include "user.h"
59 #include "login.h"
60 #include "tun.h"
61 #include "fw_query.h"
62 #include "version.h"
63
64 #ifdef HAVE_SYSTEMD
65 # include <systemd/sd-daemon.h>
66 #endif
67
68 #ifdef WINDOWS32
69 WORD req_version = MAKEWORD(2, 2);
70 WSADATA wsa_data;
71 #endif
72
73 #define PASSWORD_ENV_VAR "IODINED_PASS"
74
75 static int running = 1;
76 static char *topdomain;
77 static char password[33];
78 static struct encoder *b32;
79 static struct encoder *b64;
80 static struct encoder *b64u;
81 static struct encoder *b128;
82 static int created_users;
83
84 static int check_ip;
85 static int my_mtu;
86 static in_addr_t my_ip;
87 static int netmask;
88
89 static in_addr_t ns_ip;
90
91 static int bind_port;
92 static int debug;
93
94 #if !defined(BSD) && !defined(__GLIBC__)
95 static char *__progname;
96 #endif
97
98 static int read_dns(int, int, struct query *);
99 static void write_dns(int, struct query *, char *, int, char);
100 static void handle_full_packet(int, int, int);
101
102 /* Ask externalip.net webservice to get external ip */
103 static int get_external_ip(struct in_addr *ip)
104 {
105         int sock;
106         struct addrinfo *addr;
107         int res;
108         const char *getstr = "GET /ip/ HTTP/1.0\r\n"
109                 /* HTTP 1.0 to avoid chunked transfer coding */
110                 "Host: api.externalip.net\r\n\r\n";
111         char buf[512];
112         char *b;
113         int len;
114
115         res = getaddrinfo("api.externalip.net", "80", NULL, &addr);
116         if (res < 0) return 1;
117
118         sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
119         if (sock < 0) {
120                 freeaddrinfo(addr);
121                 return 2;
122         }
123
124         res = connect(sock, addr->ai_addr, addr->ai_addrlen);
125         freeaddrinfo(addr);
126         if (res < 0) return 3;
127
128         res = write(sock, getstr, strlen(getstr));
129         if (res != strlen(getstr)) return 4;
130
131         /* Zero buf before receiving, leave at least one zero at the end */
132         memset(buf, 0, sizeof(buf));
133         res = read(sock, buf, sizeof(buf) - 1);
134         if (res < 0) return 5;
135         len = res;
136
137         res = close(sock);
138         if (res < 0) return 6;
139
140         b = buf;
141         while (len > 9) {
142                 /* Look for split between headers and data */
143                 if (strncmp("\r\n\r\n", b, 4) == 0) break;
144                 b++;
145                 len--;
146         }
147         if (len < 10) return 7;
148         b += 4;
149
150         res = inet_aton(b, ip);
151         return (res == 0);
152 }
153
154 static void
155 sigint(int sig)
156 {
157         running = 0;
158 }
159
160 #ifdef WINDOWS32
161 #define LOG_EMERG       0
162 #define LOG_ALERT       1
163 #define LOG_CRIT        2
164 #define LOG_ERR         3
165 #define LOG_WARNING     4
166 #define LOG_NOTICE      5
167 #define LOG_INFO        6
168 #define LOG_DEBUG       7
169 static void
170 syslog(int a, const char *str, ...)
171 {
172         /* TODO: implement (add to event log), move to common.c */
173         ;
174 }
175 #endif
176
177 /* This will not check that user has passed login challenge */
178 static int
179 check_user_and_ip(int userid, struct query *q)
180 {
181         struct sockaddr_in *tempin;
182
183         /* Note: duplicate in handle_raw_login() except IP-address check */
184
185         if (userid < 0 || userid >= created_users ) {
186                 return 1;
187         }
188         if (!users[userid].active || users[userid].disabled) {
189                 return 1;
190         }
191         if (users[userid].last_pkt + 60 < time(NULL)) {
192                 return 1;
193         }
194
195         /* return early if IP checking is disabled */
196         if (!check_ip) {
197                 return 0;
198         }
199
200         tempin = (struct sockaddr_in *) &(q->from);
201         return memcmp(&(users[userid].host), &(tempin->sin_addr), sizeof(struct in_addr));
202 }
203
204 /* This checks that user has passed normal (non-raw) login challenge */
205 static int
206 check_authenticated_user_and_ip(int userid, struct query *q)
207 {
208         int res = check_user_and_ip(userid, q);
209         if (res)
210                 return res;
211
212         if (!users[userid].authenticated)
213                 return 1;
214
215         return 0;
216 }
217
218 static void
219 send_raw(int fd, char *buf, int buflen, int user, int cmd, struct query *q)
220 {
221         char packet[4096];
222         int len;
223
224         len = MIN(sizeof(packet) - RAW_HDR_LEN, buflen);
225
226         memcpy(packet, raw_header, RAW_HDR_LEN);
227         if (len) {
228                 memcpy(&packet[RAW_HDR_LEN], buf, len);
229         }
230
231         len += RAW_HDR_LEN;
232         packet[RAW_HDR_CMD] = cmd | (user & 0x0F);
233
234         if (debug >= 2) {
235                 fprintf(stderr, "TX-raw: client %s, cmd %d, %d bytes\n",
236                         format_addr(&q->from, q->fromlen), cmd, len);
237         }
238
239         sendto(fd, packet, len, 0, (struct sockaddr *) &q->from, q->fromlen);
240 }
241
242
243 static void
244 start_new_outpacket(int userid, char *data, int datalen)
245 /* Copies data to .outpacket and resets all counters.
246    data is expected to be compressed already. */
247 {
248         datalen = MIN(datalen, sizeof(users[userid].outpacket.data));
249         memcpy(users[userid].outpacket.data, data, datalen);
250         users[userid].outpacket.len = datalen;
251         users[userid].outpacket.offset = 0;
252         users[userid].outpacket.sentlen = 0;
253         users[userid].outpacket.seqno = (users[userid].outpacket.seqno + 1) & 7;
254         users[userid].outpacket.fragment = 0;
255         users[userid].outfragresent = 0;
256 }
257
258 #ifdef OUTPACKETQ_LEN
259
260 static int
261 save_to_outpacketq(int userid, char *data, int datalen)
262 /* Find space in outpacket-queue and store data (expected compressed already).
263    Returns: 1 = okay, 0 = no space. */
264 {
265         int fill;
266
267         if (users[userid].outpacketq_filled >= OUTPACKETQ_LEN)
268                 /* no space */
269                 return 0;
270
271         fill = users[userid].outpacketq_nexttouse +
272                users[userid].outpacketq_filled;
273         if (fill >= OUTPACKETQ_LEN)
274                 fill -= OUTPACKETQ_LEN;
275
276         datalen = MIN(datalen, sizeof(users[userid].outpacketq[fill].data));
277         memcpy(users[userid].outpacketq[fill].data, data, datalen);
278         users[userid].outpacketq[fill].len = datalen;
279
280         users[userid].outpacketq_filled++;
281
282         if (debug >= 3)
283                 fprintf(stderr, "    Qstore, now %d\n",
284                         users[userid].outpacketq_filled);
285
286         return 1;
287 }
288
289 static int
290 get_from_outpacketq(int userid)
291 /* Starts new outpacket from queue, if any.
292    Returns: 1 = okay, 0 = no packets were waiting. */
293 {
294         int use;
295
296         if (users[userid].outpacketq_filled <= 0)
297                 /* no packets */
298                 return 0;
299
300         use = users[userid].outpacketq_nexttouse;
301
302         start_new_outpacket(userid, users[userid].outpacketq[use].data,
303                             users[userid].outpacketq[use].len);
304
305         use++;
306         if (use >= OUTPACKETQ_LEN)
307                 use = 0;
308         users[userid].outpacketq_nexttouse = use;
309         users[userid].outpacketq_filled--;
310
311         if (debug >= 3)
312                 fprintf(stderr, "    Qget, now %d\n",
313                         users[userid].outpacketq_filled);
314
315         return 1;
316 }
317
318 #endif /* OUTPACKETQ_LEN */
319
320 #ifdef DNSCACHE_LEN
321
322 /* On the DNS cache:
323
324    This cache is implemented to better handle the aggressively impatient DNS
325    servers that very quickly re-send requests when we choose to not
326    immediately answer them in lazy mode. This cache works much better than
327    pruning(=dropping) the improper requests, since the DNS server will
328    actually get an answer instead of silence.
329
330    Because of the CMC in both ping and upstream data, unwanted cache hits
331    are prevented. Data-CMC is only 36 counts, so our cache length should
332    not exceed 36/2=18 packets. (This quick rule assumes all packets are
333    otherwise equal, which they arent: up/downstream seq/frag, tcp sequence
334    number, and of course data.)
335 */
336
337 static void
338 save_to_dnscache(int userid, struct query *q, char *answer, int answerlen)
339 /* Store answer in our little DNS cache. */
340 {
341         int fill;
342
343         if (answerlen > sizeof(users[userid].dnscache_answer[fill]))
344                 return;  /* can't store this */
345
346         fill = users[userid].dnscache_lastfilled + 1;
347         if (fill >= DNSCACHE_LEN)
348                 fill = 0;
349
350         memcpy(&(users[userid].dnscache_q[fill]), q, sizeof(struct query));
351         memcpy(users[userid].dnscache_answer[fill], answer, answerlen);
352         users[userid].dnscache_answerlen[fill] = answerlen;
353
354         users[userid].dnscache_lastfilled = fill;
355 }
356
357 static int
358 answer_from_dnscache(int dns_fd, int userid, struct query *q)
359 /* Checks cache and sends repeated answer if we alreay saw this query recently.
360    Returns: 1 = answer sent, drop this query, 0 = no answer sent, this is
361    a new query. */
362 {
363         int i;
364         int use;
365
366         for (i = 0; i < DNSCACHE_LEN ; i++) {
367                 /* Try cache most-recent-first */
368                 use = users[userid].dnscache_lastfilled - i;
369                 if (use < 0)
370                         use += DNSCACHE_LEN;
371
372                 if (users[userid].dnscache_q[use].id == 0)
373                         continue;
374                 if (users[userid].dnscache_answerlen[use] <= 0)
375                         continue;
376
377                 if (users[userid].dnscache_q[use].type != q->type ||
378                     strcmp(users[userid].dnscache_q[use].name, q->name))
379                         continue;
380
381                 /* okay, match */
382                 if (debug >= 1)
383                         fprintf(stderr, "OUT  user %d %s from dnscache\n", userid, q->name);
384
385                 write_dns(dns_fd, q, users[userid].dnscache_answer[use],
386                           users[userid].dnscache_answerlen[use],
387                           users[userid].downenc);
388
389                 q->id = 0;      /* this query was used */
390                 return 1;
391         }
392
393         /* here only when no match found */
394         return 0;
395 }
396
397 #endif /* DNSCACHE_LEN */
398
399 static inline void
400 save_to_qmem(unsigned char *qmem_cmc, unsigned short *qmem_type, int qmem_len,
401              int *qmem_lastfilled, unsigned char *cmc_to_add,
402              unsigned short type_to_add)
403 /* Remember query to check for duplicates */
404 {
405         int fill;
406
407         fill = *qmem_lastfilled + 1;
408         if (fill >= qmem_len)
409                 fill = 0;
410
411         memcpy(qmem_cmc + fill * 4, cmc_to_add, 4);
412         qmem_type[fill] = type_to_add;
413         *qmem_lastfilled = fill;
414 }
415
416 static inline void
417 save_to_qmem_pingordata(int userid, struct query *q)
418 {
419         /* Our CMC is a bit more than the "official" CMC; we store 4 bytes
420            just because we can, and because it may prevent some false matches.
421            For ping, we save the 4 decoded bytes: userid + seq/frag + CMC.
422            For data, we save the 4 _un_decoded chars in lowercase: seq/frag's
423            + 1 char CMC; that last char is non-Base32.
424          */
425
426         char cmc[8];
427         int i;
428
429         if (q->name[0] == 'P' || q->name[0] == 'p') {
430                 /* Ping packet */
431
432                 size_t cmcsize = sizeof(cmc);
433                 char *cp = strchr(q->name, '.');
434
435                 if (cp == NULL)
436                         return;  /* illegal hostname; shouldn't happen */
437
438                 /* We already unpacked in handle_null_request(), but that's
439                    lost now... Note: b32 directly, we want no undotify here! */
440                 i = b32->decode(cmc, &cmcsize, q->name + 1, (cp - q->name) - 1);
441
442                 if (i < 4)
443                         return;  /* illegal ping; shouldn't happen */
444
445                 save_to_qmem(users[userid].qmemping_cmc,
446                              users[userid].qmemping_type, QMEMPING_LEN,
447                              &users[userid].qmemping_lastfilled,
448                              (void *) cmc, q->type);
449         } else {
450                 /* Data packet, hopefully not illegal */
451                 if (strlen(q->name) < 5)
452                         return;
453
454                 /* We store CMC in lowercase; if routing via multiple parallel
455                    DNS servers, one may do case-switch and another may not,
456                    and we still want to detect duplicates.
457                    Data-header is always base32, so case-swap won't hurt.
458                  */
459                 for (i = 0; i < 4; i++)
460                         if (q->name[i+1] >= 'A' && q->name[i+1] <= 'Z')
461                                 cmc[i] = q->name[i+1] + ('a' - 'A');
462                         else
463                                 cmc[i] = q->name[i+1];
464
465                 save_to_qmem(users[userid].qmemdata_cmc,
466                              users[userid].qmemdata_type, QMEMDATA_LEN,
467                              &users[userid].qmemdata_lastfilled,
468                              (void *) cmc, q->type);
469         }
470 }
471
472 static int
473 answer_from_qmem(int dns_fd, struct query *q, unsigned char *qmem_cmc,
474                  unsigned short *qmem_type, int qmem_len,
475                  unsigned char *cmc_to_check)
476 /* Checks query memory and sends an (illegal) answer if this is a duplicate.
477    Returns: 1 = answer sent, drop this query, 0 = no answer sent, this is
478    not a duplicate. */
479 {
480         int i;
481
482         for (i = 0; i < qmem_len ; i++) {
483
484                 if (qmem_type[i] == T_UNSET)
485                         continue;
486                 if (qmem_type[i] != q->type)
487                         continue;
488                 if (memcmp(qmem_cmc + i * 4, cmc_to_check, 4))
489                         continue;
490
491                 /* okay, match */
492                 if (debug >= 1)
493                         fprintf(stderr, "OUT  from qmem for %s == duplicate, sending illegal reply\n", q->name);
494
495                 write_dns(dns_fd, q, "x", 1, 'T');
496
497                 q->id = 0;      /* this query was used */
498                 return 1;
499         }
500
501         /* here only when no match found */
502         return 0;
503 }
504
505 static inline int
506 answer_from_qmem_data(int dns_fd, int userid, struct query *q)
507 /* Quick helper function to keep handle_null_request() clean */
508 {
509         char cmc[4];
510         int i;
511
512         for (i = 0; i < 4; i++)
513                 if (q->name[i+1] >= 'A' && q->name[i+1] <= 'Z')
514                         cmc[i] = q->name[i+1] + ('a' - 'A');
515                 else
516                         cmc[i] = q->name[i+1];
517
518         return answer_from_qmem(dns_fd, q, users[userid].qmemdata_cmc,
519                                 users[userid].qmemdata_type, QMEMDATA_LEN,
520                                 (void *) cmc);
521 }
522
523 static int
524 send_chunk_or_dataless(int dns_fd, int userid, struct query *q)
525 /* Sends current fragment to user, or dataless packet if there is no
526    current fragment available (-> normal "quiet" ping reply).
527    Does not update anything, except:
528    - discards q always (query is used)
529    - forgets entire users[userid].outpacket if it was sent in one go,
530      and then tries to get new packet from outpacket-queue
531    Returns: 1 = can call us again immediately, new packet from queue;
532    0 = don't call us again for now.
533 */
534 {
535         char pkt[4096];
536         int datalen = 0;
537         int last = 0;
538
539         /* If re-sent too many times, drop entire packet */
540         if (users[userid].outpacket.len > 0 &&
541             users[userid].outfragresent > 5) {
542                 users[userid].outpacket.len = 0;
543                 users[userid].outpacket.offset = 0;
544                 users[userid].outpacket.sentlen = 0;
545                 users[userid].outfragresent = 0;
546
547 #ifdef OUTPACKETQ_LEN
548                 /* Maybe more in queue, use immediately */
549                 get_from_outpacketq(userid);
550 #endif
551         }
552
553         if (users[userid].outpacket.len > 0) {
554                 datalen = MIN(users[userid].fragsize, users[userid].outpacket.len - users[userid].outpacket.offset);
555                 datalen = MIN(datalen, sizeof(pkt)-2);
556
557                 memcpy(&pkt[2], users[userid].outpacket.data + users[userid].outpacket.offset, datalen);
558                 users[userid].outpacket.sentlen = datalen;
559                 last = (users[userid].outpacket.len == users[userid].outpacket.offset + datalen);
560
561                 users[userid].outfragresent++;
562         }
563
564         /* Build downstream data header (see doc/proto_xxxxxxxx.txt) */
565
566         /* First byte is 1 bit compression flag, 3 bits upstream seqno, 4 bits upstream fragment */
567         pkt[0] = (1<<7) | ((users[userid].inpacket.seqno & 7) << 4) |
568                 (users[userid].inpacket.fragment & 15);
569         /* Second byte is 3 bits downstream seqno, 4 bits downstream fragment, 1 bit last flag */
570         pkt[1] = ((users[userid].outpacket.seqno & 7) << 5) |
571                 ((users[userid].outpacket.fragment & 15) << 1) | (last & 1);
572
573         if (debug >= 1) {
574                 fprintf(stderr, "OUT  pkt seq# %d, frag %d (last=%d), offset %d, fragsize %d, total %d, to user %d\n",
575                         users[userid].outpacket.seqno & 7, users[userid].outpacket.fragment & 15,
576                         last, users[userid].outpacket.offset, datalen, users[userid].outpacket.len, userid);
577         }
578         write_dns(dns_fd, q, pkt, datalen + 2, users[userid].downenc);
579
580         if (q->id2 != 0) {
581                 q->id = q->id2;
582                 q->fromlen = q->fromlen2;
583                 memcpy(&(q->from), &(q->from2), q->fromlen2);
584                 if (debug >= 1)
585                         fprintf(stderr, "OUT  again to last duplicate\n");
586                 write_dns(dns_fd, q, pkt, datalen + 2, users[userid].downenc);
587         }
588
589         save_to_qmem_pingordata(userid, q);
590
591 #ifdef DNSCACHE_LEN
592         save_to_dnscache(userid, q, pkt, datalen + 2);
593 #endif
594
595         q->id = 0;                      /* this query is used */
596
597         if (datalen > 0 && datalen == users[userid].outpacket.len) {
598                 /* Whole packet was sent in one chunk, dont wait for ack */
599                 users[userid].outpacket.len = 0;
600                 users[userid].outpacket.offset = 0;
601                 users[userid].outpacket.sentlen = 0;
602                 users[userid].outfragresent = 0;
603
604 #ifdef OUTPACKETQ_LEN
605                 /* Maybe more in queue, prepare for next time */
606                 if (get_from_outpacketq(userid) == 1) {
607                         if (debug >= 3)
608                                 fprintf(stderr, "    Chunk & fromqueue: callagain\n");
609                         return 1;       /* call us again */
610                 }
611 #endif
612         }
613
614         return 0;       /* don't call us again */
615 }
616
617 static int
618 tunnel_tun(int tun_fd, int dns_fd)
619 {
620         unsigned long outlen;
621         struct ip *header;
622         char out[64*1024];
623         char in[64*1024];
624         int userid;
625         int read;
626
627         if ((read = read_tun(tun_fd, in, sizeof(in))) <= 0)
628                 return 0;
629
630         /* find target ip in packet, in is padded with 4 bytes TUN header */
631         header = (struct ip*) (in + 4);
632         userid = find_user_by_ip(header->ip_dst.s_addr);
633         if (userid < 0)
634                 return 0;
635
636         outlen = sizeof(out);
637         compress2((uint8_t*)out, &outlen, (uint8_t*)in, read, 9);
638
639         if (users[userid].conn == CONN_DNS_NULL) {
640 #ifdef OUTPACKETQ_LEN
641                 /* If a packet is being sent, try storing the new one in the queue.
642                    If the queue is full, drop the packet. TCP will hopefully notice
643                    and reduce the packet rate. */
644                 if (users[userid].outpacket.len > 0) {
645                         save_to_outpacketq(userid, out, outlen);
646                         return 0;
647                 }
648 #endif
649
650                 start_new_outpacket(userid, out, outlen);
651
652                 /* Start sending immediately if query is waiting */
653                 if (users[userid].q_sendrealsoon.id != 0)
654                         send_chunk_or_dataless(dns_fd, userid, &users[userid].q_sendrealsoon);
655                 else if (users[userid].q.id != 0)
656                         send_chunk_or_dataless(dns_fd, userid, &users[userid].q);
657
658                 return outlen;
659         } else { /* CONN_RAW_UDP */
660                 send_raw(dns_fd, out, outlen, userid, RAW_HDR_CMD_DATA, &users[userid].q);
661                 return outlen;
662         }
663 }
664
665 typedef enum {
666         VERSION_ACK,
667         VERSION_NACK,
668         VERSION_FULL
669 } version_ack_t;
670
671 static void
672 send_version_response(int fd, version_ack_t ack, uint32_t payload, int userid, struct query *q)
673 {
674         char out[9];
675
676         switch (ack) {
677         case VERSION_ACK:
678                 strncpy(out, "VACK", sizeof(out));
679                 break;
680         case VERSION_NACK:
681                 strncpy(out, "VNAK", sizeof(out));
682                 break;
683         case VERSION_FULL:
684                 strncpy(out, "VFUL", sizeof(out));
685                 break;
686         }
687
688         out[4] = ((payload >> 24) & 0xff);
689         out[5] = ((payload >> 16) & 0xff);
690         out[6] = ((payload >> 8) & 0xff);
691         out[7] = ((payload) & 0xff);
692         out[8] = userid & 0xff;
693
694         write_dns(fd, q, out, sizeof(out), users[userid].downenc);
695 }
696
697 static void
698 process_downstream_ack(int userid, int down_seq, int down_frag)
699 /* Process acks from downstream fragments.
700    After this, .offset and .fragment are updated (if ack correct),
701    or .len is set to zero when all is done.
702 */
703 {
704         if (users[userid].outpacket.len <= 0)
705                 /* No packet to apply acks to */
706                 return;
707
708         if (users[userid].outpacket.seqno != down_seq ||
709             users[userid].outpacket.fragment != down_frag)
710                 /* Not the ack we're waiting for; probably duplicate of old
711                    ack, happens a lot with ping packets */
712                 return;
713
714         /* Received proper ack */
715         users[userid].outpacket.offset += users[userid].outpacket.sentlen;
716         users[userid].outpacket.sentlen = 0;
717         users[userid].outpacket.fragment++;
718         users[userid].outfragresent = 0;
719
720         /* Is packet done? */
721         if (users[userid].outpacket.offset >= users[userid].outpacket.len) {
722                 users[userid].outpacket.len = 0;
723                 users[userid].outpacket.offset = 0;
724                 users[userid].outpacket.fragment--;     /* unneeded ++ above */
725                 /* ^keep last seqno/frag, are always returned on pings */
726                 /* users[userid].outfragresent = 0; already above */
727
728 #ifdef OUTPACKETQ_LEN
729                 /* Possibly get new packet from queue */
730                 get_from_outpacketq(userid);
731 #endif
732         }
733 }
734
735 static void
736 handle_null_request(int tun_fd, int dns_fd, struct query *q, int domain_len)
737 {
738         struct in_addr tempip;
739         char in[512];
740         char logindata[16];
741         char out[64*1024];
742         char unpacked[64*1024];
743         char *tmp[2];
744         int userid;
745         int read;
746
747         userid = -1;
748
749         /* Everything here needs at least two chars in the name */
750         if (domain_len < 2)
751                 return;
752
753         memcpy(in, q->name, MIN(domain_len, sizeof(in)));
754
755         if(in[0] == 'V' || in[0] == 'v') {
756                 int version = 0;
757
758                 read = unpack_data(unpacked, sizeof(unpacked), &(in[1]), domain_len - 1, b32);
759                 /* Version greeting, compare and send ack/nak */
760                 if (read > 4) {
761                         /* Received V + 32bits version */
762                         version = (((unpacked[0] & 0xff) << 24) |
763                                            ((unpacked[1] & 0xff) << 16) |
764                                            ((unpacked[2] & 0xff) << 8) |
765                                            ((unpacked[3] & 0xff)));
766                 }
767
768                 if (version == VERSION) {
769                         userid = find_available_user();
770                         if (userid >= 0) {
771                                 int i;
772                                 struct sockaddr_in *tempin;
773
774                                 users[userid].seed = rand();
775                                 /* Store remote IP number */
776                                 tempin = (struct sockaddr_in *) &(q->from);
777                                 memcpy(&(users[userid].host), &(tempin->sin_addr), sizeof(struct in_addr));
778
779                                 memcpy(&(users[userid].q), q, sizeof(struct query));
780                                 users[userid].encoder = get_base32_encoder();
781                                 users[userid].downenc = 'T';
782                                 send_version_response(dns_fd, VERSION_ACK, users[userid].seed, userid, q);
783                                 syslog(LOG_INFO, "accepted version for user #%d from %s",
784                                         userid, format_addr(&q->from, q->fromlen));
785                                 users[userid].q.id = 0;
786                                 users[userid].q.id2 = 0;
787                                 users[userid].q_sendrealsoon.id = 0;
788                                 users[userid].q_sendrealsoon.id2 = 0;
789                                 users[userid].q_sendrealsoon_new = 0;
790                                 users[userid].outpacket.len = 0;
791                                 users[userid].outpacket.offset = 0;
792                                 users[userid].outpacket.sentlen = 0;
793                                 users[userid].outpacket.seqno = 0;
794                                 users[userid].outpacket.fragment = 0;
795                                 users[userid].outfragresent = 0;
796                                 users[userid].inpacket.len = 0;
797                                 users[userid].inpacket.offset = 0;
798                                 users[userid].inpacket.seqno = 0;
799                                 users[userid].inpacket.fragment = 0;
800                                 users[userid].fragsize = 100; /* very safe */
801                                 users[userid].conn = CONN_DNS_NULL;
802                                 users[userid].lazy = 0;
803 #ifdef OUTPACKETQ_LEN
804                                 users[userid].outpacketq_nexttouse = 0;
805                                 users[userid].outpacketq_filled = 0;
806 #endif
807 #ifdef DNSCACHE_LEN
808                                 {
809                                         for (i = 0; i < DNSCACHE_LEN; i++) {
810                                                 users[userid].dnscache_q[i].id = 0;
811                                                 users[userid].dnscache_answerlen[i] = 0;
812                                         }
813                                 }
814                                 users[userid].dnscache_lastfilled = 0;
815 #endif
816                                 for (i = 0; i < QMEMPING_LEN; i++)
817                                         users[userid].qmemping_type[i] = T_UNSET;
818                                 users[userid].qmemping_lastfilled = 0;
819                                 for (i = 0; i < QMEMDATA_LEN; i++)
820                                         users[userid].qmemdata_type[i] = T_UNSET;
821                                 users[userid].qmemdata_lastfilled = 0;
822                         } else {
823                                 /* No space for another user */
824                                 send_version_response(dns_fd, VERSION_FULL, created_users, 0, q);
825                                 syslog(LOG_INFO, "dropped user from %s, server full",
826                                         format_addr(&q->from, q->fromlen));
827                         }
828                 } else {
829                         send_version_response(dns_fd, VERSION_NACK, VERSION, 0, q);
830                         syslog(LOG_INFO, "dropped user from %s, sent bad version %08X",
831                                 format_addr(&q->from, q->fromlen), version);
832                 }
833                 return;
834         } else if(in[0] == 'L' || in[0] == 'l') {
835                 read = unpack_data(unpacked, sizeof(unpacked), &(in[1]), domain_len - 1, b32);
836                 if (read < 17) {
837                         write_dns(dns_fd, q, "BADLEN", 6, 'T');
838                         return;
839                 }
840
841                 /* Login phase, handle auth */
842                 userid = unpacked[0];
843
844                 if (check_user_and_ip(userid, q) != 0) {
845                         write_dns(dns_fd, q, "BADIP", 5, 'T');
846                         syslog(LOG_WARNING, "dropped login request from user #%d from unexpected source %s",
847                                 userid, format_addr(&q->from, q->fromlen));
848                         return;
849                 } else {
850                         users[userid].last_pkt = time(NULL);
851                         login_calculate(logindata, 16, password, users[userid].seed);
852
853                         if (read >= 18 && (memcmp(logindata, unpacked+1, 16) == 0)) {
854                                 /* Store login ok */
855                                 users[userid].authenticated = 1;
856
857                                 /* Send ip/mtu/netmask info */
858                                 tempip.s_addr = my_ip;
859                                 tmp[0] = strdup(inet_ntoa(tempip));
860                                 tempip.s_addr = users[userid].tun_ip;
861                                 tmp[1] = strdup(inet_ntoa(tempip));
862
863                                 read = snprintf(out, sizeof(out), "%s-%s-%d-%d",
864                                                 tmp[0], tmp[1], my_mtu, netmask);
865
866                                 write_dns(dns_fd, q, out, read, users[userid].downenc);
867                                 q->id = 0;
868                                 syslog(LOG_NOTICE, "accepted password from user #%d, given IP %s", userid, tmp[1]);
869
870                                 free(tmp[1]);
871                                 free(tmp[0]);
872                         } else {
873                                 write_dns(dns_fd, q, "LNAK", 4, 'T');
874                                 syslog(LOG_WARNING, "rejected login request from user #%d from %s, bad password",
875                                         userid, format_addr(&q->from, q->fromlen));
876                         }
877                 }
878                 return;
879         } else if(in[0] == 'I' || in[0] == 'i') {
880                 /* Request for IP number */
881                 in_addr_t replyaddr;
882                 unsigned addr;
883                 char reply[5];
884
885                 userid = b32_8to5(in[1]);
886                 if (check_authenticated_user_and_ip(userid, q) != 0) {
887                         write_dns(dns_fd, q, "BADIP", 5, 'T');
888                         return; /* illegal id */
889                 }
890
891                 if (ns_ip != INADDR_ANY) {
892                         /* If set, use assigned external ip (-n option) */
893                         replyaddr = ns_ip;
894                 } else {
895                         /* otherwise return destination ip from packet */
896                         memcpy(&replyaddr, &q->destination.s_addr, sizeof(in_addr_t));
897                 }
898
899                 addr = htonl(replyaddr);
900                 reply[0] = 'I';
901                 reply[1] = (addr >> 24) & 0xFF;
902                 reply[2] = (addr >> 16) & 0xFF;
903                 reply[3] = (addr >>  8) & 0xFF;
904                 reply[4] = (addr >>  0) & 0xFF;
905                 write_dns(dns_fd, q, reply, sizeof(reply), 'T');
906         } else if(in[0] == 'Z' || in[0] == 'z') {
907                 /* Check for case conservation and chars not allowed according to RFC */
908
909                 /* Reply with received hostname as data */
910                 /* No userid here, reply with lowest-grade downenc */
911                 write_dns(dns_fd, q, in, domain_len, 'T');
912                 return;
913         } else if(in[0] == 'S' || in[0] == 's') {
914                 int codec;
915                 struct encoder *enc;
916                 if (domain_len < 3) { /* len at least 3, example: "S15" */
917                         write_dns(dns_fd, q, "BADLEN", 6, 'T');
918                         return;
919                 }
920
921                 userid = b32_8to5(in[1]);
922
923                 if (check_authenticated_user_and_ip(userid, q) != 0) {
924                         write_dns(dns_fd, q, "BADIP", 5, 'T');
925                         return; /* illegal id */
926                 }
927
928                 codec = b32_8to5(in[2]);
929
930                 switch (codec) {
931                 case 5: /* 5 bits per byte = base32 */
932                         enc = get_base32_encoder();
933                         user_switch_codec(userid, enc);
934                         write_dns(dns_fd, q, enc->name, strlen(enc->name), users[userid].downenc);
935                         break;
936                 case 6: /* 6 bits per byte = base64 */
937                         enc = get_base64_encoder();
938                         user_switch_codec(userid, enc);
939                         write_dns(dns_fd, q, enc->name, strlen(enc->name), users[userid].downenc);
940                         break;
941                 case 26: /* "2nd" 6 bits per byte = base64u, with underscore */
942                         enc = get_base64u_encoder();
943                         user_switch_codec(userid, enc);
944                         write_dns(dns_fd, q, enc->name, strlen(enc->name), users[userid].downenc);
945                         break;
946                 case 7: /* 7 bits per byte = base128 */
947                         enc = get_base128_encoder();
948                         user_switch_codec(userid, enc);
949                         write_dns(dns_fd, q, enc->name, strlen(enc->name), users[userid].downenc);
950                         break;
951                 default:
952                         write_dns(dns_fd, q, "BADCODEC", 8, users[userid].downenc);
953                         break;
954                 }
955                 return;
956         } else if(in[0] == 'O' || in[0] == 'o') {
957                 if (domain_len < 3) { /* len at least 3, example: "O1T" */
958                         write_dns(dns_fd, q, "BADLEN", 6, 'T');
959                         return;
960                 }
961
962                 userid = b32_8to5(in[1]);
963
964                 if (check_authenticated_user_and_ip(userid, q) != 0) {
965                         write_dns(dns_fd, q, "BADIP", 5, 'T');
966                         return; /* illegal id */
967                 }
968
969                 switch (in[2]) {
970                 case 'T':
971                 case 't':
972                         users[userid].downenc = 'T';
973                         write_dns(dns_fd, q, "Base32", 6, users[userid].downenc);
974                         break;
975                 case 'S':
976                 case 's':
977                         users[userid].downenc = 'S';
978                         write_dns(dns_fd, q, "Base64", 6, users[userid].downenc);
979                         break;
980                 case 'U':
981                 case 'u':
982                         users[userid].downenc = 'U';
983                         write_dns(dns_fd, q, "Base64u", 7, users[userid].downenc);
984                         break;
985                 case 'V':
986                 case 'v':
987                         users[userid].downenc = 'V';
988                         write_dns(dns_fd, q, "Base128", 7, users[userid].downenc);
989                         break;
990                 case 'R':
991                 case 'r':
992                         users[userid].downenc = 'R';
993                         write_dns(dns_fd, q, "Raw", 3, users[userid].downenc);
994                         break;
995                 case 'L':
996                 case 'l':
997                         users[userid].lazy = 1;
998                         write_dns(dns_fd, q, "Lazy", 4, users[userid].downenc);
999                         break;
1000                 case 'I':
1001                 case 'i':
1002                         users[userid].lazy = 0;
1003                         write_dns(dns_fd, q, "Immediate", 9, users[userid].downenc);
1004                         break;
1005                 default:
1006                         write_dns(dns_fd, q, "BADCODEC", 8, users[userid].downenc);
1007                         break;
1008                 }
1009                 return;
1010         } else if(in[0] == 'Y' || in[0] == 'y') {
1011                 int i;
1012                 char *datap;
1013                 int datalen;
1014
1015                 if (domain_len < 6) { /* len at least 6, example: "YTxCMC" */
1016                         write_dns(dns_fd, q, "BADLEN", 6, 'T');
1017                         return;
1018                 }
1019
1020                 i = b32_8to5(in[2]);    /* check variant */
1021
1022                 switch (i) {
1023                 case 1:
1024                         datap = DOWNCODECCHECK1;
1025                         datalen = DOWNCODECCHECK1_LEN;
1026                         break;
1027                 default:
1028                         write_dns(dns_fd, q, "BADLEN", 6, 'T');
1029                         return;
1030                 }
1031
1032                 switch (in[1]) {
1033                 case 'T':
1034                 case 't':
1035                         if (q->type == T_TXT ||
1036                             q->type == T_SRV || q->type == T_MX ||
1037                             q->type == T_CNAME || q->type == T_A) {
1038                                 write_dns(dns_fd, q, datap, datalen, 'T');
1039                                 return;
1040                         }
1041                         break;
1042                 case 'S':
1043                 case 's':
1044                         if (q->type == T_TXT ||
1045                             q->type == T_SRV || q->type == T_MX ||
1046                             q->type == T_CNAME || q->type == T_A) {
1047                                 write_dns(dns_fd, q, datap, datalen, 'S');
1048                                 return;
1049                         }
1050                         break;
1051                 case 'U':
1052                 case 'u':
1053                         if (q->type == T_TXT ||
1054                             q->type == T_SRV || q->type == T_MX ||
1055                             q->type == T_CNAME || q->type == T_A) {
1056                                 write_dns(dns_fd, q, datap, datalen, 'U');
1057                                 return;
1058                         }
1059                         break;
1060                 case 'V':
1061                 case 'v':
1062                         if (q->type == T_TXT ||
1063                             q->type == T_SRV || q->type == T_MX ||
1064                             q->type == T_CNAME || q->type == T_A) {
1065                                 write_dns(dns_fd, q, datap, datalen, 'V');
1066                                 return;
1067                         }
1068                         break;
1069                 case 'R':
1070                 case 'r':
1071                         if (q->type == T_NULL || q->type == T_TXT) {
1072                                 write_dns(dns_fd, q, datap, datalen, 'R');
1073                                 return;
1074                         }
1075                         break;
1076                 }
1077
1078                 /* if still here, then codec not available */
1079                 write_dns(dns_fd, q, "BADCODEC", 8, 'T');
1080                 return;
1081
1082         } else if(in[0] == 'R' || in[0] == 'r') {
1083                 int req_frag_size;
1084
1085                 if (domain_len < 16) {  /* we'd better have some chars for data... */
1086                         write_dns(dns_fd, q, "BADLEN", 6, 'T');
1087                         return;
1088                 }
1089
1090                 /* Downstream fragsize probe packet */
1091                 userid = (b32_8to5(in[1]) >> 1) & 15;
1092                 if (check_authenticated_user_and_ip(userid, q) != 0) {
1093                         write_dns(dns_fd, q, "BADIP", 5, 'T');
1094                         return; /* illegal id */
1095                 }
1096
1097                 req_frag_size = ((b32_8to5(in[1]) & 1) << 10) | ((b32_8to5(in[2]) & 31) << 5) | (b32_8to5(in[3]) & 31);
1098                 if (req_frag_size < 2 || req_frag_size > 2047) {
1099                         write_dns(dns_fd, q, "BADFRAG", 7, users[userid].downenc);
1100                 } else {
1101                         char buf[2048];
1102                         int i;
1103                         unsigned int v = ((unsigned int) rand()) & 0xff ;
1104
1105                         memset(buf, 0, sizeof(buf));
1106                         buf[0] = (req_frag_size >> 8) & 0xff;
1107                         buf[1] = req_frag_size & 0xff;
1108                         /* make checkable pseudo-random sequence */
1109                         buf[2] = 107;
1110                         for (i = 3; i < 2048; i++, v = (v + 107) & 0xff)
1111                                 buf[i] = v;
1112                         write_dns(dns_fd, q, buf, req_frag_size, users[userid].downenc);
1113                 }
1114                 return;
1115         } else if(in[0] == 'N' || in[0] == 'n') {
1116                 int max_frag_size;
1117
1118                 read = unpack_data(unpacked, sizeof(unpacked), &(in[1]), domain_len - 1, b32);
1119
1120                 if (read < 3) {
1121                         write_dns(dns_fd, q, "BADLEN", 6, 'T');
1122                         return;
1123                 }
1124
1125                 /* Downstream fragsize packet */
1126                 userid = unpacked[0];
1127                 if (check_authenticated_user_and_ip(userid, q) != 0) {
1128                         write_dns(dns_fd, q, "BADIP", 5, 'T');
1129                         return; /* illegal id */
1130                 }
1131
1132                 max_frag_size = ((unpacked[1] & 0xff) << 8) | (unpacked[2] & 0xff);
1133                 if (max_frag_size < 2) {
1134                         write_dns(dns_fd, q, "BADFRAG", 7, users[userid].downenc);
1135                 } else {
1136                         users[userid].fragsize = max_frag_size;
1137                         write_dns(dns_fd, q, &unpacked[1], 2, users[userid].downenc);
1138                 }
1139                 return;
1140         } else if(in[0] == 'P' || in[0] == 'p') {
1141                 int dn_seq;
1142                 int dn_frag;
1143                 int didsend = 0;
1144
1145                 /* We can't handle id=0, that's "no packet" to us. So drop
1146                    request completely. Note that DNS servers rewrite the id.
1147                    We'll drop 1 in 64k times. If DNS server retransmits with
1148                    different id, then all okay.
1149                    Else client won't retransmit, and we'll just keep the
1150                    previous ping in cache, no problem either. */
1151                 if (q->id == 0)
1152                         return;
1153
1154                 read = unpack_data(unpacked, sizeof(unpacked), &(in[1]), domain_len - 1, b32);
1155                 if (read < 4)
1156                         return;
1157
1158                 /* Ping packet, store userid */
1159                 userid = unpacked[0];
1160                 if (check_authenticated_user_and_ip(userid, q) != 0) {
1161                         write_dns(dns_fd, q, "BADIP", 5, 'T');
1162                         return; /* illegal id */
1163                 }
1164
1165 #ifdef DNSCACHE_LEN
1166                 /* Check if cached */
1167                 if (answer_from_dnscache(dns_fd, userid, q))
1168                         return;
1169 #endif
1170
1171                 /* Check if duplicate (and not in full dnscache any more) */
1172                 if (answer_from_qmem(dns_fd, q, users[userid].qmemping_cmc,
1173                                      users[userid].qmemping_type, QMEMPING_LEN,
1174                                      (void *) unpacked))
1175                         return;
1176
1177                 /* Check if duplicate of waiting queries; impatient DNS relays
1178                    like to re-try early and often (with _different_ .id!)  */
1179                 if (users[userid].q.id != 0 &&
1180                     q->type == users[userid].q.type &&
1181                     !strcmp(q->name, users[userid].q.name) &&
1182                     users[userid].lazy) {
1183                         /* We have this ping already, and it's waiting to be
1184                            answered. Always keep the last duplicate, since the
1185                            relay may have forgotten its first version already.
1186                            Our answer will go to both.
1187                            (If we already sent an answer, qmem/cache will
1188                            have triggered.) */
1189                         if (debug >= 2) {
1190                                 fprintf(stderr, "PING pkt from user %d = dupe from impatient DNS server, remembering\n",
1191                                         userid);
1192                         }
1193                         users[userid].q.id2 = q->id;
1194                         users[userid].q.fromlen2 = q->fromlen;
1195                         memcpy(&(users[userid].q.from2), &(q->from), q->fromlen);
1196                         return;
1197                 }
1198
1199                 if (users[userid].q_sendrealsoon.id != 0 &&
1200                     q->type == users[userid].q_sendrealsoon.type &&
1201                     !strcmp(q->name, users[userid].q_sendrealsoon.name)) {
1202                         /* Outer select loop will send answer immediately,
1203                            to both queries. */
1204                         if (debug >= 2) {
1205                                 fprintf(stderr, "PING pkt from user %d = dupe from impatient DNS server, remembering\n",
1206                                         userid);
1207                         }
1208                         users[userid].q_sendrealsoon.id2 = q->id;
1209                         users[userid].q_sendrealsoon.fromlen2 = q->fromlen;
1210                         memcpy(&(users[userid].q_sendrealsoon.from2),
1211                                &(q->from), q->fromlen);
1212                         return;
1213                 }
1214
1215                 dn_seq = unpacked[1] >> 4;
1216                 dn_frag = unpacked[1] & 15;
1217
1218                 if (debug >= 1) {
1219                         fprintf(stderr, "PING pkt from user %d, ack for downstream %d/%d\n",
1220                                 userid, dn_seq, dn_frag);
1221                 }
1222
1223                 process_downstream_ack(userid, dn_seq, dn_frag);
1224
1225                 if (debug >= 3) {
1226                         fprintf(stderr, "PINGret (if any) will ack upstream %d/%d\n",
1227                                 users[userid].inpacket.seqno, users[userid].inpacket.fragment);
1228                 }
1229
1230                 /* If there is a query that must be returned real soon, do it.
1231                    May contain new downstream data if the ping had a new ack.
1232                    Otherwise, may also be re-sending old data. */
1233                 if (users[userid].q_sendrealsoon.id != 0) {
1234                         send_chunk_or_dataless(dns_fd, userid, &users[userid].q_sendrealsoon);
1235                 }
1236
1237                 /* We need to store a new query, so if there still is an
1238                    earlier query waiting, always send a reply to finish it.
1239                    May contain new downstream data if the ping had a new ack.
1240                    Otherwise, may also be re-sending old data.
1241                    (This is duplicate data if we had q_sendrealsoon above.) */
1242                 if (users[userid].q.id != 0) {
1243                         didsend = 1;
1244                         if (send_chunk_or_dataless(dns_fd, userid, &users[userid].q) == 1)
1245                                 /* new packet from queue, send immediately */
1246                                 didsend = 0;
1247                 }
1248
1249                 /* Save new query and time info */
1250                 memcpy(&(users[userid].q), q, sizeof(struct query));
1251                 users[userid].last_pkt = time(NULL);
1252
1253                 /* If anything waiting and we didn't already send above, send
1254                    it now. And always send immediately if we're not lazy
1255                    (then above won't have sent at all). */
1256                 if ((!didsend && users[userid].outpacket.len > 0) ||
1257                     !users[userid].lazy)
1258                         send_chunk_or_dataless(dns_fd, userid, &users[userid].q);
1259
1260         } else if((in[0] >= '0' && in[0] <= '9')
1261                         || (in[0] >= 'a' && in[0] <= 'f')
1262                         || (in[0] >= 'A' && in[0] <= 'F')) {
1263                 int up_seq, up_frag, dn_seq, dn_frag, lastfrag;
1264                 int upstream_ok = 1;
1265                 int didsend = 0;
1266                 int code = -1;
1267
1268                 /* Need 5char header + >=1 char data */
1269                 if (domain_len < 6)
1270                         return;
1271
1272                 /* We can't handle id=0, that's "no packet" to us. So drop
1273                    request completely. Note that DNS servers rewrite the id.
1274                    We'll drop 1 in 64k times. If DNS server retransmits with
1275                    different id, then all okay.
1276                    Else client doesn't get our ack, and will retransmit in
1277                    1 second. */
1278                 if (q->id == 0)
1279                         return;
1280
1281                 if ((in[0] >= '0' && in[0] <= '9'))
1282                         code = in[0] - '0';
1283                 if ((in[0] >= 'a' && in[0] <= 'f'))
1284                         code = in[0] - 'a' + 10;
1285                 if ((in[0] >= 'A' && in[0] <= 'F'))
1286                         code = in[0] - 'A' + 10;
1287
1288                 userid = code;
1289                 /* Check user and sending ip number */
1290                 if (check_authenticated_user_and_ip(userid, q) != 0) {
1291                         write_dns(dns_fd, q, "BADIP", 5, 'T');
1292                         return; /* illegal id */
1293                 }
1294
1295 #ifdef DNSCACHE_LEN
1296                 /* Check if cached */
1297                 if (answer_from_dnscache(dns_fd, userid, q))
1298                         return;
1299 #endif
1300
1301                 /* Check if duplicate (and not in full dnscache any more) */
1302                 if (answer_from_qmem_data(dns_fd, userid, q))
1303                         return;
1304
1305                 /* Check if duplicate of waiting queries; impatient DNS relays
1306                    like to re-try early and often (with _different_ .id!)  */
1307                 if (users[userid].q.id != 0 &&
1308                     q->type == users[userid].q.type &&
1309                     !strcmp(q->name, users[userid].q.name) &&
1310                     users[userid].lazy) {
1311                         /* We have this packet already, and it's waiting to be
1312                            answered. Always keep the last duplicate, since the
1313                            relay may have forgotten its first version already.
1314                            Our answer will go to both.
1315                            (If we already sent an answer, qmem/cache will
1316                            have triggered.) */
1317                         if (debug >= 2) {
1318                                 fprintf(stderr, "IN   pkt from user %d = dupe from impatient DNS server, remembering\n",
1319                                         userid);
1320                         }
1321                         users[userid].q.id2 = q->id;
1322                         users[userid].q.fromlen2 = q->fromlen;
1323                         memcpy(&(users[userid].q.from2), &(q->from), q->fromlen);
1324                         return;
1325                 }
1326
1327                 if (users[userid].q_sendrealsoon.id != 0 &&
1328                     q->type == users[userid].q_sendrealsoon.type &&
1329                     !strcmp(q->name, users[userid].q_sendrealsoon.name)) {
1330                         /* Outer select loop will send answer immediately,
1331                            to both queries. */
1332                         if (debug >= 2) {
1333                                 fprintf(stderr, "IN   pkt from user %d = dupe from impatient DNS server, remembering\n",
1334                                         userid);
1335                         }
1336                         users[userid].q_sendrealsoon.id2 = q->id;
1337                         users[userid].q_sendrealsoon.fromlen2 = q->fromlen;
1338                         memcpy(&(users[userid].q_sendrealsoon.from2),
1339                                &(q->from), q->fromlen);
1340                         return;
1341                 }
1342
1343
1344                 /* Decode data header */
1345                 up_seq = (b32_8to5(in[1]) >> 2) & 7;
1346                 up_frag = ((b32_8to5(in[1]) & 3) << 2) | ((b32_8to5(in[2]) >> 3) & 3);
1347                 dn_seq = (b32_8to5(in[2]) & 7);
1348                 dn_frag = b32_8to5(in[3]) >> 1;
1349                 lastfrag = b32_8to5(in[3]) & 1;
1350
1351                 process_downstream_ack(userid, dn_seq, dn_frag);
1352
1353                 if (up_seq == users[userid].inpacket.seqno &&
1354                         up_frag <= users[userid].inpacket.fragment) {
1355                         /* Got repeated old packet _with data_, probably
1356                            because client didn't receive our ack. So re-send
1357                            our ack(+data) immediately to keep things flowing
1358                            fast.
1359                            If it's a _really_ old frag, it's a nameserver
1360                            that tries again, and sending our current (non-
1361                            matching) fragno won't be a problem. */
1362                         if (debug >= 1) {
1363                                 fprintf(stderr, "IN   pkt seq# %d, frag %d, dropped duplicate frag\n",
1364                                         up_seq, up_frag);
1365                         }
1366                         upstream_ok = 0;
1367                 }
1368                 else if (up_seq != users[userid].inpacket.seqno &&
1369                          recent_seqno(users[userid].inpacket.seqno, up_seq)) {
1370                         /* Duplicate of recent upstream data packet; probably
1371                            need to answer this to keep DNS server happy */
1372                         if (debug >= 1) {
1373                                 fprintf(stderr, "IN   pkt seq# %d, frag %d, dropped duplicate recent seqno\n",
1374                                         up_seq, up_frag);
1375                         }
1376                         upstream_ok = 0;
1377                 }
1378                 else if (up_seq != users[userid].inpacket.seqno) {
1379                         /* Really new packet has arrived, no recent duplicate */
1380                         /* Forget any old packet, even if incomplete */
1381                         users[userid].inpacket.seqno = up_seq;
1382                         users[userid].inpacket.fragment = up_frag;
1383                         users[userid].inpacket.len = 0;
1384                         users[userid].inpacket.offset = 0;
1385                 } else {
1386                         /* seq is same, frag is higher; don't care about
1387                            missing fragments, TCP checksum will fail */
1388                         users[userid].inpacket.fragment = up_frag;
1389                 }
1390
1391                 if (debug >= 3) {
1392                         fprintf(stderr, "INpack with upstream %d/%d, we are going to ack upstream %d/%d\n",
1393                                 up_seq, up_frag,
1394                                 users[userid].inpacket.seqno, users[userid].inpacket.fragment);
1395                 }
1396
1397                 if (upstream_ok) {
1398                         /* decode with this user's encoding */
1399                         read = unpack_data(unpacked, sizeof(unpacked), &(in[5]), domain_len - 5,
1400                                            users[userid].encoder);
1401
1402                         /* copy to packet buffer, update length */
1403                         read = MIN(read, sizeof(users[userid].inpacket.data) - users[userid].inpacket.offset);
1404                         memcpy(users[userid].inpacket.data + users[userid].inpacket.offset, unpacked, read);
1405                         users[userid].inpacket.len += read;
1406                         users[userid].inpacket.offset += read;
1407
1408                         if (debug >= 1) {
1409                                 fprintf(stderr, "IN   pkt seq# %d, frag %d (last=%d), fragsize %d, total %d, from user %d\n",
1410                                         up_seq, up_frag, lastfrag, read, users[userid].inpacket.len, userid);
1411                         }
1412                 }
1413
1414                 if (upstream_ok && lastfrag) { /* packet is complete */
1415                         handle_full_packet(tun_fd, dns_fd, userid);
1416                 }
1417
1418                 /* If there is a query that must be returned real soon, do it.
1419                    Includes an ack of the just received upstream fragment,
1420                    may contain new data. */
1421                 if (users[userid].q_sendrealsoon.id != 0) {
1422                         didsend = 1;
1423                         if (send_chunk_or_dataless(dns_fd, userid, &users[userid].q_sendrealsoon) == 1)
1424                                 /* new packet from queue, send immediately */
1425                                 didsend = 0;
1426                 }
1427
1428                 /* If we already have an earlier query waiting, we need to
1429                    get rid of it to store the new query.
1430                    - If we have new data waiting and not yet sent above,
1431                      send immediately.
1432                    - If this wasn't the last upstream fragment, then we expect
1433                      more, so ack immediately if we didn't already.
1434                    - If we are in non-lazy mode, there should be no query
1435                      waiting, but if there is, send immediately.
1436                    - In all other cases (mostly the last-fragment cases),
1437                      we can afford to wait just a tiny little while for the
1438                      TCP ack to arrive from our tun. Note that this works best
1439                      when there is only one client.
1440                  */
1441                 if (users[userid].q.id != 0) {
1442                         if ((users[userid].outpacket.len > 0 && !didsend) ||
1443                             (upstream_ok && !lastfrag && !didsend) ||
1444                             (!upstream_ok && !didsend) ||
1445                             !users[userid].lazy) {
1446                                 didsend = 1;
1447                                 if (send_chunk_or_dataless(dns_fd, userid, &users[userid].q) == 1)
1448                                         /* new packet from queue, send immediately */
1449                                         didsend = 0;
1450                         } else {
1451                                 memcpy(&(users[userid].q_sendrealsoon),
1452                                        &(users[userid].q),
1453                                        sizeof(struct query));
1454                                 users[userid].q_sendrealsoon_new = 1;
1455                                 users[userid].q.id = 0;  /* used */
1456                                 didsend = 1;
1457                         }
1458                 }
1459
1460                 /* Save new query and time info */
1461                 memcpy(&(users[userid].q), q, sizeof(struct query));
1462                 users[userid].last_pkt = time(NULL);
1463
1464                 /* If we still need to ack this upstream frag, do it to keep
1465                    upstream flowing.
1466                    - If we have new data waiting and not yet sent above,
1467                      send immediately.
1468                    - If this wasn't the last upstream fragment, then we expect
1469                      more, so ack immediately if we didn't already or are
1470                      in non-lazy mode.
1471                    - If this was the last fragment, and we didn't ack already
1472                      or are in non-lazy mode, send the ack after just a tiny
1473                      little while so that the TCP ack may have arrived from
1474                      our tun device.
1475                    - In all other cases, don't send anything now.
1476                 */
1477                 if (users[userid].outpacket.len > 0 && !didsend)
1478                         send_chunk_or_dataless(dns_fd, userid, &users[userid].q);
1479                 else if (!didsend || !users[userid].lazy) {
1480                         if (upstream_ok && lastfrag) {
1481                                 memcpy(&(users[userid].q_sendrealsoon),
1482                                        &(users[userid].q),
1483                                        sizeof(struct query));
1484                                 users[userid].q_sendrealsoon_new = 1;
1485                                 users[userid].q.id = 0;  /* used */
1486                         } else {
1487                                 send_chunk_or_dataless(dns_fd, userid, &users[userid].q);
1488                         }
1489                 }
1490         }
1491 }
1492
1493 static void
1494 handle_ns_request(int dns_fd, struct query *q)
1495 /* Mostly identical to handle_a_request() below */
1496 {
1497         char buf[64*1024];
1498         int len;
1499
1500         if (ns_ip != INADDR_ANY) {
1501                 /* If ns_ip set, overwrite destination addr with it.
1502                  * Destination addr will be sent as additional record (A, IN) */
1503                 memcpy(&q->destination.s_addr, &ns_ip, sizeof(in_addr_t));
1504         }
1505
1506         len = dns_encode_ns_response(buf, sizeof(buf), q, topdomain);
1507         if (len < 1) {
1508                 warnx("dns_encode_ns_response doesn't fit");
1509                 return;
1510         }
1511
1512         if (debug >= 2) {
1513                 fprintf(stderr, "TX: client %s, type %d, name %s, %d bytes NS reply\n",
1514                         format_addr(&q->from, q->fromlen), q->type, q->name, len);
1515         }
1516         if (sendto(dns_fd, buf, len, 0, (struct sockaddr*)&q->from, q->fromlen) <= 0) {
1517                 warn("ns reply send error");
1518         }
1519 }
1520
1521 static void
1522 handle_a_request(int dns_fd, struct query *q, int fakeip)
1523 /* Mostly identical to handle_ns_request() above */
1524 {
1525         char buf[64*1024];
1526         int len;
1527
1528         if (fakeip) {
1529                 in_addr_t ip = inet_addr("127.0.0.1");
1530                 memcpy(&q->destination.s_addr, &ip, sizeof(in_addr_t));
1531
1532         } else if (ns_ip != INADDR_ANY) {
1533                 /* If ns_ip set, overwrite destination addr with it.
1534                  * Destination addr will be sent as additional record (A, IN) */
1535                 memcpy(&q->destination.s_addr, &ns_ip, sizeof(in_addr_t));
1536         }
1537
1538         len = dns_encode_a_response(buf, sizeof(buf), q);
1539         if (len < 1) {
1540                 warnx("dns_encode_a_response doesn't fit");
1541                 return;
1542         }
1543
1544         if (debug >= 2) {
1545                 fprintf(stderr, "TX: client %s, type %d, name %s, %d bytes A reply\n",
1546                         format_addr(&q->from, q->fromlen), q->type, q->name, len);
1547         }
1548         if (sendto(dns_fd, buf, len, 0, (struct sockaddr*)&q->from, q->fromlen) <= 0) {
1549                 warn("a reply send error");
1550         }
1551 }
1552
1553 static void
1554 forward_query(int bind_fd, struct query *q)
1555 {
1556         char buf[64*1024];
1557         int len;
1558         struct fw_query fwq;
1559         struct sockaddr_in *myaddr;
1560         in_addr_t newaddr;
1561
1562         len = dns_encode(buf, sizeof(buf), q, QR_QUERY, q->name, strlen(q->name));
1563         if (len < 1) {
1564                 warnx("dns_encode doesn't fit");
1565                 return;
1566         }
1567
1568         /* Store sockaddr for q->id */
1569         memcpy(&(fwq.addr), &(q->from), q->fromlen);
1570         fwq.addrlen = q->fromlen;
1571         fwq.id = q->id;
1572         fw_query_put(&fwq);
1573
1574         newaddr = inet_addr("127.0.0.1");
1575         myaddr = (struct sockaddr_in *) &(q->from);
1576         memcpy(&(myaddr->sin_addr), &newaddr, sizeof(in_addr_t));
1577         myaddr->sin_port = htons(bind_port);
1578
1579         if (debug >= 2) {
1580                 fprintf(stderr, "TX: NS reply \n");
1581         }
1582
1583         if (sendto(bind_fd, buf, len, 0, (struct sockaddr*)&q->from, q->fromlen) <= 0) {
1584                 warn("forward query error");
1585         }
1586 }
1587
1588 static int
1589 tunnel_bind(int bind_fd, int dns_fd)
1590 {
1591         char packet[64*1024];
1592         struct sockaddr_storage from;
1593         socklen_t fromlen;
1594         struct fw_query *query;
1595         unsigned short id;
1596         int r;
1597
1598         fromlen = sizeof(struct sockaddr);
1599         r = recvfrom(bind_fd, packet, sizeof(packet), 0,
1600                 (struct sockaddr*)&from, &fromlen);
1601
1602         if (r <= 0)
1603                 return 0;
1604
1605         id = dns_get_id(packet, r);
1606
1607         if (debug >= 2) {
1608                 fprintf(stderr, "RX: Got response on query %u from DNS\n", (id & 0xFFFF));
1609         }
1610
1611         /* Get sockaddr from id */
1612         fw_query_get(id, &query);
1613         if (!query) {
1614                 if (debug >= 2) {
1615                         fprintf(stderr, "Lost sender of id %u, dropping reply\n", (id & 0xFFFF));
1616                 }
1617                 return 0;
1618         }
1619
1620         if (debug >= 2) {
1621                 fprintf(stderr, "TX: client %s id %u, %d bytes\n",
1622                         format_addr(&query->addr, query->addrlen), (id & 0xffff), r);
1623         }
1624
1625         if (sendto(dns_fd, packet, r, 0, (const struct sockaddr *) &(query->addr),
1626                 query->addrlen) <= 0) {
1627                 warn("forward reply error");
1628         }
1629
1630         return 0;
1631 }
1632
1633 static int
1634 tunnel_dns(int tun_fd, int dns_fd, int bind_fd)
1635 {
1636         struct query q;
1637         int read;
1638         int domain_len;
1639         int inside_topdomain = 0;
1640
1641         if ((read = read_dns(dns_fd, tun_fd, &q)) <= 0)
1642                 return 0;
1643
1644         if (debug >= 2) {
1645                 fprintf(stderr, "RX: client %s, type %d, name %s\n",
1646                         format_addr(&q.from, q.fromlen), q.type, q.name);
1647         }
1648
1649         domain_len = strlen(q.name) - strlen(topdomain);
1650         if (domain_len >= 0 && !strcasecmp(q.name + domain_len, topdomain))
1651                 inside_topdomain = 1;
1652         /* require dot before topdomain */
1653         if (domain_len >= 1 && q.name[domain_len - 1] != '.')
1654                 inside_topdomain = 0;
1655
1656         if (inside_topdomain) {
1657                 /* This is a query we can handle */
1658
1659                 /* Handle A-type query for ns.topdomain, possibly caused
1660                    by our proper response to any NS request */
1661                 if (domain_len == 3 && q.type == T_A &&
1662                     (q.name[0] == 'n' || q.name[0] == 'N') &&
1663                     (q.name[1] == 's' || q.name[1] == 'S') &&
1664                      q.name[2] == '.') {
1665                         handle_a_request(dns_fd, &q, 0);
1666                         return 0;
1667                 }
1668
1669                 /* Handle A-type query for www.topdomain, for anyone that's
1670                    poking around */
1671                 if (domain_len == 4 && q.type == T_A &&
1672                     (q.name[0] == 'w' || q.name[0] == 'W') &&
1673                     (q.name[1] == 'w' || q.name[1] == 'W') &&
1674                     (q.name[2] == 'w' || q.name[2] == 'W') &&
1675                      q.name[3] == '.') {
1676                         handle_a_request(dns_fd, &q, 1);
1677                         return 0;
1678                 }
1679
1680                 switch (q.type) {
1681                 case T_NULL:
1682                 case T_PRIVATE:
1683                 case T_CNAME:
1684                 case T_A:
1685                 case T_MX:
1686                 case T_SRV:
1687                 case T_TXT:
1688                         /* encoding is "transparent" here */
1689                         handle_null_request(tun_fd, dns_fd, &q, domain_len);
1690                         break;
1691                 case T_NS:
1692                         handle_ns_request(dns_fd, &q);
1693                         break;
1694                 default:
1695                         break;
1696                 }
1697         } else {
1698                 /* Forward query to other port ? */
1699                 if (bind_fd) {
1700                         forward_query(bind_fd, &q);
1701                 }
1702         }
1703         return 0;
1704 }
1705
1706 static int
1707 tunnel(int tun_fd, int dns_fd, int bind_fd, int max_idle_time)
1708 {
1709         struct timeval tv;
1710         fd_set fds;
1711         int i;
1712         int userid;
1713         time_t last_action = time(NULL);
1714
1715         while (running) {
1716                 int maxfd;
1717                 tv.tv_sec = 10;                 /* doesn't really matter */
1718                 tv.tv_usec = 0;
1719
1720                 /* Adjust timeout if there is anything to send realsoon.
1721                    Clients won't be sending new data until we send our ack,
1722                    so don't keep them waiting long. This only triggers at
1723                    final upstream fragments, which is about once per eight
1724                    requests during heavy upstream traffic.
1725                    20msec: ~8 packs every 1/50sec = ~400 DNSreq/sec,
1726                    or ~1200bytes every 1/50sec = ~0.5 Mbit/sec upstream */
1727                 for (userid = 0; userid < created_users; userid++) {
1728                         if (users[userid].active && !users[userid].disabled &&
1729                             users[userid].last_pkt + 60 > time(NULL)) {
1730                                 users[userid].q_sendrealsoon_new = 0;
1731                                 if (users[userid].q_sendrealsoon.id != 0) {
1732                                         tv.tv_sec = 0;
1733                                         tv.tv_usec = 20000;
1734                                 }
1735                         }
1736                 }
1737
1738                 FD_ZERO(&fds);
1739
1740                 FD_SET(dns_fd, &fds);
1741                 maxfd = dns_fd;
1742
1743                 if (bind_fd) {
1744                         /* wait for replies from real DNS */
1745                         FD_SET(bind_fd, &fds);
1746                         maxfd = MAX(bind_fd, maxfd);
1747                 }
1748
1749                 /* Don't read from tun if no users can accept data anyway;
1750                    tun queue/TCP buffers are larger than our outpacket-queues */
1751                 if(!all_users_waiting_to_send()) {
1752                         FD_SET(tun_fd, &fds);
1753                         maxfd = MAX(tun_fd, maxfd);
1754                 }
1755
1756                 i = select(maxfd + 1, &fds, NULL, NULL, &tv);
1757
1758                 if(i < 0) {
1759                         if (running)
1760                                 warn("select");
1761                         return 1;
1762                 }
1763
1764                 if (i==0) {
1765                         if (max_idle_time) {
1766                                 /* only trigger the check if that's worth ( ie, no need to loop over if there
1767                                 is something to send */
1768                                 if (last_action + max_idle_time < time(NULL)) {
1769                                         for (userid = 0; userid < created_users; userid++) {
1770                                                 last_action = ( users[userid].last_pkt > last_action ) ? users[userid].last_pkt : last_action;
1771                                         }
1772                                         if (last_action + max_idle_time < time(NULL)) {
1773                                                 fprintf(stderr, "Idling since too long, shutting down...\n");
1774                                                 running = 0;
1775                                         }
1776                                 }
1777                         }
1778                 } else {
1779                         if (FD_ISSET(tun_fd, &fds)) {
1780                                 tunnel_tun(tun_fd, dns_fd);
1781                         }
1782                         if (FD_ISSET(dns_fd, &fds)) {
1783                                 tunnel_dns(tun_fd, dns_fd, bind_fd);
1784                         }
1785                         if (FD_ISSET(bind_fd, &fds)) {
1786                                 tunnel_bind(bind_fd, dns_fd);
1787                         }
1788                 }
1789
1790                 /* Send realsoon's if tun or dns didn't already */
1791                 for (userid = 0; userid < created_users; userid++)
1792                         if (users[userid].active && !users[userid].disabled &&
1793                             users[userid].last_pkt + 60 > time(NULL) &&
1794                             users[userid].q_sendrealsoon.id != 0 &&
1795                             users[userid].conn == CONN_DNS_NULL &&
1796                             !users[userid].q_sendrealsoon_new)
1797                                 send_chunk_or_dataless(dns_fd, userid, &users[userid].q_sendrealsoon);
1798         }
1799
1800         return 0;
1801 }
1802
1803 static void
1804 handle_full_packet(int tun_fd, int dns_fd, int userid)
1805 {
1806         unsigned long outlen;
1807         char out[64*1024];
1808         int touser;
1809         int ret;
1810
1811         outlen = sizeof(out);
1812         ret = uncompress((uint8_t*)out, &outlen,
1813                    (uint8_t*)users[userid].inpacket.data, users[userid].inpacket.len);
1814
1815         if (ret == Z_OK) {
1816                 struct ip *hdr;
1817
1818                 hdr = (struct ip*) (out + 4);
1819                 touser = find_user_by_ip(hdr->ip_dst.s_addr);
1820
1821                 if (touser == -1) {
1822                         /* send the uncompressed packet to tun device */
1823                         write_tun(tun_fd, out, outlen);
1824                 } else {
1825                         /* send the compressed(!) packet to other client */
1826                         if (users[touser].conn == CONN_DNS_NULL) {
1827                                 if (users[touser].outpacket.len == 0) {
1828                                         start_new_outpacket(touser,
1829                                                 users[userid].inpacket.data,
1830                                                 users[userid].inpacket.len);
1831
1832                                         /* Start sending immediately if query is waiting */
1833                                         if (users[touser].q_sendrealsoon.id != 0)
1834                                                 send_chunk_or_dataless(dns_fd, touser, &users[touser].q_sendrealsoon);
1835                                         else if (users[touser].q.id != 0)
1836                                                 send_chunk_or_dataless(dns_fd, touser, &users[touser].q);
1837 #ifdef OUTPACKETQ_LEN
1838                                 } else {
1839                                         save_to_outpacketq(touser,
1840                                                 users[userid].inpacket.data,
1841                                                 users[userid].inpacket.len);
1842 #endif
1843                                 }
1844                         } else{ /* CONN_RAW_UDP */
1845                                 send_raw(dns_fd, users[userid].inpacket.data,
1846                                          users[userid].inpacket.len, touser,
1847                                          RAW_HDR_CMD_DATA, &users[touser].q);
1848                         }
1849                 }
1850         } else {
1851                 if (debug >= 1)
1852                         fprintf(stderr, "Discarded data, uncompress() result: %d\n", ret);
1853         }
1854
1855         /* This packet is done */
1856         users[userid].inpacket.len = 0;
1857         users[userid].inpacket.offset = 0;
1858 }
1859
1860 static void
1861 handle_raw_login(char *packet, int len, struct query *q, int fd, int userid)
1862 {
1863         char myhash[16];
1864
1865         if (len < 16) return;
1866
1867         /* can't use check_authenticated_user_and_ip() since IP address will be different,
1868            so duplicate here except IP address */
1869         if (userid < 0 || userid >= created_users) return;
1870         if (!users[userid].active || users[userid].disabled) return;
1871         if (!users[userid].authenticated) return;
1872         if (users[userid].last_pkt + 60 < time(NULL)) return;
1873
1874         if (debug >= 1) {
1875                 fprintf(stderr, "IN   login raw, len %d, from user %d\n",
1876                         len, userid);
1877         }
1878
1879         /* User sends hash of seed + 1 */
1880         login_calculate(myhash, 16, password, users[userid].seed + 1);
1881         if (memcmp(packet, myhash, 16) == 0) {
1882                 struct sockaddr_in *tempin;
1883
1884                 /* Update query and time info for user */
1885                 users[userid].last_pkt = time(NULL);
1886                 memcpy(&(users[userid].q), q, sizeof(struct query));
1887
1888                 /* Store remote IP number */
1889                 tempin = (struct sockaddr_in *) &(q->from);
1890                 memcpy(&(users[userid].host), &(tempin->sin_addr), sizeof(struct in_addr));
1891
1892                 /* Correct hash, reply with hash of seed - 1 */
1893                 user_set_conn_type(userid, CONN_RAW_UDP);
1894                 login_calculate(myhash, 16, password, users[userid].seed - 1);
1895                 send_raw(fd, myhash, 16, userid, RAW_HDR_CMD_LOGIN, q);
1896
1897                 users[userid].authenticated_raw = 1;
1898         }
1899 }
1900
1901 static void
1902 handle_raw_data(char *packet, int len, struct query *q, int dns_fd, int tun_fd, int userid)
1903 {
1904         if (check_authenticated_user_and_ip(userid, q) != 0) {
1905                 return;
1906         }
1907         if (!users[userid].authenticated_raw) return;
1908
1909         /* Update query and time info for user */
1910         users[userid].last_pkt = time(NULL);
1911         memcpy(&(users[userid].q), q, sizeof(struct query));
1912
1913         /* copy to packet buffer, update length */
1914         users[userid].inpacket.offset = 0;
1915         memcpy(users[userid].inpacket.data, packet, len);
1916         users[userid].inpacket.len = len;
1917
1918         if (debug >= 1) {
1919                 fprintf(stderr, "IN   pkt raw, total %d, from user %d\n",
1920                         users[userid].inpacket.len, userid);
1921         }
1922
1923         handle_full_packet(tun_fd, dns_fd, userid);
1924 }
1925
1926 static void
1927 handle_raw_ping(struct query *q, int dns_fd, int userid)
1928 {
1929         if (check_authenticated_user_and_ip(userid, q) != 0) {
1930                 return;
1931         }
1932         if (!users[userid].authenticated_raw) return;
1933
1934         /* Update query and time info for user */
1935         users[userid].last_pkt = time(NULL);
1936         memcpy(&(users[userid].q), q, sizeof(struct query));
1937
1938         if (debug >= 1) {
1939                 fprintf(stderr, "IN   ping raw, from user %d\n", userid);
1940         }
1941
1942         /* Send ping reply */
1943         send_raw(dns_fd, NULL, 0, userid, RAW_HDR_CMD_PING, q);
1944 }
1945
1946 static int
1947 raw_decode(char *packet, int len, struct query *q, int dns_fd, int tun_fd)
1948 {
1949         int raw_user;
1950
1951         /* minimum length */
1952         if (len < RAW_HDR_LEN) return 0;
1953         /* should start with header */
1954         if (memcmp(packet, raw_header, RAW_HDR_IDENT_LEN)) return 0;
1955
1956         raw_user = RAW_HDR_GET_USR(packet);
1957         switch (RAW_HDR_GET_CMD(packet)) {
1958         case RAW_HDR_CMD_LOGIN:
1959                 /* Login challenge */
1960                 handle_raw_login(&packet[RAW_HDR_LEN], len - RAW_HDR_LEN, q, dns_fd, raw_user);
1961                 break;
1962         case RAW_HDR_CMD_DATA:
1963                 /* Data packet */
1964                 handle_raw_data(&packet[RAW_HDR_LEN], len - RAW_HDR_LEN, q, dns_fd, tun_fd, raw_user);
1965                 break;
1966         case RAW_HDR_CMD_PING:
1967                 /* Keepalive packet */
1968                 handle_raw_ping(q, dns_fd, raw_user);
1969                 break;
1970         default:
1971                 warnx("Unhandled raw command %02X from user %d", RAW_HDR_GET_CMD(packet), raw_user);
1972                 break;
1973         }
1974         return 1;
1975 }
1976
1977 static int
1978 read_dns(int fd, int tun_fd, struct query *q) /* FIXME: tun_fd is because of raw_decode() below */
1979 {
1980         struct sockaddr_in from;
1981         socklen_t addrlen;
1982         char packet[64*1024];
1983         int r;
1984 #ifndef WINDOWS32
1985         char address[96];
1986         struct msghdr msg;
1987         struct iovec iov;
1988         struct cmsghdr *cmsg;
1989
1990         addrlen = sizeof(struct sockaddr);
1991         iov.iov_base = packet;
1992         iov.iov_len = sizeof(packet);
1993
1994         msg.msg_name = (caddr_t) &from;
1995         msg.msg_namelen = (unsigned) addrlen;
1996         msg.msg_iov = &iov;
1997         msg.msg_iovlen = 1;
1998         msg.msg_control = address;
1999         msg.msg_controllen = sizeof(address);
2000         msg.msg_flags = 0;
2001
2002         r = recvmsg(fd, &msg, 0);
2003 #else
2004         addrlen = sizeof(struct sockaddr);
2005         r = recvfrom(fd, packet, sizeof(packet), 0, (struct sockaddr*)&from, &addrlen);
2006 #endif /* !WINDOWS32 */
2007
2008         if (r > 0) {
2009                 memcpy((struct sockaddr*)&q->from, (struct sockaddr*)&from, addrlen);
2010                 q->fromlen = addrlen;
2011
2012                 /* TODO do not handle raw packets here! */
2013                 if (raw_decode(packet, r, q, fd, tun_fd)) {
2014                         return 0;
2015                 }
2016                 if (dns_decode(NULL, 0, q, QR_QUERY, packet, r) < 0) {
2017                         return 0;
2018                 }
2019
2020 #ifndef WINDOWS32
2021                 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
2022                         cmsg = CMSG_NXTHDR(&msg, cmsg)) {
2023
2024                         if (cmsg->cmsg_level == IPPROTO_IP &&
2025                                 cmsg->cmsg_type == DSTADDR_SOCKOPT) {
2026
2027                                 q->destination = *dstaddr(cmsg);
2028                                 break;
2029                         }
2030                 }
2031 #endif
2032
2033                 return strlen(q->name);
2034         } else if (r < 0) {
2035                 /* Error */
2036                 warn("read dns");
2037         }
2038
2039         return 0;
2040 }
2041
2042 static size_t
2043 write_dns_nameenc(char *buf, size_t buflen, char *data, int datalen, char downenc)
2044 /* Returns #bytes of data that were encoded */
2045 {
2046         static int td1 = 0;
2047         static int td2 = 0;
2048         size_t space;
2049         char *b;
2050
2051         /* Make a rotating topdomain to prevent filtering */
2052         td1+=3;
2053         td2+=7;
2054         if (td1>=26) td1-=26;
2055         if (td2>=25) td2-=25;
2056
2057         /* encode data,datalen to CNAME/MX answer
2058            (adapted from build_hostname() in encoding.c)
2059          */
2060
2061         space = MIN(0xFF, buflen) - 4 - 2;
2062         /* -1 encoding type, -3 ".xy", -2 for safety */
2063
2064         memset(buf, 0, buflen);
2065
2066         if (downenc == 'S') {
2067                 buf[0] = 'i';
2068                 if (!b64->places_dots())
2069                         space -= (space / 57);  /* space for dots */
2070                 b64->encode(buf+1, &space, data, datalen);
2071                 if (!b64->places_dots())
2072                         inline_dotify(buf, buflen);
2073         } else if (downenc == 'U') {
2074                 buf[0] = 'j';
2075                 if (!b64u->places_dots())
2076                         space -= (space / 57);  /* space for dots */
2077                 b64u->encode(buf+1, &space, data, datalen);
2078                 if (!b64u->places_dots())
2079                         inline_dotify(buf, buflen);
2080         } else if (downenc == 'V') {
2081                 buf[0] = 'k';
2082                 if (!b128->places_dots())
2083                         space -= (space / 57);  /* space for dots */
2084                 b128->encode(buf+1, &space, data, datalen);
2085                 if (!b128->places_dots())
2086                         inline_dotify(buf, buflen);
2087         } else {
2088                 buf[0] = 'h';
2089                 if (!b32->places_dots())
2090                         space -= (space / 57);  /* space for dots */
2091                 b32->encode(buf+1, &space, data, datalen);
2092                 if (!b32->places_dots())
2093                         inline_dotify(buf, buflen);
2094         }
2095
2096         /* Add dot (if it wasn't there already) and topdomain */
2097         b = buf;
2098         b += strlen(buf) - 1;
2099         if (*b != '.')
2100                 *++b = '.';
2101         b++;
2102
2103         *b = 'a' + td1;
2104         b++;
2105         *b = 'a' + td2;
2106         b++;
2107         *b = '\0';
2108
2109         return space;
2110 }
2111
2112 static void
2113 write_dns(int fd, struct query *q, char *data, int datalen, char downenc)
2114 {
2115         char buf[64*1024];
2116         int len = 0;
2117
2118         if (q->type == T_CNAME || q->type == T_A) {
2119                 char cnamebuf[1024];            /* max 255 */
2120
2121                 write_dns_nameenc(cnamebuf, sizeof(cnamebuf),
2122                                   data, datalen, downenc);
2123
2124                 len = dns_encode(buf, sizeof(buf), q, QR_ANSWER, cnamebuf,
2125                                  sizeof(cnamebuf));
2126         } else if (q->type == T_MX || q->type == T_SRV) {
2127                 char mxbuf[64*1024];
2128                 char *b = mxbuf;
2129                 int offset = 0;
2130                 int res;
2131
2132                 while (1) {
2133                         res = write_dns_nameenc(b, sizeof(mxbuf) - (b - mxbuf),
2134                                                 data + offset,
2135                                                 datalen - offset, downenc);
2136                         if (res < 1) {
2137                                 /* nothing encoded */
2138                                 b++;    /* for final \0 */
2139                                 break;
2140                         }
2141
2142                         b = b + strlen(b) + 1;
2143
2144                         offset += res;
2145                         if (offset >= datalen)
2146                                 break;
2147                 }
2148
2149                 /* Add final \0 */
2150                 *b = '\0';
2151
2152                 len = dns_encode(buf, sizeof(buf), q, QR_ANSWER, mxbuf,
2153                                  sizeof(mxbuf));
2154         } else if (q->type == T_TXT) {
2155                 /* TXT with base32 */
2156                 char txtbuf[64*1024];
2157                 size_t space = sizeof(txtbuf) - 1;;
2158
2159                 memset(txtbuf, 0, sizeof(txtbuf));
2160
2161                 if (downenc == 'S') {
2162                         txtbuf[0] = 's';        /* plain base64(Sixty-four) */
2163                         len = b64->encode(txtbuf+1, &space, data, datalen);
2164                 }
2165                 else if (downenc == 'U') {
2166                         txtbuf[0] = 'u';        /* Base64 with Underscore */
2167                         len = b64u->encode(txtbuf+1, &space, data, datalen);
2168                 }
2169                 else if (downenc == 'V') {
2170                         txtbuf[0] = 'v';        /* Base128 */
2171                         len = b128->encode(txtbuf+1, &space, data, datalen);
2172                 }
2173                 else if (downenc == 'R') {
2174                         txtbuf[0] = 'r';        /* Raw binary data */
2175                         len = MIN(datalen, sizeof(txtbuf) - 1);
2176                         memcpy(txtbuf + 1, data, len);
2177                 } else {
2178                         txtbuf[0] = 't';        /* plain base32(Thirty-two) */
2179                         len = b32->encode(txtbuf+1, &space, data, datalen);
2180                 }
2181                 len = dns_encode(buf, sizeof(buf), q, QR_ANSWER, txtbuf, len+1);
2182         } else {
2183                 /* Normal NULL-record encode */
2184                 len = dns_encode(buf, sizeof(buf), q, QR_ANSWER, data, datalen);
2185         }
2186
2187         if (len < 1) {
2188                 warnx("dns_encode doesn't fit");
2189                 return;
2190         }
2191
2192         if (debug >= 2) {
2193                 fprintf(stderr, "TX: client %s, type %d, name %s, %d bytes data\n",
2194                         format_addr(&q->from, q->fromlen), q->type, q->name, datalen);
2195         }
2196
2197         sendto(fd, buf, len, 0, (struct sockaddr*)&q->from, q->fromlen);
2198 }
2199
2200 static void
2201 usage() {
2202         extern char *__progname;
2203
2204         fprintf(stderr, "Usage: %s [-v] [-h] [-c] [-s] [-f] [-D] [-u user] "
2205                 "[-t chrootdir] [-d device] [-m mtu] [-z context] "
2206                 "[-l ip address to listen on] [-p port] [-n external ip] "
2207                 "[-b dnsport] [-P password] [-F pidfile] [-i max idle time] "
2208                 "tunnel_ip[/netmask] topdomain\n", __progname);
2209         exit(2);
2210 }
2211
2212 static void
2213 help() {
2214         extern char *__progname;
2215
2216         fprintf(stderr, "iodine IP over DNS tunneling server\n");
2217         fprintf(stderr, "Usage: %s [-v] [-h] [-c] [-s] [-f] [-D] [-u user] "
2218                 "[-t chrootdir] [-d device] [-m mtu] [-z context] "
2219                 "[-l ip address to listen on] [-p port] [-n external ip] [-b dnsport] [-P password] "
2220                 "[-F pidfile] tunnel_ip[/netmask] topdomain\n", __progname);
2221         fprintf(stderr, "  -v to print version info and exit\n");
2222         fprintf(stderr, "  -h to print this help and exit\n");
2223         fprintf(stderr, "  -c to disable check of client IP/port on each request\n");
2224         fprintf(stderr, "  -s to skip creating and configuring the tun device, "
2225                 "which then has to be created manually\n");
2226         fprintf(stderr, "  -f to keep running in foreground\n");
2227         fprintf(stderr, "  -D to increase debug level\n");
2228         fprintf(stderr, "     (using -DD in UTF-8 terminal: \"LC_ALL=C luit iodined -DD ...\")\n");
2229         fprintf(stderr, "  -u name to drop privileges and run as user 'name'\n");
2230         fprintf(stderr, "  -t dir to chroot to directory dir\n");
2231         fprintf(stderr, "  -d device to set tunnel device name\n");
2232         fprintf(stderr, "  -m mtu to set tunnel device mtu\n");
2233         fprintf(stderr, "  -z context to apply SELinux context after initialization\n");
2234         fprintf(stderr, "  -l ip address to listen on for incoming dns traffic "
2235                 "(default 0.0.0.0)\n");
2236         fprintf(stderr, "  -p port to listen on for incoming dns traffic (default 53)\n");
2237         fprintf(stderr, "  -n ip to respond with to NS queries\n");
2238         fprintf(stderr, "  -b port to forward normal DNS queries to (on localhost)\n");
2239         fprintf(stderr, "  -P password used for authentication (max 32 chars will be used)\n");
2240         fprintf(stderr, "  -F pidfile to write pid to a file\n");
2241         fprintf(stderr, "  -i maximum idle time before shutting down\n");
2242         fprintf(stderr, "tunnel_ip is the IP number of the local tunnel interface.\n");
2243         fprintf(stderr, "   /netmask sets the size of the tunnel network.\n");
2244         fprintf(stderr, "topdomain is the FQDN that is delegated to this server.\n");
2245         exit(0);
2246 }
2247
2248 static void
2249 version() {
2250         fprintf(stderr, "iodine IP over DNS tunneling server\n");
2251         fprintf(stderr, "version: 0.7.0 from 2014-06-16\n");
2252         exit(0);
2253 }
2254
2255 int
2256 main(int argc, char **argv)
2257 {
2258         extern char *__progname;
2259         char *listen_ip;
2260         char *errormsg;
2261 #ifndef WINDOWS32
2262         struct passwd *pw;
2263 #endif
2264         int foreground;
2265         char *username;
2266         char *newroot;
2267         char *context;
2268         char *device;
2269         char *pidfile;
2270         int dnsd_fd;
2271         int tun_fd;
2272
2273         /* settings for forwarding normal DNS to
2274          * local real DNS server */
2275         int bind_fd;
2276         int bind_enable;
2277
2278         int choice;
2279         int port;
2280         int mtu;
2281         int skipipconfig;
2282         char *netsize;
2283         int ns_get_externalip;
2284         int retval;
2285         int max_idle_time = 0;
2286         struct sockaddr_storage dnsaddr;
2287         int dnsaddr_len;
2288 #ifdef HAVE_SYSTEMD
2289         int nb_fds;
2290 #endif
2291
2292 #ifndef WINDOWS32
2293         pw = NULL;
2294 #endif
2295         errormsg = NULL;
2296         username = NULL;
2297         newroot = NULL;
2298         context = NULL;
2299         device = NULL;
2300         foreground = 0;
2301         bind_enable = 0;
2302         bind_fd = 0;
2303         mtu = 1130;     /* Very many relays give fragsize 1150 or slightly
2304                            higher for NULL; tun/zlib adds ~17 bytes. */
2305         listen_ip = NULL;
2306         port = 53;
2307         ns_ip = INADDR_ANY;
2308         ns_get_externalip = 0;
2309         check_ip = 1;
2310         skipipconfig = 0;
2311         debug = 0;
2312         netmask = 27;
2313         pidfile = NULL;
2314
2315         b32 = get_base32_encoder();
2316         b64 = get_base64_encoder();
2317         b64u = get_base64u_encoder();
2318         b128 = get_base128_encoder();
2319
2320         retval = 0;
2321
2322 #ifdef WINDOWS32
2323         WSAStartup(req_version, &wsa_data);
2324 #endif
2325
2326 #if !defined(BSD) && !defined(__GLIBC__)
2327         __progname = strrchr(argv[0], '/');
2328         if (__progname == NULL)
2329                 __progname = argv[0];
2330         else
2331                 __progname++;
2332 #endif
2333
2334         memset(password, 0, sizeof(password));
2335         srand(time(NULL));
2336         fw_query_init();
2337
2338         while ((choice = getopt(argc, argv, "vcsfhDu:t:d:m:l:p:n:b:P:z:F:i:")) != -1) {
2339                 switch(choice) {
2340                 case 'v':
2341                         version();
2342                         break;
2343                 case 'c':
2344                         check_ip = 0;
2345                         break;
2346                 case 's':
2347                         skipipconfig = 1;
2348                         break;
2349                 case 'f':
2350                         foreground = 1;
2351                         break;
2352                 case 'h':
2353                         help();
2354                         break;
2355                 case 'D':
2356                         debug++;
2357                         break;
2358                 case 'u':
2359                         username = optarg;
2360                         break;
2361                 case 't':
2362                         newroot = optarg;
2363                         break;
2364                 case 'd':
2365                         device = optarg;
2366                         break;
2367                 case 'm':
2368                         mtu = atoi(optarg);
2369                         break;
2370                 case 'l':
2371                         listen_ip = optarg;
2372                         break;
2373                 case 'p':
2374                         port = atoi(optarg);
2375                         break;
2376                 case 'n':
2377                         if (optarg && strcmp("auto", optarg) == 0) {
2378                                 ns_get_externalip = 1;
2379                         } else {
2380                                 ns_ip = inet_addr(optarg);
2381                         }
2382                         break;
2383                 case 'b':
2384                         bind_enable = 1;
2385                         bind_port = atoi(optarg);
2386                         break;
2387                 case 'F':
2388                         pidfile = optarg;
2389                         break;
2390                 case 'i':
2391                         max_idle_time = atoi(optarg);
2392                         break;
2393                 case 'P':
2394                         strncpy(password, optarg, sizeof(password));
2395                         password[sizeof(password)-1] = 0;
2396
2397                         /* XXX: find better way of cleaning up ps(1) */
2398                         memset(optarg, 0, strlen(optarg));
2399                         break;
2400                 case 'z':
2401                         context = optarg;
2402                         break;
2403                 default:
2404                         usage();
2405                         break;
2406                 }
2407         }
2408
2409         argc -= optind;
2410         argv += optind;
2411
2412         check_superuser(usage);
2413
2414         if (argc != 2)
2415                 usage();
2416
2417         netsize = strchr(argv[0], '/');
2418         if (netsize) {
2419                 *netsize = 0;
2420                 netsize++;
2421                 netmask = atoi(netsize);
2422         }
2423
2424         my_ip = inet_addr(argv[0]);
2425
2426         if (my_ip == INADDR_NONE) {
2427                 warnx("Bad IP address to use inside tunnel.");
2428                 usage();
2429         }
2430
2431         topdomain = strdup(argv[1]);
2432         if(check_topdomain(topdomain, &errormsg)) {
2433                 warnx("Invalid topdomain: %s", errormsg);
2434                 usage();
2435                 /* NOTREACHED */
2436         }
2437
2438         if (username != NULL) {
2439 #ifndef WINDOWS32
2440                 if ((pw = getpwnam(username)) == NULL) {
2441                         warnx("User %s does not exist!", username);
2442                         usage();
2443                 }
2444 #endif
2445         }
2446
2447         if (mtu <= 0) {
2448                 warnx("Bad MTU given.");
2449                 usage();
2450         }
2451
2452         if(port < 1 || port > 65535) {
2453                 warnx("Bad port number given.");
2454                 usage();
2455         }
2456
2457         if (port != 53) {
2458                 fprintf(stderr, "ALERT! Other dns servers expect you to run on port 53.\n");
2459                 fprintf(stderr, "You must manually forward port 53 to port %d for things to work.\n", port);
2460         }
2461
2462         if (debug) {
2463                 fprintf(stderr, "Debug level %d enabled, will stay in foreground.\n", debug);
2464                 fprintf(stderr, "Add more -D switches to set higher debug level.\n");
2465                 foreground = 1;
2466         }
2467
2468         dnsaddr_len = get_addr(listen_ip, port, AF_INET, AI_PASSIVE | AI_NUMERICHOST, &dnsaddr);
2469         if (dnsaddr_len < 0) {
2470                 warnx("Bad IP address to listen on.");
2471                 usage();
2472         }
2473
2474         if(bind_enable) {
2475                 in_addr_t dns_ip = ((struct sockaddr_in *) &dnsaddr)->sin_addr.s_addr;
2476                 if (bind_port < 1 || bind_port > 65535) {
2477                         warnx("Bad DNS server port number given.");
2478                         usage();
2479                         /* NOTREACHED */
2480                 }
2481                 /* Avoid forwarding loops */
2482                 if (bind_port == port && (dns_ip == INADDR_ANY || dns_ip == htonl(0x7f000001L))) {
2483                         warnx("Forward port is same as listen port (%d), will create a loop!", bind_port);
2484                         fprintf(stderr, "Use -l to set listen ip to avoid this.\n");
2485                         usage();
2486                         /* NOTREACHED */
2487                 }
2488                 fprintf(stderr, "Requests for domains outside of %s will be forwarded to port %d\n",
2489                         topdomain, bind_port);
2490         }
2491
2492         if (ns_get_externalip) {
2493                 struct in_addr extip;
2494                 int res = get_external_ip(&extip);
2495                 if (res) {
2496                         fprintf(stderr, "Failed to get external IP via web service.\n");
2497                         exit(3);
2498                 }
2499                 ns_ip = extip.s_addr;
2500                 fprintf(stderr, "Using %s as external IP.\n", inet_ntoa(extip));
2501         }
2502
2503         if (ns_ip == INADDR_NONE) {
2504                 warnx("Bad IP address to return as nameserver.");
2505                 usage();
2506         }
2507         if (netmask > 30 || netmask < 8) {
2508                 warnx("Bad netmask (%d bits). Use 8-30 bits.", netmask);
2509                 usage();
2510         }
2511
2512         if (strlen(password) == 0) {
2513                 if (NULL != getenv(PASSWORD_ENV_VAR))
2514                         snprintf(password, sizeof(password), "%s", getenv(PASSWORD_ENV_VAR));
2515                 else
2516                         read_password(password, sizeof(password));
2517         }
2518
2519         created_users = init_users(my_ip, netmask);
2520
2521         if ((tun_fd = open_tun(device)) == -1) {
2522                 retval = 1;
2523                 goto cleanup0;
2524         }
2525         if (!skipipconfig) {
2526                 const char *other_ip = users_get_first_ip();
2527                 if (tun_setip(argv[0], other_ip, netmask) != 0 || tun_setmtu(mtu) != 0) {
2528                         retval = 1;
2529                         free((void*) other_ip);
2530                         goto cleanup1;
2531                 }
2532                 free((void*) other_ip);
2533         }
2534 #ifdef HAVE_SYSTEMD
2535         nb_fds = sd_listen_fds(0);
2536         if (nb_fds > 1) {
2537                 retval = 1;
2538                 warnx("Too many file descriptors received!\n");
2539                 goto cleanup1;
2540         } else if (nb_fds == 1) {
2541                 dnsd_fd = SD_LISTEN_FDS_START;
2542         } else {
2543 #endif
2544                 if ((dnsd_fd = open_dns(&dnsaddr, dnsaddr_len)) < 0) {
2545                         retval = 1;
2546                         goto cleanup2;
2547                 }
2548 #ifdef HAVE_SYSTEMD
2549         }
2550 #endif
2551         if (bind_enable) {
2552                 if ((bind_fd = open_dns_from_host(NULL, 0, AF_INET, 0)) < 0) {
2553                         retval = 1;
2554                         goto cleanup3;
2555                 }
2556         }
2557
2558         my_mtu = mtu;
2559
2560         if (created_users < USERS) {
2561                 fprintf(stderr, "Limiting to %d simultaneous users because of netmask /%d\n",
2562                         created_users, netmask);
2563         }
2564         fprintf(stderr, "Listening to dns for domain %s\n", topdomain);
2565
2566         if (foreground == 0)
2567                 do_detach();
2568
2569         if (pidfile != NULL)
2570                 do_pidfile(pidfile);
2571
2572 #ifdef FREEBSD
2573         tzsetwall();
2574 #endif
2575 #ifndef WINDOWS32
2576         openlog( __progname, LOG_NDELAY, LOG_DAEMON );
2577 #endif
2578
2579         if (newroot != NULL)
2580                 do_chroot(newroot);
2581
2582         signal(SIGINT, sigint);
2583         if (username != NULL) {
2584 #ifndef WINDOWS32
2585                 gid_t gids[1];
2586                 gids[0] = pw->pw_gid;
2587                 if (setgroups(1, gids) < 0 || setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
2588                         warnx("Could not switch to user %s!\n", username);
2589                         usage();
2590                 }
2591 #endif
2592         }
2593
2594         if (context != NULL)
2595                 do_setcon(context);
2596
2597         syslog(LOG_INFO, "started, listening on port %d", port);
2598
2599         tunnel(tun_fd, dnsd_fd, bind_fd, max_idle_time);
2600
2601         syslog(LOG_INFO, "stopping");
2602 cleanup3:
2603         close_dns(bind_fd);
2604 cleanup2:
2605         close_dns(dnsd_fd);
2606 cleanup1:
2607         close_tun(tun_fd);
2608 cleanup0:
2609
2610         return retval;
2611 }