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