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