2 This file is part of GNUnet.
3 Copyright (C) 2010, 2012 Christian Grothoff
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.
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.
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/>.
18 SPDX-License-Identifier: AGPL3.0-or-later
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_HashCode' and 'struct GNUNET_PeerIdentity'.
50 #include "gnunet_crypto_lib.h"
52 * Need 'struct GNUNET_MessageHeader'.
54 #include "gnunet_common.h"
57 * Need VPN message types.
59 #include "gnunet_protocols.h"
62 * Should we print (interesting|debug) messages that can happen during
65 #define DEBUG GNUNET_NO
68 /* FIXME: define with varargs... */
69 #define LOG_DEBUG(msg) fprintf(stderr, "%s", msg);
71 #define LOG_DEBUG(msg) do {} while (0)
75 * Will this binary be run in permissions testing mode?
77 static boolean privilege_testing = FALSE;
80 * Maximum size of a GNUnet message (GNUNET_MAX_MESSAGE_SIZE)
82 #define MAX_SIZE 65536
85 * Name or Path+Name of our win32 driver.
86 * The .sys and .cat files HAVE to be in the same location as this file!
88 #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
91 * Name or Path+Name of our win64 driver.
92 * The .sys and .cat files HAVE to be in the same location as this file!
94 #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
97 * Hardware ID used in the inf-file.
98 * This might change over time, as openvpn advances their driver
100 #define HARDWARE_ID "tap0901"
103 * Minimum major-id of the driver version we can work with
105 #define TAP_WIN_MIN_MAJOR 9
108 * Minimum minor-id of the driver version we can work with.
109 * v <= 7 has buggy IPv6.
110 * v == 8 is broken for small IPv4 Packets
112 #define TAP_WIN_MIN_MINOR 9
115 * Time in seconds to wait for our virtual device to go up after telling it to do so.
117 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
118 * (in fact, 4 was chosen by a fair dice roll...)
120 #define TAP32_POSTUP_WAITTIME 4
123 * Location of the network interface list resides in registry.
125 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
128 * Our local process' PID. Used for creating a sufficiently unique additional
129 * hardware ID for our device.
131 static char secondary_hwid[LINE_LEN / 2];
134 * Device's visible Name, used to identify a network device in netsh.
135 * eg: "Local Area Connection 9"
137 static char device_visible_name[256];
140 * This is our own local instance of a virtual network interface
141 * It is (somewhat) equivalent to using tun/tap in unixoid systems
143 * Upon initialization, we create such an device node.
144 * Upon termination, we remove it again.
146 * If we crash this device might stay around.
148 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
151 * Registry Key we hand over to windows to spawn a new virtual interface
153 static SP_DEVINFO_DATA DeviceNode;
156 * GUID of our virtual device in the form of
157 * {12345678-1234-1234-1234-123456789abc} - in hex
159 static char device_guid[256];
163 * Possible states of an IO facility.
167 * overlapped I/O is ready for work
172 * overlapped I/O has been queued
177 * overlapped I/O has finished, but is waiting for it's write-partner
182 * there is a full buffer waiting
187 * Operlapped IO states for facility objects
188 * overlapped I/O has failed, stop processing
195 * 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);
251 * Like strlcpy but portable. The given string @a src is copied until its null
252 * byte or until @a n - 1 bytes have been read. The destination buffer is
253 * guaranteed to be null-terminated.
255 * @param dst destination of the copy (must be @a n bytes long)
256 * @param src source of the copy (at most @a n - 1 bytes will be read)
257 * @param n the length of the string to copy, including its terminating null
259 * @return the length of the string that was copied, excluding the terminating
263 GNUNET_strlcpy(char *dst, const char *src, size_t n)
268 GNUNET_assert(0 != n);
269 slen = strnlen(src, n - 1);
270 memcpy(dst, src, slen);
277 * Determines if the host OS is win32 or win64
285 //this is a win64 binary,
287 #elif defined(_WIN32)
288 //this is a 32bit binary, and we need to check if we are running in WOW64
289 BOOL success = FALSE;
290 BOOL on_wow64 = FALSE;
291 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
293 if (NULL != IsWow64Process)
294 success = IsWow64Process(GetCurrentProcess(), &on_wow64);
296 return success && on_wow64;
300 * Wrapper for executing a shellcommand in windows.
302 * @param command - the command + parameters to execute
303 * @return * exitcode of the program executed,
304 * * EINVAL (cmd/file not found)
305 * * EPIPE (could not read STDOUT)
308 execute_shellcommand(const char *command)
312 if ((NULL == command) ||
313 (NULL == (pipe = _popen(command, "rt"))))
317 fprintf(stderr, "DEBUG: Command output: \n");
318 char output[LINE_LEN];
319 while (NULL != fgets(output, sizeof(output), pipe))
320 fprintf(stderr, "%s", output);
323 return _pclose(pipe);
328 * @brief Sets the IPv6-Address given in address on the interface dev
330 * @param address the IPv6-Address
331 * @param prefix_len the length of the network-prefix
334 set_address6(const char *address, unsigned long prefix_len)
337 char command[LINE_LEN];
338 struct sockaddr_in6 sa6;
341 * parse the new address
343 memset(&sa6, 0, sizeof(struct sockaddr_in6));
344 sa6.sin6_family = AF_INET6;
345 if (1 != inet_pton(AF_INET6, address, &sa6.sin6_addr.s6_addr))
347 fprintf(stderr, "ERROR: Failed to parse address `%s': %s\n", address,
353 * prepare the command
355 snprintf(command, LINE_LEN,
356 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
357 device_visible_name, address, prefix_len);
361 ret = execute_shellcommand(command);
365 fprintf(stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror(ret));
371 * @brief Removes the IPv6-Address given in address from the interface dev
373 * @param address the IPv4-Address
376 remove_address6(const char *address)
378 char command[LINE_LEN];
381 // sanity checking was already done in set_address6
383 * prepare the command
385 snprintf(command, LINE_LEN,
386 "netsh interface ipv6 delete address \"%s\" store=persistent",
387 device_visible_name);
391 ret = execute_shellcommand(command);
396 "FATAL: removing IPv6 address failed: %s\n",
402 * @brief Sets the IPv4-Address given in address on the interface dev
404 * @param address the IPv4-Address
405 * @param mask the netmask
408 set_address4(const char *address, const char *mask)
411 char command[LINE_LEN];
413 struct sockaddr_in addr;
415 addr.sin_family = AF_INET;
420 if (1 != inet_pton(AF_INET, address, &addr.sin_addr.s_addr))
422 fprintf(stderr, "ERROR: Failed to parse address `%s': %s\n", address,
426 // Set Device to Subnet-Mode? do we really need openvpn/tun.c:2925 ?
429 * prepare the command
431 snprintf(command, LINE_LEN,
432 "netsh interface ipv4 add address \"%s\" %s %s store=active",
433 device_visible_name, address, mask);
437 ret = execute_shellcommand(command);
442 "FATAL: Setting IPv4 address failed: %s\n",
449 * @brief Removes the IPv4-Address given in address from the interface dev
451 * @param address the IPv4-Address
454 remove_address4(const char *address)
456 char command[LINE_LEN];
459 // sanity checking was already done in set_address4
462 * prepare the command
464 snprintf(command, LINE_LEN,
465 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
466 device_visible_name);
470 ret = execute_shellcommand(command);
474 fprintf(stderr, "FATAL: removing IPv4 address failed: %s\n", strerror(ret));
479 * Setup a new virtual interface to use for tunneling.
481 * @return: TRUE if setup was successful, else FALSE
487 * where to find our inf-file. (+ the "full" path, after windows found")
489 * We do not directly input all the props here, because openvpn will update
490 * these details over time.
492 char inf_file_path[MAX_PATH];
493 char * temp_inf_filename;
494 char hwidlist[LINE_LEN + 4];
495 char class_name[128];
500 * Set the device's hardware ID and add it to a list.
501 * This information will later on identify this device in registry.
503 str_len = GNUNET_strlcpy(hwidlist,
505 sizeof(hwidList)) + 1;
507 * this is kind of over-complicated, but allows keeps things independent of
508 * how the openvpn-hwid is actually stored.
510 * A HWID list is double-\0 terminated and \0 separated
512 str_len += GNUNET_strlcpy(&hwidlist[str_length],
514 sizeof(hwidlist) - str_len) + 1;
515 GNUNET_assert(str_len < sizeof(hwidlist));
516 hwidlist[str_len] = '\0';
520 * Locate the inf-file, we need to store it somewhere where the system can
521 * find it. We need to pick the correct driver for win32/win64.
524 GetFullPathNameA(INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
526 GetFullPathNameA(INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
528 fprintf(stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
530 * Bootstrap our device info using the drivers inf-file
532 if (!SetupDiGetINFClassA(inf_file_path,
534 class_name, sizeof(class_name) / sizeof(char),
539 * Collect all the other needed information...
540 * let the system fill our this form
542 DeviceInfo = SetupDiCreateDeviceInfoList(&class_guid, NULL);
543 if (DeviceInfo == INVALID_HANDLE_VALUE)
546 DeviceNode.cbSize = sizeof(SP_DEVINFO_DATA);
547 if (!SetupDiCreateDeviceInfoA(DeviceInfo,
556 /* Deploy all the information collected into the registry */
557 if (!SetupDiSetDeviceRegistryPropertyA(DeviceInfo,
561 str_length * sizeof(char)))
564 /* Install our new class(=device) into the system */
565 if (!SetupDiCallClassInstaller(DIF_REGISTERDEVICE,
570 /* This system call tends to take a while (several seconds!) on
571 "modern" Windoze systems */
572 if (!UpdateDriverForPlugAndPlayDevicesA(NULL,
575 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
576 NULL)) //reboot required? NEVER!
579 fprintf(stderr, "DEBUG: successfully created a network device\n");
585 * Remove our new virtual interface to use for tunneling.
586 * This function must be called AFTER setup_interface!
588 * @return: TRUE if destruction was successful, else FALSE
593 SP_REMOVEDEVICE_PARAMS remove;
595 if (INVALID_HANDLE_VALUE == DeviceInfo)
598 remove.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
599 remove.HwProfile = 0;
600 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
601 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
603 * 1. Prepare our existing device information set, and place the
604 * uninstall related information into the structure
606 if (!SetupDiSetClassInstallParamsA(DeviceInfo,
607 (PSP_DEVINFO_DATA)&DeviceNode,
608 &remove.ClassInstallHeader,
612 * 2. Uninstall the virtual interface using the class installer
614 if (!SetupDiCallClassInstaller(DIF_REMOVE,
616 (PSP_DEVINFO_DATA)&DeviceNode))
619 SetupDiDestroyDeviceInfoList(DeviceInfo);
621 fprintf(stderr, "DEBUG: removed interface successfully\n");
628 * Do all the lookup necessary to retrieve the inteface's actual name
631 * @return: TRUE if we were able to lookup the interface's name, else FALSE
634 resolve_interface_name()
636 SP_DEVINFO_LIST_DETAIL_DATA device_details;
637 char pnp_instance_id [MAX_DEVICE_ID_LEN];
638 HKEY adapter_key_handle;
644 char adapter[] = INTERFACE_REGISTRY_LOCATION;
646 /* We can obtain the PNP instance ID from our setupapi handle */
647 device_details.cbSize = sizeof(device_details);
648 if (CR_SUCCESS != CM_Get_Device_ID_ExA(DeviceNode.DevInst,
649 (PCHAR)pnp_instance_id,
652 NULL)) //hMachine, we are local
655 fprintf(stderr, "DEBUG: Resolving interface name for network device %s\n", pnp_instance_id);
657 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
658 for (retrys = 0; retrys < 120 && !retval; retrys++)
663 /* Now we can use this ID to locate the correct networks interface in registry */
664 if (ERROR_SUCCESS != RegOpenKeyExA(
669 &adapter_key_handle))
672 /* Of course there is a multitude of entries here, with arbitrary names,
673 * thus we need to iterate through there.
677 char instance_key[256];
678 char query_key [256];
679 HKEY instance_key_handle;
680 char pnpinstanceid_name[] = "PnpInstanceID";
681 char pnpinstanceid_value[256];
682 char adaptername_name[] = "Name";
685 len = 256 * sizeof(char);
686 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
687 status = RegEnumKeyExA(
697 /* this may fail due to one of two reasons:
698 * we are at the end of the list*/
699 if (ERROR_NO_MORE_ITEMS == status)
701 // * we found a broken registry key, continue with the next key.
702 if (ERROR_SUCCESS != status)
705 /* prepare our new query string: */
706 snprintf(query_key, 256, "%s\\%s\\Connection",
710 /* look inside instance_key\\Connection */
711 if (ERROR_SUCCESS != RegOpenKeyExA(
716 &instance_key_handle))
719 /* now, read our PnpInstanceID */
720 len = sizeof(pnpinstanceid_value);
721 status = RegQueryValueExA(instance_key_handle,
723 NULL, //reserved, always NULL according to MSDN
725 (LPBYTE)pnpinstanceid_value,
728 if (status != ERROR_SUCCESS || data_type != REG_SZ)
731 /* compare the value we got to our devices PNPInstanceID*/
732 if (0 != strncmp(pnpinstanceid_value, pnp_instance_id,
733 sizeof(pnpinstanceid_value) / sizeof(char)))
736 len = sizeof(device_visible_name);
737 status = RegQueryValueExA(
740 NULL, //reserved, always NULL according to MSDN
742 (LPBYTE)device_visible_name,
745 if (status != ERROR_SUCCESS || data_type != REG_SZ)
749 * we have successfully found OUR instance,
750 * save the device GUID before exiting
752 GNUNET_strlcpy(device_guid, instance_key, sizeof(device_guid));
754 fprintf(stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
757 RegCloseKey(instance_key_handle);
762 RegCloseKey(adapter_key_handle);
769 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
771 * @param handle the handle to our tap device
772 * @return TRUE if the version is sufficient, else FALSE
775 check_tapw32_version(HANDLE handle)
780 memset(&(version), 0, sizeof(version));
782 if (DeviceIoControl(handle, TAP_WIN_IOCTL_GET_VERSION,
783 &version, sizeof(version),
784 &version, sizeof(version), &len, NULL))
785 fprintf(stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
788 (version[2] ? "(DEBUG)" : ""));
790 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
791 (version[1] < TAP_WIN_MIN_MINOR))
793 fprintf(stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
804 * Creates a tun-interface called dev;
806 * @return the fd to the tun or -1 on error
811 char device_path[256];
814 if (!setup_interface())
817 return INVALID_HANDLE_VALUE;
820 if (!resolve_interface_name())
823 return INVALID_HANDLE_VALUE;
826 /* Open Windows TAP-Windows adapter */
827 snprintf(device_path, sizeof(device_path), "%s%s%s",
834 GENERIC_READ | GENERIC_WRITE,
835 0, /* was: FILE_SHARE_READ */
838 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
842 if (INVALID_HANDLE_VALUE == handle)
844 fprintf(stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
848 /* get driver version info */
849 if (!check_tapw32_version(handle))
852 return INVALID_HANDLE_VALUE;
855 /* TODO (opt?): get MTU-Size */
857 fprintf(stderr, "DEBUG: successfully opened TAP device\n");
863 * Brings a TAP device up and sets it to connected state.
865 * @param handle the handle to our TAP device
866 * @return True if the operation succeeded, else false
869 tun_up(HANDLE handle)
874 if (!DeviceIoControl(handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
875 &status, sizeof(status),
876 &status, sizeof(status), &len, NULL))
878 fprintf(stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
882 /* Wait for the device to go UP, might take some time. */
883 Sleep(TAP32_POSTUP_WAITTIME * 1000);
884 fprintf(stderr, "DEBUG: successfully set TAP device to UP\n");
891 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
894 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
895 * input handle. Then it goes into IOSTATE_QUEUED state.
896 * In case the read succeeded instantly the input facility enters 3.
899 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
900 * If it has finished, go to state 3.
901 * If it has failed, set IOSTATE_FAILED
904 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
905 * The input facility enters state IOSTATE_READY
906 * The output facility enters state IOSTATE_READY
907 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
909 * IOSTATE_WAITING is reset by the output facility, once it has completed.
911 * @param input_facility input named pipe or file to work with.
912 * @param output_facility output pipe or file to hand over data to.
913 * @return false if an event reset was impossible (OS error), else true
916 attempt_read_tap(struct io_facility * input_facility,
917 struct io_facility * output_facility)
919 struct GNUNET_MessageHeader * hdr;
922 switch (input_facility->facility_state)
926 if (!ResetEvent(input_facility->overlapped.hEvent))
931 input_facility->buffer_size = 0;
933 /* Check how the task is handled */
934 if (ReadFile(input_facility->handle,
935 input_facility->buffer,
936 sizeof(input_facility->buffer) - sizeof(struct GNUNET_MessageHeader),
937 &input_facility->buffer_size,
938 &input_facility->overlapped))
939 { /* async event processed immediately*/
940 /* reset event manually*/
941 if (!SetEvent(input_facility->overlapped.hEvent))
944 fprintf(stderr, "DEBUG: tap read succeeded immediately\n");
946 /* we successfully read something from the TAP and now need to
947 * send it our via STDOUT. Is that possible at the moment? */
948 if ((IOSTATE_READY == output_facility->facility_state ||
949 IOSTATE_WAITING == output_facility->facility_state)
950 && (0 < input_facility->buffer_size))
951 { /* hand over this buffers content and apply message header for gnunet */
952 hdr = (struct GNUNET_MessageHeader *)output_facility->buffer;
953 size = input_facility->buffer_size + sizeof(struct GNUNET_MessageHeader);
955 GNUNET_memcpy(output_facility->buffer + sizeof(struct GNUNET_MessageHeader),
956 input_facility->buffer,
957 input_facility->buffer_size);
959 output_facility->buffer_size = size;
960 hdr->size = htons(size);
961 hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
962 output_facility->facility_state = IOSTATE_READY;
964 else if (0 < input_facility->buffer_size)
965 /* If we have have read our buffer, wait for our write-partner*/
966 input_facility->facility_state = IOSTATE_WAITING;
968 else /* operation was either queued or failed*/
970 int err = GetLastError();
971 if (ERROR_IO_PENDING == err)
972 { /* operation queued */
973 input_facility->facility_state = IOSTATE_QUEUED;
976 { /* error occurred, let the rest of the elements finish */
977 input_facility->path_open = FALSE;
978 input_facility->facility_state = IOSTATE_FAILED;
979 if (IOSTATE_WAITING == output_facility->facility_state)
980 output_facility->path_open = FALSE;
982 fprintf(stderr, "FATAL: Read from handle failed, allowing write to finish\n");
988 // We are queued and should check if the read has finished
991 // there was an operation going on already, check if that has completed now.
993 if (GetOverlappedResult(input_facility->handle,
994 &input_facility->overlapped,
995 &input_facility->buffer_size,
997 { /* successful return for a queued operation */
998 if (!ResetEvent(input_facility->overlapped.hEvent))
1001 fprintf(stderr, "DEBUG: tap read succeeded delayed\n");
1003 /* we successfully read something from the TAP and now need to
1004 * send it our via STDOUT. Is that possible at the moment? */
1005 if ((IOSTATE_READY == output_facility->facility_state ||
1006 IOSTATE_WAITING == output_facility->facility_state)
1007 && 0 < input_facility->buffer_size)
1008 { /* hand over this buffers content and apply message header for gnunet */
1009 hdr = (struct GNUNET_MessageHeader *)output_facility->buffer;
1010 size = input_facility->buffer_size + sizeof(struct GNUNET_MessageHeader);
1012 GNUNET_memcpy(output_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1013 input_facility->buffer,
1014 input_facility->buffer_size);
1016 output_facility->buffer_size = size;
1017 hdr->size = htons(size);
1018 hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
1019 output_facility->facility_state = IOSTATE_READY;
1020 input_facility->facility_state = IOSTATE_READY;
1022 else if (0 < input_facility->buffer_size)
1023 { /* If we have have read our buffer, wait for our write-partner*/
1024 input_facility->facility_state = IOSTATE_WAITING;
1025 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
1029 { /* operation still pending/queued or failed? */
1030 int err = GetLastError();
1031 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1032 { /* error occurred, let the rest of the elements finish */
1033 input_facility->path_open = FALSE;
1034 input_facility->facility_state = IOSTATE_FAILED;
1035 if (IOSTATE_WAITING == output_facility->facility_state)
1036 output_facility->path_open = FALSE;
1037 fprintf(stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1043 case IOSTATE_RESUME:
1044 hdr = (struct GNUNET_MessageHeader *)output_facility->buffer;
1045 size = input_facility->buffer_size + sizeof(struct GNUNET_MessageHeader);
1047 GNUNET_memcpy(output_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1048 input_facility->buffer,
1049 input_facility->buffer_size);
1051 output_facility->buffer_size = size;
1052 hdr->size = htons(size);
1053 hdr->type = htons(GNUNET_MESSAGE_TYPE_VPN_HELPER);
1054 output_facility->facility_state = IOSTATE_READY;
1055 input_facility->facility_state = IOSTATE_READY;
1065 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1068 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1069 * input handle. Then it goes into IOSTATE_QUEUED state.
1070 * In case the read succeeded instantly the input facility enters 3.
1073 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1074 * If it has finished, go to state 3.
1075 * If it has failed, set IOSTATE_FAILED
1078 * If the facility is finished with ready
1079 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1080 * The input facility enters state IOSTATE_READY
1081 * The output facility enters state IOSTATE_READY
1082 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1084 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1086 * @param input_facility input named pipe or file to work with.
1087 * @param output_facility output pipe or file to hand over data to.
1088 * @return false if an event reset was impossible (OS error), else true
1091 attempt_read_stdin(struct io_facility * input_facility,
1092 struct io_facility * output_facility)
1094 struct GNUNET_MessageHeader * hdr;
1096 switch (input_facility->facility_state)
1100 input_facility->buffer_size = 0;
1102 partial_read_iostate_ready:
1103 if (!ResetEvent(input_facility->overlapped.hEvent))
1106 /* Check how the task is handled */
1107 if (ReadFile(input_facility->handle,
1108 input_facility->buffer + input_facility->buffer_size,
1109 sizeof(input_facility->buffer) - input_facility->buffer_size,
1110 &input_facility->buffer_size_processed,
1111 &input_facility->overlapped))
1112 { /* async event processed immediately*/
1113 hdr = (struct GNUNET_MessageHeader *)input_facility->buffer;
1115 /* reset event manually*/
1116 if (!SetEvent(input_facility->overlapped.hEvent))
1119 fprintf(stderr, "DEBUG: stdin read succeeded immediately\n");
1120 input_facility->buffer_size += input_facility->buffer_size_processed;
1122 if (ntohs(hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1123 ntohs(hdr->size) > sizeof(input_facility->buffer))
1125 fprintf(stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs(hdr->type), ntohs(hdr->size));
1126 input_facility->facility_state = IOSTATE_READY;
1129 /* we got the a part of a packet */
1130 if (ntohs(hdr->size) > input_facility->buffer_size)
1131 goto partial_read_iostate_ready;
1133 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1134 if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader) &&
1135 ((IOSTATE_READY == output_facility->facility_state) ||
1136 (IOSTATE_WAITING == output_facility->facility_state)))
1137 { /* we successfully read something from the TAP and now need to
1138 * send it our via STDOUT. Is that possible at the moment? */
1139 /* hand over this buffers content and strip gnunet message header */
1140 GNUNET_memcpy(output_facility->buffer,
1141 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1142 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1143 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1144 output_facility->facility_state = IOSTATE_READY;
1145 input_facility->facility_state = IOSTATE_READY;
1147 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1148 /* If we have have read our buffer, wait for our write-partner*/
1149 input_facility->facility_state = IOSTATE_WAITING;
1150 else /* we read nothing */
1151 input_facility->facility_state = IOSTATE_READY;
1153 else /* operation was either queued or failed*/
1155 int err = GetLastError();
1156 if (ERROR_IO_PENDING == err) /* operation queued */
1157 input_facility->facility_state = IOSTATE_QUEUED;
1159 { /* error occurred, let the rest of the elements finish */
1160 input_facility->path_open = FALSE;
1161 input_facility->facility_state = IOSTATE_FAILED;
1162 if (IOSTATE_WAITING == output_facility->facility_state)
1163 output_facility->path_open = FALSE;
1165 fprintf(stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1171 // We are queued and should check if the read has finished
1172 case IOSTATE_QUEUED:
1174 // there was an operation going on already, check if that has completed now.
1175 if (GetOverlappedResult(input_facility->handle,
1176 &input_facility->overlapped,
1177 &input_facility->buffer_size_processed,
1179 { /* successful return for a queued operation */
1180 hdr = (struct GNUNET_MessageHeader *)input_facility->buffer;
1182 if (!ResetEvent(input_facility->overlapped.hEvent))
1185 fprintf(stderr, "DEBUG: stdin read succeeded delayed\n");
1186 input_facility->buffer_size += input_facility->buffer_size_processed;
1188 if ((ntohs(hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1189 (ntohs(hdr->size) > sizeof(input_facility->buffer)))
1191 fprintf(stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs(hdr->type), ntohs(hdr->size));
1192 input_facility->facility_state = IOSTATE_READY;
1195 /* we got the a part of a packet */
1196 if (ntohs(hdr->size) > input_facility->buffer_size)
1198 goto partial_read_iostate_ready;
1200 /* we successfully read something from the TAP and now need to
1201 * send it our via STDOUT. Is that possible at the moment? */
1202 if ((IOSTATE_READY == output_facility->facility_state ||
1203 IOSTATE_WAITING == output_facility->facility_state)
1204 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1205 { /* hand over this buffers content and strip gnunet message header */
1206 GNUNET_memcpy(output_facility->buffer,
1207 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1208 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1209 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1210 output_facility->facility_state = IOSTATE_READY;
1211 input_facility->facility_state = IOSTATE_READY;
1213 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1214 input_facility->facility_state = IOSTATE_WAITING;
1216 input_facility->facility_state = IOSTATE_READY;
1219 { /* operation still pending/queued or failed? */
1220 int err = GetLastError();
1221 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1222 { /* error occurred, let the rest of the elements finish */
1223 input_facility->path_open = FALSE;
1224 input_facility->facility_state = IOSTATE_FAILED;
1225 if (IOSTATE_WAITING == output_facility->facility_state)
1226 output_facility->path_open = FALSE;
1227 fprintf(stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1233 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1234 GNUNET_memcpy(output_facility->buffer,
1235 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1236 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1237 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1238 output_facility->facility_state = IOSTATE_READY;
1239 input_facility->facility_state = IOSTATE_READY;
1249 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1251 * TODO: high level description
1253 * @param output_facility output pipe or file to hand over data to.
1254 * @param input_facility input named pipe or file to work with.
1255 * @return false if an event reset was impossible (OS error), else true
1258 attempt_write(struct io_facility * output_facility,
1259 struct io_facility * input_facility)
1261 switch (output_facility->facility_state)
1264 output_facility->buffer_size_written = 0;
1266 continue_partial_write:
1267 if (!ResetEvent(output_facility->overlapped.hEvent))
1270 /* Check how the task was handled */
1271 if (WriteFile(output_facility->handle,
1272 output_facility->buffer + output_facility->buffer_size_written,
1273 output_facility->buffer_size - output_facility->buffer_size_written,
1274 &output_facility->buffer_size_processed,
1275 &output_facility->overlapped))
1276 {/* async event processed immediately*/
1277 fprintf(stderr, "DEBUG: write succeeded immediately\n");
1278 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1280 /* reset event manually*/
1281 if (!SetEvent(output_facility->overlapped.hEvent))
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;
1297 else /* operation was either queued or failed*/
1299 int err = GetLastError();
1300 if (ERROR_IO_PENDING == err)
1301 { /* operation queued */
1302 output_facility->facility_state = IOSTATE_QUEUED;
1305 { /* error occurred, close this path */
1306 output_facility->path_open = FALSE;
1307 output_facility->facility_state = IOSTATE_FAILED;
1308 fprintf(stderr, "FATAL: Write to handle failed, exiting\n");
1313 case IOSTATE_QUEUED:
1314 // there was an operation going on already, check if that has completed now.
1316 if (GetOverlappedResult(output_facility->handle,
1317 &output_facility->overlapped,
1318 &output_facility->buffer_size_processed,
1320 {/* successful return for a queued operation */
1321 if (!ResetEvent(output_facility->overlapped.hEvent))
1324 fprintf(stderr, "DEBUG: write succeeded delayed\n");
1325 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1328 if (output_facility->buffer_size_written < output_facility->buffer_size)
1329 goto continue_partial_write;
1331 /* we are now waiting for our buffer to be filled*/
1332 output_facility->facility_state = IOSTATE_WAITING;
1334 /* we successfully wrote something and now need to reset our reader */
1335 if (IOSTATE_WAITING == input_facility->facility_state)
1336 input_facility->facility_state = IOSTATE_RESUME;
1337 else if (IOSTATE_FAILED == input_facility->facility_state)
1338 output_facility->path_open = FALSE;
1341 { /* operation still pending/queued or failed? */
1342 int err = GetLastError();
1343 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1344 { /* error occurred, close this path */
1345 output_facility->path_open = FALSE;
1346 output_facility->facility_state = IOSTATE_FAILED;
1347 fprintf(stderr, "FATAL: Write to handle failed, exiting\n");
1358 * Initialize a overlapped structure
1360 * @param elem the element to initilize
1361 * @param initial_state the initial state for this instance
1362 * @param signaled if the hEvent created should default to signaled or not
1363 * @return true on success, else false
1366 initialize_io_facility(struct io_facility * elem,
1370 elem->path_open = TRUE;
1371 elem->handle = INVALID_HANDLE_VALUE;
1372 elem->facility_state = initial_state;
1373 elem->buffer_size = 0;
1374 elem->overlapped.hEvent = CreateEvent(NULL, TRUE, signaled, NULL);
1375 if (NULL == elem->overlapped.hEvent)
1383 * Start forwarding to and from the tunnel.
1385 * @param tap_handle device handle for interacting with the Virtual interface
1388 run(HANDLE tap_handle)
1390 /* IO-Facility for reading from our virtual interface */
1391 struct io_facility tap_read;
1392 /* IO-Facility for writing to our virtual interface */
1393 struct io_facility tap_write;
1394 /* IO-Facility for reading from stdin */
1395 struct io_facility std_in;
1396 /* IO-Facility for writing to stdout */
1397 struct io_facility std_out;
1399 HANDLE parent_std_in_handle = GetStdHandle(STD_INPUT_HANDLE);
1400 HANDLE parent_std_out_handle = GetStdHandle(STD_OUTPUT_HANDLE);
1403 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1404 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1406 * DHCP and such are all features we will never use in gnunet afaik.
1407 * But for openvpn those are essential.
1409 if ((privilege_testing) || (!tun_up(tap_handle)))
1410 goto teardown_final;
1412 /* Initialize our overlapped IO structures*/
1413 if (!(initialize_io_facility(&tap_read, IOSTATE_READY, FALSE)
1414 && initialize_io_facility(&tap_write, IOSTATE_WAITING, TRUE)
1415 && initialize_io_facility(&std_in, IOSTATE_READY, FALSE)
1416 && initialize_io_facility(&std_out, IOSTATE_WAITING, TRUE)))
1417 goto teardown_final;
1419 /* Handles for STDIN and STDOUT */
1420 tap_read.handle = tap_handle;
1421 tap_write.handle = tap_handle;
1423 #ifdef DEBUG_TO_CONSOLE
1424 /* Debug output to console STDIN/STDOUT*/
1425 std_in.handle = parent_std_in_handle;
1426 std_out.handle = parent_std_out_handle;
1428 fprintf(stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1430 * Find out the types of our handles.
1431 * This part is a problem, because in windows we need to handle files,
1432 * pipes and the console differently.
1434 if ((FILE_TYPE_PIPE != GetFileType(parent_std_in_handle)) ||
1435 (FILE_TYPE_PIPE != GetFileType(parent_std_out_handle)))
1437 fprintf(stderr, "ERROR: stdin/stdout must be named pipes\n");
1441 std_in.handle = ReOpenFile(parent_std_in_handle,
1443 FILE_SHARE_WRITE | FILE_SHARE_READ,
1444 FILE_FLAG_OVERLAPPED);
1446 if (INVALID_HANDLE_VALUE == std_in.handle)
1448 fprintf(stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1452 std_out.handle = ReOpenFile(parent_std_out_handle,
1455 FILE_FLAG_OVERLAPPED);
1457 if (INVALID_HANDLE_VALUE == std_out.handle)
1459 fprintf(stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1464 fprintf(stderr, "DEBUG: mainloop has begun\n");
1466 while (std_out.path_open || tap_write.path_open)
1468 /* perform READ from stdin if possible */
1469 if (std_in.path_open && (!attempt_read_stdin(&std_in, &tap_write)))
1472 /* perform READ from tap if possible */
1473 if (tap_read.path_open && (!attempt_read_tap(&tap_read, &std_out)))
1476 /* perform WRITE to tap if possible */
1477 if (tap_write.path_open && (!attempt_write(&tap_write, &std_in)))
1480 /* perform WRITE to STDOUT if possible */
1481 if (std_out.path_open && (!attempt_write(&std_out, &tap_read)))
1485 fprintf(stderr, "DEBUG: teardown initiated\n");
1487 CancelIo(tap_handle);
1488 CancelIo(std_in.handle);
1489 CancelIo(std_out.handle);
1491 CloseHandle(tap_handle);
1496 * Open VPN tunnel interface.
1498 * @param argc must be 6
1499 * @param argv 0: binary name (gnunet-helper-vpn)
1500 * [1: dryrun/testrun (does not execute mainloop)]
1501 * 2: tunnel interface prefix (gnunet-vpn)
1502 * 3: IPv6 address (::1), "-" to disable
1503 * 4: IPv6 netmask length in bits (64), ignored if #2 is "-"
1504 * 5: IPv4 address (1.2.3.4), "-" to disable
1505 * 6: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
1508 main(int argc, char **argv)
1510 char hwid[LINE_LEN];
1513 BOOL have_ip4 = FALSE;
1514 BOOL have_ip6 = FALSE;
1516 if (argc > 1 && 0 == strcmp(argv[1], "-d"))
1518 privilege_testing = TRUE;
1521 "DEBUG: Running binary in privilege testing mode.");
1530 "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn [-d] <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n");
1534 GNUNET_strlcpy(hwid, argv[1], sizeof(hwid));
1537 * We use our PID for finding/resolving the control-panel name of our virtual
1538 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1539 * as additional hardware-id for our device.
1541 snprintf(secondary_hwid, LINE_LEN / 2, "%s-%d",
1545 if (INVALID_HANDLE_VALUE == (handle = init_tun()))
1547 fprintf(stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1557 fprintf(stderr, "DEBUG: Setting IPs, if needed\n");
1558 if (0 != strcmp(argv[2], "-"))
1560 const char *address = argv[2];
1561 long prefix_len = atol(argv[3]);
1563 if ((prefix_len < 1) || (prefix_len > 127))
1565 fprintf(stderr, "FATAL: ipv6 prefix_len out of range\n");
1570 fprintf(stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1571 if (0 != (global_ret = set_address6(address, prefix_len)))
1577 if (0 != strcmp(argv[4], "-"))
1579 const char *address = argv[4];
1580 const char *mask = argv[5];
1582 fprintf(stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1583 if (0 != (global_ret = set_address4(address, mask)))
1594 const char *address = argv[4];
1595 fprintf(stderr, "DEBUG: Removing IP4 address\n");
1596 remove_address4(address);
1600 const char *address = argv[2];
1601 fprintf(stderr, "DEBUG: Removing IP6 address\n");
1602 remove_address6(address);
1605 fprintf(stderr, "DEBUG: removing interface\n");
1607 fprintf(stderr, "DEBUG: graceful exit completed\n");