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