source: src/iodined.c @ 45a5d8

Revision 45a5d8, 66.6 KB checked in by Erik Ekman <erik@…>, 3 months ago (diff)

Adjust indentation

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