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