2 This file is part of GNUnet.
3 (C) 2010, 2012 Christian Grothoff
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.
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.
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.
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
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):
37 #ifndef __MINGW64_VERSION_MAJOR
38 #include <ddk/cfgmgr32.h>
39 #include <ddk/newdev.h>
46 #include "tap-windows.h"
48 * Need 'struct GNUNET_MessageHeader'.
50 #include "gnunet_common.h"
53 * Need VPN message types.
55 #include "gnunet_protocols.h"
58 * Should we print (interesting|debug) messages that can happen during
61 #define DEBUG GNUNET_NO
64 /* FIXME: define with varargs... */
65 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
67 #define LOG_DEBUG(msg) do {} while (0)
71 * Will this binary be run in permissions testing mode?
73 static boolean privilege_testing = FALSE;
76 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
78 #define MAX_SIZE 65536
81 * Name or Path+Name of our win32 driver.
82 * The .sys and .cat files HAVE to be in the same location as this file!
84 #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
87 * Name or Path+Name of our win64 driver.
88 * The .sys and .cat files HAVE to be in the same location as this file!
90 #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
93 * Hardware ID used in the inf-file.
94 * This might change over time, as openvpn advances their driver
96 #define HARDWARE_ID "tap0901"
99 * Minimum major-id of the driver version we can work with
101 #define TAP_WIN_MIN_MAJOR 9
104 * Minimum minor-id of the driver version we can work with.
105 * v <= 7 has buggy IPv6.
106 * v == 8 is broken for small IPv4 Packets
108 #define TAP_WIN_MIN_MINOR 9
111 * Time in seconds to wait for our virtual device to go up after telling it to do so.
113 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
114 * (in fact, 4 was chosen by a fair dice roll...)
116 #define TAP32_POSTUP_WAITTIME 4
119 * Location of the network interface list resides in registry.
121 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
124 * Our local process' PID. Used for creating a sufficiently unique additional
125 * hardware ID for our device.
127 static char secondary_hwid[LINE_LEN / 2];
130 * Device's visible Name, used to identify a network device in netsh.
131 * eg: "Local Area Connection 9"
133 static char device_visible_name[256];
136 * This is our own local instance of a virtual network interface
137 * It is (somewhat) equivalent to using tun/tap in unixoid systems
139 * Upon initialization, we create such an device node.
140 * Upon termination, we remove it again.
142 * If we crash this device might stay around.
144 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
147 * Registry Key we hand over to windows to spawn a new virtual interface
149 static SP_DEVINFO_DATA DeviceNode;
152 * GUID of our virtual device in the form of
153 * {12345678-1234-1234-1234-123456789abc} - in hex
155 static char device_guid[256];
159 * Possible states of an IO facility.
165 * overlapped I/O is ready for work
170 * overlapped I/O has been queued
175 * overlapped I/O has finished, but is waiting for it's write-partner
180 * there is a full buffer waiting
185 * Operlapped IO states for facility objects
186 * overlapped I/O has failed, stop processing
194 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
199 * The mode the state machine associated with this object is in.
201 enum IO_State facility_state;
204 * If the path is open or blocked in general (used for quickly checking)
206 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
209 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
214 * Overlaped IO structure used for asynchronous IO in windows.
216 OVERLAPPED overlapped;
219 * Buffer for reading things to and writing from...
221 unsigned char buffer[MAX_SIZE];
224 * How much of this buffer was used when reading or how much data can be written
229 * Amount of data actually written or read by readfile/writefile.
231 DWORD buffer_size_processed;
234 * How much of this buffer we have written in total
236 DWORD buffer_size_written;
240 * ReOpenFile is only available as of XP SP2 and 2003 SP1
242 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
245 * IsWow64Process definition for our is_win64, as this is a kernel function
247 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
250 * Determines if the host OS is win32 or win64
258 //this is a win64 binary,
260 #elif defined(_WIN32)
261 //this is a 32bit binary, and we need to check if we are running in WOW64
262 BOOL success = FALSE;
263 BOOL on_wow64 = FALSE;
264 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
266 if (NULL != IsWow64Process)
267 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
269 return success && on_wow64;
273 * Wrapper for executing a shellcommand in windows.
275 * @param command - the command + parameters to execute
276 * @return * exitcode of the program executed,
277 * * EINVAL (cmd/file not found)
278 * * EPIPE (could not read STDOUT)
281 execute_shellcommand (const char *command)
285 if ( (NULL == command) ||
286 (NULL == (pipe = _popen (command, "rt"))) )
290 fprintf (stderr, "DEBUG: Command output: \n");
291 char output[LINE_LEN];
292 while (NULL != fgets (output, sizeof (output), pipe))
293 fprintf (stderr, "%s", output);
296 return _pclose (pipe);
301 * @brief Sets the IPv6-Address given in address on the interface dev
303 * @param address the IPv6-Address
304 * @param prefix_len the length of the network-prefix
307 set_address6 (const char *address, unsigned long prefix_len)
310 char command[LINE_LEN];
311 struct sockaddr_in6 sa6;
314 * parse the new address
316 memset (&sa6, 0, sizeof (struct sockaddr_in6));
317 sa6.sin6_family = AF_INET6;
318 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
320 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
326 * prepare the command
328 snprintf (command, LINE_LEN,
329 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
330 device_visible_name, address, prefix_len);
334 ret = execute_shellcommand (command);
338 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
344 * @brief Removes the IPv6-Address given in address from the interface dev
346 * @param address the IPv4-Address
349 remove_address6 (const char *address)
351 char command[LINE_LEN];
354 // sanity checking was already done in set_address6
356 * prepare the command
358 snprintf (command, LINE_LEN,
359 "netsh interface ipv6 delete address \"%s\" store=persistent",
360 device_visible_name, address);
364 ret = execute_shellcommand (command);
368 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
373 * @brief Sets the IPv4-Address given in address on the interface dev
375 * @param address the IPv4-Address
376 * @param mask the netmask
379 set_address4 (const char *address, const char *mask)
382 char command[LINE_LEN];
384 struct sockaddr_in addr;
385 addr.sin_family = AF_INET;
390 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
392 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
396 // Set Device to Subnet-Mode?
397 // do we really need tun.c:2925 ?
400 * prepare the command
402 snprintf (command, LINE_LEN,
403 "netsh interface ipv4 add address \"%s\" %s %s store=active",
404 device_visible_name, address, mask);
408 ret = execute_shellcommand (command);
412 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
418 * @brief Removes the IPv4-Address given in address from the interface dev
420 * @param address the IPv4-Address
423 remove_address4 (const char *address)
425 char command[LINE_LEN];
428 // sanity checking was already done in set_address4
431 * prepare the command
433 snprintf (command, LINE_LEN,
434 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
435 device_visible_name, address);
439 ret = execute_shellcommand (command);
443 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
448 * Setup a new virtual interface to use for tunneling.
450 * @return: TRUE if setup was successful, else FALSE
456 * where to find our inf-file. (+ the "full" path, after windows found")
458 * We do not directly input all the props here, because openvpn will update
459 * these details over time.
461 char inf_file_path[MAX_PATH];
462 char * temp_inf_filename;
463 char hwidlist[LINE_LEN + 4];
464 char class_name[128];
469 * Set the device's hardware ID and add it to a list.
470 * This information will later on identify this device in registry.
472 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
474 * this is kind of over-complicated, but allows keeps things independent of
475 * how the openvpn-hwid is actually stored.
477 * A HWID list is double-\0 terminated and \0 separated
479 str_length = strlen (hwidlist) + 1;
480 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
481 str_length += strlen (&hwidlist[str_length]) + 1;
484 * Locate the inf-file, we need to store it somewhere where the system can
485 * find it. We need to pick the correct driver for win32/win64.
488 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
490 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
492 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
494 * Bootstrap our device info using the drivers inf-file
496 if ( ! SetupDiGetINFClassA (inf_file_path,
498 class_name, sizeof (class_name) / sizeof (char),
503 * Collect all the other needed information...
504 * let the system fill our this form
506 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
507 if (DeviceInfo == INVALID_HANDLE_VALUE)
510 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
511 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
520 /* Deploy all the information collected into the registry */
521 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
525 str_length * sizeof (char)))
528 /* Install our new class(=device) into the system */
529 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
534 /* This system call tends to take a while (several seconds!) on
535 "modern" Windoze systems */
536 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
539 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
540 NULL)) //reboot required? NEVER!
543 fprintf (stderr, "DEBUG: successfully created a network device\n");
549 * Remove our new virtual interface to use for tunneling.
550 * This function must be called AFTER setup_interface!
552 * @return: TRUE if destruction was successful, else FALSE
557 SP_REMOVEDEVICE_PARAMS remove;
559 if (INVALID_HANDLE_VALUE == DeviceInfo)
562 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
563 remove.HwProfile = 0;
564 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
565 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
567 * 1. Prepare our existing device information set, and place the
568 * uninstall related information into the structure
570 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
571 (PSP_DEVINFO_DATA) & DeviceNode,
572 &remove.ClassInstallHeader,
576 * 2. Uninstall the virtual interface using the class installer
578 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
580 (PSP_DEVINFO_DATA) & DeviceNode))
583 SetupDiDestroyDeviceInfoList (DeviceInfo);
585 fprintf (stderr, "DEBUG: removed interface successfully\n");
592 * Do all the lookup necessary to retrieve the inteface's actual name
595 * @return: TRUE if we were able to lookup the interface's name, else FALSE
598 resolve_interface_name ()
600 SP_DEVINFO_LIST_DETAIL_DATA device_details;
601 char pnp_instance_id [MAX_DEVICE_ID_LEN];
602 HKEY adapter_key_handle;
608 char adapter[] = INTERFACE_REGISTRY_LOCATION;
610 /* We can obtain the PNP instance ID from our setupapi handle */
611 device_details.cbSize = sizeof (device_details);
612 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
613 (PCHAR) pnp_instance_id,
616 NULL)) //hMachine, we are local
619 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
621 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
622 for (retrys = 0; retrys < 120 && !retval; retrys++)
627 /* Now we can use this ID to locate the correct networks interface in registry */
628 if (ERROR_SUCCESS != RegOpenKeyExA (
633 &adapter_key_handle))
636 /* Of course there is a multitude of entries here, with arbitrary names,
637 * thus we need to iterate through there.
641 char instance_key[256];
642 char query_key [256];
643 HKEY instance_key_handle;
644 char pnpinstanceid_name[] = "PnpInstanceID";
645 char pnpinstanceid_value[256];
646 char adaptername_name[] = "Name";
649 len = 256 * sizeof (char);
650 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
651 status = RegEnumKeyExA (
661 /* this may fail due to one of two reasons:
662 * we are at the end of the list*/
663 if (ERROR_NO_MORE_ITEMS == status)
665 // * we found a broken registry key, continue with the next key.
666 if (ERROR_SUCCESS != status)
669 /* prepare our new query string: */
670 snprintf (query_key, 256, "%s\\%s\\Connection",
674 /* look inside instance_key\\Connection */
675 if (ERROR_SUCCESS != RegOpenKeyExA (
680 &instance_key_handle))
683 /* now, read our PnpInstanceID */
684 len = sizeof (pnpinstanceid_value);
685 status = RegQueryValueExA (instance_key_handle,
687 NULL, //reserved, always NULL according to MSDN
689 (LPBYTE) pnpinstanceid_value,
692 if (status != ERROR_SUCCESS || data_type != REG_SZ)
695 /* compare the value we got to our devices PNPInstanceID*/
696 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
697 sizeof (pnpinstanceid_value) / sizeof (char)))
700 len = sizeof (device_visible_name);
701 status = RegQueryValueExA (
704 NULL, //reserved, always NULL according to MSDN
706 (LPBYTE) device_visible_name,
709 if (status != ERROR_SUCCESS || data_type != REG_SZ)
713 * we have successfully found OUR instance,
714 * save the device GUID before exiting
717 strncpy (device_guid, instance_key, 256);
719 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
722 RegCloseKey (instance_key_handle);
727 RegCloseKey (adapter_key_handle);
734 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
736 * @param handle the handle to our tap device
737 * @return TRUE if the version is sufficient, else FALSE
740 check_tapw32_version (HANDLE handle)
744 memset (&(version), 0, sizeof (version));
746 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
747 &version, sizeof (version),
748 &version, sizeof (version), &len, NULL))
749 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
752 (version[2] ? "(DEBUG)" : ""));
754 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
755 (version[1] < TAP_WIN_MIN_MINOR )){
756 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
767 * Creates a tun-interface called dev;
769 * @return the fd to the tun or -1 on error
774 char device_path[256];
777 if (! setup_interface ())
780 return INVALID_HANDLE_VALUE;
783 if (! resolve_interface_name ())
786 return INVALID_HANDLE_VALUE;
789 /* Open Windows TAP-Windows adapter */
790 snprintf (device_path, sizeof (device_path), "%s%s%s",
795 handle = CreateFile (
797 GENERIC_READ | GENERIC_WRITE,
798 0, /* was: FILE_SHARE_READ */
801 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
805 if (INVALID_HANDLE_VALUE == handle)
807 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
811 /* get driver version info */
812 if (! check_tapw32_version (handle))
814 CloseHandle (handle);
815 return INVALID_HANDLE_VALUE;
818 /* TODO (opt?): get MTU-Size */
820 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
826 * Brings a TAP device up and sets it to connected state.
828 * @param handle the handle to our TAP device
829 * @return True if the operation succeeded, else false
832 tun_up (HANDLE handle)
836 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
837 &status, sizeof (status),
838 &status, sizeof (status), &len, NULL))
840 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
844 /* Wait for the device to go UP, might take some time. */
845 Sleep (TAP32_POSTUP_WAITTIME * 1000);
846 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
853 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
856 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
857 * input handle. Then it goes into IOSTATE_QUEUED state.
858 * In case the read succeeded instantly the input facility enters 3.
861 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
862 * If it has finished, go to state 3.
863 * If it has failed, set IOSTATE_FAILED
866 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
867 * The input facility enters state IOSTATE_READY
868 * The output facility enters state IOSTATE_READY
869 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
871 * IOSTATE_WAITING is reset by the output facility, once it has completed.
873 * @param input_facility input named pipe or file to work with.
874 * @param output_facility output pipe or file to hand over data to.
875 * @return false if an event reset was impossible (OS error), else true
878 attempt_read_tap (struct io_facility * input_facility,
879 struct io_facility * output_facility)
881 struct GNUNET_MessageHeader * hdr;
884 switch (input_facility->facility_state)
888 if (! ResetEvent (input_facility->overlapped.hEvent))
893 input_facility->buffer_size = 0;
895 /* Check how the task is handled */
896 if (ReadFile (input_facility->handle,
897 input_facility->buffer,
898 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
899 &input_facility->buffer_size,
900 &input_facility->overlapped))
901 {/* async event processed immediately*/
903 /* reset event manually*/
904 if (! SetEvent (input_facility->overlapped.hEvent))
907 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
909 /* we successfully read something from the TAP and now need to
910 * send it our via STDOUT. Is that possible at the moment? */
911 if ((IOSTATE_READY == output_facility->facility_state ||
912 IOSTATE_WAITING == output_facility->facility_state)
913 && (0 < input_facility->buffer_size))
914 { /* hand over this buffers content and apply message header for gnunet */
915 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
916 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
918 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
919 input_facility->buffer,
920 input_facility->buffer_size);
922 output_facility->buffer_size = size;
923 hdr->size = htons (size);
924 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
925 output_facility->facility_state = IOSTATE_READY;
927 else if (0 < input_facility->buffer_size)
928 /* If we have have read our buffer, wait for our write-partner*/
929 input_facility->facility_state = IOSTATE_WAITING;
931 else /* operation was either queued or failed*/
933 int err = GetLastError ();
934 if (ERROR_IO_PENDING == err)
935 { /* operation queued */
936 input_facility->facility_state = IOSTATE_QUEUED;
939 { /* error occurred, let the rest of the elements finish */
940 input_facility->path_open = FALSE;
941 input_facility->facility_state = IOSTATE_FAILED;
942 if (IOSTATE_WAITING == output_facility->facility_state)
943 output_facility->path_open = FALSE;
945 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
950 // We are queued and should check if the read has finished
953 // there was an operation going on already, check if that has completed now.
955 if (GetOverlappedResult (input_facility->handle,
956 &input_facility->overlapped,
957 &input_facility->buffer_size,
959 {/* successful return for a queued operation */
960 if (! ResetEvent (input_facility->overlapped.hEvent))
963 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
965 /* we successfully read something from the TAP and now need to
966 * send it our via STDOUT. Is that possible at the moment? */
967 if ((IOSTATE_READY == output_facility->facility_state ||
968 IOSTATE_WAITING == output_facility->facility_state)
969 && 0 < input_facility->buffer_size)
970 { /* hand over this buffers content and apply message header for gnunet */
971 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
972 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
974 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
975 input_facility->buffer,
976 input_facility->buffer_size);
978 output_facility->buffer_size = size;
979 hdr->size = htons(size);
980 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
981 output_facility->facility_state = IOSTATE_READY;
982 input_facility->facility_state = IOSTATE_READY;
984 else if (0 < input_facility->buffer_size)
985 { /* If we have have read our buffer, wait for our write-partner*/
986 input_facility->facility_state = IOSTATE_WAITING;
987 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
991 { /* operation still pending/queued or failed? */
992 int err = GetLastError ();
993 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
994 { /* error occurred, let the rest of the elements finish */
995 input_facility->path_open = FALSE;
996 input_facility->facility_state = IOSTATE_FAILED;
997 if (IOSTATE_WAITING == output_facility->facility_state)
998 output_facility->path_open = FALSE;
999 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1004 case IOSTATE_RESUME:
1005 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1006 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1008 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1009 input_facility->buffer,
1010 input_facility->buffer_size);
1012 output_facility->buffer_size = size;
1013 hdr->size = htons (size);
1014 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1015 output_facility->facility_state = IOSTATE_READY;
1016 input_facility->facility_state = IOSTATE_READY;
1025 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1028 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1029 * input handle. Then it goes into IOSTATE_QUEUED state.
1030 * In case the read succeeded instantly the input facility enters 3.
1033 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1034 * If it has finished, go to state 3.
1035 * If it has failed, set IOSTATE_FAILED
1038 * If the facility is finished with ready
1039 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1040 * The input facility enters state IOSTATE_READY
1041 * The output facility enters state IOSTATE_READY
1042 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1044 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1046 * @param input_facility input named pipe or file to work with.
1047 * @param output_facility output pipe or file to hand over data to.
1048 * @return false if an event reset was impossible (OS error), else true
1051 attempt_read_stdin (struct io_facility * input_facility,
1052 struct io_facility * output_facility)
1054 struct GNUNET_MessageHeader * hdr;
1056 switch (input_facility->facility_state)
1060 input_facility->buffer_size = 0;
1062 partial_read_iostate_ready:
1063 if (! ResetEvent (input_facility->overlapped.hEvent))
1066 /* Check how the task is handled */
1067 if (ReadFile (input_facility->handle,
1068 input_facility->buffer + input_facility->buffer_size,
1069 sizeof (input_facility->buffer) - input_facility->buffer_size,
1070 &input_facility->buffer_size_processed,
1071 &input_facility->overlapped))
1072 {/* async event processed immediately*/
1073 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1075 /* reset event manually*/
1076 if (!SetEvent (input_facility->overlapped.hEvent))
1079 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1080 input_facility->buffer_size += input_facility->buffer_size_processed;
1082 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1083 ntohs (hdr->size) > sizeof (input_facility->buffer))
1085 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1086 input_facility->facility_state = IOSTATE_READY;
1089 /* we got the a part of a packet */
1090 if (ntohs (hdr->size) > input_facility->buffer_size)
1091 goto partial_read_iostate_ready;
1093 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1094 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1095 ((IOSTATE_READY == output_facility->facility_state) ||
1096 (IOSTATE_WAITING == output_facility->facility_state)))
1097 {/* we successfully read something from the TAP and now need to
1098 * send it our via STDOUT. Is that possible at the moment? */
1100 /* hand over this buffers content and strip gnunet message header */
1101 memcpy (output_facility->buffer,
1102 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1103 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1104 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1105 output_facility->facility_state = IOSTATE_READY;
1106 input_facility->facility_state = IOSTATE_READY;
1108 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1109 /* If we have have read our buffer, wait for our write-partner*/
1110 input_facility->facility_state = IOSTATE_WAITING;
1111 else /* we read nothing */
1112 input_facility->facility_state = IOSTATE_READY;
1114 else /* operation was either queued or failed*/
1116 int err = GetLastError ();
1117 if (ERROR_IO_PENDING == err) /* operation queued */
1118 input_facility->facility_state = IOSTATE_QUEUED;
1120 { /* error occurred, let the rest of the elements finish */
1121 input_facility->path_open = FALSE;
1122 input_facility->facility_state = IOSTATE_FAILED;
1123 if (IOSTATE_WAITING == output_facility->facility_state)
1124 output_facility->path_open = FALSE;
1126 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1131 // We are queued and should check if the read has finished
1132 case IOSTATE_QUEUED:
1134 // there was an operation going on already, check if that has completed now.
1135 if (GetOverlappedResult (input_facility->handle,
1136 &input_facility->overlapped,
1137 &input_facility->buffer_size_processed,
1139 {/* successful return for a queued operation */
1140 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1142 if (! ResetEvent (input_facility->overlapped.hEvent))
1145 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1146 input_facility->buffer_size += input_facility->buffer_size_processed;
1148 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1149 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1151 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1152 input_facility->facility_state = IOSTATE_READY;
1155 /* we got the a part of a packet */
1156 if (ntohs (hdr->size) > input_facility->buffer_size );
1157 goto partial_read_iostate_ready;
1159 /* we successfully read something from the TAP and now need to
1160 * send it our via STDOUT. Is that possible at the moment? */
1161 if ((IOSTATE_READY == output_facility->facility_state ||
1162 IOSTATE_WAITING == output_facility->facility_state)
1163 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1164 { /* hand over this buffers content and strip gnunet message header */
1165 memcpy (output_facility->buffer,
1166 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1167 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1168 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1169 output_facility->facility_state = IOSTATE_READY;
1170 input_facility->facility_state = IOSTATE_READY;
1172 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1173 input_facility->facility_state = IOSTATE_WAITING;
1175 input_facility->facility_state = IOSTATE_READY;
1178 { /* operation still pending/queued or failed? */
1179 int err = GetLastError ();
1180 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1181 { /* error occurred, let the rest of the elements finish */
1182 input_facility->path_open = FALSE;
1183 input_facility->facility_state = IOSTATE_FAILED;
1184 if (IOSTATE_WAITING == output_facility->facility_state)
1185 output_facility->path_open = FALSE;
1186 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1191 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1192 memcpy (output_facility->buffer,
1193 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1194 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1195 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1196 output_facility->facility_state = IOSTATE_READY;
1197 input_facility->facility_state = IOSTATE_READY;
1206 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1208 * TODO: high level description
1210 * @param output_facility output pipe or file to hand over data to.
1211 * @param input_facility input named pipe or file to work with.
1212 * @return false if an event reset was impossible (OS error), else true
1215 attempt_write (struct io_facility * output_facility,
1216 struct io_facility * input_facility)
1218 switch (output_facility->facility_state)
1221 output_facility->buffer_size_written = 0;
1223 continue_partial_write:
1224 if (! ResetEvent (output_facility->overlapped.hEvent))
1227 /* Check how the task was handled */
1228 if (WriteFile (output_facility->handle,
1229 output_facility->buffer + output_facility->buffer_size_written,
1230 output_facility->buffer_size - output_facility->buffer_size_written,
1231 &output_facility->buffer_size_processed,
1232 &output_facility->overlapped))
1233 {/* async event processed immediately*/
1235 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1236 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1238 /* reset event manually*/
1239 if (! SetEvent (output_facility->overlapped.hEvent))
1243 if (output_facility->buffer_size_written < output_facility->buffer_size)
1244 goto continue_partial_write;
1246 /* we are now waiting for our buffer to be filled*/
1247 output_facility->facility_state = IOSTATE_WAITING;
1249 /* we successfully wrote something and now need to reset our reader */
1250 if (IOSTATE_WAITING == input_facility->facility_state)
1251 input_facility->facility_state = IOSTATE_RESUME;
1252 else if (IOSTATE_FAILED == input_facility->facility_state)
1253 output_facility->path_open = FALSE;
1255 else /* operation was either queued or failed*/
1257 int err = GetLastError ();
1258 if (ERROR_IO_PENDING == err)
1259 { /* operation queued */
1260 output_facility->facility_state = IOSTATE_QUEUED;
1263 { /* error occurred, close this path */
1264 output_facility->path_open = FALSE;
1265 output_facility->facility_state = IOSTATE_FAILED;
1266 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1270 case IOSTATE_QUEUED:
1271 // there was an operation going on already, check if that has completed now.
1273 if (GetOverlappedResult (output_facility->handle,
1274 &output_facility->overlapped,
1275 &output_facility->buffer_size_processed,
1277 {/* successful return for a queued operation */
1278 if (! ResetEvent (output_facility->overlapped.hEvent))
1281 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1282 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1285 if (output_facility->buffer_size_written < output_facility->buffer_size)
1286 goto continue_partial_write;
1288 /* we are now waiting for our buffer to be filled*/
1289 output_facility->facility_state = IOSTATE_WAITING;
1291 /* we successfully wrote something and now need to reset our reader */
1292 if (IOSTATE_WAITING == input_facility->facility_state)
1293 input_facility->facility_state = IOSTATE_RESUME;
1294 else if (IOSTATE_FAILED == input_facility->facility_state)
1295 output_facility->path_open = FALSE;
1298 { /* operation still pending/queued or failed? */
1299 int err = GetLastError ();
1300 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1301 { /* error occurred, close this path */
1302 output_facility->path_open = FALSE;
1303 output_facility->facility_state = IOSTATE_FAILED;
1304 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1314 * Initialize a overlapped structure
1316 * @param elem the element to initilize
1317 * @param initial_state the initial state for this instance
1318 * @param signaled if the hEvent created should default to signaled or not
1319 * @return true on success, else false
1322 initialize_io_facility (struct io_facility * elem,
1326 elem->path_open = TRUE;
1327 elem->handle = INVALID_HANDLE_VALUE;
1328 elem->facility_state = initial_state;
1329 elem->buffer_size = 0;
1330 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1331 if (NULL == elem->overlapped.hEvent)
1339 * Start forwarding to and from the tunnel.
1341 * @param tap_handle device handle for interacting with the Virtual interface
1344 run (HANDLE tap_handle)
1346 /* IO-Facility for reading from our virtual interface */
1347 struct io_facility tap_read;
1348 /* IO-Facility for writing to our virtual interface */
1349 struct io_facility tap_write;
1350 /* IO-Facility for reading from stdin */
1351 struct io_facility std_in;
1352 /* IO-Facility for writing to stdout */
1353 struct io_facility std_out;
1355 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1356 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1359 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1360 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1362 * DHCP and such are all features we will never use in gnunet afaik.
1363 * But for openvpn those are essential.
1365 if ((privilege_testing) || (! tun_up (tap_handle) ))
1366 goto teardown_final;
1368 /* Initialize our overlapped IO structures*/
1369 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1370 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1371 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1372 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1373 goto teardown_final;
1375 /* Handles for STDIN and STDOUT */
1376 tap_read.handle = tap_handle;
1377 tap_write.handle = tap_handle;
1379 #ifdef DEBUG_TO_CONSOLE
1380 /* Debug output to console STDIN/STDOUT*/
1381 std_in.handle = parent_std_in_handle;
1382 std_out.handle = parent_std_out_handle;
1385 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1387 * Find out the types of our handles.
1388 * This part is a problem, because in windows we need to handle files,
1389 * pipes and the console differently.
1391 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1392 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1394 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1398 std_in.handle = ReOpenFile (parent_std_in_handle,
1400 FILE_SHARE_WRITE | FILE_SHARE_READ,
1401 FILE_FLAG_OVERLAPPED);
1403 if (INVALID_HANDLE_VALUE == std_in.handle)
1405 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1409 std_out.handle = ReOpenFile (parent_std_out_handle,
1412 FILE_FLAG_OVERLAPPED);
1414 if (INVALID_HANDLE_VALUE == std_out.handle)
1416 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1421 fprintf (stderr, "DEBUG: mainloop has begun\n");
1423 while (std_out.path_open || tap_write.path_open)
1425 /* perform READ from stdin if possible */
1426 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1429 /* perform READ from tap if possible */
1430 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1433 /* perform WRITE to tap if possible */
1434 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1437 /* perform WRITE to STDOUT if possible */
1438 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1441 fprintf (stderr, "DEBUG: teardown initiated\n");
1445 CancelIo (tap_handle);
1446 CancelIo (std_in.handle);
1447 CancelIo (std_out.handle);
1451 CloseHandle (tap_handle);
1454 * Open VPN tunnel interface.
1456 * @param argc must be 6
1457 * @param argv 0: binary name ("gnunet-helper-exit")
1458 * 1: tunnel interface name ("gnunet-exit")
1459 * 2: IPv4 "physical" interface name ("eth0"), or "-" to not do IPv4 NAT
1460 * 3: IPv6 address ("::1"), or "-" to skip IPv6
1461 * 4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1462 * 5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1463 * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1466 main (int argc, char **argv)
1468 char hwid[LINE_LEN];
1471 int local_ret = EINVAL;
1472 BOOL have_ip4 = FALSE;
1473 BOOL have_ip6 = FALSE;
1474 BOOL have_nat44 = FALSE;
1476 if ( (1 < argc) && (0 != strcmp (argv[1], "-d"))){
1477 privilege_testing = TRUE;
1478 fprintf (stderr, "DEBUG: Running binary in privilege testing mode.", argv[0]);
1485 fprintf (stderr, "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit [-d] <if name prefix> <uplink-interface name> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1489 strncpy (hwid, argv[1], LINE_LEN);
1490 hwid[LINE_LEN - 1] = '\0';
1493 * We use our PID for finding/resolving the control-panel name of our virtual
1494 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1495 * as additional hardware-id for our device.
1497 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1501 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1503 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1513 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1514 if (0 != strcmp (argv[3], "-"))
1516 char command[LINE_LEN];
1517 const char *address = argv[3];
1518 long prefix_len = atol (argv[4]);
1520 if ((prefix_len < 1) || (prefix_len > 127))
1522 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1527 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1528 if (0 != (global_ret = set_address6 (address, prefix_len)))
1533 /* install our the windows NAT module*/
1534 fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n");
1535 /* outside interface (maybe that's already set) */
1536 snprintf (command, LINE_LEN,
1537 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active",
1539 local_ret = execute_shellcommand (command);
1542 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1545 /* internal interface */
1546 snprintf (command, LINE_LEN,
1547 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active",
1548 device_visible_name);
1549 local_ret = execute_shellcommand (command);
1552 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1555 /* we can keep IPv6 forwarding around, as all interfaces have
1556 * their forwarding mode reset to false at bootup. */
1559 if (0 != strcmp (argv[5], "-"))
1561 const char *address = argv[5];
1562 const char *mask = argv[6];
1564 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1565 if (0 != (global_ret = set_address4 (address, mask)))
1568 // setup NAPT, if possible
1569 /* MS has REMOVED the routing/nat capabilities from Vista+, thus
1570 * we can not setup NAT like in XP or on the server. Actually the
1571 * the only feasible solution seems to be to use
1572 * Internet Connection Sharing, which introduces a horde of problems
1573 * such as sending out rogue-RAs on the external interface in an ipv6
1575 * Thus, below stuff ONLY works on
1577 * Win Server 2003 SP1+
1582 if (0 != strcmp (argv[2], "-"))
1584 char command[LINE_LEN];
1586 /* install our the windows NAT module*/
1587 fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]);
1588 local_ret = execute_shellcommand ("netsh routing ip nat install");
1591 fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret));
1595 snprintf (command, LINE_LEN,
1596 "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/
1598 local_ret = execute_shellcommand (command);
1601 fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret));
1604 /* private/internal/virtual IF */
1605 snprintf (command, LINE_LEN,
1606 "netsh routing ip nat add interface \"%s\" private",
1607 device_visible_name);
1608 local_ret = execute_shellcommand (command);
1611 fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret));
1623 const char *address = argv[5];
1625 char command[LINE_LEN];
1626 fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n");
1627 snprintf(command, LINE_LEN,
1628 "netsh routing ip nat del interface \"%s\"",
1629 device_visible_name);
1630 local_ret = execute_shellcommand(command);
1632 fprintf(stderr, "WARNING: Could not remove IPv4-NAPT from internal interface, hopefully this will have no effect in future runs: %s\n", strerror(local_ret));
1635 fprintf(stderr, "DEBUG: Removing IP4 address\n");
1636 remove_address4 (address);
1640 const char *address = argv[3];
1641 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1642 remove_address6 (address);
1645 fprintf (stderr, "DEBUG: removing interface\n");
1646 remove_interface ();
1647 fprintf (stderr, "DEBUG: graceful exit completed\n");