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