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