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_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_SERVER_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.
169 * overlapped I/O is ready for work
174 * overlapped I/O has been queued
179 * overlapped I/O has finished, but is waiting for it's write-partner
184 * there is a full buffer waiting
189 * Operlapped IO states for facility objects
190 * overlapped I/O has failed, stop processing
198 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
203 * The mode the state machine associated with this object is in.
205 enum IO_State facility_state;
208 * If the path is open or blocked in general (used for quickly checking)
210 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
213 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
218 * Overlaped IO structure used for asynchronous IO in windows.
220 OVERLAPPED overlapped;
223 * Buffer for reading things to and writing from...
225 unsigned char buffer[MAX_SIZE];
228 * How much of this buffer was used when reading or how much data can be written
233 * Amount of data actually written or read by readfile/writefile.
235 DWORD buffer_size_processed;
238 * How much of this buffer we have writte in total
240 DWORD buffer_size_written;
244 * ReOpenFile is only available as of XP SP2 and 2003 SP1
246 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
249 * IsWow64Process definition for our is_win64, as this is a kernel function
251 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
254 * Determines if the host OS is win32 or win64
262 //this is a win64 binary,
264 #elif defined(_WIN32)
265 //this is a 32bit binary, and we need to check if we are running in WOW64
266 BOOL success = FALSE;
267 BOOL on_wow64 = FALSE;
268 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
270 if (NULL != IsWow64Process)
271 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
273 return success && on_wow64;
277 * Wrapper for executing a shellcommand in windows.
279 * @param command - the command + parameters to execute
280 * @return * exitcode of the program executed,
281 * * EINVAL (cmd/file not found)
282 * * EPIPE (could not read STDOUT)
285 execute_shellcommand (const char *command)
289 if ( (NULL == command) ||
290 (NULL == (pipe = _popen (command, "rt"))) )
294 fprintf (stderr, "DEBUG: Command output: \n");
295 char output[LINE_LEN];
296 while (NULL != fgets (output, sizeof (output), pipe))
297 fprintf (stderr, "%s", output);
300 return _pclose (pipe);
305 * @brief Sets the IPv6-Address given in address on the interface dev
307 * @param address the IPv6-Address
308 * @param prefix_len the length of the network-prefix
311 set_address6 (const char *address, unsigned long prefix_len)
314 char command[LINE_LEN];
315 struct sockaddr_in6 sa6;
318 * parse the new address
320 memset (&sa6, 0, sizeof (struct sockaddr_in6));
321 sa6.sin6_family = AF_INET6;
322 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
324 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
330 * prepare the command
332 snprintf (command, LINE_LEN,
333 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
334 device_visible_name, address, prefix_len);
338 ret = execute_shellcommand (command);
342 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
348 * @brief Removes the IPv6-Address given in address from the interface dev
350 * @param address the IPv4-Address
353 remove_address6 (const char *address)
355 char command[LINE_LEN];
358 // sanity checking was already done in set_address6
360 * prepare the command
362 snprintf (command, LINE_LEN,
363 "netsh interface ipv6 delete address \"%s\" store=persistent",
364 device_visible_name);
368 ret = execute_shellcommand (command);
373 "FATAL: removing IPv6 address failed: %s\n",
379 * @brief Sets the IPv4-Address given in address on the interface dev
381 * @param address the IPv4-Address
382 * @param mask the netmask
385 set_address4 (const char *address, const char *mask)
388 char command[LINE_LEN];
390 struct sockaddr_in addr;
391 addr.sin_family = AF_INET;
396 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
398 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
402 // Set Device to Subnet-Mode? do we really need openvpn/tun.c:2925 ?
405 * prepare the command
407 snprintf (command, LINE_LEN,
408 "netsh interface ipv4 add address \"%s\" %s %s store=active",
409 device_visible_name, address, mask);
413 ret = execute_shellcommand (command);
418 "FATAL: Setting IPv4 address failed: %s\n",
425 * @brief Removes the IPv4-Address given in address from the interface dev
427 * @param address the IPv4-Address
430 remove_address4 (const char *address)
432 char command[LINE_LEN];
435 // sanity checking was already done in set_address4
438 * prepare the command
440 snprintf (command, LINE_LEN,
441 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
442 device_visible_name);
446 ret = execute_shellcommand (command);
450 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
455 * Setup a new virtual interface to use for tunneling.
457 * @return: TRUE if setup was successful, else FALSE
463 * where to find our inf-file. (+ the "full" path, after windows found")
465 * We do not directly input all the props here, because openvpn will update
466 * these details over time.
468 char inf_file_path[MAX_PATH];
469 char * temp_inf_filename;
470 char hwidlist[LINE_LEN + 4];
471 char class_name[128];
476 * Set the device's hardware ID and add it to a list.
477 * This information will later on identify this device in registry.
479 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
481 * this is kind of over-complicated, but allows keeps things independent of
482 * how the openvpn-hwid is actually stored.
484 * A HWID list is double-\0 terminated and \0 separated
486 str_length = strlen (hwidlist) + 1;
487 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
488 str_length += strlen (&hwidlist[str_length]) + 1;
491 * Locate the inf-file, we need to store it somewhere where the system can
492 * find it. We need to pick the correct driver for win32/win64.
495 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
497 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
499 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
501 * Bootstrap our device info using the drivers inf-file
503 if ( ! SetupDiGetINFClassA (inf_file_path,
505 class_name, sizeof (class_name) / sizeof (char),
510 * Collect all the other needed information...
511 * let the system fill our this form
513 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
514 if (DeviceInfo == INVALID_HANDLE_VALUE)
517 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
518 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
527 /* Deploy all the information collected into the registry */
528 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
532 str_length * sizeof (char)))
535 /* Install our new class(=device) into the system */
536 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
541 /* This system call tends to take a while (several seconds!) on
542 "modern" Windoze systems */
543 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
546 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
547 NULL)) //reboot required? NEVER!
550 fprintf (stderr, "DEBUG: successfully created a network device\n");
556 * Remove our new virtual interface to use for tunneling.
557 * This function must be called AFTER setup_interface!
559 * @return: TRUE if destruction was successful, else FALSE
564 SP_REMOVEDEVICE_PARAMS remove;
566 if (INVALID_HANDLE_VALUE == DeviceInfo)
569 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
570 remove.HwProfile = 0;
571 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
572 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
574 * 1. Prepare our existing device information set, and place the
575 * uninstall related information into the structure
577 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
578 (PSP_DEVINFO_DATA) & DeviceNode,
579 &remove.ClassInstallHeader,
583 * 2. Uninstall the virtual interface using the class installer
585 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
587 (PSP_DEVINFO_DATA) & DeviceNode))
590 SetupDiDestroyDeviceInfoList (DeviceInfo);
592 fprintf (stderr, "DEBUG: removed interface successfully\n");
599 * Do all the lookup necessary to retrieve the inteface's actual name
602 * @return: TRUE if we were able to lookup the interface's name, else FALSE
605 resolve_interface_name ()
607 SP_DEVINFO_LIST_DETAIL_DATA device_details;
608 char pnp_instance_id [MAX_DEVICE_ID_LEN];
609 HKEY adapter_key_handle;
615 char adapter[] = INTERFACE_REGISTRY_LOCATION;
617 /* We can obtain the PNP instance ID from our setupapi handle */
618 device_details.cbSize = sizeof (device_details);
619 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
620 (PCHAR) pnp_instance_id,
623 NULL)) //hMachine, we are local
626 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
628 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
629 for (retrys = 0; retrys < 120 && !retval; retrys++)
634 /* Now we can use this ID to locate the correct networks interface in registry */
635 if (ERROR_SUCCESS != RegOpenKeyExA (
640 &adapter_key_handle))
643 /* Of course there is a multitude of entries here, with arbitrary names,
644 * thus we need to iterate through there.
648 char instance_key[256];
649 char query_key [256];
650 HKEY instance_key_handle;
651 char pnpinstanceid_name[] = "PnpInstanceID";
652 char pnpinstanceid_value[256];
653 char adaptername_name[] = "Name";
656 len = 256 * sizeof (char);
657 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
658 status = RegEnumKeyExA (
668 /* this may fail due to one of two reasons:
669 * we are at the end of the list*/
670 if (ERROR_NO_MORE_ITEMS == status)
672 // * we found a broken registry key, continue with the next key.
673 if (ERROR_SUCCESS != status)
676 /* prepare our new query string: */
677 snprintf (query_key, 256, "%s\\%s\\Connection",
681 /* look inside instance_key\\Connection */
682 if (ERROR_SUCCESS != RegOpenKeyExA (
687 &instance_key_handle))
690 /* now, read our PnpInstanceID */
691 len = sizeof (pnpinstanceid_value);
692 status = RegQueryValueExA (instance_key_handle,
694 NULL, //reserved, always NULL according to MSDN
696 (LPBYTE) pnpinstanceid_value,
699 if (status != ERROR_SUCCESS || data_type != REG_SZ)
702 /* compare the value we got to our devices PNPInstanceID*/
703 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
704 sizeof (pnpinstanceid_value) / sizeof (char)))
707 len = sizeof (device_visible_name);
708 status = RegQueryValueExA (
711 NULL, //reserved, always NULL according to MSDN
713 (LPBYTE) device_visible_name,
716 if (status != ERROR_SUCCESS || data_type != REG_SZ)
720 * we have successfully found OUR instance,
721 * save the device GUID before exiting
724 strncpy (device_guid, instance_key, 256);
726 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
729 RegCloseKey (instance_key_handle);
734 RegCloseKey (adapter_key_handle);
741 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
743 * @param handle the handle to our tap device
744 * @return TRUE if the version is sufficient, else FALSE
747 check_tapw32_version (HANDLE handle)
751 memset (&(version), 0, sizeof (version));
753 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
754 &version, sizeof (version),
755 &version, sizeof (version), &len, NULL))
756 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
759 (version[2] ? "(DEBUG)" : ""));
761 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
762 (version[1] < TAP_WIN_MIN_MINOR )){
763 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
774 * Creates a tun-interface called dev;
776 * @return the fd to the tun or -1 on error
781 char device_path[256];
784 if (! setup_interface ())
787 return INVALID_HANDLE_VALUE;
790 if (! resolve_interface_name ())
793 return INVALID_HANDLE_VALUE;
796 /* Open Windows TAP-Windows adapter */
797 snprintf (device_path, sizeof (device_path), "%s%s%s",
802 handle = CreateFile (
804 GENERIC_READ | GENERIC_WRITE,
805 0, /* was: FILE_SHARE_READ */
808 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
812 if (INVALID_HANDLE_VALUE == handle)
814 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
818 /* get driver version info */
819 if (! check_tapw32_version (handle))
821 CloseHandle (handle);
822 return INVALID_HANDLE_VALUE;
825 /* TODO (opt?): get MTU-Size */
827 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
833 * Brings a TAP device up and sets it to connected state.
835 * @param handle the handle to our TAP device
836 * @return True if the operation succeeded, else false
839 tun_up (HANDLE handle)
843 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
844 &status, sizeof (status),
845 &status, sizeof (status), &len, NULL))
847 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
851 /* Wait for the device to go UP, might take some time. */
852 Sleep (TAP32_POSTUP_WAITTIME * 1000);
853 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
860 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
863 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
864 * input handle. Then it goes into IOSTATE_QUEUED state.
865 * In case the read succeeded instantly the input facility enters 3.
868 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
869 * If it has finished, go to state 3.
870 * If it has failed, set IOSTATE_FAILED
873 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
874 * The input facility enters state IOSTATE_READY
875 * The output facility enters state IOSTATE_READY
876 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
878 * IOSTATE_WAITING is reset by the output facility, once it has completed.
880 * @param input_facility input named pipe or file to work with.
881 * @param output_facility output pipe or file to hand over data to.
882 * @return false if an event reset was impossible (OS error), else true
885 attempt_read_tap (struct io_facility * input_facility,
886 struct io_facility * output_facility)
888 struct GNUNET_MessageHeader * hdr;
891 switch (input_facility->facility_state)
895 if (! ResetEvent (input_facility->overlapped.hEvent))
900 input_facility->buffer_size = 0;
902 /* Check how the task is handled */
903 if (ReadFile (input_facility->handle,
904 input_facility->buffer,
905 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
906 &input_facility->buffer_size,
907 &input_facility->overlapped))
908 {/* async event processed immediately*/
910 /* reset event manually*/
911 if (! SetEvent (input_facility->overlapped.hEvent))
914 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
916 /* we successfully read something from the TAP and now need to
917 * send it our via STDOUT. Is that possible at the moment? */
918 if ((IOSTATE_READY == output_facility->facility_state ||
919 IOSTATE_WAITING == output_facility->facility_state)
920 && (0 < input_facility->buffer_size))
921 { /* hand over this buffers content and apply message header for gnunet */
922 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
923 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
925 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
926 input_facility->buffer,
927 input_facility->buffer_size);
929 output_facility->buffer_size = size;
930 hdr->size = htons (size);
931 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
932 output_facility->facility_state = IOSTATE_READY;
934 else if (0 < input_facility->buffer_size)
935 /* If we have have read our buffer, wait for our write-partner*/
936 input_facility->facility_state = IOSTATE_WAITING;
938 else /* operation was either queued or failed*/
940 int err = GetLastError ();
941 if (ERROR_IO_PENDING == err)
942 { /* operation queued */
943 input_facility->facility_state = IOSTATE_QUEUED;
946 { /* error occurred, let the rest of the elements finish */
947 input_facility->path_open = FALSE;
948 input_facility->facility_state = IOSTATE_FAILED;
949 if (IOSTATE_WAITING == output_facility->facility_state)
950 output_facility->path_open = FALSE;
952 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
957 // We are queued and should check if the read has finished
960 // there was an operation going on already, check if that has completed now.
962 if (GetOverlappedResult (input_facility->handle,
963 &input_facility->overlapped,
964 &input_facility->buffer_size,
966 {/* successful return for a queued operation */
967 if (! ResetEvent (input_facility->overlapped.hEvent))
970 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
972 /* we successfully read something from the TAP and now need to
973 * send it our via STDOUT. Is that possible at the moment? */
974 if ((IOSTATE_READY == output_facility->facility_state ||
975 IOSTATE_WAITING == output_facility->facility_state)
976 && 0 < input_facility->buffer_size)
977 { /* hand over this buffers content and apply message header for gnunet */
978 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
979 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
981 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
982 input_facility->buffer,
983 input_facility->buffer_size);
985 output_facility->buffer_size = size;
986 hdr->size = htons(size);
987 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
988 output_facility->facility_state = IOSTATE_READY;
989 input_facility->facility_state = IOSTATE_READY;
991 else if (0 < input_facility->buffer_size)
992 { /* If we have have read our buffer, wait for our write-partner*/
993 input_facility->facility_state = IOSTATE_WAITING;
994 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
998 { /* operation still pending/queued or failed? */
999 int err = GetLastError ();
1000 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1001 { /* error occurred, let the rest of the elements finish */
1002 input_facility->path_open = FALSE;
1003 input_facility->facility_state = IOSTATE_FAILED;
1004 if (IOSTATE_WAITING == output_facility->facility_state)
1005 output_facility->path_open = FALSE;
1006 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1011 case IOSTATE_RESUME:
1012 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1013 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1015 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1016 input_facility->buffer,
1017 input_facility->buffer_size);
1019 output_facility->buffer_size = size;
1020 hdr->size = htons (size);
1021 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1022 output_facility->facility_state = IOSTATE_READY;
1023 input_facility->facility_state = IOSTATE_READY;
1032 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1035 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1036 * input handle. Then it goes into IOSTATE_QUEUED state.
1037 * In case the read succeeded instantly the input facility enters 3.
1040 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1041 * If it has finished, go to state 3.
1042 * If it has failed, set IOSTATE_FAILED
1045 * If the facility is finished with ready
1046 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1047 * The input facility enters state IOSTATE_READY
1048 * The output facility enters state IOSTATE_READY
1049 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1051 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1053 * @param input_facility input named pipe or file to work with.
1054 * @param output_facility output pipe or file to hand over data to.
1055 * @return false if an event reset was impossible (OS error), else true
1058 attempt_read_stdin (struct io_facility * input_facility,
1059 struct io_facility * output_facility)
1061 struct GNUNET_MessageHeader * hdr;
1063 switch (input_facility->facility_state)
1067 input_facility->buffer_size = 0;
1069 partial_read_iostate_ready:
1070 if (! ResetEvent (input_facility->overlapped.hEvent))
1073 /* Check how the task is handled */
1074 if (ReadFile (input_facility->handle,
1075 input_facility->buffer + input_facility->buffer_size,
1076 sizeof (input_facility->buffer) - input_facility->buffer_size,
1077 &input_facility->buffer_size_processed,
1078 &input_facility->overlapped))
1079 {/* async event processed immediately*/
1080 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1082 /* reset event manually*/
1083 if (!SetEvent (input_facility->overlapped.hEvent))
1086 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1087 input_facility->buffer_size += input_facility->buffer_size_processed;
1089 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1090 ntohs (hdr->size) > sizeof (input_facility->buffer))
1092 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1093 input_facility->facility_state = IOSTATE_READY;
1096 /* we got the a part of a packet */
1097 if (ntohs (hdr->size) > input_facility->buffer_size)
1098 goto partial_read_iostate_ready;
1100 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1101 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1102 ((IOSTATE_READY == output_facility->facility_state) ||
1103 (IOSTATE_WAITING == output_facility->facility_state)))
1104 {/* we successfully read something from the TAP and now need to
1105 * send it our via STDOUT. Is that possible at the moment? */
1107 /* hand over this buffers content and strip gnunet message header */
1108 memcpy (output_facility->buffer,
1109 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1110 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1111 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1112 output_facility->facility_state = IOSTATE_READY;
1113 input_facility->facility_state = IOSTATE_READY;
1115 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1116 /* If we have have read our buffer, wait for our write-partner*/
1117 input_facility->facility_state = IOSTATE_WAITING;
1118 else /* we read nothing */
1119 input_facility->facility_state = IOSTATE_READY;
1121 else /* operation was either queued or failed*/
1123 int err = GetLastError ();
1124 if (ERROR_IO_PENDING == err) /* operation queued */
1125 input_facility->facility_state = IOSTATE_QUEUED;
1127 { /* error occurred, let the rest of the elements finish */
1128 input_facility->path_open = FALSE;
1129 input_facility->facility_state = IOSTATE_FAILED;
1130 if (IOSTATE_WAITING == output_facility->facility_state)
1131 output_facility->path_open = FALSE;
1133 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1138 // We are queued and should check if the read has finished
1139 case IOSTATE_QUEUED:
1141 // there was an operation going on already, check if that has completed now.
1142 if (GetOverlappedResult (input_facility->handle,
1143 &input_facility->overlapped,
1144 &input_facility->buffer_size_processed,
1146 {/* successful return for a queued operation */
1147 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1149 if (! ResetEvent (input_facility->overlapped.hEvent))
1152 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1153 input_facility->buffer_size += input_facility->buffer_size_processed;
1155 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1156 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1158 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1159 input_facility->facility_state = IOSTATE_READY;
1162 /* we got the a part of a packet */
1163 if (ntohs (hdr->size) > input_facility->buffer_size );
1164 goto partial_read_iostate_ready;
1166 /* we successfully read something from the TAP and now need to
1167 * send it our via STDOUT. Is that possible at the moment? */
1168 if ((IOSTATE_READY == output_facility->facility_state ||
1169 IOSTATE_WAITING == output_facility->facility_state)
1170 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1171 { /* hand over this buffers content and strip gnunet message header */
1172 memcpy (output_facility->buffer,
1173 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1174 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1175 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1176 output_facility->facility_state = IOSTATE_READY;
1177 input_facility->facility_state = IOSTATE_READY;
1179 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1180 input_facility->facility_state = IOSTATE_WAITING;
1182 input_facility->facility_state = IOSTATE_READY;
1185 { /* operation still pending/queued or failed? */
1186 int err = GetLastError ();
1187 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1188 { /* error occurred, let the rest of the elements finish */
1189 input_facility->path_open = FALSE;
1190 input_facility->facility_state = IOSTATE_FAILED;
1191 if (IOSTATE_WAITING == output_facility->facility_state)
1192 output_facility->path_open = FALSE;
1193 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1198 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1199 memcpy (output_facility->buffer,
1200 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1201 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1202 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1203 output_facility->facility_state = IOSTATE_READY;
1204 input_facility->facility_state = IOSTATE_READY;
1213 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1215 * TODO: high level description
1217 * @param output_facility output pipe or file to hand over data to.
1218 * @param input_facility input named pipe or file to work with.
1219 * @return false if an event reset was impossible (OS error), else true
1222 attempt_write (struct io_facility * output_facility,
1223 struct io_facility * input_facility)
1225 switch (output_facility->facility_state)
1228 output_facility->buffer_size_written = 0;
1230 continue_partial_write:
1231 if (! ResetEvent (output_facility->overlapped.hEvent))
1234 /* Check how the task was handled */
1235 if (WriteFile (output_facility->handle,
1236 output_facility->buffer + output_facility->buffer_size_written,
1237 output_facility->buffer_size - output_facility->buffer_size_written,
1238 &output_facility->buffer_size_processed,
1239 &output_facility->overlapped))
1240 {/* async event processed immediately*/
1242 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1243 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1245 /* reset event manually*/
1246 if (! SetEvent (output_facility->overlapped.hEvent))
1250 if (output_facility->buffer_size_written < output_facility->buffer_size)
1251 goto continue_partial_write;
1253 /* we are now waiting for our buffer to be filled*/
1254 output_facility->facility_state = IOSTATE_WAITING;
1256 /* we successfully wrote something and now need to reset our reader */
1257 if (IOSTATE_WAITING == input_facility->facility_state)
1258 input_facility->facility_state = IOSTATE_RESUME;
1259 else if (IOSTATE_FAILED == input_facility->facility_state)
1260 output_facility->path_open = FALSE;
1262 else /* operation was either queued or failed*/
1264 int err = GetLastError ();
1265 if (ERROR_IO_PENDING == err)
1266 { /* operation queued */
1267 output_facility->facility_state = IOSTATE_QUEUED;
1270 { /* error occurred, close this path */
1271 output_facility->path_open = FALSE;
1272 output_facility->facility_state = IOSTATE_FAILED;
1273 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1277 case IOSTATE_QUEUED:
1278 // there was an operation going on already, check if that has completed now.
1280 if (GetOverlappedResult (output_facility->handle,
1281 &output_facility->overlapped,
1282 &output_facility->buffer_size_processed,
1284 {/* successful return for a queued operation */
1285 if (! ResetEvent (output_facility->overlapped.hEvent))
1288 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1289 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1292 if (output_facility->buffer_size_written < output_facility->buffer_size)
1293 goto continue_partial_write;
1295 /* we are now waiting for our buffer to be filled*/
1296 output_facility->facility_state = IOSTATE_WAITING;
1298 /* we successfully wrote something and now need to reset our reader */
1299 if (IOSTATE_WAITING == input_facility->facility_state)
1300 input_facility->facility_state = IOSTATE_RESUME;
1301 else if (IOSTATE_FAILED == input_facility->facility_state)
1302 output_facility->path_open = FALSE;
1305 { /* operation still pending/queued or failed? */
1306 int err = GetLastError ();
1307 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1308 { /* error occurred, close this path */
1309 output_facility->path_open = FALSE;
1310 output_facility->facility_state = IOSTATE_FAILED;
1311 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1321 * Initialize a overlapped structure
1323 * @param elem the element to initilize
1324 * @param initial_state the initial state for this instance
1325 * @param signaled if the hEvent created should default to signaled or not
1326 * @return true on success, else false
1329 initialize_io_facility (struct io_facility * elem,
1333 elem->path_open = TRUE;
1334 elem->handle = INVALID_HANDLE_VALUE;
1335 elem->facility_state = initial_state;
1336 elem->buffer_size = 0;
1337 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1338 if (NULL == elem->overlapped.hEvent)
1346 * Start forwarding to and from the tunnel.
1348 * @param tap_handle device handle for interacting with the Virtual interface
1351 run (HANDLE tap_handle)
1353 /* IO-Facility for reading from our virtual interface */
1354 struct io_facility tap_read;
1355 /* IO-Facility for writing to our virtual interface */
1356 struct io_facility tap_write;
1357 /* IO-Facility for reading from stdin */
1358 struct io_facility std_in;
1359 /* IO-Facility for writing to stdout */
1360 struct io_facility std_out;
1362 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1363 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1366 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1367 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1369 * DHCP and such are all features we will never use in gnunet afaik.
1370 * But for openvpn those are essential.
1372 if ((privilege_testing) || (! tun_up (tap_handle)))
1373 goto teardown_final;
1375 /* Initialize our overlapped IO structures*/
1376 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1377 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1378 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1379 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1380 goto teardown_final;
1382 /* Handles for STDIN and STDOUT */
1383 tap_read.handle = tap_handle;
1384 tap_write.handle = tap_handle;
1386 #ifdef DEBUG_TO_CONSOLE
1387 /* Debug output to console STDIN/STDOUT*/
1388 std_in.handle = parent_std_in_handle;
1389 std_out.handle = parent_std_out_handle;
1392 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1394 * Find out the types of our handles.
1395 * This part is a problem, because in windows we need to handle files,
1396 * pipes and the console differently.
1398 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1399 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1401 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1405 std_in.handle = ReOpenFile (parent_std_in_handle,
1407 FILE_SHARE_WRITE | FILE_SHARE_READ,
1408 FILE_FLAG_OVERLAPPED);
1410 if (INVALID_HANDLE_VALUE == std_in.handle)
1412 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1416 std_out.handle = ReOpenFile (parent_std_out_handle,
1419 FILE_FLAG_OVERLAPPED);
1421 if (INVALID_HANDLE_VALUE == std_out.handle)
1423 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1428 fprintf (stderr, "DEBUG: mainloop has begun\n");
1430 while (std_out.path_open || tap_write.path_open)
1432 /* perform READ from stdin if possible */
1433 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1436 /* perform READ from tap if possible */
1437 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1440 /* perform WRITE to tap if possible */
1441 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1444 /* perform WRITE to STDOUT if possible */
1445 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1449 fprintf (stderr, "DEBUG: teardown initiated\n");
1451 CancelIo (tap_handle);
1452 CancelIo (std_in.handle);
1453 CancelIo (std_out.handle);
1455 CloseHandle (tap_handle);
1460 * Open VPN tunnel interface.
1462 * @param argc must be 6
1463 * @param argv 0: binary name (gnunet-helper-vpn)
1464 * [1: dryrun/testrun (does not execute mainloop)]
1465 * 2: tunnel interface prefix (gnunet-vpn)
1466 * 3: IPv6 address (::1), "-" to disable
1467 * 4: IPv6 netmask length in bits (64), ignored if #2 is "-"
1468 * 5: IPv4 address (1.2.3.4), "-" to disable
1469 * 6: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
1472 main (int argc, char **argv)
1474 char hwid[LINE_LEN];
1477 BOOL have_ip4 = FALSE;
1478 BOOL have_ip6 = FALSE;
1480 if (argc > 1 && 0 != strcmp (argv[1], "-d")){
1481 privilege_testing = TRUE;
1484 "DEBUG: Running binary in privilege testing mode.");
1493 "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn [-d] <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n");
1497 strncpy (hwid, argv[1], LINE_LEN);
1498 hwid[LINE_LEN - 1] = '\0';
1501 * We use our PID for finding/resolving the control-panel name of our virtual
1502 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1503 * as additional hardware-id for our device.
1505 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1509 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1511 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1521 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1522 if (0 != strcmp (argv[2], "-"))
1524 const char *address = argv[2];
1525 long prefix_len = atol (argv[3]);
1527 if ((prefix_len < 1) || (prefix_len > 127))
1529 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1534 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n",address,prefix_len);
1535 if (0 != (global_ret = set_address6 (address, prefix_len)))
1541 if (0 != strcmp (argv[4], "-"))
1543 const char *address = argv[4];
1544 const char *mask = argv[5];
1546 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n",address,mask);
1547 if (0 != (global_ret = set_address4 (address, mask)))
1558 const char *address = argv[4];
1559 fprintf (stderr, "DEBUG: Removing IP4 address\n");
1560 remove_address4 (address);
1564 const char *address = argv[2];
1565 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1566 remove_address6 (address);
1569 fprintf (stderr, "DEBUG: removing interface\n");
1570 remove_interface ();
1571 fprintf (stderr, "DEBUG: graceful exit completed\n");