glitch in the license text detected by hyazinthe, thank you!
[oweals/gnunet.git] / src / exit / gnunet-helper-exit-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 exit/gnunet-helper-exit-windows.c
17  * @brief the helper for the EXIT 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 written 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, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
368 }
369
370
371 /**
372  * @brief Sets the IPv4-Address given in address on the interface dev
373  *
374  * @param address the IPv4-Address
375  * @param mask the netmask
376  */
377 static int
378 set_address4 (const char *address, const char *mask)
379 {
380   int ret = EINVAL;
381   char command[LINE_LEN];
382
383   struct sockaddr_in addr;
384   addr.sin_family = AF_INET;
385
386   /*
387    * Parse the address
388    */
389   if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
390     {
391       fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
392                strerror (errno));
393       return -1;
394     }
395   // Set Device to Subnet-Mode?
396   // do we really need 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);
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                 GNUNET_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                 GNUNET_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       GNUNET_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                 GNUNET_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                 GNUNET_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       GNUNET_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   fprintf (stderr, "DEBUG: teardown initiated\n");
1441
1442 teardown:
1443
1444   CancelIo (tap_handle);
1445   CancelIo (std_in.handle);
1446   CancelIo (std_out.handle);
1447
1448 teardown_final:
1449
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-exit")
1459  *             1: tunnel interface name ("gnunet-exit")
1460  *             2: IPv4 "physical" interface name ("eth0"), or "-" to not do IPv4 NAT
1461  *             3: IPv6 address ("::1"), or "-" to skip IPv6
1462  *             4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1463  *             5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
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 = 1;
1472   int local_ret = EINVAL;
1473   BOOL have_ip4 = FALSE;
1474   BOOL have_ip6 = FALSE;
1475   BOOL have_nat44 = FALSE;
1476
1477   if ( (1 < argc) && (0 != strcmp (argv[1], "-d"))){
1478       privilege_testing = TRUE;
1479       fprintf (stderr,
1480                "%s",
1481                "DEBUG: Running binary in privilege testing mode.");
1482       argv++;
1483       argc--;
1484     }
1485
1486   if (6 != argc)
1487     {
1488       fprintf (stderr,
1489                "%s",
1490                "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit [-d] <if name prefix> <uplink-interface name> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n");
1491       return 1;
1492     }
1493
1494   strncpy (hwid, argv[1], LINE_LEN);
1495   hwid[LINE_LEN - 1] = '\0';
1496
1497   /*
1498    * We use our PID for finding/resolving the control-panel name of our virtual
1499    * device. PIDs are (of course) unique at runtime, thus we can safely use it
1500    * as additional hardware-id for our device.
1501    */
1502   snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1503             hwid,
1504             _getpid ());
1505
1506   if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1507     {
1508       fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1509                hwid,
1510                argv[3],
1511                argv[4],
1512                argv[5],
1513                argv[6]);
1514       global_ret = -1;
1515       goto cleanup;
1516     }
1517
1518   fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1519   if (0 != strcmp (argv[3], "-"))
1520     {
1521       char command[LINE_LEN];
1522       const char *address = argv[3];
1523       long prefix_len = atol (argv[4]);
1524
1525       if ((prefix_len < 1) || (prefix_len > 127))
1526         {
1527           fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1528           global_ret = -1;
1529           goto cleanup;
1530         }
1531
1532       fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1533       if (0 != (global_ret = set_address6 (address, prefix_len)))
1534         goto cleanup;
1535
1536       have_ip6 = TRUE;
1537
1538       /* install our the windows NAT module*/
1539       fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n");
1540       /* outside interface (maybe that's already set) */
1541       snprintf (command, LINE_LEN,
1542                 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active",
1543                 argv[2]);
1544       local_ret = execute_shellcommand (command);
1545       if (0 != local_ret)
1546         {
1547           fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1548           goto cleanup;
1549         }
1550       /* internal interface */
1551       snprintf (command, LINE_LEN,
1552                 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active",
1553                 device_visible_name);
1554       local_ret = execute_shellcommand (command);
1555       if (0 != local_ret)
1556         {
1557           fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1558           goto cleanup;
1559         }
1560       /* we can keep IPv6 forwarding around, as all interfaces have
1561        * their forwarding mode reset to false at bootup. */
1562     }
1563
1564   if (0 != strcmp (argv[5], "-"))
1565     {
1566       const char *address = argv[5];
1567       const char *mask = argv[6];
1568
1569       fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1570       if (0 != (global_ret = set_address4 (address, mask)))
1571         goto cleanup;
1572
1573       // setup NAPT, if possible
1574       /* MS has REMOVED the routing/nat capabilities from Vista+, thus
1575        * we can not setup NAT like in XP or on the server. Actually the
1576        * the only feasible solution seems to be to use
1577        * Internet Connection Sharing, which introduces a horde of problems
1578        * such as sending out rogue-RAs on the external interface in an ipv6
1579        * network.
1580        * Thus, below stuff ONLY works on
1581        *   WinXP SP3
1582        *   Win Server 2003 SP1+
1583        *   Win Server 2008
1584        *   ...
1585        */
1586       have_ip4 = TRUE;
1587       if (0 != strcmp (argv[2], "-"))
1588         {
1589           char command[LINE_LEN];
1590
1591           /* install our the windows NAT module*/
1592           fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]);
1593           local_ret = execute_shellcommand ("netsh routing ip nat install");
1594           if (0 != local_ret)
1595             {
1596               fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret));
1597               goto cleanup;
1598             }
1599           /* external IF */
1600           snprintf (command, LINE_LEN,
1601                     "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/
1602                     argv[2]);
1603           local_ret = execute_shellcommand (command);
1604           if (0 != local_ret)
1605             {
1606               fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret));
1607               goto cleanup;
1608             }
1609           /* private/internal/virtual IF */
1610           snprintf (command, LINE_LEN,
1611                     "netsh routing ip nat add interface \"%s\" private",
1612                     device_visible_name);
1613           local_ret = execute_shellcommand (command);
1614           if (0 != local_ret)
1615             {
1616               fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret));
1617               goto cleanup;
1618
1619               have_nat44 = TRUE;
1620             }
1621         }
1622     }
1623
1624   run (handle);
1625 cleanup:
1626
1627   if (have_ip4) {
1628       const char *address = argv[5];
1629       if (have_nat44) {
1630           char command[LINE_LEN];
1631           fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n");
1632           snprintf(command, LINE_LEN,
1633                    "netsh routing ip nat del interface \"%s\"",
1634                    device_visible_name);
1635           local_ret = execute_shellcommand(command);
1636           if (0 != local_ret)
1637               fprintf(stderr, "WARNING: Could not remove IPv4-NAPT from internal interface, hopefully this will have no effect in future runs: %s\n", strerror(local_ret));
1638       }
1639
1640       fprintf(stderr, "DEBUG: Removing IP4 address\n");
1641       remove_address4 (address);
1642   }
1643   if (have_ip6)
1644     {
1645       const char *address = argv[3];
1646       fprintf (stderr, "DEBUG: Removing IP6 address\n");
1647       remove_address6 (address);
1648     }
1649
1650   fprintf (stderr, "DEBUG: removing interface\n");
1651   remove_interface ();
1652   fprintf (stderr, "DEBUG: graceful exit completed\n");
1653
1654   return global_ret;
1655 }