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