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