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