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
145   uint8_t code;
146
147   uint16_t checksum;
148
149   uint32_t reserved;
150 };
151
152 /**
153  * Beginning of UDP packet.
154  */
155 struct udp_packet
156 {
157   uint16_t src_port;
158
159   uint16_t dst_port;
160
161   uint32_t length;
162 };
163
164 /**
165  * Socket we use to receive "fake" ICMP replies.
166  */
167 static SOCKET icmpsock;
168
169 /**
170  * Socket we use to send our ICMP requests.
171  */
172 static SOCKET rawsock;
173
174 /**
175  * Target "dummy" address.
176  */
177 static struct in_addr dummy;
178
179
180 /**
181  * CRC-16 for IP/ICMP headers.
182  *
183  * @param data what to calculate the CRC over
184  * @param bytes number of bytes in data (must be multiple of 2)
185  * @return the CRC 16.
186  */
187 static uint16_t 
188 calc_checksum(const uint16_t *data, 
189               unsigned int bytes)
190 {
191   uint32_t sum;
192   unsigned int i;
193
194   sum = 0;
195   for (i=0;i<bytes/2;i++) 
196     sum += data[i];        
197   sum = (sum & 0xffff) + (sum >> 16);
198   sum = htons(0xffff - sum);
199   return sum;
200 }
201
202
203 /**
204  * Convert IPv4 address from text to binary form.
205  *
206  * @param af address family
207  * @param cp the address to print
208  * @param buf where to write the address result
209  * @return 1 on success
210  */
211 static int 
212 inet_pton (int af, 
213            const char *cp, 
214            struct in_addr *buf)
215 {
216   buf->s_addr = inet_addr(cp);
217   if (buf->s_addr == INADDR_NONE)
218     {
219       fprintf(stderr, 
220               "Error %d handling address %s", 
221               WSAGetLastError(), 
222               cp);
223       return 0;
224     }
225   return 1;
226 }
227
228
229 /**
230  * Send an ICMP message to the dummy IP.
231  *
232  * @param my_ip source address (our ip address)
233  */
234 static void
235 send_icmp_echo (const struct in_addr *my_ip)
236 {
237   struct icmp_packet icmp_echo;
238   struct sockaddr_in dst;
239   size_t off;
240   int err;
241   struct ip_packet ip_pkt;
242   struct icmp_packet icmp_pkt;
243   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
244
245   off = 0;
246   memset(&ip_pkt, 0, sizeof(ip_pkt));
247   ip_pkt.vers_ihl = 0x45;
248   ip_pkt.tos = 0;
249   ip_pkt.pkt_len = sizeof (packet);
250   ip_pkt.id = htons (256);
251   ip_pkt.flags_frag_offset = 0;
252   ip_pkt.ttl = IPDEFTTL;
253   ip_pkt.proto = IPPROTO_ICMP;
254   ip_pkt.checksum = 0;
255   ip_pkt.src_ip = my_ip->s_addr;
256   ip_pkt.dst_ip = dummy.s_addr;
257   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
258   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
259   off += sizeof (ip_pkt);
260
261   icmp_echo.type = ICMP_ECHO;
262   icmp_echo.code = 0;
263   icmp_echo.reserved = 0;
264   icmp_echo.checksum = 0;
265   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
266                                            sizeof (struct icmp_packet)));
267   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
268   off += sizeof (icmp_echo);
269  
270   memset (&dst, 0, sizeof (dst));
271   dst.sin_family = AF_INET;
272   dst.sin_addr = dummy;
273   err = sendto(rawsock, 
274                packet, off, 0,
275                (struct sockaddr*)&dst,
276                sizeof(dst));
277   if (err < 0) 
278     {
279 #if VERBOSE
280       fprintf(stderr,
281               "sendto failed: %s\n", strerror(errno));
282 #endif
283     }
284   else if (err != off) 
285     {
286       fprintf(stderr,
287               "Error: partial send of ICMP message\n");
288     }
289 }
290
291
292 /**
293  * We've received an ICMP response.  Process it.
294  */
295 static void
296 process_icmp_response ()
297 {
298   char buf[65536];
299   ssize_t have;
300   struct in_addr sip;
301   struct ip_packet ip_pkt;
302   struct icmp_packet icmp_pkt;
303   struct udp_packet udp_pkt;
304   size_t off;
305   int have_port;
306   int have_udp;
307   uint32_t port;
308
309   have = read (icmpsock, buf, sizeof (buf));
310   if (have == -1)
311     {
312       fprintf (stderr,
313                "Error reading raw socket: %s\n",
314                strerror (errno));
315       return; 
316     }
317   have_port = 0;
318 #if VERBOSE
319   fprintf (stderr,
320            "Received message of %u bytes\n",
321            (unsigned int) have);
322 #endif
323   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
324     {
325       have_port = 1;
326     }
327   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
328     {
329 #if VERBOSE
330       fprintf (stderr,
331                "Received ICMP message of unexpected size: %u bytes\n",
332                (unsigned int) have);
333 #endif
334       return;
335     }
336   off = 0;
337   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
338   off += sizeof (ip_pkt);
339   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
340   off += sizeof (icmp_pkt);
341   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
342        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
343        (icmp_pkt.code != 0) )
344     {
345       /* maybe we got an actual reply back... */
346       return;    
347     }
348   memcpy(&sip, 
349          &ip_pkt.src_ip, 
350          sizeof (sip));
351   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
352   off += sizeof (ip_pkt);
353   have_udp = (ip_pkt.proto == IPPROTO_UDP);
354
355   if (have_port)
356     {
357       memcpy(&port, 
358              &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], 
359              sizeof(uint32_t));
360       port = ntohs(port);
361       DWORD ssize = sizeof(buf);
362       WSAAddressToString((LPSOCKADDR)&sip, 
363                          sizeof(sip),
364                          NULL, 
365                          buf, 
366                          &ssize);
367       fprintf (stdout, 
368                "%s:%d\n",
369                buf, 
370                port);
371     }
372   else if (have_udp)
373     {
374       memcpy(&udp_pkt,
375              &buf[off],
376              sizeof(udp_pkt));
377       DWORD ssize = sizeof(buf);
378       WSAAddressToString((LPSOCKADDR)&sip, 
379                          sizeof(sip),
380                          NULL,
381                          buf, 
382                          &ssize);
383       fprintf (stdout, 
384                "%s:%d\n", 
385                buf, 
386                ntohs((int)udp_pkt.length));
387     }
388   else
389     {
390       DWORD ssize = sizeof(buf);
391       WSAAddressToString((LPSOCKADDR)&sip,
392                          sizeof(sip),
393                          NULL,
394                          buf,
395                          &ssize);
396       fprintf (stdout, 
397                "%s\n",
398                buf);
399     }
400   fflush (stdout);
401 }
402
403
404 /**
405  * Create an ICMP raw socket for reading.
406  */
407 static SOCKET
408 make_icmp_socket ()
409 {
410   SOCKET ret;
411
412   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
413   if (INVALID_SOCKET == ret)
414     {
415       fprintf (stderr,
416                "Error opening RAW socket: %s\n",
417                strerror (errno));
418       return -1;
419     }  
420   return ret;
421 }
422
423
424 /**
425  * Create an ICMP raw socket for writing.
426  */
427 static SOCKET
428 make_raw_socket ()
429 {
430   DWORD bOptVal = TRUE;
431   int bOptLen = sizeof(bOptVal);
432
433   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
434   if (INVALID_SOCKET == rawsock)
435     {
436       fprintf (stderr,
437                "Error opening RAW socket: %s\n",
438                strerror (errno));
439       return INVALID_SOCKET;
440     }
441
442   if (setsockopt(rawsock, 
443                  SOL_SOCKET, 
444                  SO_BROADCAST, 
445                  (char*)&bOptVal, bOptLen) != 0)
446     {
447       fprintf(stderr, 
448               "Error setting SO_BROADCAST to ON: %s\n",
449               strerror (errno));
450       closesocket(rawsock);
451       return INVALID_SOCKET;
452     }
453   if (setsockopt(rawsock, 
454                  IPPROTO_IP, 
455                  IP_HDRINCL, 
456                  (char*)&bOptVal, bOptLen) != 0)
457     {
458       fprintf(stderr, 
459               "Error setting IP_HDRINCL to ON: %s\n",
460               strerror (errno));
461       closesocket(rawsock);
462       return INVALID_SOCKET;
463     }
464   return rawsock;
465 }
466
467
468 int
469 main (int argc, 
470       char *const *argv)
471 {
472   struct in_addr external;
473   fd_set rs;
474   struct timeval tv;
475   WSADATA wsaData;
476
477   if (argc != 2)
478     {
479       fprintf (stderr,
480                "This program must be started with our (internal NAT) IP as the only argument.\n");
481       return 1;
482     }
483   if (1 != inet_pton (AF_INET, argv[1], &external))
484     {
485       fprintf (stderr,
486                "Error parsing IPv4 address: %s, error %s\n",
487                argv[1], strerror (errno));
488       return 1;
489     }
490   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
491     {
492       fprintf (stderr,
493                "Internal error converting dummy IP to binary.\n");
494       return 2;
495     }
496   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
497     {
498       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
499       return 2;
500     }
501   if (-1 == (icmpsock = make_icmp_socket()))
502     {
503       return 3; 
504     }
505   if (-1 == (make_raw_socket()))
506     {
507       closesocket (icmpsock);
508       return 3; 
509     }
510   while (1)
511     {
512       FD_ZERO (&rs);
513       FD_SET (icmpsock, &rs);
514       tv.tv_sec = 0;
515       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
516       if (0 != select (icmpsock + 1, &rs, NULL, NULL, &tv))
517         {
518           if (errno == EINTR)
519             continue;
520           fprintf (stderr,
521                    "select failed: %s\n",
522                    strerror (errno));
523           break;
524         }
525       if (FD_ISSET (icmpsock, &rs))
526         process_icmp_response ();
527       send_icmp_echo (&external);
528     }
529   /* select failed (internal error or OS out of resources) */
530   closesocket(icmpsock);
531   closesocket(rawsock);
532   WSACleanup ();
533   return 4; 
534 }
535
536
537 /* end of gnunet-nat-server-windows.c */