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