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