a2235bf385b082f1f210aba66852cdfea990251a
[oweals/gnunet.git] / src / exit / gnunet-helper-exit-windows.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010, 2012 Christian Grothoff
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  * @file exit/gnunet-helper-exit-windows.c
22  * @brief the helper for the EXIT service in win32 builds. 
23  * Opens a virtual network-interface, sends data received on the if to stdout, 
24  * sends data received on stdin to the interface
25  * @author Christian M. Fuchs
26  *
27  * The following list of people have reviewed this code and considered
28  * it safe since the last modification (if you reviewed it, please
29  * have your name added to the list):
30  *
31  */
32 #include <stdio.h>
33 #include <windows.h>
34 #include <setupapi.h>
35 #include <ddk/cfgmgr32.h>
36 #include <ddk/newdev.h>
37 #include <Winsock2.h>
38 #include <time.h>
39 #include "platform.h"
40 #include "tap-windows.h"
41 /**
42  * Need 'struct GNUNET_MessageHeader'.
43  */
44 #include "gnunet_common.h"
45
46 /**
47  * Need VPN message types.
48  */
49 #include "gnunet_protocols.h"
50
51 /**
52  * Should we print (interesting|debug) messages that can happen during
53  * normal operation?
54  */
55 #define DEBUG GNUNET_NO
56
57 #if DEBUG
58 /* FIXME: define with varargs... */
59 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
60 #else
61 #define LOG_DEBUG(msg) do {} while (0)
62 #endif
63
64
65 /**
66  * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
67  */
68 #define MAX_SIZE 65536
69
70 /**
71  * Name or Path+Name of our win32 driver.
72  * The .sys and .cat files HAVE to be in the same location as this file!
73  */
74 #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
75
76 /**
77  * Name or Path+Name of our win64 driver.
78  * The .sys and .cat files HAVE to be in the same location as this file!
79  */
80 #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
81
82 /**
83  * Hardware ID used in the inf-file. 
84  * This might change over time, as openvpn advances their driver
85  */
86 #define HARDWARE_ID "tap0901"
87
88 /**
89  * Minimum major-id of the driver version we can work with
90  */
91 #define TAP_WIN_MIN_MAJOR 9
92
93 /**
94  * Minimum minor-id of the driver version we can work with. 
95  * v <= 7 has buggy IPv6.
96  * v == 8 is broken for small IPv4 Packets
97  */
98 #define TAP_WIN_MIN_MINOR 9
99
100 /**
101  * Time in seconds to wait for our virtual device to go up after telling it to do so.
102  * 
103  * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
104  * (in fact, 4 was chosen by a fair dice roll...)
105  */
106 #define TAP32_POSTUP_WAITTIME 4
107
108 /**
109  * Location of the network interface list resides in registry.
110  */
111 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
112
113 /**
114  * Our local process' PID. Used for creating a sufficiently unique additional 
115  * hardware ID for our device.
116  */
117 static char secondary_hwid[LINE_LEN / 2];
118
119 /**
120  * Device's visible Name, used to identify a network device in netsh.
121  * eg: "Local Area Connection 9"
122  */
123 static char device_visible_name[256];
124
125 /** 
126  * This is our own local instance of a virtual network interface
127  * It is (somewhat) equivalent to using tun/tap in unixoid systems
128  * 
129  * Upon initialization, we create such an device node.
130  * Upon termination, we remove it again.
131  * 
132  * If we crash this device might stay around.
133  */
134 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
135
136 /**
137  * Registry Key we hand over to windows to spawn a new virtual interface
138  */
139 static SP_DEVINFO_DATA DeviceNode;
140
141 /**
142  * GUID of our virtual device in the form of 
143  * {12345678-1234-1234-1234-123456789abc} - in hex
144  */
145 static char device_guid[256];
146
147
148 /**
149  * Possible states of an IO facility.
150  */
151 enum IO_State
152 {
153
154   /** 
155    * overlapped I/O is ready for work 
156    */
157   IOSTATE_READY = 0,
158
159   /** 
160    * overlapped I/O has been queued 
161    */
162   IOSTATE_QUEUED,
163
164   /** 
165    * overlapped I/O has finished, but is waiting for it's write-partner 
166    */
167   IOSTATE_WAITING, 
168   
169   /** 
170    * there is a full buffer waiting
171    */
172   IOSTATE_RESUME,
173
174   /** 
175    * Operlapped IO states for facility objects
176    * overlapped I/O has failed, stop processing 
177    */
178   IOSTATE_FAILED 
179
180 };
181
182
183 /** 
184  * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
185  */
186 struct io_facility
187 {
188   /**
189    * The mode the state machine associated with this object is in.
190    */
191   enum IO_State facility_state;
192
193   /**
194    * If the path is open or blocked in general (used for quickly checking)
195    */
196   BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
197
198   /**
199    * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
200    */
201   HANDLE handle;
202
203   /**
204    * Overlaped IO structure used for asynchronous IO in windows.
205    */
206   OVERLAPPED overlapped;
207
208   /**
209    * Buffer for reading things to and writing from...
210    */
211   unsigned char buffer[MAX_SIZE];
212
213   /**
214    * How much of this buffer was used when reading or how much data can be written
215    */
216   DWORD buffer_size;
217
218   /**
219    * Amount of data actually written or read by readfile/writefile.
220    */
221   DWORD buffer_size_processed;
222   
223   /**
224    * How much of this buffer we have written in total
225    */
226   DWORD buffer_size_written;
227 };
228
229 /**
230  * ReOpenFile is only available as of XP SP2 and 2003 SP1
231  */
232 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
233
234 /**
235  * IsWow64Process definition for our is_win64, as this is a kernel function
236  */
237 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
238
239 /**
240  * Determines if the host OS is win32 or win64
241  * 
242  * @return true if 
243  */
244 BOOL
245 is_win64 ()
246 {
247 #if defined(_WIN64)
248   //this is a win64 binary, 
249   return TRUE; 
250 #elif defined(_WIN32)
251   //this is a 32bit binary, and we need to check if we are running in WOW64
252   BOOL success = FALSE;
253   BOOL on_wow64 = FALSE;
254   LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
255   
256   if (NULL != IsWow64Process)
257       success = IsWow64Process (GetCurrentProcess (), &on_wow64);
258   
259   return success && on_wow64;
260 #endif
261 }
262 /**
263  * Wrapper for executing a shellcommand in windows.
264  * 
265  * @param command - the command + parameters to execute
266  * @return * exitcode of the program executed, 
267  *         * EINVAL (cmd/file not found)
268  *         * EPIPE (could not read STDOUT)
269  */
270 static int
271 execute_shellcommand (const char *command)
272 {
273   FILE *pipe;
274
275   if ( (NULL == command) ||
276        (NULL == (pipe = _popen (command, "rt"))) )
277     return EINVAL;
278
279 #if DEBUG
280   fprintf (stderr, "DEBUG: Command output: \n");
281   char output[LINE_LEN];
282   while (NULL != fgets (output, sizeof (output), pipe))
283     fprintf (stderr, "%s", output);
284 #endif
285
286   return _pclose (pipe);
287 }
288
289
290 /**
291  * @brief Sets the IPv6-Address given in address on the interface dev
292  *
293  * @param address the IPv6-Address
294  * @param prefix_len the length of the network-prefix
295  */
296 static int
297 set_address6 (const char *address, unsigned long prefix_len)
298 {
299   int ret = EINVAL;
300   char command[LINE_LEN];
301   struct sockaddr_in6 sa6;
302
303   /*
304    * parse the new address
305    */
306   memset (&sa6, 0, sizeof (struct sockaddr_in6));
307   sa6.sin6_family = AF_INET6;
308   if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
309     {
310       fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
311                strerror (errno));
312       return -1;
313     }
314
315   /*
316    * prepare the command
317    */
318   snprintf (command, LINE_LEN,
319             "netsh interface ipv6 add address \"%s\" %s/%d store=active",
320             device_visible_name, address, prefix_len);
321   /*
322    * Set the address
323    */
324   ret = execute_shellcommand (command);
325
326   /* Did it work?*/
327   if (0 != ret)
328     fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
329   return ret;
330 }
331
332
333 /**
334  * @brief Removes the IPv6-Address given in address from the interface dev
335  *
336  * @param address the IPv4-Address
337  */
338 static void
339 remove_address6 (const char *address)
340 {
341   char command[LINE_LEN];
342   int ret = EINVAL;
343
344   // sanity checking was already done in set_address6
345   /*
346    * prepare the command
347    */
348   snprintf (command, LINE_LEN,
349             "netsh interface ipv6 delete address \"%s\" store=persistent",
350             device_visible_name, address);
351   /*
352    * Set the address
353    */
354   ret = execute_shellcommand (command);
355
356   /* Did it work?*/
357   if (0 != ret)
358     fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
359 }
360
361
362 /**
363  * @brief Sets the IPv4-Address given in address on the interface dev
364  *
365  * @param address the IPv4-Address
366  * @param mask the netmask
367  */
368 static int
369 set_address4 (const char *address, const char *mask)
370 {
371   int ret = EINVAL;
372   char command[LINE_LEN];
373
374   struct sockaddr_in addr;
375   addr.sin_family = AF_INET;
376
377   /*
378    * Parse the address
379    */
380   if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
381     {
382       fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
383                strerror (errno));
384       return -1;
385     }
386   // Set Device to Subnet-Mode? 
387   // do we really need tun.c:2925 ?
388
389   /*
390    * prepare the command
391    */
392   snprintf (command, LINE_LEN,
393             "netsh interface ipv4 add address \"%s\" %s %s store=active",
394             device_visible_name, address, mask);
395   /*
396    * Set the address
397    */
398   ret = execute_shellcommand (command);
399
400   /* Did it work?*/
401   if (0 != ret)
402     fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
403   return ret;
404 }
405
406
407 /**
408  * @brief Removes the IPv4-Address given in address from the interface dev
409  *
410  * @param address the IPv4-Address
411  */
412 static void
413 remove_address4 (const char *address)
414 {
415   char command[LINE_LEN];
416   int ret = EINVAL;
417
418   // sanity checking was already done in set_address4
419
420   /*
421    * prepare the command
422    */
423   snprintf (command, LINE_LEN,
424             "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
425             device_visible_name, address);
426   /*
427    * Set the address
428    */
429   ret = execute_shellcommand (command);
430
431   /* Did it work?*/
432   if (0 != ret)
433     fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
434 }
435
436
437 /**
438  * Setup a new virtual interface to use for tunneling. 
439  * 
440  * @return: TRUE if setup was successful, else FALSE
441  */
442 static BOOL
443 setup_interface ()
444 {
445   /*
446    * where to find our inf-file. (+ the "full" path, after windows found")
447    * 
448    * We do not directly input all the props here, because openvpn will update
449    * these details over time.
450    */
451   char inf_file_path[MAX_PATH];
452   char * temp_inf_filename;
453   char hwidlist[LINE_LEN + 4];
454   char class_name[128];
455   GUID class_guid;
456   int str_length = 0;
457
458   /** 
459    * Set the device's hardware ID and add it to a list.
460    * This information will later on identify this device in registry. 
461    */
462   strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
463   /**
464    * this is kind of over-complicated, but allows keeps things independent of 
465    * how the openvpn-hwid is actually stored. 
466    * 
467    * A HWID list is double-\0 terminated and \0 separated
468    */
469   str_length = strlen (hwidlist) + 1;
470   strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
471   str_length += strlen (&hwidlist[str_length]) + 1;
472   
473   /** 
474    * Locate the inf-file, we need to store it somewhere where the system can
475    * find it. We need to pick the correct driver for win32/win64.
476    */
477   if (is_win64())
478     GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
479   else
480     GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
481
482   fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
483   /** 
484    * Bootstrap our device info using the drivers inf-file
485    */
486   if ( ! SetupDiGetINFClassA (inf_file_path,
487                             &class_guid,
488                             class_name, sizeof (class_name) / sizeof (char),
489                             NULL))
490     return FALSE;
491
492   /** 
493    * Collect all the other needed information... 
494    * let the system fill our this form 
495    */
496   DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
497   if (DeviceInfo == INVALID_HANDLE_VALUE)
498     return FALSE;
499
500   DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
501   if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
502                                  class_name,
503                                  &class_guid,
504                                  NULL,
505                                  0,
506                                  DICD_GENERATE_ID,
507                                  &DeviceNode))
508     return FALSE;
509
510   /* Deploy all the information collected into the registry */
511   if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
512                                           &DeviceNode,
513                                           SPDRP_HARDWAREID,
514                                           (LPBYTE) hwidlist,
515                                           str_length * sizeof (char)))
516     return FALSE;
517
518   /* Install our new class(=device) into the system */
519   if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
520                                   DeviceInfo,
521                                   &DeviceNode))
522     return FALSE;
523
524   /* This system call tends to take a while (several seconds!) on
525      "modern" Windoze systems */
526   if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
527                                            secondary_hwid,
528                                            inf_file_path,
529                                            INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
530                                            NULL)) //reboot required? NEVER!
531     return FALSE;
532
533   fprintf (stderr, "DEBUG: successfully created a network device\n");
534   return TRUE;
535 }
536
537
538 /**
539  * Remove our new virtual interface to use for tunneling. 
540  * This function must be called AFTER setup_interface!
541  * 
542  * @return: TRUE if destruction was successful, else FALSE
543  */
544 static BOOL
545 remove_interface ()
546 {
547   SP_REMOVEDEVICE_PARAMS remove;
548
549   if (INVALID_HANDLE_VALUE == DeviceInfo)
550     return FALSE;
551
552   remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
553   remove.HwProfile = 0;
554   remove.Scope = DI_REMOVEDEVICE_GLOBAL;
555   remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
556   /*
557    * 1. Prepare our existing device information set, and place the 
558    *    uninstall related information into the structure
559    */
560   if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
561                                       (PSP_DEVINFO_DATA) & DeviceNode,
562                                       &remove.ClassInstallHeader,
563                                       sizeof (remove)))
564     return FALSE;
565   /*
566    * 2. Uninstall the virtual interface using the class installer
567    */
568   if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
569                                   DeviceInfo,
570                                   (PSP_DEVINFO_DATA) & DeviceNode))
571     return FALSE;
572
573   SetupDiDestroyDeviceInfoList (DeviceInfo);
574   
575   fprintf (stderr, "DEBUG: removed interface successfully\n");
576
577   return TRUE;
578 }
579
580
581 /**
582  * Do all the lookup necessary to retrieve the inteface's actual name
583  * off the registry. 
584  * 
585  * @return: TRUE if we were able to lookup the interface's name, else FALSE
586  */
587 static BOOL
588 resolve_interface_name ()
589 {
590   SP_DEVINFO_LIST_DETAIL_DATA device_details;
591   char pnp_instance_id [MAX_DEVICE_ID_LEN];
592   HKEY adapter_key_handle;
593   LONG status;
594   DWORD len;
595   int i = 0;
596   int retrys;
597   BOOL retval = FALSE;
598   char adapter[] = INTERFACE_REGISTRY_LOCATION;
599
600   /* We can obtain the PNP instance ID from our setupapi handle */
601   device_details.cbSize = sizeof (device_details);
602   if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
603                                           (PCHAR) pnp_instance_id,
604                                           MAX_DEVICE_ID_LEN,
605                                           0, //must be 0
606                                           NULL)) //hMachine, we are local
607     return FALSE;
608   
609   fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
610
611   /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
612   for (retrys = 0; retrys < 120 && !retval; retrys++)
613     {
614       /* sleep for 250ms*/
615       Sleep (250);
616
617       /* Now we can use this ID to locate the correct networks interface in registry */
618       if (ERROR_SUCCESS != RegOpenKeyExA (
619                                           HKEY_LOCAL_MACHINE,
620                                           adapter,
621                                           0,
622                                           KEY_READ,
623                                           &adapter_key_handle))
624         return FALSE;
625
626       /* Of course there is a multitude of entries here, with arbitrary names, 
627        * thus we need to iterate through there.
628        */
629       while (!retval)
630         {
631           char instance_key[256];
632           char query_key [256];
633           HKEY instance_key_handle;
634           char pnpinstanceid_name[] = "PnpInstanceID";
635           char pnpinstanceid_value[256];
636           char adaptername_name[] = "Name";
637           DWORD data_type;
638
639           len = 256 * sizeof (char);
640           /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
641           status = RegEnumKeyExA (
642                                   adapter_key_handle,
643                                   i,
644                                   instance_key,
645                                   &len,
646                                   NULL,
647                                   NULL,
648                                   NULL,
649                                   NULL);
650
651           /* this may fail due to one of two reasons: 
652            * we are at the end of the list*/
653           if (ERROR_NO_MORE_ITEMS == status)
654             break;
655           // * we found a broken registry key, continue with the next key.
656           if (ERROR_SUCCESS != status)
657             goto cleanup;
658
659           /* prepare our new query string: */
660           snprintf (query_key, 256, "%s\\%s\\Connection",
661                     adapter,
662                     instance_key);
663
664           /* look inside instance_key\\Connection */
665           if (ERROR_SUCCESS != RegOpenKeyExA (
666                                   HKEY_LOCAL_MACHINE,
667                                   query_key,
668                                   0,
669                                   KEY_READ,
670                                   &instance_key_handle))
671             goto cleanup;
672
673           /* now, read our PnpInstanceID */
674           len = sizeof (pnpinstanceid_value);
675           status = RegQueryValueExA (instance_key_handle,
676                                      pnpinstanceid_name,
677                                      NULL, //reserved, always NULL according to MSDN
678                                      &data_type,
679                                      (LPBYTE) pnpinstanceid_value,
680                                      &len);
681
682           if (status != ERROR_SUCCESS || data_type != REG_SZ)
683             goto cleanup;
684
685           /* compare the value we got to our devices PNPInstanceID*/
686           if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
687                             sizeof (pnpinstanceid_value) / sizeof (char)))
688             goto cleanup;
689
690           len = sizeof (device_visible_name);
691           status = RegQueryValueExA (
692                                      instance_key_handle,
693                                      adaptername_name,
694                                      NULL, //reserved, always NULL according to MSDN
695                                      &data_type,
696                                      (LPBYTE) device_visible_name,
697                                      &len);
698
699           if (status != ERROR_SUCCESS || data_type != REG_SZ)
700             goto cleanup;
701
702           /* 
703            * we have successfully found OUR instance, 
704            * save the device GUID before exiting
705            */
706
707           strncpy (device_guid, instance_key, 256);
708           retval = TRUE;
709           fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
710
711 cleanup:
712           RegCloseKey (instance_key_handle);
713
714           ++i;
715         }
716
717       RegCloseKey (adapter_key_handle);
718     }
719   return retval;
720 }
721
722
723 /**
724  * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
725  * 
726  * @param handle the handle to our tap device
727  * @return TRUE if the version is sufficient, else FALSE
728  */
729 static BOOL
730 check_tapw32_version (HANDLE handle)
731 {
732   ULONG version[3];
733   DWORD len;
734   memset (&(version), 0, sizeof (version));
735
736   if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
737                        &version, sizeof (version),
738                        &version, sizeof (version), &len, NULL))
739       fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
740                (int) version[0],
741                (int) version[1],
742                (version[2] ? "(DEBUG)" : ""));
743
744   if ((version[0] != TAP_WIN_MIN_MAJOR) ||
745       (version[1] < TAP_WIN_MIN_MINOR )){
746       fprintf (stderr, "FATAL:  This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
747                TAP_WIN_MIN_MAJOR,
748                TAP_WIN_MIN_MINOR);
749       return FALSE;
750     }
751       
752   return TRUE;
753 }
754
755
756 /**
757  * Creates a tun-interface called dev;
758  *
759  * @return the fd to the tun or -1 on error
760  */
761 static HANDLE
762 init_tun ()
763 {
764   char device_path[256];
765   HANDLE handle;
766
767   if (! setup_interface ())
768     {
769       errno = ENODEV;
770       return INVALID_HANDLE_VALUE;
771     }
772
773   if (! resolve_interface_name ())
774     {
775       errno = ENODEV;
776       return INVALID_HANDLE_VALUE;
777     }
778
779   /* Open Windows TAP-Windows adapter */
780   snprintf (device_path, sizeof (device_path), "%s%s%s",
781             USERMODEDEVICEDIR,
782             device_guid,
783             TAP_WIN_SUFFIX);
784
785   handle = CreateFile (
786                        device_path,
787                        GENERIC_READ | GENERIC_WRITE,
788                        0, /* was: FILE_SHARE_READ */
789                        0,
790                        OPEN_EXISTING,
791                        FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
792                        0
793                        );
794
795   if (INVALID_HANDLE_VALUE == handle)
796     {
797       fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
798       return handle;
799     }
800
801   /* get driver version info */
802   if (! check_tapw32_version (handle))
803     {
804       CloseHandle (handle);
805       return INVALID_HANDLE_VALUE;
806     }
807
808   /* TODO (opt?): get MTU-Size */
809
810   fprintf (stderr, "DEBUG: successfully opened TAP device\n");
811   return handle;
812 }
813
814
815 /**
816  * Brings a TAP device up and sets it to connected state.
817  * 
818  * @param handle the handle to our TAP device 
819  * @return True if the operation succeeded, else false
820  */
821 static BOOL
822 tun_up (HANDLE handle)
823 {
824   ULONG status = TRUE;
825   DWORD len;
826   if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
827                         &status, sizeof (status),
828                         &status, sizeof (status), &len, NULL))
829     {
830       fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
831       return FALSE;
832     }
833
834   /* Wait for the device to go UP, might take some time. */
835   Sleep (TAP32_POSTUP_WAITTIME * 1000);
836   fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
837
838   return TRUE;
839 }
840
841
842 /**
843  * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
844  * 
845  * 1. 
846  * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
847  * input handle. Then it goes into IOSTATE_QUEUED state. 
848  * In case the read succeeded instantly the input facility enters 3.
849  * 
850  * 2. 
851  * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
852  * If it has finished, go to state 3.
853  * If it has failed, set IOSTATE_FAILED
854  * 
855  * 3.
856  * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
857  *   The input facility enters state IOSTATE_READY
858  *   The output facility enters state IOSTATE_READY
859  * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
860  * 
861  * IOSTATE_WAITING is reset by the output facility, once it has completed.
862  * 
863  * @param input_facility input named pipe or file to work with.
864  * @param output_facility output pipe or file to hand over data to.
865  * @return false if an event reset was impossible (OS error), else true
866  */
867 static BOOL
868 attempt_read_tap (struct io_facility * input_facility,
869                   struct io_facility * output_facility)
870 {
871   struct GNUNET_MessageHeader * hdr;
872   unsigned short size;
873   
874   switch (input_facility->facility_state)
875     {
876     case IOSTATE_READY:
877       { 
878         if (! ResetEvent (input_facility->overlapped.hEvent))
879           {
880             return FALSE;
881           }
882
883         input_facility->buffer_size = 0;
884
885         /* Check how the task is handled */
886         if (ReadFile (input_facility->handle,
887                       input_facility->buffer,
888                       sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
889                       &input_facility->buffer_size,
890                       &input_facility->overlapped))
891           {/* async event processed immediately*/
892
893             /* reset event manually*/
894             if (! SetEvent (input_facility->overlapped.hEvent))
895               return FALSE;
896             
897             fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
898             
899             /* we successfully read something from the TAP and now need to
900              * send it our via STDOUT. Is that possible at the moment? */
901             if ((IOSTATE_READY == output_facility->facility_state ||
902                  IOSTATE_WAITING == output_facility->facility_state)
903                 && (0 < input_facility->buffer_size))
904               { /* hand over this buffers content and apply message header for gnunet */
905                 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
906                 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
907                 
908                 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
909                         input_facility->buffer,
910                         input_facility->buffer_size);
911
912                 output_facility->buffer_size = size;
913                 hdr->size = htons (size);
914                 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
915                 output_facility->facility_state = IOSTATE_READY;
916               }
917             else if (0 < input_facility->buffer_size)
918                 /* If we have have read our buffer, wait for our write-partner*/
919                 input_facility->facility_state = IOSTATE_WAITING;
920           }
921         else /* operation was either queued or failed*/
922           {
923             int err = GetLastError ();
924             if (ERROR_IO_PENDING == err)
925               { /* operation queued */
926                 input_facility->facility_state = IOSTATE_QUEUED;
927               }
928             else
929               { /* error occurred, let the rest of the elements finish */
930                 input_facility->path_open = FALSE;
931                 input_facility->facility_state = IOSTATE_FAILED;
932                 if (IOSTATE_WAITING == output_facility->facility_state)
933                   output_facility->path_open = FALSE;
934
935                 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
936               }
937           }
938       }
939       return TRUE;
940       // We are queued and should check if the read has finished
941     case IOSTATE_QUEUED:
942       {
943         // there was an operation going on already, check if that has completed now.
944
945         if (GetOverlappedResult (input_facility->handle,
946                                  &input_facility->overlapped,
947                                  &input_facility->buffer_size,
948                                  FALSE))
949           {/* successful return for a queued operation */
950             if (! ResetEvent (input_facility->overlapped.hEvent))
951               return FALSE;
952
953             fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
954             
955             /* we successfully read something from the TAP and now need to
956              * send it our via STDOUT. Is that possible at the moment? */
957             if ((IOSTATE_READY == output_facility->facility_state ||
958                  IOSTATE_WAITING == output_facility->facility_state)
959                 && 0 < input_facility->buffer_size)
960               { /* hand over this buffers content and apply message header for gnunet */
961                 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
962                 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
963                 
964                 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
965                         input_facility->buffer,
966                         input_facility->buffer_size);
967
968                 output_facility->buffer_size = size;
969                 hdr->size = htons(size);
970                 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
971                 output_facility->facility_state = IOSTATE_READY;
972                 input_facility->facility_state = IOSTATE_READY;
973               }
974             else if (0 < input_facility->buffer_size)
975               { /* If we have have read our buffer, wait for our write-partner*/
976                 input_facility->facility_state = IOSTATE_WAITING;
977                 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
978               }
979           }
980         else
981           { /* operation still pending/queued or failed? */
982             int err = GetLastError ();
983             if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
984               { /* error occurred, let the rest of the elements finish */
985                 input_facility->path_open = FALSE;
986                 input_facility->facility_state = IOSTATE_FAILED;
987                 if (IOSTATE_WAITING == output_facility->facility_state)
988                   output_facility->path_open = FALSE;
989                 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
990               }
991           }
992       }
993       return TRUE;
994     case IOSTATE_RESUME:
995       hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
996       size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
997
998       memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
999               input_facility->buffer,
1000               input_facility->buffer_size);
1001
1002       output_facility->buffer_size = size;
1003       hdr->size = htons (size);
1004       hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1005       output_facility->facility_state = IOSTATE_READY;
1006       input_facility->facility_state = IOSTATE_READY;
1007       return TRUE;
1008     default:
1009       return TRUE;
1010     }
1011 }
1012
1013
1014 /**
1015  * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1016  * 
1017  * 1. 
1018  * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1019  * input handle. Then it goes into IOSTATE_QUEUED state. 
1020  * In case the read succeeded instantly the input facility enters 3.
1021  * 
1022  * 2. 
1023  * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1024  * If it has finished, go to state 3.
1025  * If it has failed, set IOSTATE_FAILED
1026  * 
1027  * 3.
1028  * If the facility is finished with ready
1029  *   The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1030  *   The input facility enters state IOSTATE_READY
1031  *   The output facility enters state IOSTATE_READY
1032  * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1033  * 
1034  * IOSTATE_WAITING is reset by the output facility, once it has completed.
1035  * 
1036  * @param input_facility input named pipe or file to work with.
1037  * @param output_facility output pipe or file to hand over data to.
1038  * @return false if an event reset was impossible (OS error), else true
1039  */
1040 static BOOL
1041 attempt_read_stdin (struct io_facility * input_facility,
1042                     struct io_facility * output_facility)
1043 {
1044   struct GNUNET_MessageHeader * hdr;
1045   
1046   switch (input_facility->facility_state)
1047     {
1048     case IOSTATE_READY:
1049       {
1050         input_facility->buffer_size = 0;
1051         
1052 partial_read_iostate_ready:
1053         if (! ResetEvent (input_facility->overlapped.hEvent))
1054           return FALSE;
1055        
1056         /* Check how the task is handled */
1057         if (ReadFile (input_facility->handle,
1058                            input_facility->buffer + input_facility->buffer_size,
1059                            sizeof (input_facility->buffer) - input_facility->buffer_size,
1060                            &input_facility->buffer_size_processed,
1061                            &input_facility->overlapped))
1062           {/* async event processed immediately*/
1063             hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1064
1065             /* reset event manually*/
1066             if (!SetEvent (input_facility->overlapped.hEvent))
1067               return FALSE;
1068
1069             fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1070             input_facility->buffer_size += input_facility->buffer_size_processed;
1071
1072             if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1073                 ntohs (hdr->size) > sizeof (input_facility->buffer))
1074               {
1075                 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1076                 input_facility->facility_state = IOSTATE_READY;
1077                 return TRUE;
1078               }
1079             /* we got the a part of a packet */
1080             if (ntohs (hdr->size) > input_facility->buffer_size)
1081               goto partial_read_iostate_ready;
1082
1083             /* have we read more than 0 bytes of payload? (sizeread > header)*/
1084             if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1085                 ((IOSTATE_READY == output_facility->facility_state) ||
1086                  (IOSTATE_WAITING == output_facility->facility_state)))
1087               {/* we successfully read something from the TAP and now need to
1088              * send it our via STDOUT. Is that possible at the moment? */
1089
1090                 /* hand over this buffers content and strip gnunet message header */
1091                 memcpy (output_facility->buffer,
1092                         input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1093                         input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1094                 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1095                 output_facility->facility_state = IOSTATE_READY;
1096                 input_facility->facility_state = IOSTATE_READY;
1097               }
1098             else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1099               /* If we have have read our buffer, wait for our write-partner*/
1100               input_facility->facility_state = IOSTATE_WAITING;
1101             else /* we read nothing */
1102               input_facility->facility_state = IOSTATE_READY;
1103           } 
1104         else /* operation was either queued or failed*/
1105           {
1106             int err = GetLastError ();
1107             if (ERROR_IO_PENDING == err) /* operation queued */
1108                 input_facility->facility_state = IOSTATE_QUEUED;
1109             else
1110               { /* error occurred, let the rest of the elements finish */
1111                 input_facility->path_open = FALSE;
1112                 input_facility->facility_state = IOSTATE_FAILED;
1113                 if (IOSTATE_WAITING == output_facility->facility_state)
1114                   output_facility->path_open = FALSE;
1115
1116                 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1117               }
1118           }
1119       }
1120       return TRUE;
1121       // We are queued and should check if the read has finished
1122     case IOSTATE_QUEUED:
1123       {
1124         // there was an operation going on already, check if that has completed now.
1125         if (GetOverlappedResult (input_facility->handle,
1126                                  &input_facility->overlapped,
1127                                  &input_facility->buffer_size_processed,
1128                                  FALSE))
1129           {/* successful return for a queued operation */
1130             hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1131             
1132             if (! ResetEvent (input_facility->overlapped.hEvent))
1133               return FALSE;
1134             
1135             fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1136             input_facility->buffer_size += input_facility->buffer_size_processed;
1137             
1138             if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1139                 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1140               {
1141                 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1142                 input_facility->facility_state = IOSTATE_READY;
1143                 return TRUE;
1144               }
1145             /* we got the a part of a packet */
1146             if (ntohs (hdr->size) > input_facility->buffer_size );
1147               goto partial_read_iostate_ready;
1148
1149             /* we successfully read something from the TAP and now need to
1150              * send it our via STDOUT. Is that possible at the moment? */
1151             if ((IOSTATE_READY == output_facility->facility_state ||
1152                  IOSTATE_WAITING == output_facility->facility_state)
1153                 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1154               { /* hand over this buffers content and strip gnunet message header */
1155                 memcpy (output_facility->buffer,
1156                         input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1157                         input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1158                 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1159                 output_facility->facility_state = IOSTATE_READY;
1160                 input_facility->facility_state = IOSTATE_READY;
1161               }
1162             else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1163               input_facility->facility_state = IOSTATE_WAITING;
1164             else
1165               input_facility->facility_state = IOSTATE_READY;
1166           }
1167         else
1168           { /* operation still pending/queued or failed? */
1169             int err = GetLastError ();
1170             if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1171               { /* error occurred, let the rest of the elements finish */
1172                 input_facility->path_open = FALSE;
1173                 input_facility->facility_state = IOSTATE_FAILED;
1174                 if (IOSTATE_WAITING == output_facility->facility_state)
1175                   output_facility->path_open = FALSE;
1176                 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1177               }
1178           }
1179       }
1180       return TRUE;
1181     case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1182       memcpy (output_facility->buffer,
1183               input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1184               input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1185       output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1186       output_facility->facility_state = IOSTATE_READY;
1187       input_facility->facility_state = IOSTATE_READY;
1188       return TRUE;
1189     default:
1190       return TRUE;
1191     }
1192 }
1193
1194
1195 /**
1196  * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1197  *
1198  * TODO: high level description
1199  * 
1200  * @param output_facility output pipe or file to hand over data to.
1201  * @param input_facility input named pipe or file to work with.
1202  * @return false if an event reset was impossible (OS error), else true
1203  */
1204 static BOOL
1205 attempt_write (struct io_facility * output_facility,
1206                struct io_facility * input_facility)
1207 {
1208   switch (output_facility->facility_state)
1209     {
1210     case IOSTATE_READY:
1211       output_facility->buffer_size_written = 0;
1212       
1213 continue_partial_write:
1214       if (! ResetEvent (output_facility->overlapped.hEvent))
1215         return FALSE;
1216
1217       /* Check how the task was handled */
1218       if (WriteFile (output_facility->handle,
1219                           output_facility->buffer + output_facility->buffer_size_written,
1220                           output_facility->buffer_size - output_facility->buffer_size_written,
1221                           &output_facility->buffer_size_processed,
1222                           &output_facility->overlapped))
1223         {/* async event processed immediately*/
1224
1225           fprintf (stderr, "DEBUG: write succeeded immediately\n");
1226           output_facility->buffer_size_written += output_facility->buffer_size_processed;
1227           
1228           /* reset event manually*/
1229           if (! SetEvent (output_facility->overlapped.hEvent))
1230             return FALSE;
1231
1232           /* partial write */
1233           if (output_facility->buffer_size_written < output_facility->buffer_size)
1234             goto continue_partial_write;
1235           
1236           /* we are now waiting for our buffer to be filled*/
1237           output_facility->facility_state = IOSTATE_WAITING;
1238
1239           /* we successfully wrote something and now need to reset our reader */
1240           if (IOSTATE_WAITING == input_facility->facility_state)
1241             input_facility->facility_state = IOSTATE_RESUME;
1242           else if (IOSTATE_FAILED == input_facility->facility_state)
1243             output_facility->path_open = FALSE;
1244         }
1245       else /* operation was either queued or failed*/
1246         {
1247           int err = GetLastError ();
1248           if (ERROR_IO_PENDING == err)
1249             { /* operation queued */
1250               output_facility->facility_state = IOSTATE_QUEUED;
1251             }
1252           else
1253             { /* error occurred, close this path */
1254               output_facility->path_open = FALSE;
1255               output_facility->facility_state = IOSTATE_FAILED;
1256               fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1257             }
1258         }
1259       return TRUE;
1260     case IOSTATE_QUEUED:
1261       // there was an operation going on already, check if that has completed now.
1262       
1263       if (GetOverlappedResult (output_facility->handle,
1264                                     &output_facility->overlapped,
1265                                     &output_facility->buffer_size_processed,
1266                                     FALSE))
1267         {/* successful return for a queued operation */
1268           if (! ResetEvent (output_facility->overlapped.hEvent))
1269             return FALSE;
1270           
1271           fprintf (stderr, "DEBUG: write succeeded delayed\n");
1272           output_facility->buffer_size_written += output_facility->buffer_size_processed;
1273           
1274           /* partial write */
1275           if (output_facility->buffer_size_written < output_facility->buffer_size)
1276             goto continue_partial_write;
1277           
1278           /* we are now waiting for our buffer to be filled*/
1279           output_facility->facility_state = IOSTATE_WAITING;
1280           
1281           /* we successfully wrote something and now need to reset our reader */
1282           if (IOSTATE_WAITING == input_facility->facility_state)
1283             input_facility->facility_state = IOSTATE_RESUME;
1284           else if (IOSTATE_FAILED == input_facility->facility_state)
1285             output_facility->path_open = FALSE;
1286         }
1287       else
1288         { /* operation still pending/queued or failed? */
1289           int err = GetLastError ();
1290           if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1291             { /* error occurred, close this path */
1292               output_facility->path_open = FALSE;
1293               output_facility->facility_state = IOSTATE_FAILED;
1294               fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1295             }
1296         }
1297     default: 
1298       return TRUE;
1299     }
1300 }
1301
1302
1303 /**
1304  * Initialize a overlapped structure
1305  * 
1306  * @param elem the element to initilize
1307  * @param initial_state the initial state for this instance
1308  * @param signaled if the hEvent created should default to signaled or not
1309  * @return true on success, else false
1310  */
1311 static BOOL
1312 initialize_io_facility (struct io_facility * elem,
1313                         int initial_state,
1314                         BOOL signaled)
1315 {
1316   elem->path_open = TRUE;
1317   elem->handle = INVALID_HANDLE_VALUE;
1318   elem->facility_state = initial_state;
1319   elem->buffer_size = 0;
1320   elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1321   if (NULL == elem->overlapped.hEvent)
1322     return FALSE;
1323
1324   return TRUE;
1325 }
1326
1327
1328 /**
1329  * Start forwarding to and from the tunnel.
1330  *
1331  * @param tap_handle device handle for interacting with the Virtual interface
1332  */
1333 static void
1334 run (HANDLE tap_handle)
1335 {
1336   /* IO-Facility for reading from our virtual interface */
1337   struct io_facility tap_read;
1338   /* IO-Facility for writing to our virtual interface */
1339   struct io_facility tap_write;
1340   /* IO-Facility for reading from stdin */
1341   struct io_facility std_in;
1342   /* IO-Facility for writing to stdout */
1343   struct io_facility std_out;
1344
1345   HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1346   HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1347
1348   /* tun up: */
1349   /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1350    * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1351    *  
1352    * DHCP and such are all features we will never use in gnunet afaik.
1353    * But for openvpn those are essential.
1354    */
1355   if (! tun_up (tap_handle))
1356     return;
1357
1358   /* Initialize our overlapped IO structures*/
1359   if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1360         && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1361         && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1362         && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1363     goto teardown_final;
1364
1365   /* Handles for STDIN and STDOUT */
1366   tap_read.handle = tap_handle;
1367   tap_write.handle = tap_handle;
1368
1369 #ifdef DEBUG_TO_CONSOLE
1370   /* Debug output to console STDIN/STDOUT*/
1371   std_in.handle = parent_std_in_handle;
1372   std_out.handle = parent_std_out_handle;
1373   
1374 #else
1375   fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1376   /* 
1377    * Find out the types of our handles. 
1378    * This part is a problem, because in windows we need to handle files, 
1379    * pipes and the console differently.
1380    */
1381   if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1382       (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1383     {
1384       fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1385       goto teardown;
1386     }
1387
1388   std_in.handle = ReOpenFile (parent_std_in_handle,
1389                               GENERIC_READ,
1390                               FILE_SHARE_WRITE | FILE_SHARE_READ,
1391                               FILE_FLAG_OVERLAPPED);
1392
1393   if (INVALID_HANDLE_VALUE == std_in.handle)
1394     {
1395       fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1396       goto teardown;
1397     }
1398
1399   std_out.handle = ReOpenFile (parent_std_out_handle,
1400                                GENERIC_WRITE,
1401                                FILE_SHARE_READ,
1402                                FILE_FLAG_OVERLAPPED);
1403
1404   if (INVALID_HANDLE_VALUE == std_out.handle)
1405     {
1406       fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1407       goto teardown;
1408     }
1409 #endif
1410   
1411   fprintf (stderr, "DEBUG: mainloop has begun\n");
1412   
1413   while (std_out.path_open || tap_write.path_open)
1414     {
1415       /* perform READ from stdin if possible */
1416       if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1417         break;
1418
1419       /* perform READ from tap if possible */
1420       if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1421         break;
1422
1423       /* perform WRITE to tap if possible */
1424       if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1425         break;
1426
1427       /* perform WRITE to STDOUT if possible */
1428       if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1429         break;
1430     }
1431
1432 teardown:
1433
1434   fprintf (stderr, "DEBUG: teardown initiated\n");
1435       
1436   CancelIo (tap_handle);
1437   CancelIo (std_in.handle);
1438   CancelIo (std_out.handle);
1439
1440 teardown_final:
1441       
1442   CloseHandle (tap_handle);
1443 }
1444 /**
1445  * Open VPN tunnel interface.
1446  *
1447  * @param argc must be 6
1448  * @param argv 0: binary name ("gnunet-helper-exit")
1449  *             1: tunnel interface name ("gnunet-exit")
1450  *             2: IPv4 "physical" interface name ("eth0"), or "-" to not do IPv4 NAT
1451  *             3: IPv6 address ("::1"), or "-" to skip IPv6
1452  *             4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1453  *             5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1454  *             6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1455  */
1456 int
1457 main (int argc, char **argv)
1458 {
1459   char hwid[LINE_LEN];
1460   HANDLE handle;
1461   int global_ret = 1;
1462   int local_ret = EINVAL;
1463   BOOL have_ip4 = FALSE;
1464   BOOL have_ip6 = FALSE;
1465   BOOL have_nat44 = FALSE;
1466
1467   if (6 != argc)
1468     {
1469       fprintf (stderr, "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit <if name prefix> <uplink-interface name> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1470       return 1;
1471     }
1472
1473   strncpy (hwid, argv[1], LINE_LEN);
1474   hwid[LINE_LEN - 1] = '\0';
1475
1476   /* 
1477    * We use our PID for finding/resolving the control-panel name of our virtual 
1478    * device. PIDs are (of course) unique at runtime, thus we can safely use it 
1479    * as additional hardware-id for our device.
1480    */
1481   snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1482             hwid,
1483             _getpid ());
1484
1485   if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1486     {
1487       fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1488                hwid,
1489                argv[3],
1490                argv[4],
1491                argv[5],
1492                argv[6]);
1493       global_ret = -1;
1494       goto cleanup;
1495     }
1496
1497   fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1498   if (0 != strcmp (argv[3], "-"))
1499     {
1500       char command[LINE_LEN];
1501       const char *address = argv[3];
1502       long prefix_len = atol (argv[4]);
1503
1504       if ((prefix_len < 1) || (prefix_len > 127))
1505         {
1506           fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1507           global_ret = -1;
1508           goto cleanup;
1509         }
1510
1511       fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1512       if (0 != (global_ret = set_address6 (address, prefix_len)))
1513         goto cleanup;
1514
1515       have_ip6 = TRUE;
1516
1517       /* install our the windows NAT module*/
1518       fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n");
1519       /* outside interface (maybe that's already set) */
1520       snprintf (command, LINE_LEN,
1521                 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active",
1522                 argv[2]);
1523       local_ret = execute_shellcommand (command);
1524       if (0 != local_ret)
1525         {
1526           fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1527           goto cleanup;
1528         }
1529       /* internal interface */
1530       snprintf (command, LINE_LEN,
1531                 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active",
1532                 device_visible_name);
1533       local_ret = execute_shellcommand (command);
1534       if (0 != local_ret)
1535         {
1536           fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1537           goto cleanup;
1538         }
1539       /* we can keep IPv6 forwarding around, as all interfaces have 
1540        * their forwarding mode reset to false at bootup. */
1541     }
1542
1543   if (0 != strcmp (argv[5], "-"))
1544     {
1545       const char *address = argv[5];
1546       const char *mask = argv[6];
1547
1548       fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1549       if (0 != (global_ret = set_address4 (address, mask)))
1550         goto cleanup;
1551
1552       // setup NAPT, if possible
1553       /* MS has REMOVED the routing/nat capabilities from Vista+, thus
1554        * we can not setup NAT like in XP or on the server. Actually the
1555        * the only feasible solution seems to be to use 
1556        * Internet Connection Sharing, which introduces a horde of problems
1557        * such as sending out rogue-RAs on the external interface in an ipv6
1558        * network.
1559        * Thus, below stuff ONLY works on 
1560        *   WinXP SP3
1561        *   Win Server 2003 SP1+
1562        *   Win Server 2008
1563        *   ...
1564        */
1565       have_ip4 = TRUE;
1566       if (0 != strcmp (argv[2], "-"))
1567         {
1568           char command[LINE_LEN];
1569
1570           /* install our the windows NAT module*/
1571           fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]);
1572           local_ret = execute_shellcommand ("netsh routing ip nat install");
1573           if (0 != local_ret)
1574             {
1575               fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret));
1576               goto cleanup;
1577             }
1578           /* external IF */
1579           snprintf (command, LINE_LEN,
1580                     "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/
1581                     argv[2]);
1582           local_ret = execute_shellcommand (command);
1583           if (0 != local_ret)
1584             {
1585               fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret));
1586               goto cleanup;
1587             }
1588           /* private/internal/virtual IF */
1589           snprintf (command, LINE_LEN,
1590                     "netsh routing ip nat add interface \"%s\" private",
1591                     device_visible_name);
1592           local_ret = execute_shellcommand (command);
1593           if (0 != local_ret)
1594             {
1595               fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret));
1596               goto cleanup;
1597
1598               have_nat44 = TRUE;
1599             }
1600         }
1601     }
1602
1603   run (handle);
1604   global_ret = 0;
1605 cleanup:
1606
1607   if (have_ip4) {
1608       const char *address = argv[5];
1609       if (have_nat44) {
1610           char command[LINE_LEN];
1611           fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n");
1612           snprintf(command, LINE_LEN,
1613                    "netsh routing ip nat del interface \"%s\"",
1614                    device_visible_name);
1615           local_ret = execute_shellcommand(command);
1616           if (0 != local_ret)
1617               fprintf(stderr, "WARNING: Could not remove IPv4-NAPT from internal interface, hopefully this will have no effect in future runs: %s\n", strerror(local_ret));
1618       }
1619       
1620       fprintf(stderr, "DEBUG: Removing IP4 address\n");
1621       remove_address4 (address);
1622   }
1623   if (have_ip6)
1624     {
1625       const char *address = argv[3];
1626       fprintf (stderr, "DEBUG: Removing IP6 address\n");
1627       remove_address6 (address);
1628     }
1629
1630   fprintf (stderr, "DEBUG: removing interface\n");
1631   remove_interface ();
1632   fprintf (stderr, "DEBUG: graceful exit completed\n");
1633
1634   return global_ret;
1635 }