windoze sucks
[oweals/gnunet.git] / src / transport / gnunet-nat-server-windows.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file src/transport/gnunet-nat-server-windows.c
23  * @brief Windows tool to help bypass NATs using ICMP method
24  *        This code will work under W32 only
25  * @author Christian Grothoff
26  *
27  * This program will send ONE ICMP message every 500 ms RAW sockets
28  * to a DUMMY IP address and also listens for ICMP replies.  Since
29  * it uses RAW sockets, it must be run as an administrative user.
30  * In order to keep the security risk of the resulting binary
31  * minimal, the program ONLY opens the two RAW sockets with administrative
32  * privileges, then drops them and only then starts to process
33  * command line arguments.  The code also does not link against
34  * any shared libraries (except libc) and is strictly minimal
35  * (except for checking for errors).  The following list of people
36  * have reviewed this code and considered it safe since the last
37  * modification (if you reviewed it, please have your name added
38  * to the list):
39  *
40  * - Nathan Evans
41  */
42 #define _GNU_SOURCE
43
44 #ifdef WIN32
45 #include <winsock2.h>
46 #else
47 #include <sys/types.h> 
48 #include <sys/socket.h>
49 #include <arpa/inet.h>
50 #include <sys/select.h>
51 #include <netinet/ip.h>
52 #include <netinet/ip_icmp.h>
53 #include <netinet/in.h>
54 #endif
55 #include <sys/time.h>
56 #include <sys/types.h>
57 #include <unistd.h>
58 #include <stdio.h>
59 #include <string.h>
60 #include <errno.h>
61 #include <stdlib.h>
62 #include <stdint.h>
63 #include <time.h>
64
65
66 #ifdef WIN32
67 typedef unsigned int uid_t;
68 typedef SOCKET Socket;
69 typedef unsigned short ushort;
70 #define ICMP_ECHO 8
71 #define IPDEFTTL        64              /* default ttl, from RFC 1340 */
72 #define ICMP_TIME_EXCEEDED      11      /* Time Exceeded                */
73 #define IP_HDRINCL      3       /* int; Header is included with data.  */
74 #else
75 typedef int Socket;
76 #endif
77
78 /**
79  * Must match IP given in the client.
80  */
81 #define DUMMY_IP "192.0.2.86"
82
83 #define VERBOSE 0
84
85 /**
86  * How often do we send our ICMP messages to receive replies?
87  */
88 #define ICMP_SEND_FREQUENCY_MS 500
89
90 struct ip_packet 
91 {
92   uint8_t vers_ihl;
93   uint8_t tos;
94   uint16_t pkt_len;
95   uint16_t id;
96   uint16_t flags_frag_offset;
97   uint8_t ttl;
98   uint8_t proto;
99   uint16_t checksum;
100   uint32_t src_ip;
101   uint32_t dst_ip;
102 };
103
104 struct icmp_packet 
105 {
106   uint8_t type;
107   uint8_t code;
108   uint16_t checksum;
109   uint32_t reserved;
110 };
111
112 struct udp_packet
113 {
114   uint16_t src_port;
115
116   uint16_t dst_port;
117
118   uint32_t length;
119 };
120
121 static Socket icmpsock;
122
123 static Socket rawsock;
124
125 static struct in_addr dummy;
126
127 static uint16_t 
128 calc_checksum(const uint16_t *data, 
129               unsigned int bytes)
130 {
131   uint32_t sum;
132   unsigned int i;
133
134   sum = 0;
135   for (i=0;i<bytes/2;i++) 
136     sum += data[i];        
137   sum = (sum & 0xffff) + (sum >> 16);
138   sum = htons(0xffff - sum);
139   return sum;
140 }
141
142 #if WIN32
143 /**
144  * @param af address family
145  * @param cp the address to print
146  * @param buf where to write the address result
147  */
148 static int inet_pton (int af, char *cp, void *buf)
149 {
150   int ret;
151   int ssize;
152
153   ssize = sizeof(struct sockaddr_storage);
154   fprintf (stderr, "in_addr size %d", ssize);
155   fprintf (stderr, "buf size %d", sizeof(buf));
156   ret = WSAStringToAddress (cp, af, NULL, (LPSOCKADDR)buf, &ssize);
157   if (ret != 0)
158     {
159
160       fprintf(stderr, "Error %d handling address %s", WSAGetLastError(), cp);
161     }
162   if (ret == 0)
163     return 1;
164   else
165     return 0;
166 }
167 #endif
168
169 static void
170 make_echo (const struct in_addr *src_ip,
171            struct icmp_packet *echo)
172 {
173   memset(echo, 0, sizeof(struct icmp_packet));
174   echo->type = ICMP_ECHO;
175   echo->code = 0;
176   echo->reserved = 0;
177   echo->checksum = 0;
178   echo->checksum = htons(calc_checksum((uint16_t*)echo, sizeof (struct icmp_packet)));
179 }
180
181
182 /**
183  * Send an ICMP message to the dummy IP.
184  *
185  * @param my_ip source address (our ip address)
186  */
187 static void
188 send_icmp_echo (const struct in_addr *my_ip)
189 {
190   struct icmp_packet icmp_echo;
191   struct sockaddr_in dst;
192   size_t off;
193   int err;
194   struct ip_packet ip_pkt;
195   struct icmp_packet icmp_pkt;
196   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
197
198   off = 0;
199   memset(&ip_pkt, 0, sizeof(ip_pkt));
200   ip_pkt.vers_ihl = 0x45;
201   ip_pkt.tos = 0;
202   ip_pkt.pkt_len = sizeof (packet);
203   ip_pkt.id = 1;
204   ip_pkt.flags_frag_offset = 0;
205   ip_pkt.ttl = IPDEFTTL;
206   ip_pkt.proto = IPPROTO_ICMP;
207   ip_pkt.checksum = 0; 
208   ip_pkt.src_ip = my_ip->s_addr;
209   ip_pkt.dst_ip = dummy.s_addr;
210   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
211   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
212   off += sizeof (ip_pkt);
213   make_echo (my_ip, &icmp_echo);
214   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
215   off += sizeof (icmp_echo);
216  
217   memset (&dst, 0, sizeof (dst));
218   dst.sin_family = AF_INET;
219   dst.sin_addr = dummy;
220   err = sendto(rawsock, 
221                packet, off, 0, 
222                (struct sockaddr*)&dst, 
223                sizeof(dst));
224   if (err < 0) 
225     {
226 #if VERBOSE
227       fprintf(stderr,
228               "sendto failed: %s\n", strerror(errno));
229 #endif
230     }
231   else if (err != off) 
232     {
233       fprintf(stderr,
234               "Error: partial send of ICMP message\n");
235     }
236 }
237
238
239 static void
240 process_icmp_response ()
241 {
242   char buf[65536];
243   ssize_t have;
244   struct in_addr sip;
245   struct ip_packet ip_pkt;
246   struct icmp_packet icmp_pkt;
247   struct udp_packet udp_pkt;
248   size_t off;
249   int have_port;
250   int have_udp;
251   uint32_t port;
252   have = read (icmpsock, buf, sizeof (buf));
253   if (have == -1)
254     {
255       fprintf (stderr,
256                "Error reading raw socket: %s\n",
257                strerror (errno));
258       return; 
259     }
260   have_port = 0;
261
262   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
263     {
264       have_port = 1;
265     }
266   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
267     {
268 #if VERBOSE
269       fprintf (stderr,
270                "Received ICMP message of unexpected size: %u bytes\n",
271                (unsigned int) have);
272 #endif
273       return;
274     }
275   off = 0;
276   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
277   off += sizeof (ip_pkt);
278   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
279   off += sizeof (icmp_pkt);
280   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
281        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
282        (icmp_pkt.code != 0) )
283     {
284       /* maybe we got an actual reply back... */
285       return;    
286     }
287   memcpy(&sip, 
288          &ip_pkt.src_ip, 
289          sizeof (sip));
290
291   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
292   off += sizeof (ip_pkt);
293
294   have_udp = 0;
295   if (ip_pkt.proto == IPPROTO_UDP)
296     {
297       have_udp = 1;
298     }
299
300   if (have_port)
301     {
302       memcpy(&port, &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], sizeof(uint32_t));
303       port = ntohs(port);
304 #ifdef WIN32
305       DWORD ssize = sizeof(buf);
306       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
307       fprintf (stdout, "%s:%d\n", buf, port);
308 #else
309       fprintf (stdout,
310               "%s:%d\n",
311               inet_ntop (AF_INET,
312                          &sip,
313                          buf,
314                          sizeof (buf)), port);
315 #endif
316     }
317   else if (have_udp)
318     {
319       memcpy(&udp_pkt, &buf[off], sizeof(udp_pkt));
320 #ifdef WIN32
321       DWORD ssize = sizeof(buf);
322       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
323       fprintf (stdout, "%s:%d\n", buf, ntohs((int)udp_pkt.length));
324 #else
325       fprintf (stdout,
326                "%s:%d\n",
327                inet_ntop (AF_INET,
328                           &sip,
329                           buf,
330                           sizeof (buf)), ntohl(udp_pkt.length));
331 #endif
332     }
333   else
334     {
335 #ifdef WIN32
336       DWORD ssize = sizeof(buf);
337       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
338       fprintf (stdout, "%s\n", buf);
339 #else
340       fprintf (stdout,
341               "%s\n",
342               inet_ntop (AF_INET,
343                          &sip,
344                          buf,
345                          sizeof (buf)));
346 #endif
347     }
348   fflush (stdout);
349 }
350
351
352 static Socket
353 make_icmp_socket ()
354 {
355   Socket ret;
356
357   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
358   if (-1 == ret)
359     {
360       fprintf (stderr,
361                "Error opening RAW socket: %s\n",
362                strerror (errno));
363       return -1;
364     }  
365 #if WIN32
366   if (ret == INVALID_SOCKET)
367     {
368       fprintf (stderr, "Invalid socket %d!\n", ret);
369       closesocket (ret);
370     }
371 #else
372   if (ret >= FD_SETSIZE) 
373     {
374       fprintf (stderr,
375                "Socket number too large (%d > %u)\n",
376                ret,
377                (unsigned int) FD_SETSIZE);
378       close (ret);
379       return -1;
380     }
381 #endif
382   return ret;
383 }
384
385
386 static Socket
387 make_raw_socket ()
388 {
389   const int one = 1;
390   Socket ret;
391
392   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
393   if (-1 == ret)
394     {
395       fprintf (stderr,
396                "Error opening RAW socket: %s\n",
397                strerror (errno));
398       return -1;
399     }  
400   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
401                  (char *)&one, sizeof(one)) == -1)
402     fprintf(stderr,
403             "setsockopt failed: %s\n",
404             strerror (errno));
405   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
406                  (char *)&one, sizeof(one)) == -1)
407     fprintf(stderr,
408             "setsockopt failed: %s\n",
409             strerror (errno));
410   return ret;
411 }
412
413
414 int
415 main (int argc, char *const *argv)
416 {
417   struct sockaddr_storage external;
418   fd_set rs;
419   struct timeval tv;
420 #ifndef WIN32
421   uid_t uid;
422 #else
423   struct sockaddr_storage saddr;
424 #endif
425
426 #ifdef WIN32
427   // WSA startup
428   WSADATA wsaData;
429   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
430   {
431       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
432       return 4;                       // ERROR
433   }
434 #endif
435
436   if (-1 == (icmpsock = make_icmp_socket()))
437     return 1; 
438   if (-1 == (rawsock = make_raw_socket()))
439     {
440       close (icmpsock);
441       return 1; 
442     }
443 #ifndef WIN32
444   uid = getuid ();
445   if (0 != setresuid (uid, uid, uid))
446     fprintf (stderr,
447              "Failed to setresuid: %s\n",
448              strerror (errno));
449 #endif
450   if (argc != 2)
451     {
452       fprintf (stderr,
453                "This program must be started with our (internal NAT) IP as the only argument.\n");
454       return 1;
455     }
456
457   if (1 != inet_pton (AF_INET, argv[1], &saddr))
458     {
459       fprintf (stderr,
460                "Error parsing IPv4 address: %s, error %s\n",
461                argv[1], strerror (errno));
462       return 1;
463     }
464
465   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) abort ();
466   while (1)
467     {
468       FD_ZERO (&rs);
469       FD_SET (icmpsock, &rs);
470       tv.tv_sec = 0;
471       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
472       select (icmpsock + 1, &rs, NULL, NULL, &tv);
473       if (FD_ISSET (icmpsock, &rs))
474         process_icmp_response ();
475       send_icmp_echo (&external);
476     }  
477
478 #ifdef WIN32
479   closesocket(icmpsock);
480   closesocket(rawsock);
481   WSACleanup ();
482 #endif
483   return 0;
484 }
485
486
487 /* end of gnunet-nat-server-windows.c */