yes, windows still 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 1
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   u_char vers_ihl;         // Version (4 bits) + Internet header length (4 bits)
104   u_char tos;             // Type of service
105   u_short pkt_len;           // Total length
106   u_short id;             // Identification
107   u_short flags_frag_offset;       // Flags (3 bits) + Fragment offset (13 bits)
108   u_char  ttl;            // Time to live
109   u_char  proto;          // Protocol
110   u_short checksum;            // Header checksum
111   u_long  src_ip;     // Source address
112   u_long  dst_ip;     // Destination address
113 };
114
115 struct icmp_packet 
116 {
117   uint8_t type;
118   uint8_t code;
119   uint16_t checksum;
120   uint32_t reserved;
121 };
122
123 struct udp_packet
124 {
125   uint16_t src_port;
126
127   uint16_t dst_port;
128
129   uint32_t length;
130 };
131
132 static Socket icmpsock;
133
134 static Socket rawsock;
135
136 static struct in_addr dummy;
137
138 static uint16_t 
139 calc_checksum(const uint16_t *data, 
140               unsigned int bytes)
141 {
142   uint32_t sum;
143   unsigned int i;
144
145   sum = 0;
146   for (i=0;i<bytes/2;i++) 
147     sum += data[i];        
148   sum = (sum & 0xffff) + (sum >> 16);
149   sum = htons(0xffff - sum);
150   return sum;
151 }
152
153 #if WIN32
154 /**
155  * @param af address family
156  * @param cp the address to print
157  * @param buf where to write the address result
158  */
159 static int inet_pton (int af, char *cp, struct in_addr *buf)
160 {
161   //ret = WSAStringToAddress (cp, af, NULL, (LPSOCKADDR)buf, &ssize);
162   buf->s_addr = inet_addr(cp);
163   if (buf->s_addr == INADDR_NONE)
164     {
165       fprintf(stderr, "Error %d handling address %s", WSAGetLastError(), cp);
166       return 0;
167     }
168   else
169     return 1;
170 }
171 #endif
172
173 static void
174 make_echo (const struct in_addr *src_ip,
175            struct icmp_packet *echo)
176 {
177   memset(echo, 0, sizeof(struct icmp_packet));
178   echo->type = ICMP_ECHO;
179   echo->code = 0;
180   echo->reserved = 0;
181   echo->checksum = 0;
182   echo->checksum = htons(calc_checksum((uint16_t*)echo, sizeof (struct icmp_packet)));
183 }
184
185
186 /**
187  * Send an ICMP message to the dummy IP.
188  *
189  * @param my_ip source address (our ip address)
190  */
191 static void
192 send_icmp_echo (const struct in_addr *my_ip)
193 {
194   struct icmp_packet icmp_echo;
195   struct sockaddr_in dst;
196   size_t off;
197   int err;
198   struct ip_packet ip_pkt;
199   struct icmp_packet icmp_pkt;
200   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
201
202   off = 0;
203   memset(&ip_pkt, 0, sizeof(ip_pkt));
204   ip_pkt.vers_ihl = 0x45;
205   ip_pkt.tos = 0;
206   //ip_pkt.pkt_len = sizeof (packet);
207   //ip_pkt.id = 1;
208   //ip_pkt.flags_frag_offset = 0;
209   //ip_pkt.ttl = IPDEFTTL;
210   //ip_pkt.proto = IPPROTO_ICMP;
211   //ip_pkt.checksum = 0;
212   //ip_pkt.src_ip = my_ip->s_addr;
213   //ip_pkt.dst_ip = dummy.s_addr;
214   //ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
215   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
216   off += sizeof (ip_pkt);
217
218   memset (&dst, 0, sizeof (dst));
219   dst.sin_family = AF_INET;
220   dst.sin_addr = dummy;
221   err = sendto(rawsock,
222                packet, off, 0,
223                (struct sockaddr*)&dst,
224                sizeof(dst));
225
226   make_echo (my_ip, &icmp_echo);
227   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
228   off += sizeof (icmp_echo);
229  
230   memset (&dst, 0, sizeof (dst));
231   dst.sin_family = AF_INET;
232   dst.sin_addr = dummy;
233   err = sendto(rawsock, 
234                packet, off, 0,
235                (struct sockaddr*)&dst,
236                sizeof(dst));
237   if (err < 0) 
238     {
239 #if VERBOSE
240       fprintf(stderr,
241               "sendto failed: %s\n", strerror(errno));
242 #endif
243     }
244   else if (err != off) 
245     {
246       fprintf(stderr,
247               "Error: partial send of ICMP message\n");
248     }
249 }
250
251
252 static void
253 process_icmp_response ()
254 {
255   char buf[65536];
256   ssize_t have;
257   struct in_addr sip;
258   struct ip_packet ip_pkt;
259   struct icmp_packet icmp_pkt;
260   struct udp_packet udp_pkt;
261   size_t off;
262   int have_port;
263   int have_udp;
264   uint32_t port;
265   have = read (icmpsock, buf, sizeof (buf));
266   if (have == -1)
267     {
268       fprintf (stderr,
269                "Error reading raw socket: %s\n",
270                strerror (errno));
271       return; 
272     }
273   have_port = 0;
274 #if VERBOSE
275   fprintf (stderr,
276            "Received message of %u bytes\n",
277            (unsigned int) have);
278 #endif
279   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
280     {
281       have_port = 1;
282     }
283   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
284     {
285 #if VERBOSE
286       fprintf (stderr,
287                "Received ICMP message of unexpected size: %u bytes\n",
288                (unsigned int) have);
289 #endif
290       return;
291     }
292   off = 0;
293   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
294   off += sizeof (ip_pkt);
295   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
296   off += sizeof (icmp_pkt);
297   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
298        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
299        (icmp_pkt.code != 0) )
300     {
301       /* maybe we got an actual reply back... */
302       return;    
303     }
304   memcpy(&sip, 
305          &ip_pkt.src_ip, 
306          sizeof (sip));
307
308   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
309   off += sizeof (ip_pkt);
310
311   have_udp = 0;
312   if (ip_pkt.proto == IPPROTO_UDP)
313     {
314       have_udp = 1;
315     }
316
317   if (have_port)
318     {
319       memcpy(&port, &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], sizeof(uint32_t));
320       port = ntohs(port);
321 #ifdef WIN32
322       DWORD ssize = sizeof(buf);
323       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
324       fprintf (stdout, "%s:%d\n", buf, port);
325 #else
326       fprintf (stdout,
327               "%s:%d\n",
328               inet_ntop (AF_INET,
329                          &sip,
330                          buf,
331                          sizeof (buf)), port);
332 #endif
333     }
334   else if (have_udp)
335     {
336       memcpy(&udp_pkt, &buf[off], sizeof(udp_pkt));
337 #ifdef WIN32
338       DWORD ssize = sizeof(buf);
339       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
340       fprintf (stdout, "%s:%d\n", buf, ntohs((int)udp_pkt.length));
341 #else
342       fprintf (stdout,
343                "%s:%d\n",
344                inet_ntop (AF_INET,
345                           &sip,
346                           buf,
347                           sizeof (buf)), ntohl(udp_pkt.length));
348 #endif
349     }
350   else
351     {
352 #ifdef WIN32
353       DWORD ssize = sizeof(buf);
354       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
355       fprintf (stdout, "%s\n", buf);
356 #else
357       fprintf (stdout,
358               "%s\n",
359               inet_ntop (AF_INET,
360                          &sip,
361                          buf,
362                          sizeof (buf)));
363 #endif
364     }
365   fflush (stdout);
366 }
367
368
369 static Socket
370 make_icmp_socket ()
371 {
372   Socket ret;
373
374   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
375   if (-1 == ret)
376     {
377       fprintf (stderr,
378                "Error opening RAW socket: %s\n",
379                strerror (errno));
380       return -1;
381     }  
382 #if WIN32
383   if (ret == INVALID_SOCKET)
384     {
385       fprintf (stderr, "Invalid socket %d!\n", ret);
386       closesocket (ret);
387     }
388 #else
389   if (ret >= FD_SETSIZE) 
390     {
391       fprintf (stderr,
392                "Socket number too large (%d > %u)\n",
393                ret,
394                (unsigned int) FD_SETSIZE);
395       close (ret);
396       return -1;
397     }
398 #endif
399   return ret;
400 }
401
402
403 static Socket
404 make_raw_socket ()
405 {
406   const int one = 1;
407   Socket ret;
408
409   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
410   if (-1 == ret)
411     {
412       fprintf (stderr,
413                "Error opening RAW socket: %s\n",
414                strerror (errno));
415       return -1;
416     }  
417   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
418                  (char *)&one, sizeof(one)) == -1)
419     fprintf(stderr,
420             "setsockopt failed: %s\n",
421             strerror (errno));
422   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
423                  (char *)&one, sizeof(one)) == -1)
424     fprintf(stderr,
425             "setsockopt failed: %s\n",
426             strerror (errno));
427   return ret;
428 }
429
430
431 int
432 main (int argc, char *const *argv)
433 {
434   struct in_addr external;
435   fd_set rs;
436   struct timeval tv;
437 #ifndef WIN32
438   uid_t uid;
439 #endif
440
441 #ifdef WIN32
442   // WSA startup
443   WSADATA wsaData;
444   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
445   {
446       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
447       return 4;                       // ERROR
448   }
449 #endif
450
451   if (-1 == (icmpsock = make_icmp_socket()))
452     return 1; 
453   if (-1 == (rawsock = make_raw_socket()))
454     {
455       close (icmpsock);
456       return 1; 
457     }
458 #ifndef WIN32
459   uid = getuid ();
460   if (0 != setresuid (uid, uid, uid))
461     fprintf (stderr,
462              "Failed to setresuid: %s\n",
463              strerror (errno));
464 #endif
465   if (argc != 2)
466     {
467       fprintf (stderr,
468                "This program must be started with our (internal NAT) IP as the only argument.\n");
469       return 1;
470     }
471
472   if (1 != inet_pton (AF_INET, argv[1], &external))
473     {
474       fprintf (stderr,
475                "Error parsing IPv4 address: %s, error %s\n",
476                argv[1], strerror (errno));
477       return 1;
478     }
479
480   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) abort ();
481   while (1)
482     {
483       FD_ZERO (&rs);
484       FD_SET (icmpsock, &rs);
485       tv.tv_sec = 0;
486       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
487       select (icmpsock + 1, &rs, NULL, NULL, &tv);
488       if (FD_ISSET (icmpsock, &rs))
489         process_icmp_response ();
490       send_icmp_echo (&external);
491     }  
492
493 #ifdef WIN32
494   closesocket(icmpsock);
495   closesocket(rawsock);
496   WSACleanup ();
497 #endif
498   return 0;
499 }
500
501
502 /* end of gnunet-nat-server-windows.c */