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