code cleanup
[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
45 #include <winsock2.h>
46 #include <ws2tcpip.h>
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <unistd.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <errno.h>
53 #include <stdlib.h>
54 #include <stdint.h>
55 #include <time.h>
56
57 /**
58  * Should we print some debug output?
59  */
60 #define VERBOSE 0
61
62 #define IPDEFTTL 64
63
64 #define ICMP_ECHO 8
65
66 #define ICMP_TIME_EXCEEDED      11      /* Time Exceeded
67
68 /**
69  * Must match IP given in the client.
70  */
71 #define DUMMY_IP "192.0.2.86"
72
73 /**
74  * How often do we send our ICMP messages to receive replies?
75  */
76 #define ICMP_SEND_FREQUENCY_MS 500
77
78 /**
79  * IPv4 header.
80  */
81 struct ip_packet 
82 {
83
84   /**
85    * Version (4 bits) + Internet header length (4 bits) 
86    */
87   u_char vers_ihl; 
88
89   /**
90    * Type of service
91    */
92   u_char tos;  
93
94   /**
95    * Total length
96    */
97   u_short pkt_len;  
98
99   /**
100    * Identification
101    */
102   u_short id;    
103
104   /**
105    * Flags (3 bits) + Fragment offset (13 bits)
106    */
107   u_short flags_frag_offset; 
108
109   /**
110    * Time to live
111    */
112   u_char  ttl;   
113
114   /**
115    * Protocol       
116    */
117   u_char  proto; 
118
119   /**
120    * Header checksum
121    */
122   u_short checksum; 
123
124   /**
125    * Source address
126    */
127   u_long  src_ip;  
128
129   /**
130    * Destination address 
131    */
132   u_long  dst_ip;  
133 };
134
135 /**
136  * Format of ICMP packet.
137  */
138 struct icmp_packet 
139 {
140   uint8_t type;
141   uint8_t code;
142   uint16_t checksum;
143   uint32_t reserved;
144 };
145
146 /**
147  * Beginning of UDP packet.
148  */
149 struct udp_packet
150 {
151   uint16_t src_port;
152
153   uint16_t dst_port;
154
155   uint32_t length;
156 };
157
158 static SOCKET icmpsock;
159
160 static SOCKET rawsock;
161
162 static struct in_addr dummy;
163
164 /**
165  * CRC-16 for IP/ICMP headers.
166  */
167 static uint16_t 
168 calc_checksum(const uint16_t *data, 
169               unsigned int bytes)
170 {
171   uint32_t sum;
172   unsigned int i;
173
174   sum = 0;
175   for (i=0;i<bytes/2;i++) 
176     sum += data[i];        
177   sum = (sum & 0xffff) + (sum >> 16);
178   sum = htons(0xffff - sum);
179   return sum;
180 }
181
182 /**
183  * Convert IPv4 address from text to binary form.
184  *
185  * @param af address family
186  * @param cp the address to print
187  * @param buf where to write the address result
188  */
189 static int 
190 inet_pton (int af, 
191            const char *cp, 
192            struct in_addr *buf)
193 {
194   buf->s_addr = inet_addr(cp);
195   if (buf->s_addr == INADDR_NONE)
196     {
197       fprintf(stderr, 
198               "Error %d handling address %s", 
199               WSAGetLastError(), 
200               cp);
201       return 0;
202     }
203   return 1;
204 }
205
206
207 /**
208  * Send an ICMP message to the dummy IP.
209  *
210  * @param my_ip source address (our ip address)
211  */
212 static void
213 send_icmp_echo (const struct in_addr *my_ip)
214 {
215   struct icmp_packet icmp_echo;
216   struct sockaddr_in dst;
217   size_t off;
218   int err;
219   struct ip_packet ip_pkt;
220   struct icmp_packet icmp_pkt;
221   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
222
223   off = 0;
224   memset(&ip_pkt, 0, sizeof(ip_pkt));
225   ip_pkt.vers_ihl = 0x45;
226   ip_pkt.tos = 0;
227   ip_pkt.pkt_len = sizeof (packet);
228   ip_pkt.id = htons (256);
229   ip_pkt.flags_frag_offset = 0;
230   ip_pkt.ttl = IPDEFTTL;
231   ip_pkt.proto = IPPROTO_ICMP;
232   ip_pkt.checksum = 0;
233   ip_pkt.src_ip = my_ip->s_addr;
234   ip_pkt.dst_ip = dummy.s_addr;
235   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
236   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
237   off += sizeof (ip_pkt);
238
239   icmp_echo.type = ICMP_ECHO;
240   icmp_echo.code = 0;
241   icmp_echo.reserved = 0;
242   icmp_echo.checksum = 0;
243   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
244                                            sizeof (struct icmp_packet)));
245   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
246   off += sizeof (icmp_echo);
247  
248   memset (&dst, 0, sizeof (dst));
249   dst.sin_family = AF_INET;
250   dst.sin_addr = dummy;
251   err = sendto(rawsock, 
252                packet, off, 0,
253                (struct sockaddr*)&dst,
254                sizeof(dst));
255   if (err < 0) 
256     {
257 #if VERBOSE
258       fprintf(stderr,
259               "sendto failed: %s\n", strerror(errno));
260 #endif
261     }
262   else if (err != off) 
263     {
264       fprintf(stderr,
265               "Error: partial send of ICMP message\n");
266     }
267 }
268
269
270 static void
271 process_icmp_response ()
272 {
273   char buf[65536];
274   ssize_t have;
275   struct in_addr sip;
276   struct ip_packet ip_pkt;
277   struct icmp_packet icmp_pkt;
278   struct udp_packet udp_pkt;
279   size_t off;
280   int have_port;
281   int have_udp;
282   uint32_t port;
283
284   have = read (icmpsock, buf, sizeof (buf));
285   if (have == -1)
286     {
287       fprintf (stderr,
288                "Error reading raw socket: %s\n",
289                strerror (errno));
290       return; 
291     }
292   have_port = 0;
293 #if VERBOSE
294   fprintf (stderr,
295            "Received message of %u bytes\n",
296            (unsigned int) have);
297 #endif
298   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
299     {
300       have_port = 1;
301     }
302   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
303     {
304 #if VERBOSE
305       fprintf (stderr,
306                "Received ICMP message of unexpected size: %u bytes\n",
307                (unsigned int) have);
308 #endif
309       return;
310     }
311   off = 0;
312   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
313   off += sizeof (ip_pkt);
314   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
315   off += sizeof (icmp_pkt);
316   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
317        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
318        (icmp_pkt.code != 0) )
319     {
320       /* maybe we got an actual reply back... */
321       return;    
322     }
323   memcpy(&sip, 
324          &ip_pkt.src_ip, 
325          sizeof (sip));
326   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
327   off += sizeof (ip_pkt);
328   have_udp = (ip_pkt.proto == IPPROTO_UDP);
329
330   if (have_port)
331     {
332       memcpy(&port, 
333              &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], 
334              sizeof(uint32_t));
335       port = ntohs(port);
336       DWORD ssize = sizeof(buf);
337       WSAAddressToString((LPSOCKADDR)&sip, 
338                          sizeof(sip),
339                          NULL, 
340                          buf, 
341                          &ssize);
342       fprintf (stdout, 
343                "%s:%d\n",
344                buf, 
345                port);
346     }
347   else if (have_udp)
348     {
349       memcpy(&udp_pkt,
350              &buf[off],
351              sizeof(udp_pkt));
352       DWORD ssize = sizeof(buf);
353       WSAAddressToString((LPSOCKADDR)&sip, 
354                          sizeof(sip),
355                          NULL,
356                          buf, 
357                          &ssize);
358       fprintf (stdout, 
359                "%s:%d\n", 
360                buf, 
361                ntohs((int)udp_pkt.length));
362     }
363   else
364     {
365       DWORD ssize = sizeof(buf);
366       WSAAddressToString((LPSOCKADDR)&sip,
367                          sizeof(sip),
368                          NULL,
369                          buf,
370                          &ssize);
371       fprintf (stdout, 
372                "%s\n",
373                buf);
374     }
375   fflush (stdout);
376 }
377
378
379 static SOCKET
380 make_icmp_socket ()
381 {
382   SOCKET ret;
383
384   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
385   if (INVALID_SOCKET == ret)
386     {
387       fprintf (stderr,
388                "Error opening RAW socket: %s\n",
389                strerror (errno));
390       return -1;
391     }  
392   return ret;
393 }
394
395
396 static SOCKET
397 make_raw_socket ()
398 {
399   DWORD bOptVal = TRUE;
400   int bOptLen = sizeof(bOptVal);
401
402   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
403   if (INVALID_SOCKET == rawsock)
404     {
405       fprintf (stderr,
406                "Error opening RAW socket: %s\n",
407                strerror (errno));
408       return INVALID_SOCKET;
409     }
410
411   if (setsockopt(rawsock, 
412                  SOL_SOCKET, 
413                  SO_BROADCAST, 
414                  (char*)&bOptVal, bOptLen) != 0)
415     {
416       fprintf(stderr, 
417               "Error setting SO_BROADCAST to ON: %s\n",
418               strerror (errno));
419       closesocket(rawsock);
420       return INVALID_SOCKET;
421     }
422   if (setsockopt(rawsock, 
423                  IPPROTO_IP, 
424                  IP_HDRINCL, 
425                  (char*)&bOptVal, bOptLen) != 0)
426     {
427       fprintf(stderr, 
428               "Error setting IP_HDRINCL to ON: %s\n",
429               strerror (errno));
430       closesocket(rawsock);
431       return INVALID_SOCKET;
432     }
433   return rawsock;
434 }
435
436
437 int
438 main (int argc, 
439       char *const *argv)
440 {
441   struct in_addr external;
442   fd_set rs;
443   struct timeval tv;
444   WSADATA wsaData;
445
446   if (argc != 2)
447     {
448       fprintf (stderr,
449                "This program must be started with our (internal NAT) IP as the only argument.\n");
450       return 1;
451     }
452   if (1 != inet_pton (AF_INET, argv[1], &external))
453     {
454       fprintf (stderr,
455                "Error parsing IPv4 address: %s, error %s\n",
456                argv[1], strerror (errno));
457       return 1;
458     }
459   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
460     {
461       fprintf (stderr,
462                "Internal error converting dummy IP to binary.\n");
463       return 2;
464     }
465   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
466     {
467       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
468       return 2;
469     }
470   if (-1 == (icmpsock = make_icmp_socket()))
471     {
472       return 3; 
473     }
474   if (-1 == (make_raw_socket()))
475     {
476       closesocket (icmpsock);
477       return 3; 
478     }
479   while (1)
480     {
481       FD_ZERO (&rs);
482       FD_SET (icmpsock, &rs);
483       tv.tv_sec = 0;
484       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
485       if (0 != select (icmpsock + 1, &rs, NULL, NULL, &tv))
486         {
487           if (errno == EINTR)
488             continue;
489           fprintf (stderr,
490                    "select failed: %s\n",
491                    strerror (errno));
492           break;
493         }
494       if (FD_ISSET (icmpsock, &rs))
495         process_icmp_response ();
496       send_icmp_echo (&external);
497     }
498   closesocket(icmpsock);
499   closesocket(rawsock);
500   WSACleanup ();
501   return 4; /* select failed! */
502 }
503
504
505 /* end of gnunet-nat-server-windows.c */