windoze 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 0
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   make_echo (my_ip, &icmp_echo);
207   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
208   off += sizeof (icmp_echo);
209  
210   memset (&dst, 0, sizeof (dst));
211   dst.sin_family = AF_INET;
212   dst.sin_addr = dummy;
213   err = sendto(rawsock, 
214                packet, off, 0, 
215                (struct sockaddr*)&dst, 
216                sizeof(dst));
217   if (err < 0) 
218     {
219 #if VERBOSE
220       fprintf(stderr,
221               "sendto failed: %s\n", strerror(errno));
222 #endif
223     }
224   else if (err != off) 
225     {
226       fprintf(stderr,
227               "Error: partial send of ICMP message\n");
228     }
229 }
230
231
232 static void
233 process_icmp_response ()
234 {
235   char buf[65536];
236   ssize_t have;
237   struct in_addr sip;
238   struct ip_packet ip_pkt;
239   struct icmp_packet icmp_pkt;
240   struct udp_packet udp_pkt;
241   size_t off;
242   int have_port;
243   int have_udp;
244   uint32_t port;
245   have = read (icmpsock, buf, sizeof (buf));
246   if (have == -1)
247     {
248       fprintf (stderr,
249                "Error reading raw socket: %s\n",
250                strerror (errno));
251       return; 
252     }
253   have_port = 0;
254
255   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
256     {
257       have_port = 1;
258     }
259   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
260     {
261 #if VERBOSE
262       fprintf (stderr,
263                "Received ICMP message of unexpected size: %u bytes\n",
264                (unsigned int) have);
265 #endif
266       return;
267     }
268   off = 0;
269   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
270   off += sizeof (ip_pkt);
271   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
272   off += sizeof (icmp_pkt);
273   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
274        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
275        (icmp_pkt.code != 0) )
276     {
277       /* maybe we got an actual reply back... */
278       return;    
279     }
280   memcpy(&sip, 
281          &ip_pkt.src_ip, 
282          sizeof (sip));
283
284   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
285   off += sizeof (ip_pkt);
286
287   have_udp = 0;
288   if (ip_pkt.proto == IPPROTO_UDP)
289     {
290       have_udp = 1;
291     }
292
293   if (have_port)
294     {
295       memcpy(&port, &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], sizeof(uint32_t));
296       port = ntohs(port);
297 #ifdef WIN32
298       DWORD ssize = sizeof(buf);
299       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
300       fprintf (stdout, "%s:%d\n", buf, port);
301 #else
302       fprintf (stdout,
303               "%s:%d\n",
304               inet_ntop (AF_INET,
305                          &sip,
306                          buf,
307                          sizeof (buf)), port);
308 #endif
309     }
310   else if (have_udp)
311     {
312       memcpy(&udp_pkt, &buf[off], sizeof(udp_pkt));
313 #ifdef WIN32
314       DWORD ssize = sizeof(buf);
315       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
316       fprintf (stdout, "%s:%d\n", buf, ntohs((int)udp_pkt.length));
317 #else
318       fprintf (stdout,
319                "%s:%d\n",
320                inet_ntop (AF_INET,
321                           &sip,
322                           buf,
323                           sizeof (buf)), ntohl(udp_pkt.length));
324 #endif
325     }
326   else
327     {
328 #ifdef WIN32
329       DWORD ssize = sizeof(buf);
330       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
331       fprintf (stdout, "%s\n", buf);
332 #else
333       fprintf (stdout,
334               "%s\n",
335               inet_ntop (AF_INET,
336                          &sip,
337                          buf,
338                          sizeof (buf)));
339 #endif
340     }
341   fflush (stdout);
342 }
343
344
345 static Socket
346 make_icmp_socket ()
347 {
348   Socket ret;
349
350   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
351   if (-1 == ret)
352     {
353       fprintf (stderr,
354                "Error opening RAW socket: %s\n",
355                strerror (errno));
356       return -1;
357     }  
358 #if WIN32
359   if (ret == INVALID_SOCKET)
360     {
361       fprintf (stderr, "Invalid socket %d!\n", ret);
362       closesocket (ret);
363     }
364 #else
365   if (ret >= FD_SETSIZE) 
366     {
367       fprintf (stderr,
368                "Socket number too large (%d > %u)\n",
369                ret,
370                (unsigned int) FD_SETSIZE);
371       close (ret);
372       return -1;
373     }
374 #endif
375   return ret;
376 }
377
378
379 static Socket
380 make_raw_socket ()
381 {
382   const int one = 1;
383   Socket ret;
384
385   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
386   if (-1 == ret)
387     {
388       fprintf (stderr,
389                "Error opening RAW socket: %s\n",
390                strerror (errno));
391       return -1;
392     }  
393   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
394                  (char *)&one, sizeof(one)) == -1)
395     fprintf(stderr,
396             "setsockopt failed: %s\n",
397             strerror (errno));
398   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
399                  (char *)&one, sizeof(one)) == -1)
400     fprintf(stderr,
401             "setsockopt failed: %s\n",
402             strerror (errno));
403   return ret;
404 }
405
406
407 int
408 main (int argc, char *const *argv)
409 {
410   struct in_addr external;
411   fd_set rs;
412   struct timeval tv;
413 #ifndef WIN32
414   uid_t uid;
415 #endif
416
417 #ifdef WIN32
418   // WSA startup
419   WSADATA wsaData;
420   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
421   {
422       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
423       return 4;                       // ERROR
424   }
425 #endif
426
427   if (-1 == (icmpsock = make_icmp_socket()))
428     return 1; 
429   if (-1 == (rawsock = make_raw_socket()))
430     {
431       close (icmpsock);
432       return 1; 
433     }
434 #ifndef WIN32
435   uid = getuid ();
436   if (0 != setresuid (uid, uid, uid))
437     fprintf (stderr,
438              "Failed to setresuid: %s\n",
439              strerror (errno));
440 #endif
441   if (argc != 2)
442     {
443       fprintf (stderr,
444                "This program must be started with our (internal NAT) IP as the only argument.\n");
445       return 1;
446     }
447
448   if (1 != inet_pton (AF_INET, argv[1], &external))
449     {
450       fprintf (stderr,
451                "Error parsing IPv4 address: %s, error %s\n",
452                argv[1], strerror (errno));
453       return 1;
454     }
455
456   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) abort ();
457   while (1)
458     {
459       FD_ZERO (&rs);
460       FD_SET (icmpsock, &rs);
461       tv.tv_sec = 0;
462       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
463       select (icmpsock + 1, &rs, NULL, NULL, &tv);
464       if (FD_ISSET (icmpsock, &rs))
465         process_icmp_response ();
466       send_icmp_echo (&external);
467     }  
468
469 #ifdef WIN32
470   closesocket(icmpsock);
471   closesocket(rawsock);
472   WSACleanup ();
473 #endif
474   return 0;
475 }
476
477
478 /* end of gnunet-nat-server-windows.c */