M testbed/testbed.h
[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/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/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 dev the interface to remove
337  * @param address the IPv4-Address
338  * @param mask the netmask
339  */
340 static void
341 remove_address6 (const char *address)
342 {
343   char command[LINE_LEN];
344   int ret = EINVAL;
345
346   // sanity checking was already done in set_address6
347   /*
348    * prepare the command
349    */
350   snprintf (command, LINE_LEN,
351             "netsh interface ipv6 delete address \"%s\" store=persistent",
352             device_visible_name, address);
353   /*
354    * Set the address
355    */
356   ret = execute_shellcommand (command);
357
358   /* Did it work?*/
359   if (0 != ret)
360     fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
361 }
362
363
364 /**
365  * @brief Sets the IPv4-Address given in address on the interface dev
366  *
367  * @param dev the interface to configure
368  * @param address the IPv4-Address
369  * @param mask the netmask
370  */
371 static int
372 set_address4 (const char *address, const char *mask)
373 {
374   int ret = EINVAL;
375   char command[LINE_LEN];
376
377   struct sockaddr_in addr;
378   addr.sin_family = AF_INET;
379
380   /*
381    * Parse the address
382    */
383   if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
384     {
385       fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
386                strerror (errno));
387       return -1;
388     }
389   // Set Device to Subnet-Mode? 
390   // do we really need tun.c:2925 ?
391
392   /*
393    * prepare the command
394    */
395   snprintf (command, LINE_LEN,
396             "netsh interface ipv4 add address \"%s\" %s %s store=active",
397             device_visible_name, address, mask);
398   /*
399    * Set the address
400    */
401   ret = execute_shellcommand (command);
402
403   /* Did it work?*/
404   if (0 != ret)
405     fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
406   return ret;
407 }
408
409
410 /**
411  * @brief Removes the IPv4-Address given in address from the interface dev
412  *
413  * @param dev the interface to remove
414  * @param address the IPv4-Address
415  * @param mask the netmask
416  */
417 static void
418 remove_address4 (const char *address)
419 {
420   char command[LINE_LEN];
421   int ret = EINVAL;
422
423   // sanity checking was already done in set_address4
424
425   /*
426    * prepare the command
427    */
428   snprintf (command, LINE_LEN,
429             "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
430             device_visible_name, address);
431   /*
432    * Set the address
433    */
434   ret = execute_shellcommand (command);
435
436   /* Did it work?*/
437   if (0 != ret)
438     fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
439 }
440
441
442 /**
443  * Setup a new virtual interface to use for tunneling. 
444  * 
445  * @return: TRUE if setup was successful, else FALSE
446  */
447 static BOOL
448 setup_interface ()
449 {
450   /*
451    * where to find our inf-file. (+ the "full" path, after windows found")
452    * 
453    * We do not directly input all the props here, because openvpn will update
454    * these details over time.
455    */
456   char inf_file_path[MAX_PATH];
457   char * temp_inf_filename;
458   char hwidlist[LINE_LEN + 4];
459   char class_name[128];
460   GUID class_guid;
461   int str_length = 0;
462
463   /** 
464    * Set the device's hardware ID and add it to a list.
465    * This information will later on identify this device in registry. 
466    */
467   strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
468   /**
469    * this is kind of over-complicated, but allows keeps things independent of 
470    * how the openvpn-hwid is actually stored. 
471    * 
472    * A HWID list is double-\0 terminated and \0 separated
473    */
474   str_length = strlen (hwidlist) + 1;
475   strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
476   str_length += strlen (&hwidlist[str_length]) + 1;
477   
478   /** 
479    * Locate the inf-file, we need to store it somewhere where the system can
480    * find it. We need to pick the correct driver for win32/win64.
481    */
482   if (is_win64())
483     GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
484   else
485     GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
486
487   fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
488   /** 
489    * Bootstrap our device info using the drivers inf-file
490    */
491   if ( ! SetupDiGetINFClassA (inf_file_path,
492                             &class_guid,
493                             class_name, sizeof (class_name) / sizeof (char),
494                             NULL))
495     return FALSE;
496
497   /** 
498    * Collect all the other needed information... 
499    * let the system fill our this form 
500    */
501   DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
502   if (DeviceInfo == INVALID_HANDLE_VALUE)
503     return FALSE;
504
505   DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
506   if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
507                                  class_name,
508                                  &class_guid,
509                                  NULL,
510                                  0,
511                                  DICD_GENERATE_ID,
512                                  &DeviceNode))
513     return FALSE;
514
515   /* Deploy all the information collected into the registry */
516   if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
517                                           &DeviceNode,
518                                           SPDRP_HARDWAREID,
519                                           (LPBYTE) hwidlist,
520                                           str_length * sizeof (char)))
521     return FALSE;
522
523   /* Install our new class(=device) into the system */
524   if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
525                                   DeviceInfo,
526                                   &DeviceNode))
527     return FALSE;
528
529   /* This system call tends to take a while (several seconds!) on
530      "modern" Windoze systems */
531   if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
532                                            secondary_hwid,
533                                            inf_file_path,
534                                            INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
535                                            NULL)) //reboot required? NEVER!
536     return FALSE;
537
538   fprintf (stderr, "DEBUG: successfully created a network device\n");
539   return TRUE;
540 }
541
542
543 /**
544  * Remove our new virtual interface to use for tunneling. 
545  * This function must be called AFTER setup_interface!
546  * 
547  * @return: TRUE if destruction was successful, else FALSE
548  */
549 static BOOL
550 remove_interface ()
551 {
552   SP_REMOVEDEVICE_PARAMS remove;
553
554   if (INVALID_HANDLE_VALUE == DeviceInfo)
555     return FALSE;
556
557   remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
558   remove.HwProfile = 0;
559   remove.Scope = DI_REMOVEDEVICE_GLOBAL;
560   remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
561   /*
562    * 1. Prepare our existing device information set, and place the 
563    *    uninstall related information into the structure
564    */
565   if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
566                                       (PSP_DEVINFO_DATA) & DeviceNode,
567                                       &remove.ClassInstallHeader,
568                                       sizeof (remove)))
569     return FALSE;
570   /*
571    * 2. Uninstall the virtual interface using the class installer
572    */
573   if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
574                                   DeviceInfo,
575                                   (PSP_DEVINFO_DATA) & DeviceNode))
576     return FALSE;
577
578   SetupDiDestroyDeviceInfoList (DeviceInfo);
579   
580   fprintf (stderr, "DEBUG: removed interface successfully\n");
581
582   return TRUE;
583 }
584
585
586 /**
587  * Do all the lookup necessary to retrieve the inteface's actual name
588  * off the registry. 
589  * 
590  * @return: TRUE if we were able to lookup the interface's name, else FALSE
591  */
592 static BOOL
593 resolve_interface_name ()
594 {
595   SP_DEVINFO_LIST_DETAIL_DATA device_details;
596   char pnp_instance_id [MAX_DEVICE_ID_LEN];
597   HKEY adapter_key_handle;
598   LONG status;
599   DWORD len;
600   int i = 0;
601   int retrys;
602   BOOL retval = FALSE;
603   char adapter[] = INTERFACE_REGISTRY_LOCATION;
604
605   /* We can obtain the PNP instance ID from our setupapi handle */
606   device_details.cbSize = sizeof (device_details);
607   if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
608                                           (PCHAR) pnp_instance_id,
609                                           MAX_DEVICE_ID_LEN,
610                                           0, //must be 0
611                                           NULL)) //hMachine, we are local
612     return FALSE;
613   
614   fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
615
616   /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
617   for (retrys = 0; retrys < 120 && !retval; retrys++)
618     {
619       /* sleep for 250ms*/
620       Sleep (250);
621
622       /* Now we can use this ID to locate the correct networks interface in registry */
623       if (ERROR_SUCCESS != RegOpenKeyExA (
624                                           HKEY_LOCAL_MACHINE,
625                                           adapter,
626                                           0,
627                                           KEY_READ,
628                                           &adapter_key_handle))
629         return FALSE;
630
631       /* Of course there is a multitude of entries here, with arbitrary names, 
632        * thus we need to iterate through there.
633        */
634       while (!retval)
635         {
636           char instance_key[256];
637           char query_key [256];
638           HKEY instance_key_handle;
639           char pnpinstanceid_name[] = "PnpInstanceID";
640           char pnpinstanceid_value[256];
641           char adaptername_name[] = "Name";
642           DWORD data_type;
643
644           len = 256 * sizeof (char);
645           /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
646           status = RegEnumKeyExA (
647                                   adapter_key_handle,
648                                   i,
649                                   instance_key,
650                                   &len,
651                                   NULL,
652                                   NULL,
653                                   NULL,
654                                   NULL);
655
656           /* this may fail due to one of two reasons: 
657            * we are at the end of the list*/
658           if (ERROR_NO_MORE_ITEMS == status)
659             break;
660           // * we found a broken registry key, continue with the next key.
661           if (ERROR_SUCCESS != status)
662             goto cleanup;
663
664           /* prepare our new query string: */
665           snprintf (query_key, 256, "%s\\%s\\Connection",
666                     adapter,
667                     instance_key);
668
669           /* look inside instance_key\\Connection */
670           if (ERROR_SUCCESS != RegOpenKeyExA (
671                                   HKEY_LOCAL_MACHINE,
672                                   query_key,
673                                   0,
674                                   KEY_READ,
675                                   &instance_key_handle))
676             goto cleanup;
677
678           /* now, read our PnpInstanceID */
679           len = sizeof (pnpinstanceid_value);
680           status = RegQueryValueExA (instance_key_handle,
681                                      pnpinstanceid_name,
682                                      NULL, //reserved, always NULL according to MSDN
683                                      &data_type,
684                                      (LPBYTE) pnpinstanceid_value,
685                                      &len);
686
687           if (status != ERROR_SUCCESS || data_type != REG_SZ)
688             goto cleanup;
689
690           /* compare the value we got to our devices PNPInstanceID*/
691           if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
692                             sizeof (pnpinstanceid_value) / sizeof (char)))
693             goto cleanup;
694
695           len = sizeof (device_visible_name);
696           status = RegQueryValueExA (
697                                      instance_key_handle,
698                                      adaptername_name,
699                                      NULL, //reserved, always NULL according to MSDN
700                                      &data_type,
701                                      (LPBYTE) device_visible_name,
702                                      &len);
703
704           if (status != ERROR_SUCCESS || data_type != REG_SZ)
705             goto cleanup;
706
707           /* 
708            * we have successfully found OUR instance, 
709            * save the device GUID before exiting
710            */
711
712           strncpy (device_guid, instance_key, 256);
713           retval = TRUE;
714           fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
715
716 cleanup:
717           RegCloseKey (instance_key_handle);
718
719           ++i;
720         }
721
722       RegCloseKey (adapter_key_handle);
723     }
724   return retval;
725 }
726
727
728 /**
729  * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
730  * 
731  * @param handle the handle to our tap device
732  * @return TRUE if the version is sufficient, else FALSE
733  */
734 static BOOL
735 check_tapw32_version (HANDLE handle)
736 {
737   ULONG version[3];
738   DWORD len;
739   memset (&(version), 0, sizeof (version));
740
741   if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
742                        &version, sizeof (version),
743                        &version, sizeof (version), &len, NULL))
744       fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
745                (int) version[0],
746                (int) version[1],
747                (version[2] ? "(DEBUG)" : ""));
748
749   if ((version[0] != TAP_WIN_MIN_MAJOR) ||
750       (version[1] < TAP_WIN_MIN_MINOR )){
751       fprintf (stderr, "FATAL:  This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
752                TAP_WIN_MIN_MAJOR,
753                TAP_WIN_MIN_MINOR);
754       return FALSE;
755     }
756       
757   return TRUE;
758 }
759
760
761 /**
762  * Creates a tun-interface called dev;
763  *
764  * @return the fd to the tun or -1 on error
765  */
766 static HANDLE
767 init_tun ()
768 {
769   char device_path[256];
770   HANDLE handle;
771
772   if (! setup_interface ())
773     {
774       errno = ENODEV;
775       return INVALID_HANDLE_VALUE;
776     }
777
778   if (! resolve_interface_name ())
779     {
780       errno = ENODEV;
781       return INVALID_HANDLE_VALUE;
782     }
783
784   /* Open Windows TAP-Windows adapter */
785   snprintf (device_path, sizeof (device_path), "%s%s%s",
786             USERMODEDEVICEDIR,
787             device_guid,
788             TAP_WIN_SUFFIX);
789
790   handle = CreateFile (
791                        device_path,
792                        GENERIC_READ | GENERIC_WRITE,
793                        0, /* was: FILE_SHARE_READ */
794                        0,
795                        OPEN_EXISTING,
796                        FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
797                        0
798                        );
799
800   if (INVALID_HANDLE_VALUE == handle)
801     {
802       fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
803       return handle;
804     }
805
806   /* get driver version info */
807   if (! check_tapw32_version (handle))
808     {
809       CloseHandle (handle);
810       return INVALID_HANDLE_VALUE;
811     }
812
813   /* TODO (opt?): get MTU-Size */
814
815   fprintf (stderr, "DEBUG: successfully opened TAP device\n");
816   return handle;
817 }
818
819
820 /**
821  * Brings a TAP device up and sets it to connected state.
822  * 
823  * @param handle the handle to our TAP device 
824  * @return True if the operation succeeded, else false
825  */
826 static BOOL
827 tun_up (HANDLE handle)
828 {
829   ULONG status = TRUE;
830   DWORD len;
831   if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
832                         &status, sizeof (status),
833                         &status, sizeof (status), &len, NULL))
834     {
835       fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
836       return FALSE;
837     }
838
839   /* Wait for the device to go UP, might take some time. */
840   Sleep (TAP32_POSTUP_WAITTIME * 1000);
841   fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
842
843   return TRUE;
844 }
845
846
847 /**
848  * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
849  * 
850  * 1. 
851  * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
852  * input handle. Then it goes into IOSTATE_QUEUED state. 
853  * In case the read succeeded instantly the input facility enters 3.
854  * 
855  * 2. 
856  * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
857  * If it has finished, go to state 3.
858  * If it has failed, set IOSTATE_FAILED
859  * 
860  * 3.
861  * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
862  *   The input facility enters state IOSTATE_READY
863  *   The output facility enters state IOSTATE_READY
864  * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
865  * 
866  * IOSTATE_WAITING is reset by the output facility, once it has completed.
867  * 
868  * @param input_facility input named pipe or file to work with.
869  * @param output_facility output pipe or file to hand over data to.
870  * @return false if an event reset was impossible (OS error), else true
871  */
872 static BOOL
873 attempt_read_tap (struct io_facility * input_facility,
874                   struct io_facility * output_facility)
875 {
876   struct GNUNET_MessageHeader * hdr;
877   unsigned short size;
878   
879   switch (input_facility->facility_state)
880     {
881     case IOSTATE_READY:
882       { 
883         if (! ResetEvent (input_facility->overlapped.hEvent))
884           {
885             return FALSE;
886           }
887
888         input_facility->buffer_size = 0;
889
890         /* Check how the task is handled */
891         if (ReadFile (input_facility->handle,
892                       input_facility->buffer,
893                       sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
894                       &input_facility->buffer_size,
895                       &input_facility->overlapped))
896           {/* async event processed immediately*/
897
898             /* reset event manually*/
899             if (! SetEvent (input_facility->overlapped.hEvent))
900               return FALSE;
901             
902             fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
903             
904             /* we successfully read something from the TAP and now need to
905              * send it our via STDOUT. Is that possible at the moment? */
906             if ((IOSTATE_READY == output_facility->facility_state ||
907                  IOSTATE_WAITING == output_facility->facility_state)
908                 && (0 < input_facility->buffer_size))
909               { /* hand over this buffers content and apply message header for gnunet */
910                 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
911                 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
912                 
913                 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
914                         input_facility->buffer,
915                         input_facility->buffer_size);
916
917                 output_facility->buffer_size = size;
918                 hdr->size = htons (size);
919                 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
920                 output_facility->facility_state = IOSTATE_READY;
921               }
922             else if (0 < input_facility->buffer_size)
923                 /* If we have have read our buffer, wait for our write-partner*/
924                 input_facility->facility_state = IOSTATE_WAITING;
925           }
926         else /* operation was either queued or failed*/
927           {
928             int err = GetLastError ();
929             if (ERROR_IO_PENDING == err)
930               { /* operation queued */
931                 input_facility->facility_state = IOSTATE_QUEUED;
932               }
933             else
934               { /* error occurred, let the rest of the elements finish */
935                 input_facility->path_open = FALSE;
936                 input_facility->facility_state = IOSTATE_FAILED;
937                 if (IOSTATE_WAITING == output_facility->facility_state)
938                   output_facility->path_open = FALSE;
939
940                 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
941               }
942           }
943       }
944       return TRUE;
945       // We are queued and should check if the read has finished
946     case IOSTATE_QUEUED:
947       {
948         // there was an operation going on already, check if that has completed now.
949
950         if (GetOverlappedResult (input_facility->handle,
951                                  &input_facility->overlapped,
952                                  &input_facility->buffer_size,
953                                  FALSE))
954           {/* successful return for a queued operation */
955             if (! ResetEvent (input_facility->overlapped.hEvent))
956               return FALSE;
957
958             fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
959             
960             /* we successfully read something from the TAP and now need to
961              * send it our via STDOUT. Is that possible at the moment? */
962             if ((IOSTATE_READY == output_facility->facility_state ||
963                  IOSTATE_WAITING == output_facility->facility_state)
964                 && 0 < input_facility->buffer_size)
965               { /* hand over this buffers content and apply message header for gnunet */
966                 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
967                 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
968                 
969                 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
970                         input_facility->buffer,
971                         input_facility->buffer_size);
972
973                 output_facility->buffer_size = size;
974                 hdr->size = htons(size);
975                 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
976                 output_facility->facility_state = IOSTATE_READY;
977                 input_facility->facility_state = IOSTATE_READY;
978               }
979             else if (0 < input_facility->buffer_size)
980               { /* If we have have read our buffer, wait for our write-partner*/
981                 input_facility->facility_state = IOSTATE_WAITING;
982                 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
983               }
984           }
985         else
986           { /* operation still pending/queued or failed? */
987             int err = GetLastError ();
988             if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
989               { /* error occurred, let the rest of the elements finish */
990                 input_facility->path_open = FALSE;
991                 input_facility->facility_state = IOSTATE_FAILED;
992                 if (IOSTATE_WAITING == output_facility->facility_state)
993                   output_facility->path_open = FALSE;
994                 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
995               }
996           }
997       }
998       return TRUE;
999     case IOSTATE_RESUME:
1000       hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1001       size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1002
1003       memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1004               input_facility->buffer,
1005               input_facility->buffer_size);
1006
1007       output_facility->buffer_size = size;
1008       hdr->size = htons (size);
1009       hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1010       output_facility->facility_state = IOSTATE_READY;
1011       input_facility->facility_state = IOSTATE_READY;
1012       return TRUE;
1013     default:
1014       return TRUE;
1015     }
1016 }
1017
1018
1019 /**
1020  * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1021  * 
1022  * 1. 
1023  * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1024  * input handle. Then it goes into IOSTATE_QUEUED state. 
1025  * In case the read succeeded instantly the input facility enters 3.
1026  * 
1027  * 2. 
1028  * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1029  * If it has finished, go to state 3.
1030  * If it has failed, set IOSTATE_FAILED
1031  * 
1032  * 3.
1033  * If the facility is finished with ready
1034  *   The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1035  *   The input facility enters state IOSTATE_READY
1036  *   The output facility enters state IOSTATE_READY
1037  * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1038  * 
1039  * IOSTATE_WAITING is reset by the output facility, once it has completed.
1040  * 
1041  * @param input_facility input named pipe or file to work with.
1042  * @param output_facility output pipe or file to hand over data to.
1043  * @return false if an event reset was impossible (OS error), else true
1044  */
1045 static BOOL
1046 attempt_read_stdin (struct io_facility * input_facility,
1047                     struct io_facility * output_facility)
1048 {
1049   struct GNUNET_MessageHeader * hdr;
1050   
1051   switch (input_facility->facility_state)
1052     {
1053     case IOSTATE_READY:
1054       {
1055         input_facility->buffer_size = 0;
1056         
1057 partial_read_iostate_ready:
1058         if (! ResetEvent (input_facility->overlapped.hEvent))
1059           return FALSE;
1060        
1061         /* Check how the task is handled */
1062         if (ReadFile (input_facility->handle,
1063                            input_facility->buffer + input_facility->buffer_size,
1064                            sizeof (input_facility->buffer) - input_facility->buffer_size,
1065                            &input_facility->buffer_size_processed,
1066                            &input_facility->overlapped))
1067           {/* async event processed immediately*/
1068             hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1069
1070             /* reset event manually*/
1071             if (!SetEvent (input_facility->overlapped.hEvent))
1072               return FALSE;
1073
1074             fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1075             input_facility->buffer_size += input_facility->buffer_size_processed;
1076
1077             if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1078                 ntohs (hdr->size) > sizeof (input_facility->buffer))
1079               {
1080                 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1081                 input_facility->facility_state = IOSTATE_READY;
1082                 return TRUE;
1083               }
1084             /* we got the a part of a packet */
1085             if (ntohs (hdr->size) > input_facility->buffer_size)
1086               goto partial_read_iostate_ready;
1087
1088             /* have we read more than 0 bytes of payload? (sizeread > header)*/
1089             if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1090                 ((IOSTATE_READY == output_facility->facility_state) ||
1091                  (IOSTATE_WAITING == output_facility->facility_state)))
1092               {/* we successfully read something from the TAP and now need to
1093              * send it our via STDOUT. Is that possible at the moment? */
1094
1095                 /* hand over this buffers content and strip gnunet message header */
1096                 memcpy (output_facility->buffer,
1097                         input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1098                         input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1099                 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1100                 output_facility->facility_state = IOSTATE_READY;
1101                 input_facility->facility_state = IOSTATE_READY;
1102               }
1103             else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1104               /* If we have have read our buffer, wait for our write-partner*/
1105               input_facility->facility_state = IOSTATE_WAITING;
1106             else /* we read nothing */
1107               input_facility->facility_state = IOSTATE_READY;
1108           } 
1109         else /* operation was either queued or failed*/
1110           {
1111             int err = GetLastError ();
1112             if (ERROR_IO_PENDING == err) /* operation queued */
1113                 input_facility->facility_state = IOSTATE_QUEUED;
1114             else
1115               { /* error occurred, let the rest of the elements finish */
1116                 input_facility->path_open = FALSE;
1117                 input_facility->facility_state = IOSTATE_FAILED;
1118                 if (IOSTATE_WAITING == output_facility->facility_state)
1119                   output_facility->path_open = FALSE;
1120
1121                 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1122               }
1123           }
1124       }
1125       return TRUE;
1126       // We are queued and should check if the read has finished
1127     case IOSTATE_QUEUED:
1128       {
1129         // there was an operation going on already, check if that has completed now.
1130         if (GetOverlappedResult (input_facility->handle,
1131                                  &input_facility->overlapped,
1132                                  &input_facility->buffer_size_processed,
1133                                  FALSE))
1134           {/* successful return for a queued operation */
1135             hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1136             
1137             if (! ResetEvent (input_facility->overlapped.hEvent))
1138               return FALSE;
1139             
1140             fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1141             input_facility->buffer_size += input_facility->buffer_size_processed;
1142             
1143             if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1144                 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1145               {
1146                 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1147                 input_facility->facility_state = IOSTATE_READY;
1148                 return TRUE;
1149               }
1150             /* we got the a part of a packet */
1151             if (ntohs (hdr->size) > input_facility->buffer_size );
1152               goto partial_read_iostate_ready;
1153
1154             /* we successfully read something from the TAP and now need to
1155              * send it our via STDOUT. Is that possible at the moment? */
1156             if ((IOSTATE_READY == output_facility->facility_state ||
1157                  IOSTATE_WAITING == output_facility->facility_state)
1158                 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1159               { /* hand over this buffers content and strip gnunet message header */
1160                 memcpy (output_facility->buffer,
1161                         input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1162                         input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1163                 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1164                 output_facility->facility_state = IOSTATE_READY;
1165                 input_facility->facility_state = IOSTATE_READY;
1166               }
1167             else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1168               input_facility->facility_state = IOSTATE_WAITING;
1169             else
1170               input_facility->facility_state = IOSTATE_READY;
1171           }
1172         else
1173           { /* operation still pending/queued or failed? */
1174             int err = GetLastError ();
1175             if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1176               { /* error occurred, let the rest of the elements finish */
1177                 input_facility->path_open = FALSE;
1178                 input_facility->facility_state = IOSTATE_FAILED;
1179                 if (IOSTATE_WAITING == output_facility->facility_state)
1180                   output_facility->path_open = FALSE;
1181                 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1182               }
1183           }
1184       }
1185       return TRUE;
1186     case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1187       memcpy (output_facility->buffer,
1188               input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1189               input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1190       output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1191       output_facility->facility_state = IOSTATE_READY;
1192       input_facility->facility_state = IOSTATE_READY;
1193       return TRUE;
1194     default:
1195       return TRUE;
1196     }
1197 }
1198
1199
1200 /**
1201  * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1202  *
1203  * TODO: high level description
1204  * 
1205  * @param output_facility output pipe or file to hand over data to.
1206  * @param input_facility input named pipe or file to work with.
1207  * @return false if an event reset was impossible (OS error), else true
1208  */
1209 static BOOL
1210 attempt_write (struct io_facility * output_facility,
1211                struct io_facility * input_facility)
1212 {
1213   switch (output_facility->facility_state)
1214     {
1215     case IOSTATE_READY:
1216       output_facility->buffer_size_written = 0;
1217       
1218 continue_partial_write:
1219       if (! ResetEvent (output_facility->overlapped.hEvent))
1220         return FALSE;
1221
1222       /* Check how the task was handled */
1223       if (WriteFile (output_facility->handle,
1224                           output_facility->buffer + output_facility->buffer_size_written,
1225                           output_facility->buffer_size - output_facility->buffer_size_written,
1226                           &output_facility->buffer_size_processed,
1227                           &output_facility->overlapped))
1228         {/* async event processed immediately*/
1229
1230           fprintf (stderr, "DEBUG: write succeeded immediately\n");
1231           output_facility->buffer_size_written += output_facility->buffer_size_processed;
1232           
1233           /* reset event manually*/
1234           if (! SetEvent (output_facility->overlapped.hEvent))
1235             return FALSE;
1236
1237           /* partial write */
1238           if (output_facility->buffer_size_written < output_facility->buffer_size)
1239             goto continue_partial_write;
1240           
1241           /* we are now waiting for our buffer to be filled*/
1242           output_facility->facility_state = IOSTATE_WAITING;
1243
1244           /* we successfully wrote something and now need to reset our reader */
1245           if (IOSTATE_WAITING == input_facility->facility_state)
1246             input_facility->facility_state = IOSTATE_RESUME;
1247           else if (IOSTATE_FAILED == input_facility->facility_state)
1248             output_facility->path_open = FALSE;
1249         }
1250       else /* operation was either queued or failed*/
1251         {
1252           int err = GetLastError ();
1253           if (ERROR_IO_PENDING == err)
1254             { /* operation queued */
1255               output_facility->facility_state = IOSTATE_QUEUED;
1256             }
1257           else
1258             { /* error occurred, close this path */
1259               output_facility->path_open = FALSE;
1260               output_facility->facility_state = IOSTATE_FAILED;
1261               fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1262             }
1263         }
1264       return TRUE;
1265     case IOSTATE_QUEUED:
1266       // there was an operation going on already, check if that has completed now.
1267       
1268       if (GetOverlappedResult (output_facility->handle,
1269                                     &output_facility->overlapped,
1270                                     &output_facility->buffer_size_processed,
1271                                     FALSE))
1272         {/* successful return for a queued operation */
1273           if (! ResetEvent (output_facility->overlapped.hEvent))
1274             return FALSE;
1275           
1276           fprintf (stderr, "DEBUG: write succeeded delayed\n");
1277           output_facility->buffer_size_written += output_facility->buffer_size_processed;
1278           
1279           /* partial write */
1280           if (output_facility->buffer_size_written < output_facility->buffer_size)
1281             goto continue_partial_write;
1282           
1283           /* we are now waiting for our buffer to be filled*/
1284           output_facility->facility_state = IOSTATE_WAITING;
1285           
1286           /* we successfully wrote something and now need to reset our reader */
1287           if (IOSTATE_WAITING == input_facility->facility_state)
1288             input_facility->facility_state = IOSTATE_RESUME;
1289           else if (IOSTATE_FAILED == input_facility->facility_state)
1290             output_facility->path_open = FALSE;
1291         }
1292       else
1293         { /* operation still pending/queued or failed? */
1294           int err = GetLastError ();
1295           if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1296             { /* error occurred, close this path */
1297               output_facility->path_open = FALSE;
1298               output_facility->facility_state = IOSTATE_FAILED;
1299               fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1300             }
1301         }
1302     default: 
1303       return TRUE;
1304     }
1305 }
1306
1307
1308 /**
1309  * Initialize a overlapped structure
1310  * 
1311  * @param elem the element to initilize
1312  * @param initial_state the initial state for this instance
1313  * @param signaled if the hEvent created should default to signaled or not
1314  * @return true on success, else false
1315  */
1316 static BOOL
1317 initialize_io_facility (struct io_facility * elem,
1318                         int initial_state,
1319                         BOOL signaled)
1320 {
1321   elem->path_open = TRUE;
1322   elem->handle = INVALID_HANDLE_VALUE;
1323   elem->facility_state = initial_state;
1324   elem->buffer_size = 0;
1325   elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1326   if (NULL == elem->overlapped.hEvent)
1327     return FALSE;
1328
1329   return TRUE;
1330 }
1331
1332
1333 /**
1334  * Start forwarding to and from the tunnel.
1335  *
1336  * @param fd_tun tunnel FD
1337  */
1338 static void
1339 run (HANDLE tap_handle)
1340 {
1341   /* IO-Facility for reading from our virtual interface */
1342   struct io_facility tap_read;
1343   /* IO-Facility for writing to our virtual interface */
1344   struct io_facility tap_write;
1345   /* IO-Facility for reading from stdin */
1346   struct io_facility std_in;
1347   /* IO-Facility for writing to stdout */
1348   struct io_facility std_out;
1349
1350   HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1351   HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1352
1353   /* tun up: */
1354   /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1355    * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1356    *  
1357    * DHCP and such are all features we will never use in gnunet afaik.
1358    * But for openvpn those are essential.
1359    */
1360   if (! tun_up (tap_handle))
1361     return;
1362
1363   /* Initialize our overlapped IO structures*/
1364   if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1365         && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1366         && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1367         && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1368     goto teardown_final;
1369
1370   /* Handles for STDIN and STDOUT */
1371   tap_read.handle = tap_handle;
1372   tap_write.handle = tap_handle;
1373
1374 #ifdef DEBUG_TO_CONSOLE
1375   /* Debug output to console STDIN/STDOUT*/
1376   std_in.handle = parent_std_in_handle;
1377   std_out.handle = parent_std_out_handle;
1378   
1379 #else
1380   fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1381   /* 
1382    * Find out the types of our handles. 
1383    * This part is a problem, because in windows we need to handle files, 
1384    * pipes and the console differently.
1385    */
1386   if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1387       (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1388     {
1389       fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1390       goto teardown;
1391     }
1392
1393   std_in.handle = ReOpenFile (parent_std_in_handle,
1394                               GENERIC_READ,
1395                               FILE_SHARE_WRITE | FILE_SHARE_READ,
1396                               FILE_FLAG_OVERLAPPED);
1397
1398   if (INVALID_HANDLE_VALUE == std_in.handle)
1399     {
1400       fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1401       goto teardown;
1402     }
1403
1404   std_out.handle = ReOpenFile (parent_std_out_handle,
1405                                GENERIC_WRITE,
1406                                FILE_SHARE_READ,
1407                                FILE_FLAG_OVERLAPPED);
1408
1409   if (INVALID_HANDLE_VALUE == std_out.handle)
1410     {
1411       fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1412       goto teardown;
1413     }
1414 #endif
1415   
1416   fprintf (stderr, "DEBUG: mainloop has begun\n");
1417   
1418   while (std_out.path_open || tap_write.path_open)
1419     {
1420       /* perform READ from stdin if possible */
1421       if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1422         break;
1423
1424       /* perform READ from tap if possible */
1425       if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1426         break;
1427
1428       /* perform WRITE to tap if possible */
1429       if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1430         break;
1431
1432       /* perform WRITE to STDOUT if possible */
1433       if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1434         break;
1435     }
1436
1437 teardown:
1438
1439   fprintf (stderr, "DEBUG: teardown initiated\n");
1440       
1441   CancelIo (tap_handle);
1442   CancelIo (std_in.handle);
1443   CancelIo (std_out.handle);
1444
1445 teardown_final:
1446       
1447   CloseHandle (tap_handle);
1448 }
1449
1450
1451 /**
1452  * Open VPN tunnel interface.
1453  *
1454  * @param argc must be 6
1455  * @param argv 0: binary name ("gnunet-helper-exit")
1456  *             1: tunnel interface name ("gnunet-exit")
1457  *             2: IPv4 "physical" interface name ("eth0"), or "%" to not do IPv4 NAT
1458  *             3: IPv6 address ("::1"), or "-" to skip IPv6
1459  *             4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1460  *             5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1461  *             6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1462  */
1463 int
1464 main (int argc, char **argv)
1465 {
1466   char hwid[LINE_LEN];
1467   HANDLE handle;
1468   int global_ret = 0;
1469   BOOL have_ip4 = FALSE;
1470   BOOL have_ip6 = FALSE;
1471
1472   if (6 != argc)
1473     {
1474       fprintf (stderr, "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1475       return 1;
1476     }
1477
1478   strncpy (hwid, argv[1], LINE_LEN);
1479   hwid[LINE_LEN - 1] = '\0';
1480
1481   /* 
1482    * We use our PID for finding/resolving the control-panel name of our virtual 
1483    * device. PIDs are (of course) unique at runtime, thus we can safely use it 
1484    * as additional hardware-id for our device.
1485    */
1486   snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1487             hwid,
1488             _getpid ());
1489
1490   if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1491     {
1492       fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1493                hwid,
1494                argv[3],
1495                argv[4],
1496                argv[5],
1497                argv[6]);
1498       global_ret = -1;
1499       goto cleanup;
1500     }
1501
1502   fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1503   if (0 != strcmp (argv[3], "-"))
1504     {
1505       const char *address = argv[3];
1506       long prefix_len = atol (argv[4]);
1507
1508       if ((prefix_len < 1) || (prefix_len > 127))
1509         {
1510           fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1511           global_ret = -1;
1512           goto cleanup;
1513         }
1514
1515       fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n",address,prefix_len);
1516       if (0 != (global_ret = set_address6 (address, prefix_len)))
1517         goto cleanup;
1518
1519       have_ip6 = TRUE;
1520     }
1521
1522   if (0 != strcmp (argv[5], "-"))
1523     {
1524       const char *address = argv[5];
1525       const char *mask = argv[6];
1526
1527       fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n",address,mask);
1528       if (0 != (global_ret = set_address4 (address, mask)))
1529         goto cleanup;
1530
1531       // setup NAT, if possible
1532       if (0 != strcmp (argv[2], "%"))
1533         {
1534           /* TODO: " Windows Firewall with Advanced Security" (lol)
1535            * 
1536            * MS has REMOVED the routing/nat capabilities since Vista, thus
1537            * we can not setup NAT like in XP. Our best bet is 
1538            * to determine if we are running on XP, if we do, use netsh routing
1539            * else we need to use WFAS and do things ourselfs
1540            */
1541         }
1542       
1543       have_ip4 = TRUE;
1544     }
1545
1546   run (handle);
1547   global_ret = 0;
1548 cleanup:
1549
1550   if (have_ip4)
1551     {
1552       const char *address = argv[5];
1553       fprintf (stderr, "DEBUG: Removing IP4 address\n");
1554       remove_address4 (address);
1555     }
1556   if (have_ip6)
1557     {
1558       const char *address = argv[3];
1559       fprintf (stderr, "DEBUG: Removing IP6 address\n");
1560       remove_address6 (address);
1561     }
1562
1563   fprintf (stderr, "DEBUG: removing interface\n");
1564   remove_interface ();
1565   fprintf (stderr, "DEBUG: graceful exit completed\n");
1566
1567   return global_ret;
1568 }