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