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