workingish?
[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
45 #include <winsock2.h>
46 #include <ws2tcpip.h>
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <unistd.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <errno.h>
53 #include <stdlib.h>
54 #include <stdint.h>
55 #include <time.h>
56
57 typedef unsigned int uid_t;
58 typedef SOCKET Socket;
59 typedef unsigned short ushort;
60 #define IPDEFTTL 64
61 #define ICMP_ECHO 8
62 #define ICMP_TIME_EXCEEDED      11      /* Time Exceeded
63
64 /**
65  * Must match IP given in the client.
66  */
67 #define DUMMY_IP "192.0.2.86"
68
69 #define VERBOSE 1
70
71 /**
72  * How often do we send our ICMP messages to receive replies?
73  */
74 #define ICMP_SEND_FREQUENCY_MS 500
75
76 struct ip_packet 
77 {
78   /*uint8_t vers_ihl;
79   uint8_t tos;
80   uint16_t pkt_len;
81   uint16_t id;
82   uint16_t flags_frag_offset;
83   uint8_t ttl;
84   uint8_t proto;
85   uint16_t checksum;
86   uint32_t src_ip;
87   uint32_t dst_ip;*/
88
89   u_char vers_ihl;         // Version (4 bits) + Internet header length (4 bits)
90   u_char tos;             // Type of service
91   u_short pkt_len;           // Total length
92   u_short id;             // Identification
93   u_short flags_frag_offset;       // Flags (3 bits) + Fragment offset (13 bits)
94   u_char  ttl;            // Time to live
95   u_char  proto;          // Protocol
96   u_short checksum;            // Header checksum
97   u_long  src_ip;     // Source address
98   u_long  dst_ip;     // Destination address
99 };
100
101 struct icmp_packet 
102 {
103   uint8_t type;
104   uint8_t code;
105   uint16_t checksum;
106   uint32_t reserved;
107 };
108
109 struct udp_packet
110 {
111   uint16_t src_port;
112
113   uint16_t dst_port;
114
115   uint32_t length;
116 };
117
118 static Socket icmpsock;
119
120 static Socket rawsock;
121
122 static struct in_addr dummy;
123
124 static uint16_t 
125 calc_checksum(const uint16_t *data, 
126               unsigned int bytes)
127 {
128   uint32_t sum;
129   unsigned int i;
130
131   sum = 0;
132   for (i=0;i<bytes/2;i++) 
133     sum += data[i];        
134   sum = (sum & 0xffff) + (sum >> 16);
135   sum = htons(0xffff - sum);
136   return sum;
137 }
138
139 /**
140  * @param af address family
141  * @param cp the address to print
142  * @param buf where to write the address result
143  */
144 static int inet_pton (int af, char *cp, struct in_addr *buf)
145 {
146   //ret = WSAStringToAddress (cp, af, NULL, (LPSOCKADDR)buf, &ssize);
147   buf->s_addr = inet_addr(cp);
148   if (buf->s_addr == INADDR_NONE)
149     {
150       fprintf(stderr, "Error %d handling address %s", WSAGetLastError(), cp);
151       return 0;
152     }
153   else
154     return 1;
155 }
156
157 static void
158 make_echo (const struct in_addr *src_ip,
159            struct icmp_packet *echo)
160 {
161   memset(echo, 0, sizeof(struct icmp_packet));
162   echo->type = ICMP_ECHO;
163   echo->code = 0;
164   echo->reserved = 0;
165   echo->checksum = 0;
166   echo->checksum = htons(calc_checksum((uint16_t*)echo, sizeof (struct icmp_packet)));
167 }
168
169
170 /**
171  * Send an ICMP message to the dummy IP.
172  *
173  * @param my_ip source address (our ip address)
174  */
175 static void
176 send_icmp_echo (const struct in_addr *my_ip)
177 {
178   struct icmp_packet icmp_echo;
179   struct sockaddr_in dst;
180   size_t off;
181   int err;
182   struct ip_packet ip_pkt;
183   struct icmp_packet icmp_pkt;
184   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
185
186   off = 0;
187   memset(&ip_pkt, 0, sizeof(ip_pkt));
188   ip_pkt.vers_ihl = 0x45;
189   ip_pkt.tos = 0;
190   ip_pkt.pkt_len = sizeof (packet);
191   ip_pkt.id = htons (256);
192   ip_pkt.flags_frag_offset = 0;
193   ip_pkt.ttl = IPDEFTTL;
194   ip_pkt.proto = IPPROTO_ICMP;
195   ip_pkt.checksum = 0;
196   ip_pkt.src_ip = my_ip->s_addr;
197   ip_pkt.dst_ip = dummy.s_addr;
198   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
199   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
200   off += sizeof (ip_pkt);
201
202   make_echo (my_ip, &icmp_echo);
203   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
204   off += sizeof (icmp_echo);
205  
206   memset (&dst, 0, sizeof (dst));
207   dst.sin_family = AF_INET;
208   dst.sin_addr = dummy;
209   err = sendto(rawsock, 
210                packet, off, 0,
211                (struct sockaddr*)&dst,
212                sizeof(dst));
213   if (err < 0) 
214     {
215 #if VERBOSE
216       fprintf(stderr,
217               "sendto failed: %s\n", strerror(errno));
218 #endif
219     }
220   else if (err != off) 
221     {
222       fprintf(stderr,
223               "Error: partial send of ICMP message\n");
224     }
225 }
226
227
228 static void
229 process_icmp_response ()
230 {
231   char buf[65536];
232   ssize_t have;
233   struct in_addr sip;
234   struct ip_packet ip_pkt;
235   struct icmp_packet icmp_pkt;
236   struct udp_packet udp_pkt;
237   size_t off;
238   int have_port;
239   int have_udp;
240   uint32_t port;
241   have = read (icmpsock, buf, sizeof (buf));
242   if (have == -1)
243     {
244       fprintf (stderr,
245                "Error reading raw socket: %s\n",
246                strerror (errno));
247       return; 
248     }
249   have_port = 0;
250 #if VERBOSE
251   fprintf (stderr,
252            "Received message of %u bytes\n",
253            (unsigned int) have);
254 #endif
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       DWORD ssize = sizeof(buf);
298       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
299       fprintf (stdout, "%s:%d\n", buf, port);
300
301     }
302   else if (have_udp)
303     {
304       memcpy(&udp_pkt, &buf[off], sizeof(udp_pkt));
305       DWORD ssize = sizeof(buf);
306       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
307       fprintf (stdout, "%s:%d\n", buf, ntohs((int)udp_pkt.length));
308     }
309   else
310     {
311       DWORD ssize = sizeof(buf);
312       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
313       fprintf (stdout, "%s\n", buf);
314     }
315   fflush (stdout);
316 }
317
318
319 static Socket
320 make_icmp_socket ()
321 {
322   Socket ret;
323
324   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
325   if (-1 == ret)
326     {
327       fprintf (stderr,
328                "Error opening RAW socket: %s\n",
329                strerror (errno));
330       return -1;
331     }  
332   if (ret == INVALID_SOCKET)
333     {
334       fprintf (stderr, "Invalid socket %d!\n", ret);
335       closesocket (ret);
336     }
337   return ret;
338 }
339
340
341 static Socket
342 make_raw_socket ()
343 {
344   DWORD bOptVal = TRUE;
345   int bOptLen = sizeof(bOptVal);
346
347   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
348   if (-1 == rawsock)
349     {
350       fprintf (stderr,
351                "Error opening RAW socket: %s\n",
352                strerror (errno));
353       return -1;
354     }
355
356   if (setsockopt(rawsock, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen) != 0)
357     fprintf(stderr, "Error setting SO_BROADCAST: ON\n");
358
359   if (setsockopt(rawsock, IPPROTO_IP, IP_HDRINCL, (char*)&bOptVal, bOptLen) != 0)
360     fprintf(stderr, "Error setting IP_HDRINCL: ON\n");
361   return rawsock;
362 }
363
364
365 int
366 main (int argc, char *const *argv)
367 {
368   struct in_addr external;
369   fd_set rs;
370   struct timeval tv;
371
372   // WSA startup
373   WSADATA wsaData;
374   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
375   {
376       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
377       return 4;                       // ERROR
378   }
379
380   if (-1 == (icmpsock = make_icmp_socket()))
381     return 1; 
382   if (-1 == (make_raw_socket()))
383     {
384       close (icmpsock);
385       return 1; 
386     }
387
388   if (argc != 2)
389     {
390       fprintf (stderr,
391                "This program must be started with our (internal NAT) IP as the only argument.\n");
392       return 1;
393     }
394
395   if (1 != inet_pton (AF_INET, argv[1], &external))
396     {
397       fprintf (stderr,
398                "Error parsing IPv4 address: %s, error %s\n",
399                argv[1], strerror (errno));
400       return 1;
401     }
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   closesocket(icmpsock);
417   closesocket(rawsock);
418   WSACleanup ();
419   return 0;
420 }
421
422
423 /* end of gnunet-nat-server-windows.c */