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 vpn/gnunet-helper-vpn-windows.c
22 * @brief the helper for the VPN 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 writte 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? do we really need openvpn/tun.c:2925 ?
399 * prepare the command
401 snprintf (command, LINE_LEN,
402 "netsh interface ipv4 add address \"%s\" %s %s store=active",
403 device_visible_name, address, mask);
407 ret = execute_shellcommand (command);
411 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
417 * @brief Removes the IPv4-Address given in address from the interface dev
419 * @param address the IPv4-Address
422 remove_address4 (const char *address)
424 char command[LINE_LEN];
427 // sanity checking was already done in set_address4
430 * prepare the command
432 snprintf (command, LINE_LEN,
433 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
434 device_visible_name, address);
438 ret = execute_shellcommand (command);
442 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
447 * Setup a new virtual interface to use for tunneling.
449 * @return: TRUE if setup was successful, else FALSE
455 * where to find our inf-file. (+ the "full" path, after windows found")
457 * We do not directly input all the props here, because openvpn will update
458 * these details over time.
460 char inf_file_path[MAX_PATH];
461 char * temp_inf_filename;
462 char hwidlist[LINE_LEN + 4];
463 char class_name[128];
468 * Set the device's hardware ID and add it to a list.
469 * This information will later on identify this device in registry.
471 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
473 * this is kind of over-complicated, but allows keeps things independent of
474 * how the openvpn-hwid is actually stored.
476 * A HWID list is double-\0 terminated and \0 separated
478 str_length = strlen (hwidlist) + 1;
479 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
480 str_length += strlen (&hwidlist[str_length]) + 1;
483 * Locate the inf-file, we need to store it somewhere where the system can
484 * find it. We need to pick the correct driver for win32/win64.
487 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
489 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
491 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
493 * Bootstrap our device info using the drivers inf-file
495 if ( ! SetupDiGetINFClassA (inf_file_path,
497 class_name, sizeof (class_name) / sizeof (char),
502 * Collect all the other needed information...
503 * let the system fill our this form
505 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
506 if (DeviceInfo == INVALID_HANDLE_VALUE)
509 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
510 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
519 /* Deploy all the information collected into the registry */
520 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
524 str_length * sizeof (char)))
527 /* Install our new class(=device) into the system */
528 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
533 /* This system call tends to take a while (several seconds!) on
534 "modern" Windoze systems */
535 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
538 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
539 NULL)) //reboot required? NEVER!
542 fprintf (stderr, "DEBUG: successfully created a network device\n");
548 * Remove our new virtual interface to use for tunneling.
549 * This function must be called AFTER setup_interface!
551 * @return: TRUE if destruction was successful, else FALSE
556 SP_REMOVEDEVICE_PARAMS remove;
558 if (INVALID_HANDLE_VALUE == DeviceInfo)
561 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
562 remove.HwProfile = 0;
563 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
564 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
566 * 1. Prepare our existing device information set, and place the
567 * uninstall related information into the structure
569 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
570 (PSP_DEVINFO_DATA) & DeviceNode,
571 &remove.ClassInstallHeader,
575 * 2. Uninstall the virtual interface using the class installer
577 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
579 (PSP_DEVINFO_DATA) & DeviceNode))
582 SetupDiDestroyDeviceInfoList (DeviceInfo);
584 fprintf (stderr, "DEBUG: removed interface successfully\n");
591 * Do all the lookup necessary to retrieve the inteface's actual name
594 * @return: TRUE if we were able to lookup the interface's name, else FALSE
597 resolve_interface_name ()
599 SP_DEVINFO_LIST_DETAIL_DATA device_details;
600 char pnp_instance_id [MAX_DEVICE_ID_LEN];
601 HKEY adapter_key_handle;
607 char adapter[] = INTERFACE_REGISTRY_LOCATION;
609 /* We can obtain the PNP instance ID from our setupapi handle */
610 device_details.cbSize = sizeof (device_details);
611 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
612 (PCHAR) pnp_instance_id,
615 NULL)) //hMachine, we are local
618 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
620 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
621 for (retrys = 0; retrys < 120 && !retval; retrys++)
626 /* Now we can use this ID to locate the correct networks interface in registry */
627 if (ERROR_SUCCESS != RegOpenKeyExA (
632 &adapter_key_handle))
635 /* Of course there is a multitude of entries here, with arbitrary names,
636 * thus we need to iterate through there.
640 char instance_key[256];
641 char query_key [256];
642 HKEY instance_key_handle;
643 char pnpinstanceid_name[] = "PnpInstanceID";
644 char pnpinstanceid_value[256];
645 char adaptername_name[] = "Name";
648 len = 256 * sizeof (char);
649 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
650 status = RegEnumKeyExA (
660 /* this may fail due to one of two reasons:
661 * we are at the end of the list*/
662 if (ERROR_NO_MORE_ITEMS == status)
664 // * we found a broken registry key, continue with the next key.
665 if (ERROR_SUCCESS != status)
668 /* prepare our new query string: */
669 snprintf (query_key, 256, "%s\\%s\\Connection",
673 /* look inside instance_key\\Connection */
674 if (ERROR_SUCCESS != RegOpenKeyExA (
679 &instance_key_handle))
682 /* now, read our PnpInstanceID */
683 len = sizeof (pnpinstanceid_value);
684 status = RegQueryValueExA (instance_key_handle,
686 NULL, //reserved, always NULL according to MSDN
688 (LPBYTE) pnpinstanceid_value,
691 if (status != ERROR_SUCCESS || data_type != REG_SZ)
694 /* compare the value we got to our devices PNPInstanceID*/
695 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
696 sizeof (pnpinstanceid_value) / sizeof (char)))
699 len = sizeof (device_visible_name);
700 status = RegQueryValueExA (
703 NULL, //reserved, always NULL according to MSDN
705 (LPBYTE) device_visible_name,
708 if (status != ERROR_SUCCESS || data_type != REG_SZ)
712 * we have successfully found OUR instance,
713 * save the device GUID before exiting
716 strncpy (device_guid, instance_key, 256);
718 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
721 RegCloseKey (instance_key_handle);
726 RegCloseKey (adapter_key_handle);
733 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
735 * @param handle the handle to our tap device
736 * @return TRUE if the version is sufficient, else FALSE
739 check_tapw32_version (HANDLE handle)
743 memset (&(version), 0, sizeof (version));
745 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
746 &version, sizeof (version),
747 &version, sizeof (version), &len, NULL))
748 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
751 (version[2] ? "(DEBUG)" : ""));
753 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
754 (version[1] < TAP_WIN_MIN_MINOR )){
755 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
766 * Creates a tun-interface called dev;
768 * @return the fd to the tun or -1 on error
773 char device_path[256];
776 if (! setup_interface ())
779 return INVALID_HANDLE_VALUE;
782 if (! resolve_interface_name ())
785 return INVALID_HANDLE_VALUE;
788 /* Open Windows TAP-Windows adapter */
789 snprintf (device_path, sizeof (device_path), "%s%s%s",
794 handle = CreateFile (
796 GENERIC_READ | GENERIC_WRITE,
797 0, /* was: FILE_SHARE_READ */
800 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
804 if (INVALID_HANDLE_VALUE == handle)
806 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
810 /* get driver version info */
811 if (! check_tapw32_version (handle))
813 CloseHandle (handle);
814 return INVALID_HANDLE_VALUE;
817 /* TODO (opt?): get MTU-Size */
819 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
825 * Brings a TAP device up and sets it to connected state.
827 * @param handle the handle to our TAP device
828 * @return True if the operation succeeded, else false
831 tun_up (HANDLE handle)
835 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
836 &status, sizeof (status),
837 &status, sizeof (status), &len, NULL))
839 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
843 /* Wait for the device to go UP, might take some time. */
844 Sleep (TAP32_POSTUP_WAITTIME * 1000);
845 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
852 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
855 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
856 * input handle. Then it goes into IOSTATE_QUEUED state.
857 * In case the read succeeded instantly the input facility enters 3.
860 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
861 * If it has finished, go to state 3.
862 * If it has failed, set IOSTATE_FAILED
865 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
866 * The input facility enters state IOSTATE_READY
867 * The output facility enters state IOSTATE_READY
868 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
870 * IOSTATE_WAITING is reset by the output facility, once it has completed.
872 * @param input_facility input named pipe or file to work with.
873 * @param output_facility output pipe or file to hand over data to.
874 * @return false if an event reset was impossible (OS error), else true
877 attempt_read_tap (struct io_facility * input_facility,
878 struct io_facility * output_facility)
880 struct GNUNET_MessageHeader * hdr;
883 switch (input_facility->facility_state)
887 if (! ResetEvent (input_facility->overlapped.hEvent))
892 input_facility->buffer_size = 0;
894 /* Check how the task is handled */
895 if (ReadFile (input_facility->handle,
896 input_facility->buffer,
897 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
898 &input_facility->buffer_size,
899 &input_facility->overlapped))
900 {/* async event processed immediately*/
902 /* reset event manually*/
903 if (! SetEvent (input_facility->overlapped.hEvent))
906 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
908 /* we successfully read something from the TAP and now need to
909 * send it our via STDOUT. Is that possible at the moment? */
910 if ((IOSTATE_READY == output_facility->facility_state ||
911 IOSTATE_WAITING == output_facility->facility_state)
912 && (0 < input_facility->buffer_size))
913 { /* hand over this buffers content and apply message header for gnunet */
914 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
915 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
917 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
918 input_facility->buffer,
919 input_facility->buffer_size);
921 output_facility->buffer_size = size;
922 hdr->size = htons (size);
923 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
924 output_facility->facility_state = IOSTATE_READY;
926 else if (0 < input_facility->buffer_size)
927 /* If we have have read our buffer, wait for our write-partner*/
928 input_facility->facility_state = IOSTATE_WAITING;
930 else /* operation was either queued or failed*/
932 int err = GetLastError ();
933 if (ERROR_IO_PENDING == err)
934 { /* operation queued */
935 input_facility->facility_state = IOSTATE_QUEUED;
938 { /* error occurred, let the rest of the elements finish */
939 input_facility->path_open = FALSE;
940 input_facility->facility_state = IOSTATE_FAILED;
941 if (IOSTATE_WAITING == output_facility->facility_state)
942 output_facility->path_open = FALSE;
944 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
949 // We are queued and should check if the read has finished
952 // there was an operation going on already, check if that has completed now.
954 if (GetOverlappedResult (input_facility->handle,
955 &input_facility->overlapped,
956 &input_facility->buffer_size,
958 {/* successful return for a queued operation */
959 if (! ResetEvent (input_facility->overlapped.hEvent))
962 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
964 /* we successfully read something from the TAP and now need to
965 * send it our via STDOUT. Is that possible at the moment? */
966 if ((IOSTATE_READY == output_facility->facility_state ||
967 IOSTATE_WAITING == output_facility->facility_state)
968 && 0 < input_facility->buffer_size)
969 { /* hand over this buffers content and apply message header for gnunet */
970 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
971 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
973 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
974 input_facility->buffer,
975 input_facility->buffer_size);
977 output_facility->buffer_size = size;
978 hdr->size = htons(size);
979 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
980 output_facility->facility_state = IOSTATE_READY;
981 input_facility->facility_state = IOSTATE_READY;
983 else if (0 < input_facility->buffer_size)
984 { /* If we have have read our buffer, wait for our write-partner*/
985 input_facility->facility_state = IOSTATE_WAITING;
986 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
990 { /* operation still pending/queued or failed? */
991 int err = GetLastError ();
992 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
993 { /* error occurred, let the rest of the elements finish */
994 input_facility->path_open = FALSE;
995 input_facility->facility_state = IOSTATE_FAILED;
996 if (IOSTATE_WAITING == output_facility->facility_state)
997 output_facility->path_open = FALSE;
998 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1003 case IOSTATE_RESUME:
1004 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1005 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1007 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1008 input_facility->buffer,
1009 input_facility->buffer_size);
1011 output_facility->buffer_size = size;
1012 hdr->size = htons (size);
1013 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1014 output_facility->facility_state = IOSTATE_READY;
1015 input_facility->facility_state = IOSTATE_READY;
1024 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1027 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1028 * input handle. Then it goes into IOSTATE_QUEUED state.
1029 * In case the read succeeded instantly the input facility enters 3.
1032 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1033 * If it has finished, go to state 3.
1034 * If it has failed, set IOSTATE_FAILED
1037 * If the facility is finished with ready
1038 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1039 * The input facility enters state IOSTATE_READY
1040 * The output facility enters state IOSTATE_READY
1041 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1043 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1045 * @param input_facility input named pipe or file to work with.
1046 * @param output_facility output pipe or file to hand over data to.
1047 * @return false if an event reset was impossible (OS error), else true
1050 attempt_read_stdin (struct io_facility * input_facility,
1051 struct io_facility * output_facility)
1053 struct GNUNET_MessageHeader * hdr;
1055 switch (input_facility->facility_state)
1059 input_facility->buffer_size = 0;
1061 partial_read_iostate_ready:
1062 if (! ResetEvent (input_facility->overlapped.hEvent))
1065 /* Check how the task is handled */
1066 if (ReadFile (input_facility->handle,
1067 input_facility->buffer + input_facility->buffer_size,
1068 sizeof (input_facility->buffer) - input_facility->buffer_size,
1069 &input_facility->buffer_size_processed,
1070 &input_facility->overlapped))
1071 {/* async event processed immediately*/
1072 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1074 /* reset event manually*/
1075 if (!SetEvent (input_facility->overlapped.hEvent))
1078 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1079 input_facility->buffer_size += input_facility->buffer_size_processed;
1081 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1082 ntohs (hdr->size) > sizeof (input_facility->buffer))
1084 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1085 input_facility->facility_state = IOSTATE_READY;
1088 /* we got the a part of a packet */
1089 if (ntohs (hdr->size) > input_facility->buffer_size)
1090 goto partial_read_iostate_ready;
1092 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1093 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1094 ((IOSTATE_READY == output_facility->facility_state) ||
1095 (IOSTATE_WAITING == output_facility->facility_state)))
1096 {/* we successfully read something from the TAP and now need to
1097 * send it our via STDOUT. Is that possible at the moment? */
1099 /* hand over this buffers content and strip gnunet message header */
1100 memcpy (output_facility->buffer,
1101 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1102 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1103 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1104 output_facility->facility_state = IOSTATE_READY;
1105 input_facility->facility_state = IOSTATE_READY;
1107 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1108 /* If we have have read our buffer, wait for our write-partner*/
1109 input_facility->facility_state = IOSTATE_WAITING;
1110 else /* we read nothing */
1111 input_facility->facility_state = IOSTATE_READY;
1113 else /* operation was either queued or failed*/
1115 int err = GetLastError ();
1116 if (ERROR_IO_PENDING == err) /* operation queued */
1117 input_facility->facility_state = IOSTATE_QUEUED;
1119 { /* error occurred, let the rest of the elements finish */
1120 input_facility->path_open = FALSE;
1121 input_facility->facility_state = IOSTATE_FAILED;
1122 if (IOSTATE_WAITING == output_facility->facility_state)
1123 output_facility->path_open = FALSE;
1125 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1130 // We are queued and should check if the read has finished
1131 case IOSTATE_QUEUED:
1133 // there was an operation going on already, check if that has completed now.
1134 if (GetOverlappedResult (input_facility->handle,
1135 &input_facility->overlapped,
1136 &input_facility->buffer_size_processed,
1138 {/* successful return for a queued operation */
1139 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1141 if (! ResetEvent (input_facility->overlapped.hEvent))
1144 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1145 input_facility->buffer_size += input_facility->buffer_size_processed;
1147 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1148 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1150 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1151 input_facility->facility_state = IOSTATE_READY;
1154 /* we got the a part of a packet */
1155 if (ntohs (hdr->size) > input_facility->buffer_size );
1156 goto partial_read_iostate_ready;
1158 /* we successfully read something from the TAP and now need to
1159 * send it our via STDOUT. Is that possible at the moment? */
1160 if ((IOSTATE_READY == output_facility->facility_state ||
1161 IOSTATE_WAITING == output_facility->facility_state)
1162 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1163 { /* hand over this buffers content and strip gnunet message header */
1164 memcpy (output_facility->buffer,
1165 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1166 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1167 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1168 output_facility->facility_state = IOSTATE_READY;
1169 input_facility->facility_state = IOSTATE_READY;
1171 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1172 input_facility->facility_state = IOSTATE_WAITING;
1174 input_facility->facility_state = IOSTATE_READY;
1177 { /* operation still pending/queued or failed? */
1178 int err = GetLastError ();
1179 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1180 { /* error occurred, let the rest of the elements finish */
1181 input_facility->path_open = FALSE;
1182 input_facility->facility_state = IOSTATE_FAILED;
1183 if (IOSTATE_WAITING == output_facility->facility_state)
1184 output_facility->path_open = FALSE;
1185 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1190 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1191 memcpy (output_facility->buffer,
1192 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1193 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1194 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1195 output_facility->facility_state = IOSTATE_READY;
1196 input_facility->facility_state = IOSTATE_READY;
1205 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1207 * TODO: high level description
1209 * @param output_facility output pipe or file to hand over data to.
1210 * @param input_facility input named pipe or file to work with.
1211 * @return false if an event reset was impossible (OS error), else true
1214 attempt_write (struct io_facility * output_facility,
1215 struct io_facility * input_facility)
1217 switch (output_facility->facility_state)
1220 output_facility->buffer_size_written = 0;
1222 continue_partial_write:
1223 if (! ResetEvent (output_facility->overlapped.hEvent))
1226 /* Check how the task was handled */
1227 if (WriteFile (output_facility->handle,
1228 output_facility->buffer + output_facility->buffer_size_written,
1229 output_facility->buffer_size - output_facility->buffer_size_written,
1230 &output_facility->buffer_size_processed,
1231 &output_facility->overlapped))
1232 {/* async event processed immediately*/
1234 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1235 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1237 /* reset event manually*/
1238 if (! SetEvent (output_facility->overlapped.hEvent))
1242 if (output_facility->buffer_size_written < output_facility->buffer_size)
1243 goto continue_partial_write;
1245 /* we are now waiting for our buffer to be filled*/
1246 output_facility->facility_state = IOSTATE_WAITING;
1248 /* we successfully wrote something and now need to reset our reader */
1249 if (IOSTATE_WAITING == input_facility->facility_state)
1250 input_facility->facility_state = IOSTATE_RESUME;
1251 else if (IOSTATE_FAILED == input_facility->facility_state)
1252 output_facility->path_open = FALSE;
1254 else /* operation was either queued or failed*/
1256 int err = GetLastError ();
1257 if (ERROR_IO_PENDING == err)
1258 { /* operation queued */
1259 output_facility->facility_state = IOSTATE_QUEUED;
1262 { /* error occurred, close this path */
1263 output_facility->path_open = FALSE;
1264 output_facility->facility_state = IOSTATE_FAILED;
1265 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1269 case IOSTATE_QUEUED:
1270 // there was an operation going on already, check if that has completed now.
1272 if (GetOverlappedResult (output_facility->handle,
1273 &output_facility->overlapped,
1274 &output_facility->buffer_size_processed,
1276 {/* successful return for a queued operation */
1277 if (! ResetEvent (output_facility->overlapped.hEvent))
1280 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1281 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1284 if (output_facility->buffer_size_written < output_facility->buffer_size)
1285 goto continue_partial_write;
1287 /* we are now waiting for our buffer to be filled*/
1288 output_facility->facility_state = IOSTATE_WAITING;
1290 /* we successfully wrote something and now need to reset our reader */
1291 if (IOSTATE_WAITING == input_facility->facility_state)
1292 input_facility->facility_state = IOSTATE_RESUME;
1293 else if (IOSTATE_FAILED == input_facility->facility_state)
1294 output_facility->path_open = FALSE;
1297 { /* operation still pending/queued or failed? */
1298 int err = GetLastError ();
1299 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1300 { /* error occurred, close this path */
1301 output_facility->path_open = FALSE;
1302 output_facility->facility_state = IOSTATE_FAILED;
1303 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1313 * Initialize a overlapped structure
1315 * @param elem the element to initilize
1316 * @param initial_state the initial state for this instance
1317 * @param signaled if the hEvent created should default to signaled or not
1318 * @return true on success, else false
1321 initialize_io_facility (struct io_facility * elem,
1325 elem->path_open = TRUE;
1326 elem->handle = INVALID_HANDLE_VALUE;
1327 elem->facility_state = initial_state;
1328 elem->buffer_size = 0;
1329 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1330 if (NULL == elem->overlapped.hEvent)
1338 * Start forwarding to and from the tunnel.
1340 * @param tap_handle device handle for interacting with the Virtual interface
1343 run (HANDLE tap_handle)
1345 /* IO-Facility for reading from our virtual interface */
1346 struct io_facility tap_read;
1347 /* IO-Facility for writing to our virtual interface */
1348 struct io_facility tap_write;
1349 /* IO-Facility for reading from stdin */
1350 struct io_facility std_in;
1351 /* IO-Facility for writing to stdout */
1352 struct io_facility std_out;
1354 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1355 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1358 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1359 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1361 * DHCP and such are all features we will never use in gnunet afaik.
1362 * But for openvpn those are essential.
1364 if ((privilege_testing) || (! tun_up (tap_handle)))
1365 goto teardown_final;
1367 /* Initialize our overlapped IO structures*/
1368 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1369 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1370 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1371 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1372 goto teardown_final;
1374 /* Handles for STDIN and STDOUT */
1375 tap_read.handle = tap_handle;
1376 tap_write.handle = tap_handle;
1378 #ifdef DEBUG_TO_CONSOLE
1379 /* Debug output to console STDIN/STDOUT*/
1380 std_in.handle = parent_std_in_handle;
1381 std_out.handle = parent_std_out_handle;
1384 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1386 * Find out the types of our handles.
1387 * This part is a problem, because in windows we need to handle files,
1388 * pipes and the console differently.
1390 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1391 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1393 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1397 std_in.handle = ReOpenFile (parent_std_in_handle,
1399 FILE_SHARE_WRITE | FILE_SHARE_READ,
1400 FILE_FLAG_OVERLAPPED);
1402 if (INVALID_HANDLE_VALUE == std_in.handle)
1404 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1408 std_out.handle = ReOpenFile (parent_std_out_handle,
1411 FILE_FLAG_OVERLAPPED);
1413 if (INVALID_HANDLE_VALUE == std_out.handle)
1415 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1420 fprintf (stderr, "DEBUG: mainloop has begun\n");
1422 while (std_out.path_open || tap_write.path_open)
1424 /* perform READ from stdin if possible */
1425 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1428 /* perform READ from tap if possible */
1429 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1432 /* perform WRITE to tap if possible */
1433 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1436 /* perform WRITE to STDOUT if possible */
1437 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1441 fprintf (stderr, "DEBUG: teardown initiated\n");
1443 CancelIo (tap_handle);
1444 CancelIo (std_in.handle);
1445 CancelIo (std_out.handle);
1447 CloseHandle (tap_handle);
1452 * Open VPN tunnel interface.
1454 * @param argc must be 6
1455 * @param argv 0: binary name (gnunet-helper-vpn)
1456 * [1: dryrun/testrun (does not execute mainloop)]
1457 * 2: tunnel interface prefix (gnunet-vpn)
1458 * 3: IPv6 address (::1), "-" to disable
1459 * 4: IPv6 netmask length in bits (64), ignored if #2 is "-"
1460 * 5: IPv4 address (1.2.3.4), "-" to disable
1461 * 6: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
1464 main (int argc, char **argv)
1466 char hwid[LINE_LEN];
1469 BOOL have_ip4 = FALSE;
1470 BOOL have_ip6 = FALSE;
1472 if (argc > 1 && 0 != strcmp (argv[1], "-d")){
1473 privilege_testing = TRUE;
1474 fprintf (stderr, "DEBUG: Running binary in privilege testing mode.", argv[0]);
1481 fprintf (stderr, "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn [-d] <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1485 strncpy (hwid, argv[1], LINE_LEN);
1486 hwid[LINE_LEN - 1] = '\0';
1489 * We use our PID for finding/resolving the control-panel name of our virtual
1490 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1491 * as additional hardware-id for our device.
1493 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1497 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1499 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1509 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1510 if (0 != strcmp (argv[2], "-"))
1512 const char *address = argv[2];
1513 long prefix_len = atol (argv[3]);
1515 if ((prefix_len < 1) || (prefix_len > 127))
1517 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1522 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n",address,prefix_len);
1523 if (0 != (global_ret = set_address6 (address, prefix_len)))
1529 if (0 != strcmp (argv[4], "-"))
1531 const char *address = argv[4];
1532 const char *mask = argv[5];
1534 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n",address,mask);
1535 if (0 != (global_ret = set_address4 (address, mask)))
1546 const char *address = argv[4];
1547 fprintf (stderr, "DEBUG: Removing IP4 address\n");
1548 remove_address4 (address);
1552 const char *address = argv[2];
1553 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1554 remove_address6 (address);
1557 fprintf (stderr, "DEBUG: removing interface\n");
1558 remove_interface ();
1559 fprintf (stderr, "DEBUG: graceful exit completed\n");