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/>.
19 * @file vpn/gnunet-helper-vpn-windows.c
20 * @brief the helper for the VPN service in win32 builds.
21 * Opens a virtual network-interface, sends data received on the if to stdout,
22 * sends data received on stdin to the interface
23 * @author Christian M. Fuchs
25 * The following list of people have reviewed this code and considered
26 * it safe since the last modification (if you reviewed it, please
27 * have your name added to the list):
35 #ifndef __MINGW64_VERSION_MAJOR
36 #include <ddk/cfgmgr32.h>
37 #include <ddk/newdev.h>
44 #include "tap-windows.h"
46 * Need 'struct GNUNET_HashCode' and 'struct GNUNET_PeerIdentity'.
48 #include "gnunet_crypto_lib.h"
50 * Need 'struct GNUNET_MessageHeader'.
52 #include "gnunet_common.h"
55 * Need VPN message types.
57 #include "gnunet_protocols.h"
60 * Should we print (interesting|debug) messages that can happen during
63 #define DEBUG GNUNET_NO
66 /* FIXME: define with varargs... */
67 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
69 #define LOG_DEBUG(msg) do {} while (0)
73 * Will this binary be run in permissions testing mode?
75 static boolean privilege_testing = FALSE;
78 * Maximum size of a GNUnet message (GNUNET_MAX_MESSAGE_SIZE)
80 #define MAX_SIZE 65536
83 * Name or Path+Name of our win32 driver.
84 * The .sys and .cat files HAVE to be in the same location as this file!
86 #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
89 * Name or Path+Name of our win64 driver.
90 * The .sys and .cat files HAVE to be in the same location as this file!
92 #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
95 * Hardware ID used in the inf-file.
96 * This might change over time, as openvpn advances their driver
98 #define HARDWARE_ID "tap0901"
101 * Minimum major-id of the driver version we can work with
103 #define TAP_WIN_MIN_MAJOR 9
106 * Minimum minor-id of the driver version we can work with.
107 * v <= 7 has buggy IPv6.
108 * v == 8 is broken for small IPv4 Packets
110 #define TAP_WIN_MIN_MINOR 9
113 * Time in seconds to wait for our virtual device to go up after telling it to do so.
115 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
116 * (in fact, 4 was chosen by a fair dice roll...)
118 #define TAP32_POSTUP_WAITTIME 4
121 * Location of the network interface list resides in registry.
123 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
126 * Our local process' PID. Used for creating a sufficiently unique additional
127 * hardware ID for our device.
129 static char secondary_hwid[LINE_LEN / 2];
132 * Device's visible Name, used to identify a network device in netsh.
133 * eg: "Local Area Connection 9"
135 static char device_visible_name[256];
138 * This is our own local instance of a virtual network interface
139 * It is (somewhat) equivalent to using tun/tap in unixoid systems
141 * Upon initialization, we create such an device node.
142 * Upon termination, we remove it again.
144 * If we crash this device might stay around.
146 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
149 * Registry Key we hand over to windows to spawn a new virtual interface
151 static SP_DEVINFO_DATA DeviceNode;
154 * GUID of our virtual device in the form of
155 * {12345678-1234-1234-1234-123456789abc} - in hex
157 static char device_guid[256];
161 * 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
196 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
201 * The mode the state machine associated with this object is in.
203 enum IO_State facility_state;
206 * If the path is open or blocked in general (used for quickly checking)
208 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
211 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
216 * Overlaped IO structure used for asynchronous IO in windows.
218 OVERLAPPED overlapped;
221 * Buffer for reading things to and writing from...
223 unsigned char buffer[MAX_SIZE];
226 * How much of this buffer was used when reading or how much data can be written
231 * Amount of data actually written or read by readfile/writefile.
233 DWORD buffer_size_processed;
236 * How much of this buffer we have writte in total
238 DWORD buffer_size_written;
242 * ReOpenFile is only available as of XP SP2 and 2003 SP1
244 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
247 * IsWow64Process definition for our is_win64, as this is a kernel function
249 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
252 * Determines if the host OS is win32 or win64
260 //this is a win64 binary,
262 #elif defined(_WIN32)
263 //this is a 32bit binary, and we need to check if we are running in WOW64
264 BOOL success = FALSE;
265 BOOL on_wow64 = FALSE;
266 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
268 if (NULL != IsWow64Process)
269 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
271 return success && on_wow64;
275 * Wrapper for executing a shellcommand in windows.
277 * @param command - the command + parameters to execute
278 * @return * exitcode of the program executed,
279 * * EINVAL (cmd/file not found)
280 * * EPIPE (could not read STDOUT)
283 execute_shellcommand (const char *command)
287 if ( (NULL == command) ||
288 (NULL == (pipe = _popen (command, "rt"))) )
292 fprintf (stderr, "DEBUG: Command output: \n");
293 char output[LINE_LEN];
294 while (NULL != fgets (output, sizeof (output), pipe))
295 fprintf (stderr, "%s", output);
298 return _pclose (pipe);
303 * @brief Sets the IPv6-Address given in address on the interface dev
305 * @param address the IPv6-Address
306 * @param prefix_len the length of the network-prefix
309 set_address6 (const char *address, unsigned long prefix_len)
312 char command[LINE_LEN];
313 struct sockaddr_in6 sa6;
316 * parse the new address
318 memset (&sa6, 0, sizeof (struct sockaddr_in6));
319 sa6.sin6_family = AF_INET6;
320 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
322 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
328 * prepare the command
330 snprintf (command, LINE_LEN,
331 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
332 device_visible_name, address, prefix_len);
336 ret = execute_shellcommand (command);
340 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
346 * @brief Removes the IPv6-Address given in address from the interface dev
348 * @param address the IPv4-Address
351 remove_address6 (const char *address)
353 char command[LINE_LEN];
356 // sanity checking was already done in set_address6
358 * prepare the command
360 snprintf (command, LINE_LEN,
361 "netsh interface ipv6 delete address \"%s\" store=persistent",
362 device_visible_name);
366 ret = execute_shellcommand (command);
371 "FATAL: removing IPv6 address failed: %s\n",
377 * @brief Sets the IPv4-Address given in address on the interface dev
379 * @param address the IPv4-Address
380 * @param mask the netmask
383 set_address4 (const char *address, const char *mask)
386 char command[LINE_LEN];
388 struct sockaddr_in addr;
389 addr.sin_family = AF_INET;
394 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
396 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
400 // Set Device to Subnet-Mode? do we really need openvpn/tun.c:2925 ?
403 * prepare the command
405 snprintf (command, LINE_LEN,
406 "netsh interface ipv4 add address \"%s\" %s %s store=active",
407 device_visible_name, address, mask);
411 ret = execute_shellcommand (command);
416 "FATAL: Setting IPv4 address failed: %s\n",
423 * @brief Removes the IPv4-Address given in address from the interface dev
425 * @param address the IPv4-Address
428 remove_address4 (const char *address)
430 char command[LINE_LEN];
433 // sanity checking was already done in set_address4
436 * prepare the command
438 snprintf (command, LINE_LEN,
439 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
440 device_visible_name);
444 ret = execute_shellcommand (command);
448 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
453 * Setup a new virtual interface to use for tunneling.
455 * @return: TRUE if setup was successful, else FALSE
461 * where to find our inf-file. (+ the "full" path, after windows found")
463 * We do not directly input all the props here, because openvpn will update
464 * these details over time.
466 char inf_file_path[MAX_PATH];
467 char * temp_inf_filename;
468 char hwidlist[LINE_LEN + 4];
469 char class_name[128];
474 * Set the device's hardware ID and add it to a list.
475 * This information will later on identify this device in registry.
477 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
479 * this is kind of over-complicated, but allows keeps things independent of
480 * how the openvpn-hwid is actually stored.
482 * A HWID list is double-\0 terminated and \0 separated
484 str_length = strlen (hwidlist) + 1;
485 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
486 str_length += strlen (&hwidlist[str_length]) + 1;
489 * Locate the inf-file, we need to store it somewhere where the system can
490 * find it. We need to pick the correct driver for win32/win64.
493 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
495 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
497 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
499 * Bootstrap our device info using the drivers inf-file
501 if ( ! SetupDiGetINFClassA (inf_file_path,
503 class_name, sizeof (class_name) / sizeof (char),
508 * Collect all the other needed information...
509 * let the system fill our this form
511 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
512 if (DeviceInfo == INVALID_HANDLE_VALUE)
515 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
516 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
525 /* Deploy all the information collected into the registry */
526 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
530 str_length * sizeof (char)))
533 /* Install our new class(=device) into the system */
534 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
539 /* This system call tends to take a while (several seconds!) on
540 "modern" Windoze systems */
541 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
544 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
545 NULL)) //reboot required? NEVER!
548 fprintf (stderr, "DEBUG: successfully created a network device\n");
554 * Remove our new virtual interface to use for tunneling.
555 * This function must be called AFTER setup_interface!
557 * @return: TRUE if destruction was successful, else FALSE
562 SP_REMOVEDEVICE_PARAMS remove;
564 if (INVALID_HANDLE_VALUE == DeviceInfo)
567 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
568 remove.HwProfile = 0;
569 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
570 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
572 * 1. Prepare our existing device information set, and place the
573 * uninstall related information into the structure
575 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
576 (PSP_DEVINFO_DATA) & DeviceNode,
577 &remove.ClassInstallHeader,
581 * 2. Uninstall the virtual interface using the class installer
583 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
585 (PSP_DEVINFO_DATA) & DeviceNode))
588 SetupDiDestroyDeviceInfoList (DeviceInfo);
590 fprintf (stderr, "DEBUG: removed interface successfully\n");
597 * Do all the lookup necessary to retrieve the inteface's actual name
600 * @return: TRUE if we were able to lookup the interface's name, else FALSE
603 resolve_interface_name ()
605 SP_DEVINFO_LIST_DETAIL_DATA device_details;
606 char pnp_instance_id [MAX_DEVICE_ID_LEN];
607 HKEY adapter_key_handle;
613 char adapter[] = INTERFACE_REGISTRY_LOCATION;
615 /* We can obtain the PNP instance ID from our setupapi handle */
616 device_details.cbSize = sizeof (device_details);
617 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
618 (PCHAR) pnp_instance_id,
621 NULL)) //hMachine, we are local
624 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
626 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
627 for (retrys = 0; retrys < 120 && !retval; retrys++)
632 /* Now we can use this ID to locate the correct networks interface in registry */
633 if (ERROR_SUCCESS != RegOpenKeyExA (
638 &adapter_key_handle))
641 /* Of course there is a multitude of entries here, with arbitrary names,
642 * thus we need to iterate through there.
646 char instance_key[256];
647 char query_key [256];
648 HKEY instance_key_handle;
649 char pnpinstanceid_name[] = "PnpInstanceID";
650 char pnpinstanceid_value[256];
651 char adaptername_name[] = "Name";
654 len = 256 * sizeof (char);
655 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
656 status = RegEnumKeyExA (
666 /* this may fail due to one of two reasons:
667 * we are at the end of the list*/
668 if (ERROR_NO_MORE_ITEMS == status)
670 // * we found a broken registry key, continue with the next key.
671 if (ERROR_SUCCESS != status)
674 /* prepare our new query string: */
675 snprintf (query_key, 256, "%s\\%s\\Connection",
679 /* look inside instance_key\\Connection */
680 if (ERROR_SUCCESS != RegOpenKeyExA (
685 &instance_key_handle))
688 /* now, read our PnpInstanceID */
689 len = sizeof (pnpinstanceid_value);
690 status = RegQueryValueExA (instance_key_handle,
692 NULL, //reserved, always NULL according to MSDN
694 (LPBYTE) pnpinstanceid_value,
697 if (status != ERROR_SUCCESS || data_type != REG_SZ)
700 /* compare the value we got to our devices PNPInstanceID*/
701 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
702 sizeof (pnpinstanceid_value) / sizeof (char)))
705 len = sizeof (device_visible_name);
706 status = RegQueryValueExA (
709 NULL, //reserved, always NULL according to MSDN
711 (LPBYTE) device_visible_name,
714 if (status != ERROR_SUCCESS || data_type != REG_SZ)
718 * we have successfully found OUR instance,
719 * save the device GUID before exiting
722 strncpy (device_guid, instance_key, 256);
724 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
727 RegCloseKey (instance_key_handle);
732 RegCloseKey (adapter_key_handle);
739 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
741 * @param handle the handle to our tap device
742 * @return TRUE if the version is sufficient, else FALSE
745 check_tapw32_version (HANDLE handle)
749 memset (&(version), 0, sizeof (version));
751 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
752 &version, sizeof (version),
753 &version, sizeof (version), &len, NULL))
754 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
757 (version[2] ? "(DEBUG)" : ""));
759 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
760 (version[1] < TAP_WIN_MIN_MINOR )){
761 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
772 * Creates a tun-interface called dev;
774 * @return the fd to the tun or -1 on error
779 char device_path[256];
782 if (! setup_interface ())
785 return INVALID_HANDLE_VALUE;
788 if (! resolve_interface_name ())
791 return INVALID_HANDLE_VALUE;
794 /* Open Windows TAP-Windows adapter */
795 snprintf (device_path, sizeof (device_path), "%s%s%s",
800 handle = CreateFile (
802 GENERIC_READ | GENERIC_WRITE,
803 0, /* was: FILE_SHARE_READ */
806 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
810 if (INVALID_HANDLE_VALUE == handle)
812 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
816 /* get driver version info */
817 if (! check_tapw32_version (handle))
819 CloseHandle (handle);
820 return INVALID_HANDLE_VALUE;
823 /* TODO (opt?): get MTU-Size */
825 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
831 * Brings a TAP device up and sets it to connected state.
833 * @param handle the handle to our TAP device
834 * @return True if the operation succeeded, else false
837 tun_up (HANDLE handle)
841 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
842 &status, sizeof (status),
843 &status, sizeof (status), &len, NULL))
845 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
849 /* Wait for the device to go UP, might take some time. */
850 Sleep (TAP32_POSTUP_WAITTIME * 1000);
851 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
858 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
861 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
862 * input handle. Then it goes into IOSTATE_QUEUED state.
863 * In case the read succeeded instantly the input facility enters 3.
866 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
867 * If it has finished, go to state 3.
868 * If it has failed, set IOSTATE_FAILED
871 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
872 * The input facility enters state IOSTATE_READY
873 * The output facility enters state IOSTATE_READY
874 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
876 * IOSTATE_WAITING is reset by the output facility, once it has completed.
878 * @param input_facility input named pipe or file to work with.
879 * @param output_facility output pipe or file to hand over data to.
880 * @return false if an event reset was impossible (OS error), else true
883 attempt_read_tap (struct io_facility * input_facility,
884 struct io_facility * output_facility)
886 struct GNUNET_MessageHeader * hdr;
889 switch (input_facility->facility_state)
893 if (! ResetEvent (input_facility->overlapped.hEvent))
898 input_facility->buffer_size = 0;
900 /* Check how the task is handled */
901 if (ReadFile (input_facility->handle,
902 input_facility->buffer,
903 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
904 &input_facility->buffer_size,
905 &input_facility->overlapped))
906 {/* async event processed immediately*/
908 /* reset event manually*/
909 if (! SetEvent (input_facility->overlapped.hEvent))
912 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
914 /* we successfully read something from the TAP and now need to
915 * send it our via STDOUT. Is that possible at the moment? */
916 if ((IOSTATE_READY == output_facility->facility_state ||
917 IOSTATE_WAITING == output_facility->facility_state)
918 && (0 < input_facility->buffer_size))
919 { /* hand over this buffers content and apply message header for gnunet */
920 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
921 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
923 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
924 input_facility->buffer,
925 input_facility->buffer_size);
927 output_facility->buffer_size = size;
928 hdr->size = htons (size);
929 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
930 output_facility->facility_state = IOSTATE_READY;
932 else if (0 < input_facility->buffer_size)
933 /* If we have have read our buffer, wait for our write-partner*/
934 input_facility->facility_state = IOSTATE_WAITING;
936 else /* operation was either queued or failed*/
938 int err = GetLastError ();
939 if (ERROR_IO_PENDING == err)
940 { /* operation queued */
941 input_facility->facility_state = IOSTATE_QUEUED;
944 { /* error occurred, let the rest of the elements finish */
945 input_facility->path_open = FALSE;
946 input_facility->facility_state = IOSTATE_FAILED;
947 if (IOSTATE_WAITING == output_facility->facility_state)
948 output_facility->path_open = FALSE;
950 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
955 // We are queued and should check if the read has finished
958 // there was an operation going on already, check if that has completed now.
960 if (GetOverlappedResult (input_facility->handle,
961 &input_facility->overlapped,
962 &input_facility->buffer_size,
964 {/* successful return for a queued operation */
965 if (! ResetEvent (input_facility->overlapped.hEvent))
968 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
970 /* we successfully read something from the TAP and now need to
971 * send it our via STDOUT. Is that possible at the moment? */
972 if ((IOSTATE_READY == output_facility->facility_state ||
973 IOSTATE_WAITING == output_facility->facility_state)
974 && 0 < input_facility->buffer_size)
975 { /* hand over this buffers content and apply message header for gnunet */
976 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
977 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
979 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
980 input_facility->buffer,
981 input_facility->buffer_size);
983 output_facility->buffer_size = size;
984 hdr->size = htons(size);
985 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
986 output_facility->facility_state = IOSTATE_READY;
987 input_facility->facility_state = IOSTATE_READY;
989 else if (0 < input_facility->buffer_size)
990 { /* If we have have read our buffer, wait for our write-partner*/
991 input_facility->facility_state = IOSTATE_WAITING;
992 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
996 { /* operation still pending/queued or failed? */
997 int err = GetLastError ();
998 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
999 { /* error occurred, let the rest of the elements finish */
1000 input_facility->path_open = FALSE;
1001 input_facility->facility_state = IOSTATE_FAILED;
1002 if (IOSTATE_WAITING == output_facility->facility_state)
1003 output_facility->path_open = FALSE;
1004 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1009 case IOSTATE_RESUME:
1010 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1011 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1013 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1014 input_facility->buffer,
1015 input_facility->buffer_size);
1017 output_facility->buffer_size = size;
1018 hdr->size = htons (size);
1019 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1020 output_facility->facility_state = IOSTATE_READY;
1021 input_facility->facility_state = IOSTATE_READY;
1030 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1033 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1034 * input handle. Then it goes into IOSTATE_QUEUED state.
1035 * In case the read succeeded instantly the input facility enters 3.
1038 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1039 * If it has finished, go to state 3.
1040 * If it has failed, set IOSTATE_FAILED
1043 * If the facility is finished with ready
1044 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1045 * The input facility enters state IOSTATE_READY
1046 * The output facility enters state IOSTATE_READY
1047 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1049 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1051 * @param input_facility input named pipe or file to work with.
1052 * @param output_facility output pipe or file to hand over data to.
1053 * @return false if an event reset was impossible (OS error), else true
1056 attempt_read_stdin (struct io_facility * input_facility,
1057 struct io_facility * output_facility)
1059 struct GNUNET_MessageHeader * hdr;
1061 switch (input_facility->facility_state)
1065 input_facility->buffer_size = 0;
1067 partial_read_iostate_ready:
1068 if (! ResetEvent (input_facility->overlapped.hEvent))
1071 /* Check how the task is handled */
1072 if (ReadFile (input_facility->handle,
1073 input_facility->buffer + input_facility->buffer_size,
1074 sizeof (input_facility->buffer) - input_facility->buffer_size,
1075 &input_facility->buffer_size_processed,
1076 &input_facility->overlapped))
1077 {/* async event processed immediately*/
1078 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1080 /* reset event manually*/
1081 if (!SetEvent (input_facility->overlapped.hEvent))
1084 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1085 input_facility->buffer_size += input_facility->buffer_size_processed;
1087 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1088 ntohs (hdr->size) > sizeof (input_facility->buffer))
1090 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1091 input_facility->facility_state = IOSTATE_READY;
1094 /* we got the a part of a packet */
1095 if (ntohs (hdr->size) > input_facility->buffer_size)
1096 goto partial_read_iostate_ready;
1098 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1099 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1100 ((IOSTATE_READY == output_facility->facility_state) ||
1101 (IOSTATE_WAITING == output_facility->facility_state)))
1102 {/* we successfully read something from the TAP and now need to
1103 * send it our via STDOUT. Is that possible at the moment? */
1105 /* hand over this buffers content and strip gnunet message header */
1106 GNUNET_memcpy (output_facility->buffer,
1107 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1108 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1109 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1110 output_facility->facility_state = IOSTATE_READY;
1111 input_facility->facility_state = IOSTATE_READY;
1113 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1114 /* If we have have read our buffer, wait for our write-partner*/
1115 input_facility->facility_state = IOSTATE_WAITING;
1116 else /* we read nothing */
1117 input_facility->facility_state = IOSTATE_READY;
1119 else /* operation was either queued or failed*/
1121 int err = GetLastError ();
1122 if (ERROR_IO_PENDING == err) /* operation queued */
1123 input_facility->facility_state = IOSTATE_QUEUED;
1125 { /* error occurred, let the rest of the elements finish */
1126 input_facility->path_open = FALSE;
1127 input_facility->facility_state = IOSTATE_FAILED;
1128 if (IOSTATE_WAITING == output_facility->facility_state)
1129 output_facility->path_open = FALSE;
1131 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1136 // We are queued and should check if the read has finished
1137 case IOSTATE_QUEUED:
1139 // there was an operation going on already, check if that has completed now.
1140 if (GetOverlappedResult (input_facility->handle,
1141 &input_facility->overlapped,
1142 &input_facility->buffer_size_processed,
1144 {/* successful return for a queued operation */
1145 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1147 if (! ResetEvent (input_facility->overlapped.hEvent))
1150 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1151 input_facility->buffer_size += input_facility->buffer_size_processed;
1153 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1154 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1156 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1157 input_facility->facility_state = IOSTATE_READY;
1160 /* we got the a part of a packet */
1161 if (ntohs (hdr->size) > input_facility->buffer_size );
1162 goto partial_read_iostate_ready;
1164 /* we successfully read something from the TAP and now need to
1165 * send it our via STDOUT. Is that possible at the moment? */
1166 if ((IOSTATE_READY == output_facility->facility_state ||
1167 IOSTATE_WAITING == output_facility->facility_state)
1168 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1169 { /* hand over this buffers content and strip gnunet message header */
1170 GNUNET_memcpy (output_facility->buffer,
1171 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1172 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1173 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1174 output_facility->facility_state = IOSTATE_READY;
1175 input_facility->facility_state = IOSTATE_READY;
1177 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1178 input_facility->facility_state = IOSTATE_WAITING;
1180 input_facility->facility_state = IOSTATE_READY;
1183 { /* operation still pending/queued or failed? */
1184 int err = GetLastError ();
1185 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1186 { /* error occurred, let the rest of the elements finish */
1187 input_facility->path_open = FALSE;
1188 input_facility->facility_state = IOSTATE_FAILED;
1189 if (IOSTATE_WAITING == output_facility->facility_state)
1190 output_facility->path_open = FALSE;
1191 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1196 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1197 GNUNET_memcpy (output_facility->buffer,
1198 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1199 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1200 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1201 output_facility->facility_state = IOSTATE_READY;
1202 input_facility->facility_state = IOSTATE_READY;
1211 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1213 * TODO: high level description
1215 * @param output_facility output pipe or file to hand over data to.
1216 * @param input_facility input named pipe or file to work with.
1217 * @return false if an event reset was impossible (OS error), else true
1220 attempt_write (struct io_facility * output_facility,
1221 struct io_facility * input_facility)
1223 switch (output_facility->facility_state)
1226 output_facility->buffer_size_written = 0;
1228 continue_partial_write:
1229 if (! ResetEvent (output_facility->overlapped.hEvent))
1232 /* Check how the task was handled */
1233 if (WriteFile (output_facility->handle,
1234 output_facility->buffer + output_facility->buffer_size_written,
1235 output_facility->buffer_size - output_facility->buffer_size_written,
1236 &output_facility->buffer_size_processed,
1237 &output_facility->overlapped))
1238 {/* async event processed immediately*/
1240 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1241 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1243 /* reset event manually*/
1244 if (! SetEvent (output_facility->overlapped.hEvent))
1248 if (output_facility->buffer_size_written < output_facility->buffer_size)
1249 goto continue_partial_write;
1251 /* we are now waiting for our buffer to be filled*/
1252 output_facility->facility_state = IOSTATE_WAITING;
1254 /* we successfully wrote something and now need to reset our reader */
1255 if (IOSTATE_WAITING == input_facility->facility_state)
1256 input_facility->facility_state = IOSTATE_RESUME;
1257 else if (IOSTATE_FAILED == input_facility->facility_state)
1258 output_facility->path_open = FALSE;
1260 else /* operation was either queued or failed*/
1262 int err = GetLastError ();
1263 if (ERROR_IO_PENDING == err)
1264 { /* operation queued */
1265 output_facility->facility_state = IOSTATE_QUEUED;
1268 { /* error occurred, close this path */
1269 output_facility->path_open = FALSE;
1270 output_facility->facility_state = IOSTATE_FAILED;
1271 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1275 case IOSTATE_QUEUED:
1276 // there was an operation going on already, check if that has completed now.
1278 if (GetOverlappedResult (output_facility->handle,
1279 &output_facility->overlapped,
1280 &output_facility->buffer_size_processed,
1282 {/* successful return for a queued operation */
1283 if (! ResetEvent (output_facility->overlapped.hEvent))
1286 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1287 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1290 if (output_facility->buffer_size_written < output_facility->buffer_size)
1291 goto continue_partial_write;
1293 /* we are now waiting for our buffer to be filled*/
1294 output_facility->facility_state = IOSTATE_WAITING;
1296 /* we successfully wrote something and now need to reset our reader */
1297 if (IOSTATE_WAITING == input_facility->facility_state)
1298 input_facility->facility_state = IOSTATE_RESUME;
1299 else if (IOSTATE_FAILED == input_facility->facility_state)
1300 output_facility->path_open = FALSE;
1303 { /* operation still pending/queued or failed? */
1304 int err = GetLastError ();
1305 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1306 { /* error occurred, close this path */
1307 output_facility->path_open = FALSE;
1308 output_facility->facility_state = IOSTATE_FAILED;
1309 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1319 * Initialize a overlapped structure
1321 * @param elem the element to initilize
1322 * @param initial_state the initial state for this instance
1323 * @param signaled if the hEvent created should default to signaled or not
1324 * @return true on success, else false
1327 initialize_io_facility (struct io_facility * elem,
1331 elem->path_open = TRUE;
1332 elem->handle = INVALID_HANDLE_VALUE;
1333 elem->facility_state = initial_state;
1334 elem->buffer_size = 0;
1335 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1336 if (NULL == elem->overlapped.hEvent)
1344 * Start forwarding to and from the tunnel.
1346 * @param tap_handle device handle for interacting with the Virtual interface
1349 run (HANDLE tap_handle)
1351 /* IO-Facility for reading from our virtual interface */
1352 struct io_facility tap_read;
1353 /* IO-Facility for writing to our virtual interface */
1354 struct io_facility tap_write;
1355 /* IO-Facility for reading from stdin */
1356 struct io_facility std_in;
1357 /* IO-Facility for writing to stdout */
1358 struct io_facility std_out;
1360 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1361 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1364 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1365 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1367 * DHCP and such are all features we will never use in gnunet afaik.
1368 * But for openvpn those are essential.
1370 if ((privilege_testing) || (! tun_up (tap_handle)))
1371 goto teardown_final;
1373 /* Initialize our overlapped IO structures*/
1374 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1375 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1376 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1377 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1378 goto teardown_final;
1380 /* Handles for STDIN and STDOUT */
1381 tap_read.handle = tap_handle;
1382 tap_write.handle = tap_handle;
1384 #ifdef DEBUG_TO_CONSOLE
1385 /* Debug output to console STDIN/STDOUT*/
1386 std_in.handle = parent_std_in_handle;
1387 std_out.handle = parent_std_out_handle;
1390 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1392 * Find out the types of our handles.
1393 * This part is a problem, because in windows we need to handle files,
1394 * pipes and the console differently.
1396 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1397 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1399 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1403 std_in.handle = ReOpenFile (parent_std_in_handle,
1405 FILE_SHARE_WRITE | FILE_SHARE_READ,
1406 FILE_FLAG_OVERLAPPED);
1408 if (INVALID_HANDLE_VALUE == std_in.handle)
1410 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1414 std_out.handle = ReOpenFile (parent_std_out_handle,
1417 FILE_FLAG_OVERLAPPED);
1419 if (INVALID_HANDLE_VALUE == std_out.handle)
1421 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1426 fprintf (stderr, "DEBUG: mainloop has begun\n");
1428 while (std_out.path_open || tap_write.path_open)
1430 /* perform READ from stdin if possible */
1431 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1434 /* perform READ from tap if possible */
1435 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1438 /* perform WRITE to tap if possible */
1439 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1442 /* perform WRITE to STDOUT if possible */
1443 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1447 fprintf (stderr, "DEBUG: teardown initiated\n");
1449 CancelIo (tap_handle);
1450 CancelIo (std_in.handle);
1451 CancelIo (std_out.handle);
1453 CloseHandle (tap_handle);
1458 * Open VPN tunnel interface.
1460 * @param argc must be 6
1461 * @param argv 0: binary name (gnunet-helper-vpn)
1462 * [1: dryrun/testrun (does not execute mainloop)]
1463 * 2: tunnel interface prefix (gnunet-vpn)
1464 * 3: IPv6 address (::1), "-" to disable
1465 * 4: IPv6 netmask length in bits (64), ignored if #2 is "-"
1466 * 5: IPv4 address (1.2.3.4), "-" to disable
1467 * 6: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
1470 main (int argc, char **argv)
1472 char hwid[LINE_LEN];
1475 BOOL have_ip4 = FALSE;
1476 BOOL have_ip6 = FALSE;
1478 if (argc > 1 && 0 == strcmp (argv[1], "-d")){
1479 privilege_testing = TRUE;
1482 "DEBUG: Running binary in privilege testing mode.");
1491 "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn [-d] <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n");
1495 strncpy (hwid, argv[1], LINE_LEN);
1496 hwid[LINE_LEN - 1] = '\0';
1499 * We use our PID for finding/resolving the control-panel name of our virtual
1500 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1501 * as additional hardware-id for our device.
1503 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1507 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1509 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1519 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1520 if (0 != strcmp (argv[2], "-"))
1522 const char *address = argv[2];
1523 long prefix_len = atol (argv[3]);
1525 if ((prefix_len < 1) || (prefix_len > 127))
1527 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1532 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n",address,prefix_len);
1533 if (0 != (global_ret = set_address6 (address, prefix_len)))
1539 if (0 != strcmp (argv[4], "-"))
1541 const char *address = argv[4];
1542 const char *mask = argv[5];
1544 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n",address,mask);
1545 if (0 != (global_ret = set_address4 (address, mask)))
1556 const char *address = argv[4];
1557 fprintf (stderr, "DEBUG: Removing IP4 address\n");
1558 remove_address4 (address);
1562 const char *address = argv[2];
1563 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1564 remove_address6 (address);
1567 fprintf (stderr, "DEBUG: removing interface\n");
1568 remove_interface ();
1569 fprintf (stderr, "DEBUG: graceful exit completed\n");