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