[svn-upgrade] Integrating new upstream version, iodine (0.5.1)
[debian/iodine.git] / src / iodine.c
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/types.h>
24 #include <sys/param.h>
25 #include <sys/time.h>
26 #include <fcntl.h>
27 #include <zlib.h>
28
29 #ifdef WINDOWS32
30 #include "windows.h"
31 #include <winsock2.h>
32 #else
33 #include <arpa/nameser.h>
34 #ifdef DARWIN
35 #include <arpa/nameser8_compat.h>
36 #endif
37 #include <sys/socket.h>
38 #include <err.h>
39 #include <arpa/inet.h>
40 #include <netinet/in.h>
41 #include <grp.h>
42 #include <pwd.h>
43 #include <netdb.h>
44 #endif
45
46 #include "common.h"
47 #include "encoding.h"
48 #include "base32.h"
49 #include "base64.h"
50 #include "dns.h"
51 #include "login.h"
52 #include "tun.h"
53 #include "version.h"
54
55 #ifdef WINDOWS32
56 WORD req_version = MAKEWORD(2, 2);
57 WSADATA wsa_data;
58 #endif
59
60 static void send_ping(int fd);
61 static void send_chunk(int fd);
62 static int build_hostname(char *buf, size_t buflen, 
63         const char *data, const size_t datalen, 
64         const char *topdomain, struct encoder *encoder);
65
66 static int running = 1;
67 static char password[33];
68
69 static struct sockaddr_in nameserv;
70 static char *topdomain;
71
72 static uint16_t rand_seed;
73 static int downstream_seqno;
74 static int downstream_fragment;
75 static int down_ack_seqno;
76 static int down_ack_fragment;
77
78 /* Current up/downstream IP packet */
79 static struct packet outpkt;
80 static struct packet inpkt;
81
82 /* My userid at the server */
83 static char userid;
84
85 /* DNS id for next packet */
86 static uint16_t chunkid;
87
88 /* Base32 encoder used for non-data packets */
89 static struct encoder *b32;
90
91 /* The encoder used for data packets
92  * Defaults to Base32, can be changed after handshake */
93 static struct encoder *dataenc;
94
95 /* result of case preservation check done after login */
96 static int case_preserved;
97
98 #if !defined(BSD) && !defined(__GLIBC__)
99 static char *__progname;
100 #endif
101
102 static void
103 sighandler(int sig) 
104 {
105         running = 0;
106 }
107
108 static void
109 send_query(int fd, char *hostname)
110 {
111         char packet[4096];
112         struct query q;
113         size_t len;
114
115         q.id = ++chunkid;
116         q.type = T_NULL;
117
118         len = dns_encode(packet, sizeof(packet), &q, QR_QUERY, hostname, strlen(hostname));
119
120         sendto(fd, packet, len, 0, (struct sockaddr*)&nameserv, sizeof(nameserv));
121 }
122
123 static void
124 send_packet(int fd, char cmd, const char *data, const size_t datalen)
125 {
126         char buf[4096];
127
128         buf[0] = cmd;
129         
130         build_hostname(buf + 1, sizeof(buf) - 1, data, datalen, topdomain, b32);
131         send_query(fd, buf);
132 }
133
134 static int
135 build_hostname(char *buf, size_t buflen, 
136                 const char *data, const size_t datalen, 
137                 const char *topdomain, struct encoder *encoder)
138 {
139         int encsize;
140         size_t space;
141         char *b;
142
143         space = MIN(0xFF, buflen) - strlen(topdomain) - 7;
144         if (!encoder->places_dots())
145                 space -= (space / 57); /* space for dots */
146
147         memset(buf, 0, buflen);
148         
149         encsize = encoder->encode(buf, &space, data, datalen);
150
151         if (!encoder->places_dots())
152                 inline_dotify(buf, buflen);
153
154         b = buf;
155         b += strlen(buf);
156
157         if (*b != '.') 
158                 *b++ = '.';
159
160         strncpy(b, topdomain, strlen(topdomain)+1);
161
162         return space;
163 }
164
165 static int
166 is_sending()
167 {
168         return (outpkt.len != 0);
169 }
170
171 static int
172 read_dns(int fd, char *buf, int buflen)
173 {
174         struct sockaddr_in from;
175         char data[64*1024];
176         socklen_t addrlen;
177         struct query q;
178         int rv;
179         int r;
180
181         addrlen = sizeof(struct sockaddr);
182         if ((r = recvfrom(fd, data, sizeof(data), 0, 
183                           (struct sockaddr*)&from, &addrlen)) == -1) {
184                 warn("recvfrom");
185                 return 0;
186         }
187
188         rv = dns_decode(buf, buflen, &q, QR_ANSWER, data, r);
189
190         /* decode the data header, update seqno and frag before next request */
191         if (rv >= 2) {
192                 downstream_seqno = (buf[1] >> 5) & 7;
193                 downstream_fragment = (buf[1] >> 1) & 15;
194         }
195
196
197         if (is_sending()) {
198                 if (chunkid == q.id) {
199                         /* Got ACK on sent packet */
200                         outpkt.offset += outpkt.sentlen;
201                         if (outpkt.offset == outpkt.len) {
202                                 /* Packet completed */
203                                 outpkt.offset = 0;
204                                 outpkt.len = 0;
205                                 outpkt.sentlen = 0;
206
207                                 /* If the ack contains unacked frag number but no data, 
208                                  * send a ping to ack the frag number and get more data*/
209                                 if (rv == 2 && (
210                                         downstream_seqno != down_ack_seqno ||
211                                         downstream_fragment != down_ack_fragment
212                                         )) {
213                                         
214                                         send_ping(fd);
215                                 }
216                         } else {
217                                 /* More to send */
218                                 send_chunk(fd);
219                         }
220
221                 }
222         }
223         return rv;
224 }
225
226
227 static int
228 tunnel_tun(int tun_fd, int dns_fd)
229 {
230         unsigned long outlen;
231         unsigned long inlen;
232         char out[64*1024];
233         char in[64*1024];
234         size_t read;
235
236         if ((read = read_tun(tun_fd, in, sizeof(in))) <= 0)
237                 return -1;
238
239         outlen = sizeof(out);
240         inlen = read;
241         compress2((uint8_t*)out, &outlen, (uint8_t*)in, inlen, 9);
242
243         memcpy(outpkt.data, out, MIN(outlen, sizeof(outpkt.data)));
244         outpkt.sentlen = 0;
245         outpkt.offset = 0;
246         outpkt.len = outlen;
247         outpkt.seqno++;
248         outpkt.fragment = 0;
249
250         send_chunk(dns_fd);
251
252         return read;
253 }
254
255 static int
256 tunnel_dns(int tun_fd, int dns_fd)
257 {
258         unsigned long datalen;
259         char buf[64*1024];
260         size_t read;
261
262         if ((read = read_dns(dns_fd, buf, sizeof(buf))) <= 2) 
263                 return -1;
264
265         if (downstream_seqno != inpkt.seqno) {
266                 /* New packet */
267                 inpkt.seqno = downstream_seqno;
268                 inpkt.fragment = downstream_fragment;
269                 inpkt.len = 0;
270         } else if (downstream_fragment <= inpkt.fragment) {
271                 /* Duplicate fragment */
272                 return -1;
273         }
274         inpkt.fragment = downstream_fragment;
275
276         datalen = MIN(read - 2, sizeof(inpkt.data) - inpkt.len);
277
278         /* Skip 2 byte data header and append to packet */
279         memcpy(&inpkt.data[inpkt.len], &buf[2], datalen);
280         inpkt.len += datalen;
281
282         if (buf[1] & 1) { /* If last fragment flag is set */
283                 /* Uncompress packet and send to tun */
284                 datalen = sizeof(buf);
285                 if (uncompress((uint8_t*)buf, &datalen, (uint8_t*) inpkt.data, inpkt.len) == Z_OK) {
286                         write_tun(tun_fd, buf, datalen);
287                 }
288                 inpkt.len = 0;
289         }
290
291         /* If we have nothing to send, send a ping to get more data */
292         if (!is_sending()) 
293                 send_ping(dns_fd);
294         
295         return read;
296 }
297
298 static int
299 tunnel(int tun_fd, int dns_fd)
300 {
301         struct timeval tv;
302         fd_set fds;
303         int rv;
304         int i;
305
306         rv = 0;
307
308         while (running) {
309                 tv.tv_sec = 1;
310                 tv.tv_usec = 0;
311
312
313                 FD_ZERO(&fds);
314                 if (!is_sending()) {
315                         FD_SET(tun_fd, &fds);
316                 }
317                 FD_SET(dns_fd, &fds);
318
319                 i = select(MAX(tun_fd, dns_fd) + 1, &fds, NULL, NULL, &tv);
320                 
321                 if (running == 0)
322                         break;
323
324                 if (i < 0) 
325                         err(1, "select");
326
327                 if (i == 0) /* timeout */
328                         send_ping(dns_fd);
329                 else {
330                         if (FD_ISSET(tun_fd, &fds)) {
331                                 if (tunnel_tun(tun_fd, dns_fd) <= 0)
332                                         continue;
333                         }
334                         if (FD_ISSET(dns_fd, &fds)) {
335                                 if (tunnel_dns(tun_fd, dns_fd) <= 0)
336                                         continue;
337                         } 
338                 }
339         }
340
341         return rv;
342 }
343
344 static void
345 send_chunk(int fd)
346 {
347         char hex[] = "0123456789ABCDEF";
348         char buf[4096];
349         int avail;
350         int code;
351         char *p;
352
353         p = outpkt.data;
354         p += outpkt.offset;
355         avail = outpkt.len - outpkt.offset;
356
357         outpkt.sentlen = build_hostname(buf + 4, sizeof(buf) - 4, p, avail, topdomain, dataenc);
358
359         /* Build upstream data header (see doc/proto_xxxxxxxx.txt) */
360
361         buf[0] = hex[userid & 15]; /* First byte is 4 bits userid */
362
363         code = ((outpkt.seqno & 7) << 2) | ((outpkt.fragment & 15) >> 2);
364         buf[1] = b32_5to8(code); /* Second byte is 3 bits seqno, 2 upper bits fragment count */
365
366         code = ((outpkt.fragment & 3) << 3) | (downstream_seqno & 7);
367         buf[2] = b32_5to8(code); /* Third byte is 2 bits lower fragment count, 3 bits downstream packet seqno */
368
369         code = ((downstream_fragment & 15) << 1) | (outpkt.sentlen == avail);
370         buf[3] = b32_5to8(code); /* Fourth byte is 4 bits downstream fragment count, 1 bit last frag flag */
371
372         down_ack_seqno = downstream_seqno;
373         down_ack_fragment = downstream_fragment;
374
375         outpkt.fragment++;
376         send_query(fd, buf);
377 }
378
379 static void
380 send_login(int fd, char *login, int len)
381 {
382         char data[19];
383
384         memset(data, 0, sizeof(data));
385         data[0] = userid;
386         memcpy(&data[1], login, MIN(len, 16));
387
388         data[17] = (rand_seed >> 8) & 0xff;
389         data[18] = (rand_seed >> 0) & 0xff;
390         
391         rand_seed++;
392
393         send_packet(fd, 'L', data, sizeof(data));
394 }
395
396 static void
397 send_ping(int fd)
398 {
399         char data[4];
400         
401         if (is_sending()) {
402                 outpkt.sentlen = 0;
403                 outpkt.offset = 0;
404                 outpkt.len = 0;
405         }
406
407         data[0] = userid;
408         data[1] = ((downstream_seqno & 7) << 4) | (downstream_fragment & 15);
409         data[2] = (rand_seed >> 8) & 0xff;
410         data[3] = (rand_seed >> 0) & 0xff;
411         
412         down_ack_seqno = downstream_seqno;
413         down_ack_fragment = downstream_fragment;
414         
415         rand_seed++;
416
417         send_packet(fd, 'P', data, sizeof(data));
418 }
419
420 static void
421 send_fragsize_probe(int fd, int fragsize)
422 {
423         char probedata[256];
424         char buf[4096];
425
426         /* build a large query domain which is random and maximum size */
427         memset(probedata, MIN(1, rand_seed & 0xff), sizeof(probedata));
428         probedata[1] = MIN(1, (rand_seed >> 8) & 0xff);
429         rand_seed++;
430         build_hostname(buf + 4, sizeof(buf) - 4, probedata, sizeof(probedata), topdomain, dataenc);
431
432         fragsize &= 2047;
433
434         buf[0] = 'r'; /* Probe downstream fragsize packet */
435         buf[1] = b32_5to8((userid << 1) | ((fragsize >> 10) & 1));
436         buf[2] = b32_5to8((fragsize >> 5) & 31);
437         buf[3] = b32_5to8(fragsize & 31);
438
439         send_query(fd, buf);
440 }
441
442 static void
443 send_set_downstream_fragsize(int fd, int fragsize)
444 {
445         char data[5];
446         
447         data[0] = userid;
448         data[1] = (fragsize & 0xff00) >> 8;
449         data[2] = (fragsize & 0x00ff);
450         data[3] = (rand_seed >> 8) & 0xff;
451         data[4] = (rand_seed >> 0) & 0xff;
452         
453         rand_seed++;
454
455         send_packet(fd, 'N', data, sizeof(data));
456 }
457
458 static void 
459 send_version(int fd, uint32_t version)
460 {
461         char data[6];
462
463         data[0] = (version >> 24) & 0xff;
464         data[1] = (version >> 16) & 0xff;
465         data[2] = (version >> 8) & 0xff;
466         data[3] = (version >> 0) & 0xff;
467
468         data[4] = (rand_seed >> 8) & 0xff;
469         data[5] = (rand_seed >> 0) & 0xff;
470         
471         rand_seed++;
472
473         send_packet(fd, 'V', data, sizeof(data));
474 }
475
476 static void
477 send_case_check(int fd)
478 {
479         /* The '+' plus character is not allowed according to RFC. 
480          * Expect to get SERVFAIL or similar if it is rejected.
481          */
482         char buf[512] = "zZ+-aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyY1234.";
483
484         strncat(buf, topdomain, 512 - strlen(buf));
485         send_query(fd, buf);
486 }
487
488 static void
489 send_codec_switch(int fd, int userid, int bits)
490 {
491         char buf[512] = "S__.";
492         buf[1] = b32_5to8(userid);
493         buf[2] = b32_5to8(bits);
494         
495         strncat(buf, topdomain, 512 - strlen(buf));
496         send_query(fd, buf);
497 }
498         
499 static int
500 handshake_version(int dns_fd, int *seed)
501 {
502         struct timeval tv;
503         char in[4096];
504         fd_set fds;
505         uint32_t payload;
506         int i;
507         int r;
508         int read;
509
510         for (i = 0; running && i < 5; i++) {
511                 tv.tv_sec = i + 1;
512                 tv.tv_usec = 0;
513
514                 send_version(dns_fd, VERSION);
515                 
516                 FD_ZERO(&fds);
517                 FD_SET(dns_fd, &fds);
518
519                 r = select(dns_fd + 1, &fds, NULL, NULL, &tv);
520
521                 if(r > 0) {
522                         read = read_dns(dns_fd, in, sizeof(in));
523                         
524                         if(read <= 0) {
525                                 if (read == 0) {
526                                         warn("handshake read");
527                                 }
528                                 /* if read < 0 then warning has been printed already */
529                                 continue;
530                         }
531
532                         if (read >= 9) {
533                                 payload =  (((in[4] & 0xff) << 24) |
534                                                 ((in[5] & 0xff) << 16) |
535                                                 ((in[6] & 0xff) << 8) |
536                                                 ((in[7] & 0xff)));
537
538                                 if (strncmp("VACK", in, 4) == 0) {
539                                         *seed = payload;
540                                         userid = in[8];
541
542                                         fprintf(stderr, "Version ok, both using protocol v 0x%08x. You are user #%d\n", VERSION, userid);
543                                         return 0;
544                                 } else if (strncmp("VNAK", in, 4) == 0) {
545                                         warnx("You use protocol v 0x%08x, server uses v 0x%08x. Giving up", 
546                                                         VERSION, payload);
547                                         return 1;
548                                 } else if (strncmp("VFUL", in, 4) == 0) {
549                                         warnx("Server full, all %d slots are taken. Try again later", payload);
550                                         return 1;
551                                 }
552                         } else 
553                                 warnx("did not receive proper login challenge");
554                 }
555                 
556                 fprintf(stderr, "Retrying version check...\n");
557         }
558         warnx("couldn't connect to server");
559         return 1;
560 }
561
562 static int
563 handshake_login(int dns_fd, int seed)
564 {
565         struct timeval tv;
566         char in[4096];
567         char login[16];
568         char server[65];
569         char client[65];
570         int mtu;
571         fd_set fds;
572         int i;
573         int r;
574         int read;
575
576         login_calculate(login, 16, password, seed);
577         
578         for (i=0; running && i<5 ;i++) {
579                 tv.tv_sec = i + 1;
580                 tv.tv_usec = 0;
581
582                 send_login(dns_fd, login, 16);
583                 
584                 FD_ZERO(&fds);
585                 FD_SET(dns_fd, &fds);
586
587                 r = select(dns_fd + 1, &fds, NULL, NULL, &tv);
588
589                 if(r > 0) {
590                         read = read_dns(dns_fd, in, sizeof(in));
591                         
592                         if(read <= 0) {
593                                 warn("read");
594                                 continue;
595                         }
596
597                         if (read > 0) {
598                                 int netmask;
599                                 if (strncmp("LNAK", in, 4) == 0) {
600                                         fprintf(stderr, "Bad password\n");
601                                         return 1;
602                                 } else if (sscanf(in, "%64[^-]-%64[^-]-%d-%d", 
603                                         server, client, &mtu, &netmask) == 4) {
604                                         
605                                         server[64] = 0;
606                                         client[64] = 0;
607                                         if (tun_setip(client, netmask) == 0 && 
608                                                 tun_setmtu(mtu) == 0) {
609                                                 return 0;
610                                         } else {
611                                                 warnx("Received handshake with bad data");
612                                         }
613                                 } else {
614                                         fprintf(stderr, "Received bad handshake\n");
615                                 }
616                         }
617                 }
618
619                 fprintf(stderr, "Retrying login...\n");
620         }
621         warnx("couldn't login to server");
622         return 1;
623 }
624
625 static void
626 handshake_case_check(int dns_fd)
627 {
628         struct timeval tv;
629         char in[4096];
630         fd_set fds;
631         int i;
632         int r;
633         int read;
634
635         case_preserved = 0;
636         for (i=0; running && i<5 ;i++) {
637                 tv.tv_sec = i + 1;
638                 tv.tv_usec = 0;
639
640                 send_case_check(dns_fd);
641                 
642                 FD_ZERO(&fds);
643                 FD_SET(dns_fd, &fds);
644
645                 r = select(dns_fd + 1, &fds, NULL, NULL, &tv);
646
647                 if(r > 0) {
648                         read = read_dns(dns_fd, in, sizeof(in));
649                         
650                         if (read > 0) {
651                                 if (in[0] == 'z' || in[0] == 'Z') {
652                                         if (read < (27 * 2)) {
653                                                 fprintf(stderr, "Received short case check reply. Will use base32 encoder\n");
654                                                 return;
655                                         } else {
656                                                 int k;
657
658                                                 /* TODO enhance this, base128 is probably also possible */
659                                                 case_preserved = 1;
660                                                 for (k = 0; k < 27 && case_preserved; k += 2) {
661                                                         if (in[k] == in[k+1]) {
662                                                                 /* test string: zZ+-aAbBcCdDeE... */
663                                                                 case_preserved = 0;
664                                                         }
665                                                 }
666                                                 return;
667                                         }
668                                 } else {
669                                         fprintf(stderr, "Received bad case check reply\n");
670                                 }
671                         } else {
672                                 fprintf(stderr, "Got error on case check, will use base32\n");
673                                 return;
674                         }
675                 }
676
677                 fprintf(stderr, "Retrying case check...\n");
678         }
679
680         fprintf(stderr, "No reply on case check, continuing\n");
681 }
682
683 static void
684 handshake_switch_codec(int dns_fd)
685 {
686         struct timeval tv;
687         char in[4096];
688         fd_set fds;
689         int i;
690         int r;
691         int read;
692
693         dataenc = get_base64_encoder();
694         fprintf(stderr, "Switching to %s codec\n", dataenc->name);
695         /* Send to server that this user will use base64 from now on */
696         for (i=0; running && i<5 ;i++) {
697                 int bits;
698                 tv.tv_sec = i + 1;
699                 tv.tv_usec = 0;
700
701                 bits = 6; /* base64 = 6 bits per byte */
702
703                 send_codec_switch(dns_fd, userid, bits);
704                 
705                 FD_ZERO(&fds);
706                 FD_SET(dns_fd, &fds);
707
708                 r = select(dns_fd + 1, &fds, NULL, NULL, &tv);
709
710                 if(r > 0) {
711                         read = read_dns(dns_fd, in, sizeof(in));
712                         
713                         if (read > 0) {
714                                 if (strncmp("BADLEN", in, 6) == 0) {
715                                         fprintf(stderr, "Server got bad message length. ");
716                                         goto codec_revert;
717                                 } else if (strncmp("BADIP", in, 5) == 0) {
718                                         fprintf(stderr, "Server rejected sender IP address. ");
719                                         goto codec_revert;
720                                 } else if (strncmp("BADCODEC", in, 8) == 0) {
721                                         fprintf(stderr, "Server rejected the selected codec. ");
722                                         goto codec_revert;
723                                 }
724                                 in[read] = 0; /* zero terminate */
725                                 fprintf(stderr, "Server switched to codec %s\n", in);
726                                 return;
727                         }
728                 }
729                 fprintf(stderr, "Retrying codec switch...\n");
730         }
731         fprintf(stderr, "No reply from server on codec switch. ");
732
733 codec_revert: 
734         fprintf(stderr, "Falling back to base32\n");
735         dataenc = get_base32_encoder();
736 }
737
738 static int
739 handshake_autoprobe_fragsize(int dns_fd)
740 {
741         struct timeval tv;
742         char in[4096];
743         fd_set fds;
744         int i;
745         int r;
746         int read;
747         int proposed_fragsize = 768;
748         int range = 768;
749         int max_fragsize = 0;
750
751         max_fragsize = 0;
752         fprintf(stderr, "Autoprobing max downstream fragment size... (skip with -m fragsize)\n"); 
753         while (running && range > 0 && (range >= 8 || !max_fragsize)) {
754                 for (i=0; running && i<3 ;i++) {
755                         tv.tv_sec = 1;
756                         tv.tv_usec = 0;
757                         send_fragsize_probe(dns_fd, proposed_fragsize);
758
759                         FD_ZERO(&fds);
760                         FD_SET(dns_fd, &fds);
761
762                         r = select(dns_fd + 1, &fds, NULL, NULL, &tv);
763
764                         if(r > 0) {
765                                 read = read_dns(dns_fd, in, sizeof(in));
766                                 
767                                 if (read > 0) {
768                                         /* We got a reply */
769                                         int acked_fragsize = ((in[0] & 0xff) << 8) | (in[1] & 0xff);
770                                         if (acked_fragsize == proposed_fragsize) {
771                                                 if (read == proposed_fragsize) {
772                                                         fprintf(stderr, "%d ok.. ", acked_fragsize);
773                                                         fflush(stderr);
774                                                         max_fragsize = acked_fragsize;
775                                                 }
776                                         }
777                                         if (strncmp("BADIP", in, 5) == 0) {
778                                                 fprintf(stderr, "got BADIP.. ");
779                                                 fflush(stderr);
780                                         }
781                                         break;
782                                 }
783                         }
784                         fprintf(stderr, ".");
785                         fflush(stderr);
786                 }
787                 range >>= 1;
788                 if (max_fragsize == proposed_fragsize) {
789                         /* Try bigger */
790                         proposed_fragsize += range;
791                 } else {
792                         /* Try smaller */
793                         fprintf(stderr, "%d not ok.. ", proposed_fragsize);
794                         fflush(stderr);
795                         proposed_fragsize -= range;
796                 }
797         }
798         if (!running) {
799                 fprintf(stderr, "\n");
800                 warnx("stopped while autodetecting fragment size (Try probing manually with -m)");
801                 return 0;
802         }
803         if (range == 0) {
804                 /* Tried all the way down to 2 and found no good size */
805                 fprintf(stderr, "\n");
806                 warnx("found no accepted fragment size. (Try probing manually with -m)");
807                 return 0;
808         }
809         fprintf(stderr, "will use %d\n", max_fragsize);
810         return max_fragsize;
811 }
812
813 static void
814 handshake_set_fragsize(int dns_fd, int fragsize)
815 {
816         struct timeval tv;
817         char in[4096];
818         fd_set fds;
819         int i;
820         int r;
821         int read;
822
823         fprintf(stderr, "Setting downstream fragment size to max %d...\n", fragsize);
824         for (i=0; running && i<5 ;i++) {
825                 tv.tv_sec = i + 1;
826                 tv.tv_usec = 0;
827
828                 send_set_downstream_fragsize(dns_fd, fragsize);
829                 
830                 FD_ZERO(&fds);
831                 FD_SET(dns_fd, &fds);
832
833                 r = select(dns_fd + 1, &fds, NULL, NULL, &tv);
834
835                 if(r > 0) {
836                         read = read_dns(dns_fd, in, sizeof(in));
837                         
838                         if (read > 0) {
839                                 int accepted_fragsize;
840
841                                 if (strncmp("BADFRAG", in, 7) == 0) {
842                                         fprintf(stderr, "Server rejected fragsize. Keeping default.");
843                                         return;
844                                 } else if (strncmp("BADIP", in, 5) == 0) {
845                                         fprintf(stderr, "Server rejected sender IP address.\n");
846                                         return;
847                                 }
848
849                                 accepted_fragsize = ((in[0] & 0xff) << 8) | (in[1] & 0xff);
850                                 return;
851                         }
852                 }
853                 fprintf(stderr, "Retrying set fragsize...\n");
854         }
855         fprintf(stderr, "No reply from server when setting fragsize. Keeping default.\n");
856 }
857
858 static int
859 handshake(int dns_fd, int autodetect_frag_size, int fragsize)
860 {
861         int seed;
862         int r;
863
864         r = handshake_version(dns_fd, &seed);
865         if (r) {
866                 return r;
867         }
868
869         r = handshake_login(dns_fd, seed);
870         if (r) {
871                 return r;
872         }
873
874         handshake_case_check(dns_fd);
875
876         if (case_preserved) {
877                 handshake_switch_codec(dns_fd);
878         }
879
880         if (autodetect_frag_size) {
881                 fragsize = handshake_autoprobe_fragsize(dns_fd);
882                 if (!fragsize) {
883                         return 1;
884                 }
885         }
886
887         handshake_set_fragsize(dns_fd, fragsize);
888
889         return 0;
890 }
891
892 static char *
893 get_resolvconf_addr()
894 {
895         static char addr[16];
896         char *rv;
897 #ifndef WINDOWS32
898         char buf[80];
899         FILE *fp;
900         
901         rv = NULL;
902
903         if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) 
904                 err(1, "/etc/resolve.conf");
905         
906         while (feof(fp) == 0) {
907                 fgets(buf, sizeof(buf), fp);
908
909                 if (sscanf(buf, "nameserver %15s", addr) == 1) {
910                         rv = addr;
911                         break;
912                 }
913         }
914         
915         fclose(fp);
916 #else /* !WINDOWS32 */
917         FIXED_INFO  *fixed_info;
918         ULONG       buflen;
919         DWORD       ret;
920
921         rv = NULL;
922         fixed_info = malloc(sizeof(FIXED_INFO));
923         buflen = sizeof(FIXED_INFO);
924
925         if (GetNetworkParams(fixed_info, &buflen) == ERROR_BUFFER_OVERFLOW) {
926                 /* official ugly api workaround */
927                 free(fixed_info);
928                 fixed_info = malloc(buflen);
929         }
930
931         ret = GetNetworkParams(fixed_info, &buflen);
932         if (ret == NO_ERROR) {
933                 strncpy(addr, fixed_info->DnsServerList.IpAddress.String, sizeof(addr));
934                 addr[15] = 0;
935                 rv = addr;
936         }
937         free(fixed_info);
938 #endif
939         return rv;
940 }
941
942 static void
943 set_nameserver(const char *cp) 
944 {
945         struct in_addr addr;
946
947         if (inet_aton(cp, &addr) != 1)
948                 errx(1, "error parsing nameserver address: '%s'", cp);
949
950         memset(&nameserv, 0, sizeof(nameserv));
951         nameserv.sin_family = AF_INET;
952         nameserv.sin_port = htons(53);
953         nameserv.sin_addr = addr;
954 }
955
956 static void
957 usage() {
958         extern char *__progname;
959
960         fprintf(stderr, "Usage: %s [-v] [-h] [-f] [-u user] [-t chrootdir] [-d device] "
961                         "[-P password] [-m maxfragsize] [nameserver] topdomain\n", __progname);
962         exit(2);
963 }
964
965 static void
966 help() {
967         extern char *__progname;
968
969         fprintf(stderr, "iodine IP over DNS tunneling client\n");
970         fprintf(stderr, "Usage: %s [-v] [-h] [-f] [-u user] [-t chrootdir] [-d device] "
971                         "[-P password] [-m maxfragsize] [nameserver] topdomain\n", __progname);
972         fprintf(stderr, "  -v to print version info and exit\n");
973         fprintf(stderr, "  -h to print this help and exit\n");
974         fprintf(stderr, "  -f to keep running in foreground\n");
975         fprintf(stderr, "  -u name to drop privileges and run as user 'name'\n");
976         fprintf(stderr, "  -t dir to chroot to directory dir\n");
977         fprintf(stderr, "  -d device to set tunnel device name\n");
978         fprintf(stderr, "  -P password used for authentication (max 32 chars will be used)\n");
979         fprintf(stderr, "  -m maxfragsize, to limit size of downstream packets\n");
980         fprintf(stderr, "nameserver is the IP number of the relaying nameserver, if absent /etc/resolv.conf is used\n");
981         fprintf(stderr, "topdomain is the FQDN that is delegated to the tunnel endpoint.\n");
982
983         exit(0);
984 }
985
986 static void
987 version() {
988         printf("iodine IP over DNS tunneling client\n");
989         printf("version: 0.5.1 from 2009-03-21\n");
990
991         exit(0);
992 }
993
994 int
995 main(int argc, char **argv)
996 {
997         char *nameserv_addr;
998 #ifndef WINDOWS32
999         struct passwd *pw;
1000 #endif
1001         char *username;
1002         int foreground;
1003         char *newroot;
1004         char *device;
1005         int choice;
1006         int tun_fd;
1007         int dns_fd;
1008         int max_downstream_frag_size;
1009         int autodetect_frag_size;
1010
1011         memset(password, 0, 33);
1012         username = NULL;
1013         foreground = 0;
1014         newroot = NULL;
1015         device = NULL;
1016         chunkid = 0;
1017
1018         outpkt.seqno = 0;
1019         inpkt.len = 0;
1020
1021         autodetect_frag_size = 1;
1022         max_downstream_frag_size = 3072;
1023
1024         b32 = get_base32_encoder();
1025         dataenc = get_base32_encoder();
1026
1027 #ifdef WINDOWS32
1028         WSAStartup(req_version, &wsa_data);
1029 #endif
1030         
1031 #if !defined(BSD) && !defined(__GLIBC__)
1032         __progname = strrchr(argv[0], '/');
1033         if (__progname == NULL)
1034                 __progname = argv[0];
1035         else
1036                 __progname++;
1037 #endif
1038
1039         while ((choice = getopt(argc, argv, "vfhu:t:d:P:m:")) != -1) {
1040                 switch(choice) {
1041                 case 'v':
1042                         version();
1043                         /* NOTREACHED */
1044                         break;
1045                 case 'f':
1046                         foreground = 1;
1047                         break;
1048                 case 'h':
1049                         help();
1050                         /* NOTREACHED */
1051                         break;
1052                 case 'u':
1053                         username = optarg;
1054                         break;
1055                 case 't':
1056                         newroot = optarg;
1057                         break;
1058                 case 'd':
1059                         device = optarg;
1060                         break;
1061                 case 'P':
1062                         strncpy(password, optarg, sizeof(password));
1063                         password[sizeof(password)-1] = 0;
1064                         
1065                         /* XXX: find better way of cleaning up ps(1) */
1066                         memset(optarg, 0, strlen(optarg)); 
1067                         break;
1068                 case 'm':
1069                         autodetect_frag_size = 0;
1070                         max_downstream_frag_size = atoi(optarg);
1071                         break;
1072                 default:
1073                         usage();
1074                         /* NOTREACHED */
1075                 }
1076         }
1077         
1078         check_superuser(usage);
1079
1080         argc -= optind;
1081         argv += optind;
1082
1083         switch (argc) {
1084         case 1:
1085                 nameserv_addr = get_resolvconf_addr();
1086                 topdomain = strdup(argv[0]);
1087                 break;
1088         case 2:
1089                 nameserv_addr = argv[0];
1090                 topdomain = strdup(argv[1]);
1091                 break;
1092         default:
1093                 usage();
1094                 /* NOTREACHED */
1095         }
1096
1097         if (max_downstream_frag_size < 1 || max_downstream_frag_size > 0xffff) {
1098                 warnx("Use a max frag size between 1 and 65535 bytes.\n");
1099                 usage();
1100                 /* NOTREACHED */
1101         }
1102
1103         set_nameserver(nameserv_addr);
1104
1105         if(strlen(topdomain) <= 128) {
1106                 if(check_topdomain(topdomain)) {
1107                         warnx("Topdomain contains invalid characters.\n");
1108                         usage();
1109                         /* NOTREACHED */
1110                 }
1111         } else {
1112                 warnx("Use a topdomain max 128 chars long.\n");
1113                 usage();
1114                 /* NOTREACHED */
1115         }
1116
1117         if (username != NULL) {
1118 #ifndef WINDOWS32
1119                 if ((pw = getpwnam(username)) == NULL) {
1120                         warnx("User %s does not exist!\n", username);
1121                         usage();
1122                         /* NOTREACHED */
1123                 }
1124 #endif
1125         }
1126         
1127         if (strlen(password) == 0) 
1128                 read_password(password, sizeof(password));
1129
1130         if ((tun_fd = open_tun(device)) == -1)
1131                 goto cleanup1;
1132         if ((dns_fd = open_dns(0, INADDR_ANY)) == -1)
1133                 goto cleanup2;
1134
1135         signal(SIGINT, sighandler);
1136         signal(SIGTERM, sighandler);
1137
1138         if(handshake(dns_fd, autodetect_frag_size, max_downstream_frag_size))
1139                 goto cleanup2;
1140         
1141         fprintf(stderr, "Sending queries for %s to %s\n", topdomain, nameserv_addr);
1142
1143         if (foreground == 0) 
1144                 do_detach();
1145
1146         if (newroot != NULL)
1147                 do_chroot(newroot);
1148         
1149         if (username != NULL) {
1150 #ifndef WINDOWS32
1151                 gid_t gids[1];
1152                 gids[0] = pw->pw_gid;
1153                 if (setgroups(1, gids) < 0 || setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) {
1154                         warnx("Could not switch to user %s!\n", username);
1155                         usage();
1156                         /* NOTREACHED */
1157                 }
1158 #endif
1159         }
1160         
1161         downstream_seqno = 0;
1162         downstream_fragment = 0;
1163         down_ack_seqno = 0;
1164         down_ack_fragment = 0;
1165         
1166         tunnel(tun_fd, dns_fd);
1167
1168 cleanup2:
1169         close_dns(dns_fd);
1170         close_tun(tun_fd);
1171 cleanup1:
1172
1173         return 0;
1174 }