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