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
143 static void
144 make_echo (const struct in_addr *src_ip,
145            struct icmp_packet *echo)
146 {
147   memset(echo, 0, sizeof(struct icmp_packet));
148   echo->type = ICMP_ECHO;
149   echo->code = 0;
150   echo->reserved = 0;
151   echo->checksum = 0;
152   echo->checksum = htons(calc_checksum((uint16_t*)echo, sizeof (struct icmp_packet)));
153 }
154
155
156 /**
157  * Send an ICMP message to the dummy IP.
158  *
159  * @param my_ip source address (our ip address)
160  */
161 static void
162 send_icmp_echo (const struct in_addr *my_ip)
163 {
164   struct icmp_packet icmp_echo;
165   struct sockaddr_in dst;
166   size_t off;
167   int err;
168   struct ip_packet ip_pkt;
169   struct icmp_packet icmp_pkt;
170   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
171
172   off = 0;
173   memset(&ip_pkt, 0, sizeof(ip_pkt));
174   ip_pkt.vers_ihl = 0x45;
175   ip_pkt.tos = 0;
176   ip_pkt.pkt_len = sizeof (packet);
177   ip_pkt.id = 1;
178   ip_pkt.flags_frag_offset = 0;
179   ip_pkt.ttl = IPDEFTTL;
180   ip_pkt.proto = IPPROTO_ICMP;
181   ip_pkt.checksum = 0; 
182   ip_pkt.src_ip = my_ip->s_addr;
183   ip_pkt.dst_ip = dummy.s_addr;
184   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
185   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
186   off += sizeof (ip_pkt);
187   make_echo (my_ip, &icmp_echo);
188   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
189   off += sizeof (icmp_echo);
190  
191   memset (&dst, 0, sizeof (dst));
192   dst.sin_family = AF_INET;
193   dst.sin_addr = dummy;
194   err = sendto(rawsock, 
195                packet, off, 0, 
196                (struct sockaddr*)&dst, 
197                sizeof(dst));
198   if (err < 0) 
199     {
200 #if VERBOSE
201       fprintf(stderr,
202               "sendto failed: %s\n", strerror(errno));
203 #endif
204     }
205   else if (err != off) 
206     {
207       fprintf(stderr,
208               "Error: partial send of ICMP message\n");
209     }
210 }
211
212
213 static void
214 process_icmp_response ()
215 {
216   char buf[65536];
217   ssize_t have;
218   struct in_addr sip;
219   struct ip_packet ip_pkt;
220   struct icmp_packet icmp_pkt;
221   struct udp_packet udp_pkt;
222   size_t off;
223   int have_port;
224   int have_udp;
225   uint32_t port;
226   char addr_buf[13];
227   have = read (icmpsock, buf, sizeof (buf));
228   if (have == -1)
229     {
230       fprintf (stderr,
231                "Error reading raw socket: %s\n",
232                strerror (errno));
233       return; 
234     }
235   have_port = 0;
236
237   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
238     {
239       have_port = 1;
240     }
241   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
242     {
243 #if VERBOSE
244       fprintf (stderr,
245                "Received ICMP message of unexpected size: %u bytes\n",
246                (unsigned int) have);
247 #endif
248       return;
249     }
250   off = 0;
251   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
252   off += sizeof (ip_pkt);
253   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
254   off += sizeof (icmp_pkt);
255   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
256        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
257        (icmp_pkt.code != 0) )
258     {
259       /* maybe we got an actual reply back... */
260       return;    
261     }
262   memcpy(&sip, 
263          &ip_pkt.src_ip, 
264          sizeof (sip));
265
266   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
267   off += sizeof (ip_pkt);
268
269   have_udp = 0;
270   if (ip_pkt.proto == IPPROTO_UDP)
271     {
272       have_udp = 1;
273     }
274
275   if (have_port)
276     {
277       memcpy(&port, &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], sizeof(uint32_t));
278       port = ntohs(port);
279 #ifdef WIN32
280       memset(addr_buf, 0, 12);
281       strncpy (addr_buf, inet_ntoa (&sip), 12);
282       fprintf (stdout, "%s:%d\n", addr_buf, port);
283 #else
284       fprintf (stdout,
285               "%s:%d\n",
286               inet_ntop (AF_INET,
287                          &sip,
288                          buf,
289                          sizeof (buf)), port);
290 #endif
291     }
292   else if (have_udp)
293     {
294       memcpy(&udp_pkt, &buf[off], sizeof(udp_pkt));
295       fprintf (stdout,
296                "%s:%d\n",
297                inet_ntop (AF_INET,
298                           &sip,
299                           buf,
300                           sizeof (buf)), ntohl(udp_pkt.length));
301     }
302   else
303     {
304       fprintf (stdout,
305               "%s\n",
306               inet_ntop (AF_INET,
307                          &sip,
308                          buf,
309                          sizeof (buf)));
310     }
311   fflush (stdout);
312 }
313
314
315 static Socket
316 make_icmp_socket ()
317 {
318   Socket ret;
319
320   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
321   if (-1 == ret)
322     {
323       fprintf (stderr,
324                "Error opening RAW socket: %s\n",
325                strerror (errno));
326       return -1;
327     }  
328   if (ret >= FD_SETSIZE) 
329     {
330       fprintf (stderr,
331                "Socket number too large (%d > %u)\n",
332                ret,
333                (unsigned int) FD_SETSIZE);
334 #ifdef WIN32
335       closesocket (ret);
336 #else
337       close (ret);
338 #endif
339       return -1;
340     }
341   return ret;
342 }
343
344
345 static Socket
346 make_raw_socket ()
347 {
348   const int one = 1;
349   Socket ret;
350
351   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
352   if (-1 == ret)
353     {
354       fprintf (stderr,
355                "Error opening RAW socket: %s\n",
356                strerror (errno));
357       return -1;
358     }  
359   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
360                  (char *)&one, sizeof(one)) == -1)
361     fprintf(stderr,
362             "setsockopt failed: %s\n",
363             strerror (errno));
364   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
365                  (char *)&one, sizeof(one)) == -1)
366     fprintf(stderr,
367             "setsockopt failed: %s\n",
368             strerror (errno));
369   return ret;
370 }
371
372
373 int
374 main (int argc, char *const *argv)
375 {
376   struct in_addr external;
377   fd_set rs;
378   struct timeval tv;
379   uid_t uid;
380
381 #ifdef WIN32
382   // WSA startup
383   WSADATA wsaData;
384   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
385   {
386       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
387       return 4;                       // ERROR
388   }
389 #endif
390
391   if (-1 == (icmpsock = make_icmp_socket()))
392     return 1; 
393   if (-1 == (rawsock = make_raw_socket()))
394     {
395       close (icmpsock);
396       return 1; 
397     }
398   uid = getuid ();
399   if (0 != setresuid (uid, uid, uid))
400     fprintf (stderr,
401              "Failed to setresuid: %s\n",
402              strerror (errno));    
403   if (argc != 2)
404     {
405       fprintf (stderr,
406                "This program must be started with our (internal NAT) IP as the only argument.\n");
407       return 1;
408     }
409   if (1 != inet_pton (AF_INET, argv[1], &external))
410     {
411       fprintf (stderr,
412                "Error parsing IPv4 address: %s\n",
413                strerror (errno));
414       return 1;
415     }
416   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) abort ();
417   while (1)
418     {
419       FD_ZERO (&rs);
420       FD_SET (icmpsock, &rs);
421       tv.tv_sec = 0;
422       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
423       select (icmpsock + 1, &rs, NULL, NULL, &tv);
424       if (FD_ISSET (icmpsock, &rs))
425         process_icmp_response ();
426       send_icmp_echo (&external);
427     }  
428
429 #ifdef WIN32
430   closesocket(icmpsock);
431   closesocket(rawsock);
432   WSACleanup ();
433 #endif
434   return 0;
435 }
436
437
438 /* end of gnunet-nat-server-windows.c */