2 This file is part of GNUnet.
3 (C) 2010, 2012 Christian Grothoff
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file exit/gnunet-helper-exit-windows.c
22 * @brief the helper for the EXIT service in win32 builds.
23 * Opens a virtual network-interface, sends data received on the if to stdout,
24 * sends data received on stdin to the interface
25 * @author Christian M. Fuchs
27 * The following list of people have reviewed this code and considered
28 * it safe since the last modification (if you reviewed it, please
29 * have your name added to the list):
35 #include <ddk/cfgmgr32.h>
36 #include <ddk/newdev.h>
40 #include "tap-windows.h"
42 * Need 'struct GNUNET_MessageHeader'.
44 #include "gnunet_common.h"
47 * Need VPN message types.
49 #include "gnunet_protocols.h"
52 * Should we print (interesting|debug) messages that can happen during
55 #define DEBUG GNUNET_NO
58 /* FIXME: define with varargs... */
59 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
61 #define LOG_DEBUG(msg) do {} while (0)
66 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
68 #define MAX_SIZE 65536
71 * Name or Path+Name of our win32 driver.
72 * The .sys and .cat files HAVE to be in the same location as this file!
74 #define INF_FILE "share/gnunet/tapw32/OemWin2k.inf"
77 * Name or Path+Name of our win64 driver.
78 * The .sys and .cat files HAVE to be in the same location as this file!
80 #define INF_FILE64 "share/gnunet/tapw64/OemWin2k.inf"
83 * Hardware ID used in the inf-file.
84 * This might change over time, as openvpn advances their driver
86 #define HARDWARE_ID "tap0901"
89 * Minimum major-id of the driver version we can work with
91 #define TAP_WIN_MIN_MAJOR 9
94 * Minimum minor-id of the driver version we can work with.
95 * v <= 7 has buggy IPv6.
96 * v == 8 is broken for small IPv4 Packets
98 #define TAP_WIN_MIN_MINOR 9
101 * Time in seconds to wait for our virtual device to go up after telling it to do so.
103 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
104 * (in fact, 4 was chosen by a fair dice roll...)
106 #define TAP32_POSTUP_WAITTIME 4
109 * Location of the network interface list resides in registry.
111 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
114 * Our local process' PID. Used for creating a sufficiently unique additional
115 * hardware ID for our device.
117 static char secondary_hwid[LINE_LEN / 2];
120 * Device's visible Name, used to identify a network device in netsh.
121 * eg: "Local Area Connection 9"
123 static char device_visible_name[256];
126 * This is our own local instance of a virtual network interface
127 * It is (somewhat) equivalent to using tun/tap in unixoid systems
129 * Upon initialization, we create such an device node.
130 * Upon termination, we remove it again.
132 * If we crash this device might stay around.
134 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
137 * Registry Key we hand over to windows to spawn a new virtual interface
139 static SP_DEVINFO_DATA DeviceNode;
142 * GUID of our virtual device in the form of
143 * {12345678-1234-1234-1234-123456789abc} - in hex
145 static char device_guid[256];
149 * Possible states of an IO facility.
155 * overlapped I/O is ready for work
160 * overlapped I/O has been queued
165 * overlapped I/O has finished, but is waiting for it's write-partner
170 * there is a full buffer waiting
175 * Operlapped IO states for facility objects
176 * overlapped I/O has failed, stop processing
184 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
189 * The mode the state machine associated with this object is in.
191 enum IO_State facility_state;
194 * If the path is open or blocked in general (used for quickly checking)
196 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
199 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
204 * Overlaped IO structure used for asynchronous IO in windows.
206 OVERLAPPED overlapped;
209 * Buffer for reading things to and writing from...
211 unsigned char buffer[MAX_SIZE];
214 * How much of this buffer was used when reading or how much data can be written
219 * Amount of data actually written or read by readfile/writefile.
221 DWORD buffer_size_processed;
224 * How much of this buffer we have written in total
226 DWORD buffer_size_written;
230 * ReOpenFile is only available as of XP SP2 and 2003 SP1
232 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
235 * IsWow64Process definition for our is_win64, as this is a kernel function
237 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
240 * Determines if the host OS is win32 or win64
248 //this is a win64 binary,
250 #elif defined(_WIN32)
251 //this is a 32bit binary, and we need to check if we are running in WOW64
252 BOOL success = FALSE;
253 BOOL on_wow64 = FALSE;
254 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
256 if (NULL != IsWow64Process)
257 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
259 return success && on_wow64;
263 * Wrapper for executing a shellcommand in windows.
265 * @param command - the command + parameters to execute
266 * @return * exitcode of the program executed,
267 * * EINVAL (cmd/file not found)
268 * * EPIPE (could not read STDOUT)
271 execute_shellcommand (const char *command)
275 if ( (NULL == command) ||
276 (NULL == (pipe = _popen (command, "rt"))) )
280 fprintf (stderr, "DEBUG: Command output: \n");
281 char output[LINE_LEN];
282 while (NULL != fgets (output, sizeof (output), pipe))
283 fprintf (stderr, "%s", output);
286 return _pclose (pipe);
291 * @brief Sets the IPv6-Address given in address on the interface dev
293 * @param address the IPv6-Address
294 * @param prefix_len the length of the network-prefix
297 set_address6 (const char *address, unsigned long prefix_len)
300 char command[LINE_LEN];
301 struct sockaddr_in6 sa6;
304 * parse the new address
306 memset (&sa6, 0, sizeof (struct sockaddr_in6));
307 sa6.sin6_family = AF_INET6;
308 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
310 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
316 * prepare the command
318 snprintf (command, LINE_LEN,
319 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
320 device_visible_name, address, prefix_len);
324 ret = execute_shellcommand (command);
328 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
334 * @brief Removes the IPv6-Address given in address from the interface dev
336 * @param dev the interface to remove
337 * @param address the IPv4-Address
338 * @param mask the netmask
341 remove_address6 (const char *address)
343 char command[LINE_LEN];
346 // sanity checking was already done in set_address6
348 * prepare the command
350 snprintf (command, LINE_LEN,
351 "netsh interface ipv6 delete address \"%s\" store=persistent",
352 device_visible_name, address);
356 ret = execute_shellcommand (command);
360 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
365 * @brief Sets the IPv4-Address given in address on the interface dev
367 * @param dev the interface to configure
368 * @param address the IPv4-Address
369 * @param mask the netmask
372 set_address4 (const char *address, const char *mask)
375 char command[LINE_LEN];
377 struct sockaddr_in addr;
378 addr.sin_family = AF_INET;
383 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
385 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
389 // Set Device to Subnet-Mode?
390 // do we really need tun.c:2925 ?
393 * prepare the command
395 snprintf (command, LINE_LEN,
396 "netsh interface ipv4 add address \"%s\" %s %s store=active",
397 device_visible_name, address, mask);
401 ret = execute_shellcommand (command);
405 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
411 * @brief Removes the IPv4-Address given in address from the interface dev
413 * @param dev the interface to remove
414 * @param address the IPv4-Address
415 * @param mask the netmask
418 remove_address4 (const char *address)
420 char command[LINE_LEN];
423 // sanity checking was already done in set_address4
426 * prepare the command
428 snprintf (command, LINE_LEN,
429 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
430 device_visible_name, address);
434 ret = execute_shellcommand (command);
438 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
443 * Setup a new virtual interface to use for tunneling.
445 * @return: TRUE if setup was successful, else FALSE
451 * where to find our inf-file. (+ the "full" path, after windows found")
453 * We do not directly input all the props here, because openvpn will update
454 * these details over time.
456 char inf_file_path[MAX_PATH];
457 char * temp_inf_filename;
458 char hwidlist[LINE_LEN + 4];
459 char class_name[128];
464 * Set the device's hardware ID and add it to a list.
465 * This information will later on identify this device in registry.
467 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
469 * this is kind of over-complicated, but allows keeps things independent of
470 * how the openvpn-hwid is actually stored.
472 * A HWID list is double-\0 terminated and \0 separated
474 str_length = strlen (hwidlist) + 1;
475 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
476 str_length += strlen (&hwidlist[str_length]) + 1;
479 * Locate the inf-file, we need to store it somewhere where the system can
480 * find it. We need to pick the correct driver for win32/win64.
483 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
485 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
487 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
489 * Bootstrap our device info using the drivers inf-file
491 if ( ! SetupDiGetINFClassA (inf_file_path,
493 class_name, sizeof (class_name) / sizeof (char),
498 * Collect all the other needed information...
499 * let the system fill our this form
501 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
502 if (DeviceInfo == INVALID_HANDLE_VALUE)
505 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
506 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
515 /* Deploy all the information collected into the registry */
516 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
520 str_length * sizeof (char)))
523 /* Install our new class(=device) into the system */
524 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
529 /* This system call tends to take a while (several seconds!) on
530 "modern" Windoze systems */
531 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
534 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
535 NULL)) //reboot required? NEVER!
538 fprintf (stderr, "DEBUG: successfully created a network device\n");
544 * Remove our new virtual interface to use for tunneling.
545 * This function must be called AFTER setup_interface!
547 * @return: TRUE if destruction was successful, else FALSE
552 SP_REMOVEDEVICE_PARAMS remove;
554 if (INVALID_HANDLE_VALUE == DeviceInfo)
557 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
558 remove.HwProfile = 0;
559 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
560 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
562 * 1. Prepare our existing device information set, and place the
563 * uninstall related information into the structure
565 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
566 (PSP_DEVINFO_DATA) & DeviceNode,
567 &remove.ClassInstallHeader,
571 * 2. Uninstall the virtual interface using the class installer
573 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
575 (PSP_DEVINFO_DATA) & DeviceNode))
578 SetupDiDestroyDeviceInfoList (DeviceInfo);
580 fprintf (stderr, "DEBUG: removed interface successfully\n");
587 * Do all the lookup necessary to retrieve the inteface's actual name
590 * @return: TRUE if we were able to lookup the interface's name, else FALSE
593 resolve_interface_name ()
595 SP_DEVINFO_LIST_DETAIL_DATA device_details;
596 char pnp_instance_id [MAX_DEVICE_ID_LEN];
597 HKEY adapter_key_handle;
603 char adapter[] = INTERFACE_REGISTRY_LOCATION;
605 /* We can obtain the PNP instance ID from our setupapi handle */
606 device_details.cbSize = sizeof (device_details);
607 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
608 (PCHAR) pnp_instance_id,
611 NULL)) //hMachine, we are local
614 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
616 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
617 for (retrys = 0; retrys < 120 && !retval; retrys++)
622 /* Now we can use this ID to locate the correct networks interface in registry */
623 if (ERROR_SUCCESS != RegOpenKeyExA (
628 &adapter_key_handle))
631 /* Of course there is a multitude of entries here, with arbitrary names,
632 * thus we need to iterate through there.
636 char instance_key[256];
637 char query_key [256];
638 HKEY instance_key_handle;
639 char pnpinstanceid_name[] = "PnpInstanceID";
640 char pnpinstanceid_value[256];
641 char adaptername_name[] = "Name";
644 len = 256 * sizeof (char);
645 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
646 status = RegEnumKeyExA (
656 /* this may fail due to one of two reasons:
657 * we are at the end of the list*/
658 if (ERROR_NO_MORE_ITEMS == status)
660 // * we found a broken registry key, continue with the next key.
661 if (ERROR_SUCCESS != status)
664 /* prepare our new query string: */
665 snprintf (query_key, 256, "%s\\%s\\Connection",
669 /* look inside instance_key\\Connection */
670 if (ERROR_SUCCESS != RegOpenKeyExA (
675 &instance_key_handle))
678 /* now, read our PnpInstanceID */
679 len = sizeof (pnpinstanceid_value);
680 status = RegQueryValueExA (instance_key_handle,
682 NULL, //reserved, always NULL according to MSDN
684 (LPBYTE) pnpinstanceid_value,
687 if (status != ERROR_SUCCESS || data_type != REG_SZ)
690 /* compare the value we got to our devices PNPInstanceID*/
691 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
692 sizeof (pnpinstanceid_value) / sizeof (char)))
695 len = sizeof (device_visible_name);
696 status = RegQueryValueExA (
699 NULL, //reserved, always NULL according to MSDN
701 (LPBYTE) device_visible_name,
704 if (status != ERROR_SUCCESS || data_type != REG_SZ)
708 * we have successfully found OUR instance,
709 * save the device GUID before exiting
712 strncpy (device_guid, instance_key, 256);
714 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
717 RegCloseKey (instance_key_handle);
722 RegCloseKey (adapter_key_handle);
729 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
731 * @param handle the handle to our tap device
732 * @return TRUE if the version is sufficient, else FALSE
735 check_tapw32_version (HANDLE handle)
739 memset (&(version), 0, sizeof (version));
741 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
742 &version, sizeof (version),
743 &version, sizeof (version), &len, NULL))
744 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
747 (version[2] ? "(DEBUG)" : ""));
749 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
750 (version[1] < TAP_WIN_MIN_MINOR )){
751 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
762 * Creates a tun-interface called dev;
764 * @return the fd to the tun or -1 on error
769 char device_path[256];
772 if (! setup_interface ())
775 return INVALID_HANDLE_VALUE;
778 if (! resolve_interface_name ())
781 return INVALID_HANDLE_VALUE;
784 /* Open Windows TAP-Windows adapter */
785 snprintf (device_path, sizeof (device_path), "%s%s%s",
790 handle = CreateFile (
792 GENERIC_READ | GENERIC_WRITE,
793 0, /* was: FILE_SHARE_READ */
796 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
800 if (INVALID_HANDLE_VALUE == handle)
802 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
806 /* get driver version info */
807 if (! check_tapw32_version (handle))
809 CloseHandle (handle);
810 return INVALID_HANDLE_VALUE;
813 /* TODO (opt?): get MTU-Size */
815 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
821 * Brings a TAP device up and sets it to connected state.
823 * @param handle the handle to our TAP device
824 * @return True if the operation succeeded, else false
827 tun_up (HANDLE handle)
831 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
832 &status, sizeof (status),
833 &status, sizeof (status), &len, NULL))
835 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
839 /* Wait for the device to go UP, might take some time. */
840 Sleep (TAP32_POSTUP_WAITTIME * 1000);
841 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
848 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
851 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
852 * input handle. Then it goes into IOSTATE_QUEUED state.
853 * In case the read succeeded instantly the input facility enters 3.
856 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
857 * If it has finished, go to state 3.
858 * If it has failed, set IOSTATE_FAILED
861 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
862 * The input facility enters state IOSTATE_READY
863 * The output facility enters state IOSTATE_READY
864 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
866 * IOSTATE_WAITING is reset by the output facility, once it has completed.
868 * @param input_facility input named pipe or file to work with.
869 * @param output_facility output pipe or file to hand over data to.
870 * @return false if an event reset was impossible (OS error), else true
873 attempt_read_tap (struct io_facility * input_facility,
874 struct io_facility * output_facility)
876 struct GNUNET_MessageHeader * hdr;
879 switch (input_facility->facility_state)
883 if (! ResetEvent (input_facility->overlapped.hEvent))
888 input_facility->buffer_size = 0;
890 /* Check how the task is handled */
891 if (ReadFile (input_facility->handle,
892 input_facility->buffer,
893 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
894 &input_facility->buffer_size,
895 &input_facility->overlapped))
896 {/* async event processed immediately*/
898 /* reset event manually*/
899 if (! SetEvent (input_facility->overlapped.hEvent))
902 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
904 /* we successfully read something from the TAP and now need to
905 * send it our via STDOUT. Is that possible at the moment? */
906 if ((IOSTATE_READY == output_facility->facility_state ||
907 IOSTATE_WAITING == output_facility->facility_state)
908 && (0 < input_facility->buffer_size))
909 { /* hand over this buffers content and apply message header for gnunet */
910 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
911 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
913 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
914 input_facility->buffer,
915 input_facility->buffer_size);
917 output_facility->buffer_size = size;
918 hdr->size = htons (size);
919 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
920 output_facility->facility_state = IOSTATE_READY;
922 else if (0 < input_facility->buffer_size)
923 /* If we have have read our buffer, wait for our write-partner*/
924 input_facility->facility_state = IOSTATE_WAITING;
926 else /* operation was either queued or failed*/
928 int err = GetLastError ();
929 if (ERROR_IO_PENDING == err)
930 { /* operation queued */
931 input_facility->facility_state = IOSTATE_QUEUED;
934 { /* error occurred, let the rest of the elements finish */
935 input_facility->path_open = FALSE;
936 input_facility->facility_state = IOSTATE_FAILED;
937 if (IOSTATE_WAITING == output_facility->facility_state)
938 output_facility->path_open = FALSE;
940 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
945 // We are queued and should check if the read has finished
948 // there was an operation going on already, check if that has completed now.
950 if (GetOverlappedResult (input_facility->handle,
951 &input_facility->overlapped,
952 &input_facility->buffer_size,
954 {/* successful return for a queued operation */
955 if (! ResetEvent (input_facility->overlapped.hEvent))
958 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
960 /* we successfully read something from the TAP and now need to
961 * send it our via STDOUT. Is that possible at the moment? */
962 if ((IOSTATE_READY == output_facility->facility_state ||
963 IOSTATE_WAITING == output_facility->facility_state)
964 && 0 < input_facility->buffer_size)
965 { /* hand over this buffers content and apply message header for gnunet */
966 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
967 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
969 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
970 input_facility->buffer,
971 input_facility->buffer_size);
973 output_facility->buffer_size = size;
974 hdr->size = htons(size);
975 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
976 output_facility->facility_state = IOSTATE_READY;
977 input_facility->facility_state = IOSTATE_READY;
979 else if (0 < input_facility->buffer_size)
980 { /* If we have have read our buffer, wait for our write-partner*/
981 input_facility->facility_state = IOSTATE_WAITING;
982 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
986 { /* operation still pending/queued or failed? */
987 int err = GetLastError ();
988 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
989 { /* error occurred, let the rest of the elements finish */
990 input_facility->path_open = FALSE;
991 input_facility->facility_state = IOSTATE_FAILED;
992 if (IOSTATE_WAITING == output_facility->facility_state)
993 output_facility->path_open = FALSE;
994 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1000 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1001 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1003 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1004 input_facility->buffer,
1005 input_facility->buffer_size);
1007 output_facility->buffer_size = size;
1008 hdr->size = htons (size);
1009 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1010 output_facility->facility_state = IOSTATE_READY;
1011 input_facility->facility_state = IOSTATE_READY;
1020 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1023 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1024 * input handle. Then it goes into IOSTATE_QUEUED state.
1025 * In case the read succeeded instantly the input facility enters 3.
1028 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1029 * If it has finished, go to state 3.
1030 * If it has failed, set IOSTATE_FAILED
1033 * If the facility is finished with ready
1034 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1035 * The input facility enters state IOSTATE_READY
1036 * The output facility enters state IOSTATE_READY
1037 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1039 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1041 * @param input_facility input named pipe or file to work with.
1042 * @param output_facility output pipe or file to hand over data to.
1043 * @return false if an event reset was impossible (OS error), else true
1046 attempt_read_stdin (struct io_facility * input_facility,
1047 struct io_facility * output_facility)
1049 struct GNUNET_MessageHeader * hdr;
1051 switch (input_facility->facility_state)
1055 input_facility->buffer_size = 0;
1057 partial_read_iostate_ready:
1058 if (! ResetEvent (input_facility->overlapped.hEvent))
1061 /* Check how the task is handled */
1062 if (ReadFile (input_facility->handle,
1063 input_facility->buffer + input_facility->buffer_size,
1064 sizeof (input_facility->buffer) - input_facility->buffer_size,
1065 &input_facility->buffer_size_processed,
1066 &input_facility->overlapped))
1067 {/* async event processed immediately*/
1068 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1070 /* reset event manually*/
1071 if (!SetEvent (input_facility->overlapped.hEvent))
1074 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1075 input_facility->buffer_size += input_facility->buffer_size_processed;
1077 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1078 ntohs (hdr->size) > sizeof (input_facility->buffer))
1080 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1081 input_facility->facility_state = IOSTATE_READY;
1084 /* we got the a part of a packet */
1085 if (ntohs (hdr->size) > input_facility->buffer_size)
1086 goto partial_read_iostate_ready;
1088 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1089 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1090 ((IOSTATE_READY == output_facility->facility_state) ||
1091 (IOSTATE_WAITING == output_facility->facility_state)))
1092 {/* we successfully read something from the TAP and now need to
1093 * send it our via STDOUT. Is that possible at the moment? */
1095 /* hand over this buffers content and strip gnunet message header */
1096 memcpy (output_facility->buffer,
1097 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1098 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1099 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1100 output_facility->facility_state = IOSTATE_READY;
1101 input_facility->facility_state = IOSTATE_READY;
1103 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1104 /* If we have have read our buffer, wait for our write-partner*/
1105 input_facility->facility_state = IOSTATE_WAITING;
1106 else /* we read nothing */
1107 input_facility->facility_state = IOSTATE_READY;
1109 else /* operation was either queued or failed*/
1111 int err = GetLastError ();
1112 if (ERROR_IO_PENDING == err) /* operation queued */
1113 input_facility->facility_state = IOSTATE_QUEUED;
1115 { /* error occurred, let the rest of the elements finish */
1116 input_facility->path_open = FALSE;
1117 input_facility->facility_state = IOSTATE_FAILED;
1118 if (IOSTATE_WAITING == output_facility->facility_state)
1119 output_facility->path_open = FALSE;
1121 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1126 // We are queued and should check if the read has finished
1127 case IOSTATE_QUEUED:
1129 // there was an operation going on already, check if that has completed now.
1130 if (GetOverlappedResult (input_facility->handle,
1131 &input_facility->overlapped,
1132 &input_facility->buffer_size_processed,
1134 {/* successful return for a queued operation */
1135 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1137 if (! ResetEvent (input_facility->overlapped.hEvent))
1140 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1141 input_facility->buffer_size += input_facility->buffer_size_processed;
1143 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1144 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1146 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1147 input_facility->facility_state = IOSTATE_READY;
1150 /* we got the a part of a packet */
1151 if (ntohs (hdr->size) > input_facility->buffer_size );
1152 goto partial_read_iostate_ready;
1154 /* we successfully read something from the TAP and now need to
1155 * send it our via STDOUT. Is that possible at the moment? */
1156 if ((IOSTATE_READY == output_facility->facility_state ||
1157 IOSTATE_WAITING == output_facility->facility_state)
1158 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1159 { /* hand over this buffers content and strip gnunet message header */
1160 memcpy (output_facility->buffer,
1161 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1162 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1163 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1164 output_facility->facility_state = IOSTATE_READY;
1165 input_facility->facility_state = IOSTATE_READY;
1167 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1168 input_facility->facility_state = IOSTATE_WAITING;
1170 input_facility->facility_state = IOSTATE_READY;
1173 { /* operation still pending/queued or failed? */
1174 int err = GetLastError ();
1175 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1176 { /* error occurred, let the rest of the elements finish */
1177 input_facility->path_open = FALSE;
1178 input_facility->facility_state = IOSTATE_FAILED;
1179 if (IOSTATE_WAITING == output_facility->facility_state)
1180 output_facility->path_open = FALSE;
1181 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1186 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1187 memcpy (output_facility->buffer,
1188 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1189 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1190 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1191 output_facility->facility_state = IOSTATE_READY;
1192 input_facility->facility_state = IOSTATE_READY;
1201 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1203 * TODO: high level description
1205 * @param output_facility output pipe or file to hand over data to.
1206 * @param input_facility input named pipe or file to work with.
1207 * @return false if an event reset was impossible (OS error), else true
1210 attempt_write (struct io_facility * output_facility,
1211 struct io_facility * input_facility)
1213 switch (output_facility->facility_state)
1216 output_facility->buffer_size_written = 0;
1218 continue_partial_write:
1219 if (! ResetEvent (output_facility->overlapped.hEvent))
1222 /* Check how the task was handled */
1223 if (WriteFile (output_facility->handle,
1224 output_facility->buffer + output_facility->buffer_size_written,
1225 output_facility->buffer_size - output_facility->buffer_size_written,
1226 &output_facility->buffer_size_processed,
1227 &output_facility->overlapped))
1228 {/* async event processed immediately*/
1230 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1231 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1233 /* reset event manually*/
1234 if (! SetEvent (output_facility->overlapped.hEvent))
1238 if (output_facility->buffer_size_written < output_facility->buffer_size)
1239 goto continue_partial_write;
1241 /* we are now waiting for our buffer to be filled*/
1242 output_facility->facility_state = IOSTATE_WAITING;
1244 /* we successfully wrote something and now need to reset our reader */
1245 if (IOSTATE_WAITING == input_facility->facility_state)
1246 input_facility->facility_state = IOSTATE_RESUME;
1247 else if (IOSTATE_FAILED == input_facility->facility_state)
1248 output_facility->path_open = FALSE;
1250 else /* operation was either queued or failed*/
1252 int err = GetLastError ();
1253 if (ERROR_IO_PENDING == err)
1254 { /* operation queued */
1255 output_facility->facility_state = IOSTATE_QUEUED;
1258 { /* error occurred, close this path */
1259 output_facility->path_open = FALSE;
1260 output_facility->facility_state = IOSTATE_FAILED;
1261 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1265 case IOSTATE_QUEUED:
1266 // there was an operation going on already, check if that has completed now.
1268 if (GetOverlappedResult (output_facility->handle,
1269 &output_facility->overlapped,
1270 &output_facility->buffer_size_processed,
1272 {/* successful return for a queued operation */
1273 if (! ResetEvent (output_facility->overlapped.hEvent))
1276 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1277 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1280 if (output_facility->buffer_size_written < output_facility->buffer_size)
1281 goto continue_partial_write;
1283 /* we are now waiting for our buffer to be filled*/
1284 output_facility->facility_state = IOSTATE_WAITING;
1286 /* we successfully wrote something and now need to reset our reader */
1287 if (IOSTATE_WAITING == input_facility->facility_state)
1288 input_facility->facility_state = IOSTATE_RESUME;
1289 else if (IOSTATE_FAILED == input_facility->facility_state)
1290 output_facility->path_open = FALSE;
1293 { /* operation still pending/queued or failed? */
1294 int err = GetLastError ();
1295 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1296 { /* error occurred, close this path */
1297 output_facility->path_open = FALSE;
1298 output_facility->facility_state = IOSTATE_FAILED;
1299 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1309 * Initialize a overlapped structure
1311 * @param elem the element to initilize
1312 * @param initial_state the initial state for this instance
1313 * @param signaled if the hEvent created should default to signaled or not
1314 * @return true on success, else false
1317 initialize_io_facility (struct io_facility * elem,
1321 elem->path_open = TRUE;
1322 elem->handle = INVALID_HANDLE_VALUE;
1323 elem->facility_state = initial_state;
1324 elem->buffer_size = 0;
1325 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1326 if (NULL == elem->overlapped.hEvent)
1334 * Start forwarding to and from the tunnel.
1336 * @param fd_tun tunnel FD
1339 run (HANDLE tap_handle)
1341 /* IO-Facility for reading from our virtual interface */
1342 struct io_facility tap_read;
1343 /* IO-Facility for writing to our virtual interface */
1344 struct io_facility tap_write;
1345 /* IO-Facility for reading from stdin */
1346 struct io_facility std_in;
1347 /* IO-Facility for writing to stdout */
1348 struct io_facility std_out;
1350 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1351 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1354 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1355 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1357 * DHCP and such are all features we will never use in gnunet afaik.
1358 * But for openvpn those are essential.
1360 if (! tun_up (tap_handle))
1363 /* Initialize our overlapped IO structures*/
1364 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1365 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1366 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1367 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1368 goto teardown_final;
1370 /* Handles for STDIN and STDOUT */
1371 tap_read.handle = tap_handle;
1372 tap_write.handle = tap_handle;
1374 #ifdef DEBUG_TO_CONSOLE
1375 /* Debug output to console STDIN/STDOUT*/
1376 std_in.handle = parent_std_in_handle;
1377 std_out.handle = parent_std_out_handle;
1380 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1382 * Find out the types of our handles.
1383 * This part is a problem, because in windows we need to handle files,
1384 * pipes and the console differently.
1386 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1387 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1389 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1393 std_in.handle = ReOpenFile (parent_std_in_handle,
1395 FILE_SHARE_WRITE | FILE_SHARE_READ,
1396 FILE_FLAG_OVERLAPPED);
1398 if (INVALID_HANDLE_VALUE == std_in.handle)
1400 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1404 std_out.handle = ReOpenFile (parent_std_out_handle,
1407 FILE_FLAG_OVERLAPPED);
1409 if (INVALID_HANDLE_VALUE == std_out.handle)
1411 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1416 fprintf (stderr, "DEBUG: mainloop has begun\n");
1418 while (std_out.path_open || tap_write.path_open)
1420 /* perform READ from stdin if possible */
1421 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1424 /* perform READ from tap if possible */
1425 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1428 /* perform WRITE to tap if possible */
1429 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1432 /* perform WRITE to STDOUT if possible */
1433 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1439 fprintf (stderr, "DEBUG: teardown initiated\n");
1441 CancelIo (tap_handle);
1442 CancelIo (std_in.handle);
1443 CancelIo (std_out.handle);
1447 CloseHandle (tap_handle);
1452 * Open VPN tunnel interface.
1454 * @param argc must be 6
1455 * @param argv 0: binary name ("gnunet-helper-exit")
1456 * 1: tunnel interface name ("gnunet-exit")
1457 * 2: IPv4 "physical" interface name ("eth0"), or "%" to not do IPv4 NAT
1458 * 3: IPv6 address ("::1"), or "-" to skip IPv6
1459 * 4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1460 * 5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1461 * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1464 main (int argc, char **argv)
1466 char hwid[LINE_LEN];
1469 BOOL have_ip4 = FALSE;
1470 BOOL have_ip6 = FALSE;
1474 fprintf (stderr, "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1478 strncpy (hwid, argv[1], LINE_LEN);
1479 hwid[LINE_LEN - 1] = '\0';
1482 * We use our PID for finding/resolving the control-panel name of our virtual
1483 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1484 * as additional hardware-id for our device.
1486 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1490 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1492 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1502 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1503 if (0 != strcmp (argv[3], "-"))
1505 const char *address = argv[3];
1506 long prefix_len = atol (argv[4]);
1508 if ((prefix_len < 1) || (prefix_len > 127))
1510 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1515 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n",address,prefix_len);
1516 if (0 != (global_ret = set_address6 (address, prefix_len)))
1522 if (0 != strcmp (argv[5], "-"))
1524 const char *address = argv[5];
1525 const char *mask = argv[6];
1527 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n",address,mask);
1528 if (0 != (global_ret = set_address4 (address, mask)))
1531 // setup NAT, if possible
1532 if (0 != strcmp (argv[2], "%"))
1534 /* TODO: " Windows Firewall with Advanced Security" (lol)
1536 * MS has REMOVED the routing/nat capabilities since Vista, thus
1537 * we can not setup NAT like in XP. Our best bet is
1538 * to determine if we are running on XP, if we do, use netsh routing
1539 * else we need to use WFAS and do things ourselfs
1552 const char *address = argv[5];
1553 fprintf (stderr, "DEBUG: Removing IP4 address\n");
1554 remove_address4 (address);
1558 const char *address = argv[3];
1559 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1560 remove_address6 (address);
1563 fprintf (stderr, "DEBUG: removing interface\n");
1564 remove_interface ();
1565 fprintf (stderr, "DEBUG: graceful exit completed\n");