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