more 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  * Must match IP given in the client.
64  */
65 #define DUMMY_IP "192.0.2.86"
66
67 /**
68  * TTL to use for our outgoing messages.
69  */
70 #define IPDEFTTL 64
71
72 #define ICMP_ECHO 8
73
74 #define ICMP_TIME_EXCEEDED      11      /* Time Exceeded */
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   uint8_t vers_ihl; 
91
92   /**
93    * Type of service
94    */
95   uint8_t tos;  
96
97   /**
98    * Total length
99    */
100   uint16_t pkt_len;  
101
102   /**
103    * Identification
104    */
105   uint16_t id;    
106
107   /**
108    * Flags (3 bits) + Fragment offset (13 bits)
109    */
110   uint16_t flags_frag_offset; 
111
112   /**
113    * Time to live
114    */
115   uint8_t  ttl;   
116
117   /**
118    * Protocol       
119    */
120   uint8_t  proto; 
121
122   /**
123    * Header checksum
124    */
125   uint16_t checksum; 
126
127   /**
128    * Source address
129    */
130   uint32_t  src_ip;  
131
132   /**
133    * Destination address 
134    */
135   uint32_t  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[off], &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   uint32_t port;
307
308   have = read (icmpsock, buf, sizeof (buf));
309   if (have == -1)
310     {
311       fprintf (stderr,
312                "Error reading raw socket: %s\n",
313                strerror (errno));
314       return; 
315     }
316   have_port = 0;
317 #if VERBOSE
318   fprintf (stderr,
319            "Received message of %u bytes\n",
320            (unsigned int) have);
321 #endif
322   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
323     {
324       have_port = 1;
325     }
326   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
327     {
328 #if VERBOSE
329       fprintf (stderr,
330                "Received ICMP message of unexpected size: %u bytes\n",
331                (unsigned int) have);
332 #endif
333       return;
334     }
335   off = 0;
336   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
337   off += sizeof (ip_pkt);
338   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
339   off += sizeof (icmp_pkt);
340   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
341        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
342        (icmp_pkt.code != 0) )
343     {
344       /* maybe we got an actual reply back... */
345       return;    
346     }
347   memcpy(&sip, 
348          &ip_pkt.src_ip, 
349          sizeof (sip));
350   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
351   off += sizeof (ip_pkt);
352
353   if (have_port)
354     {
355       memcpy(&port, 
356              &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], 
357              sizeof(uint32_t));
358       port = ntohs(port);
359       DWORD ssize = sizeof(buf);
360       WSAAddressToString((LPSOCKADDR)&sip, 
361                          sizeof(sip),
362                          NULL, 
363                          buf, 
364                          &ssize);
365       fprintf (stdout, 
366                "%s:%d\n",
367                buf, 
368                port);
369     }
370   else if (ip_pkt.proto == IPPROTO_UDP)
371     {
372       memcpy(&udp_pkt,
373              &buf[off],
374              sizeof(udp_pkt));
375       DWORD ssize = sizeof(buf);
376       WSAAddressToString((LPSOCKADDR)&sip, 
377                          sizeof(sip),
378                          NULL,
379                          buf, 
380                          &ssize);
381       fprintf (stdout, 
382                "%s:%d\n", 
383                buf, 
384                ntohs((uint16_t)udp_pkt.length));
385     }
386   else
387     {
388       DWORD ssize = sizeof(buf);
389       WSAAddressToString((LPSOCKADDR)&sip,
390                          sizeof(sip),
391                          NULL,
392                          buf,
393                          &ssize);
394       fprintf (stdout, 
395                "%s\n",
396                buf);
397     }
398   fflush (stdout);
399 }
400
401
402 /**
403  * Create an ICMP raw socket for reading.
404  *
405  * @return INVALID_SOCKET on error
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 INVALID_SOCKET;
419     }  
420   return ret;
421 }
422
423
424 /**
425  * Create an ICMP raw socket for writing.
426  *
427  * @return INVALID_SOCKET on error
428  */
429 static SOCKET
430 make_raw_socket ()
431 {
432   DWORD bOptVal = TRUE;
433   int bOptLen = sizeof(bOptVal);
434
435   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
436   if (INVALID_SOCKET == rawsock)
437     {
438       fprintf (stderr,
439                "Error opening RAW socket: %s\n",
440                strerror (errno));
441       return INVALID_SOCKET;
442     }
443
444   if (setsockopt(rawsock, 
445                  SOL_SOCKET, 
446                  SO_BROADCAST, 
447                  (char*)&bOptVal, bOptLen) != 0)
448     {
449       fprintf(stderr, 
450               "Error setting SO_BROADCAST to ON: %s\n",
451               strerror (errno));
452       closesocket(rawsock);
453       return INVALID_SOCKET;
454     }
455   if (setsockopt(rawsock, 
456                  IPPROTO_IP, 
457                  IP_HDRINCL, 
458                  (char*)&bOptVal, bOptLen) != 0)
459     {
460       fprintf(stderr, 
461               "Error setting IP_HDRINCL to ON: %s\n",
462               strerror (errno));
463       closesocket(rawsock);
464       return INVALID_SOCKET;
465     }
466   return rawsock;
467 }
468
469
470 int
471 main (int argc, 
472       char *const *argv)
473 {
474   struct in_addr external;
475   fd_set rs;
476   struct timeval tv;
477   WSADATA wsaData;
478
479   if (argc != 2)
480     {
481       fprintf (stderr,
482                "This program must be started with our (internal NAT) IP as the only argument.\n");
483       return 1;
484     }
485   if (1 != inet_pton (AF_INET, argv[1], &external))
486     {
487       fprintf (stderr,
488                "Error parsing IPv4 address: %s, error %s\n",
489                argv[1], strerror (errno));
490       return 1;
491     }
492   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
493     {
494       fprintf (stderr,
495                "Internal error converting dummy IP to binary.\n");
496       return 2;
497     }
498   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
499     {
500       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
501       return 2;
502     }
503   if (INVALID_SOCKET == (icmpsock = make_icmp_socket()))
504     {
505       return 3; 
506     }
507   if (INVALID_SOCKET == (make_raw_socket()))
508     {
509       closesocket (icmpsock);
510       return 3; 
511     }
512   while (1)
513     {
514       FD_ZERO (&rs);
515       FD_SET (icmpsock, &rs);
516       tv.tv_sec = 0;
517       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
518       if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
519         {
520           if (errno == EINTR)
521             continue;
522           fprintf (stderr,
523                    "select failed: %s\n",
524                    strerror (errno));
525           break;
526         }
527       if (FD_ISSET (icmpsock, &rs))
528         process_icmp_response ();
529       send_icmp_echo (&external);
530     }
531   /* select failed (internal error or OS out of resources) */
532   closesocket(icmpsock);
533   closesocket(rawsock);
534   WSACleanup ();
535   return 4; 
536 }
537
538
539 /* end of gnunet-nat-server-windows.c */