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.
22 * @file vpn/gnunet-helper-vpn-windows.c
23 * @brief the helper for the VPN service in win32 builds.
24 * Opens a virtual network-interface, sends data received on the if to stdout,
25 * sends data received on stdin to the interface
26 * @author Christian M. Fuchs
28 * The following list of people have reviewed this code and considered
29 * it safe since the last modification (if you reviewed it, please
30 * have your name added to the list):
37 #include <ddk/cfgmgr32.h>
38 #include <ddk/newdev.h>
42 #include "tap-windows.h"
44 * Need 'struct GNUNET_MessageHeader'.
46 #include "gnunet_common.h"
49 * Need VPN message types.
51 #include "gnunet_protocols.h"
54 * Should we print (interesting|debug) messages that can happen during
57 #define DEBUG GNUNET_NO
60 /* FIXME: define with varargs... */
61 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
63 #define LOG_DEBUG(msg) do {} while (0)
68 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
70 #define MAX_SIZE 65536
73 * Name or Path+Name of our win32 driver.
74 * The .sys and .cat files HAVE to be in the same location as this file!
76 #define INF_FILE "share/gnunet/tapw32/OemWin2k.inf"
79 * Name or Path+Name of our win64 driver.
80 * The .sys and .cat files HAVE to be in the same location as this file!
82 #define INF_FILE64 "share/gnunet/tapw64/OemWin2k.inf"
85 * Hardware ID used in the inf-file.
86 * This might change over time, as openvpn advances their driver
88 #define HARDWARE_ID "tap0901"
91 * Minimum major-id of the driver version we can work with
93 #define TAP_WIN_MIN_MAJOR 9
96 * Minimum minor-id of the driver version we can work with.
97 * v <= 7 has buggy IPv6.
98 * v == 8 is broken for small IPv4 Packets
100 #define TAP_WIN_MIN_MINOR 9
103 * Time in seconds to wait for our virtual device to go up after telling it to do so.
105 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
106 * (in fact, 4 was chosen by a fair dice roll...)
108 #define TAP32_POSTUP_WAITTIME 4
111 * Location of the network interface list resides in registry.
113 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
116 * Our local process' PID. Used for creating a sufficiently unique additional
117 * hardware ID for our device.
119 static char secondary_hwid[LINE_LEN / 2];
122 * Device's visible Name, used to identify a network device in netsh.
123 * eg: "Local Area Connection 9"
125 static char device_visible_name[256];
128 * This is our own local instance of a virtual network interface
129 * It is (somewhat) equivalent to using tun/tap in unixoid systems
131 * Upon initialization, we create such an device node.
132 * Upon termination, we remove it again.
134 * If we crash this device might stay around.
136 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
139 * Registry Key we hand over to windows to spawn a new virtual interface
141 static SP_DEVINFO_DATA DeviceNode;
144 * GUID of our virtual device in the form of
145 * {12345678-1234-1234-1234-123456789abc} - in hex
147 static char device_guid[256];
151 * Possible states of an IO facility.
157 * overlapped I/O is ready for work
162 * overlapped I/O has been queued
167 * overlapped I/O has finished, but is waiting for it's write-partner
172 * there is a full buffer waiting
177 * Operlapped IO states for facility objects
178 * overlapped I/O has failed, stop processing
186 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
191 * The mode the state machine associated with this object is in.
193 enum IO_State facility_state;
196 * If the path is open or blocked in general (used for quickly checking)
198 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
201 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
206 * Overlaped IO structure used for asynchronous IO in windows.
208 OVERLAPPED overlapped;
211 * Buffer for reading things to and writing from...
213 unsigned char buffer[MAX_SIZE];
216 * How much of this buffer was used when reading or how much data can be written
221 * Amount of data actually written or read by readfile/writefile.
223 DWORD buffer_size_processed;
226 * How much of this buffer we have writte in total
228 DWORD buffer_size_written;
232 * ReOpenFile is only available as of XP SP2 and 2003 SP1
234 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
237 * IsWow64Process definition for our is_win64, as this is a kernel function
239 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
242 * Determines if the host OS is win32 or win64
250 //this is a win64 binary,
252 #elif defined(_WIN32)
253 //this is a 32bit binary, and we need to check if we are running in WOW64
254 BOOL success = FALSE;
255 BOOL on_wow64 = FALSE;
256 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
258 if (NULL != IsWow64Process)
259 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
261 return success && on_wow64;
265 * Wrapper for executing a shellcommand in windows.
267 * @param command - the command + parameters to execute
268 * @return * exitcode of the program executed,
269 * * EINVAL (cmd/file not found)
270 * * EPIPE (could not read STDOUT)
273 execute_shellcommand (const char *command)
277 if ( (NULL == command) ||
278 (NULL == (pipe = _popen (command, "rt"))) )
282 fprintf (stderr, "DEBUG: Command output: \n");
283 char output[LINE_LEN];
284 while (NULL != fgets (output, sizeof (output), pipe))
285 fprintf (stderr, "%s", output);
288 return _pclose (pipe);
293 * @brief Sets the IPv6-Address given in address on the interface dev
295 * @param address the IPv6-Address
296 * @param prefix_len the length of the network-prefix
299 set_address6 (const char *address, unsigned long prefix_len)
302 char command[LINE_LEN];
303 struct sockaddr_in6 sa6;
306 * parse the new address
308 memset (&sa6, 0, sizeof (struct sockaddr_in6));
309 sa6.sin6_family = AF_INET6;
310 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
312 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
318 * prepare the command
320 snprintf (command, LINE_LEN,
321 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
322 device_visible_name, address, prefix_len);
326 ret = execute_shellcommand (command);
330 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
336 * @brief Removes the IPv6-Address given in address from the interface dev
338 * @param dev the interface to remove
339 * @param address the IPv4-Address
340 * @param mask the netmask
343 remove_address6 (const char *address)
345 char command[LINE_LEN];
348 // sanity checking was already done in set_address6
350 * prepare the command
352 snprintf (command, LINE_LEN,
353 "netsh interface ipv6 delete address \"%s\" store=persistent",
354 device_visible_name, address);
358 ret = execute_shellcommand (command);
362 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
367 * @brief Sets the IPv4-Address given in address on the interface dev
369 * @param dev the interface to configure
370 * @param address the IPv4-Address
371 * @param mask the netmask
374 set_address4 (const char *address, const char *mask)
377 char command[LINE_LEN];
379 struct sockaddr_in addr;
380 addr.sin_family = AF_INET;
385 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
387 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
391 // Set Device to Subnet-Mode?
392 // do we really need tun.c:2925 ?
395 * prepare the command
397 snprintf (command, LINE_LEN,
398 "netsh interface ipv4 add address \"%s\" %s %s store=active",
399 device_visible_name, address, mask);
403 ret = execute_shellcommand (command);
407 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
413 * @brief Removes the IPv4-Address given in address from the interface dev
415 * @param dev the interface to remove
416 * @param address the IPv4-Address
417 * @param mask the netmask
420 remove_address4 (const char *address)
422 char command[LINE_LEN];
425 // sanity checking was already done in set_address4
428 * prepare the command
430 snprintf (command, LINE_LEN,
431 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
432 device_visible_name, address);
436 ret = execute_shellcommand (command);
440 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
445 * Setup a new virtual interface to use for tunneling.
447 * @return: TRUE if setup was successful, else FALSE
453 * where to find our inf-file. (+ the "full" path, after windows found")
455 * We do not directly input all the props here, because openvpn will update
456 * these details over time.
458 char inf_file_path[MAX_PATH];
459 char * temp_inf_filename;
460 char hwidlist[LINE_LEN + 4];
461 char class_name[128];
466 * Set the device's hardware ID and add it to a list.
467 * This information will later on identify this device in registry.
469 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
471 * this is kind of over-complicated, but allows keeps things independent of
472 * how the openvpn-hwid is actually stored.
474 * A HWID list is double-\0 terminated and \0 separated
476 str_length = strlen (hwidlist) + 1;
477 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
478 str_length += strlen (&hwidlist[str_length]) + 1;
481 * Locate the inf-file, we need to store it somewhere where the system can
482 * find it. We need to pick the correct driver for win32/win64.
485 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
487 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
489 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
491 * Bootstrap our device info using the drivers inf-file
493 if ( ! SetupDiGetINFClassA (inf_file_path,
495 class_name, sizeof (class_name) / sizeof (char),
500 * Collect all the other needed information...
501 * let the system fill our this form
503 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
504 if (DeviceInfo == INVALID_HANDLE_VALUE)
507 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
508 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
517 /* Deploy all the information collected into the registry */
518 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
522 str_length * sizeof (char)))
525 /* Install our new class(=device) into the system */
526 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
531 /* This system call tends to take a while (several seconds!) on
532 "modern" Windoze systems */
533 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
536 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
537 NULL)) //reboot required? NEVER!
540 fprintf (stderr, "DEBUG: successfully created a network device\n");
546 * Remove our new virtual interface to use for tunneling.
547 * This function must be called AFTER setup_interface!
549 * @return: TRUE if destruction was successful, else FALSE
554 SP_REMOVEDEVICE_PARAMS remove;
556 if (INVALID_HANDLE_VALUE == DeviceInfo)
559 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
560 remove.HwProfile = 0;
561 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
562 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
564 * 1. Prepare our existing device information set, and place the
565 * uninstall related information into the structure
567 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
568 (PSP_DEVINFO_DATA) & DeviceNode,
569 &remove.ClassInstallHeader,
573 * 2. Uninstall the virtual interface using the class installer
575 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
577 (PSP_DEVINFO_DATA) & DeviceNode))
580 SetupDiDestroyDeviceInfoList (DeviceInfo);
582 fprintf (stderr, "DEBUG: removed interface successfully\n");
589 * Do all the lookup necessary to retrieve the inteface's actual name
592 * @return: TRUE if we were able to lookup the interface's name, else FALSE
595 resolve_interface_name ()
597 SP_DEVINFO_LIST_DETAIL_DATA device_details;
598 char pnp_instance_id [MAX_DEVICE_ID_LEN];
599 HKEY adapter_key_handle;
605 char adapter[] = INTERFACE_REGISTRY_LOCATION;
607 /* We can obtain the PNP instance ID from our setupapi handle */
608 device_details.cbSize = sizeof (device_details);
609 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
610 (PCHAR) pnp_instance_id,
613 NULL)) //hMachine, we are local
616 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
618 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
619 for (retrys = 0; retrys < 120 && !retval; retrys++)
624 /* Now we can use this ID to locate the correct networks interface in registry */
625 if (ERROR_SUCCESS != RegOpenKeyExA (
630 &adapter_key_handle))
633 /* Of course there is a multitude of entries here, with arbitrary names,
634 * thus we need to iterate through there.
638 char instance_key[256];
639 char query_key [256];
640 HKEY instance_key_handle;
641 char pnpinstanceid_name[] = "PnpInstanceID";
642 char pnpinstanceid_value[256];
643 char adaptername_name[] = "Name";
646 len = 256 * sizeof (char);
647 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
648 status = RegEnumKeyExA (
658 /* this may fail due to one of two reasons:
659 * we are at the end of the list*/
660 if (ERROR_NO_MORE_ITEMS == status)
662 // * we found a broken registry key, continue with the next key.
663 if (ERROR_SUCCESS != status)
666 /* prepare our new query string: */
667 snprintf (query_key, 256, "%s\\%s\\Connection",
671 /* look inside instance_key\\Connection */
672 if (ERROR_SUCCESS != RegOpenKeyExA (
677 &instance_key_handle))
680 /* now, read our PnpInstanceID */
681 len = sizeof (pnpinstanceid_value);
682 status = RegQueryValueExA (instance_key_handle,
684 NULL, //reserved, always NULL according to MSDN
686 (LPBYTE) pnpinstanceid_value,
689 if (status != ERROR_SUCCESS || data_type != REG_SZ)
692 /* compare the value we got to our devices PNPInstanceID*/
693 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
694 sizeof (pnpinstanceid_value) / sizeof (char)))
697 len = sizeof (device_visible_name);
698 status = RegQueryValueExA (
701 NULL, //reserved, always NULL according to MSDN
703 (LPBYTE) device_visible_name,
706 if (status != ERROR_SUCCESS || data_type != REG_SZ)
710 * we have successfully found OUR instance,
711 * save the device GUID before exiting
714 strncpy (device_guid, instance_key, 256);
716 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
719 RegCloseKey (instance_key_handle);
724 RegCloseKey (adapter_key_handle);
731 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
733 * @param handle the handle to our tap device
734 * @return TRUE if the version is sufficient, else FALSE
737 check_tapw32_version (HANDLE handle)
741 memset (&(version), 0, sizeof (version));
743 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
744 &version, sizeof (version),
745 &version, sizeof (version), &len, NULL))
746 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
749 (version[2] ? "(DEBUG)" : ""));
751 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
752 (version[1] < TAP_WIN_MIN_MINOR )){
753 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
764 * Creates a tun-interface called dev;
766 * @return the fd to the tun or -1 on error
771 char device_path[256];
774 if (! setup_interface ())
777 return INVALID_HANDLE_VALUE;
780 if (! resolve_interface_name ())
783 return INVALID_HANDLE_VALUE;
786 /* Open Windows TAP-Windows adapter */
787 snprintf (device_path, sizeof (device_path), "%s%s%s",
792 handle = CreateFile (
794 GENERIC_READ | GENERIC_WRITE,
795 0, /* was: FILE_SHARE_READ */
798 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
802 if (INVALID_HANDLE_VALUE == handle)
804 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
808 /* get driver version info */
809 if (! check_tapw32_version (handle))
811 CloseHandle (handle);
812 return INVALID_HANDLE_VALUE;
815 /* TODO (opt?): get MTU-Size */
817 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
823 * Brings a TAP device up and sets it to connected state.
825 * @param handle the handle to our TAP device
826 * @return True if the operation succeeded, else false
829 tun_up (HANDLE handle)
833 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
834 &status, sizeof (status),
835 &status, sizeof (status), &len, NULL))
837 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
841 /* Wait for the device to go UP, might take some time. */
842 Sleep (TAP32_POSTUP_WAITTIME * 1000);
843 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
850 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
853 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
854 * input handle. Then it goes into IOSTATE_QUEUED state.
855 * In case the read succeeded instantly the input facility enters 3.
858 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
859 * If it has finished, go to state 3.
860 * If it has failed, set IOSTATE_FAILED
863 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
864 * The input facility enters state IOSTATE_READY
865 * The output facility enters state IOSTATE_READY
866 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
868 * IOSTATE_WAITING is reset by the output facility, once it has completed.
870 * @param input_facility input named pipe or file to work with.
871 * @param output_facility output pipe or file to hand over data to.
872 * @return false if an event reset was impossible (OS error), else true
875 attempt_read_tap (struct io_facility * input_facility,
876 struct io_facility * output_facility)
878 struct GNUNET_MessageHeader * hdr;
881 switch (input_facility->facility_state)
885 if (! ResetEvent (input_facility->overlapped.hEvent))
890 input_facility->buffer_size = 0;
892 /* Check how the task is handled */
893 if (ReadFile (input_facility->handle,
894 input_facility->buffer,
895 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
896 &input_facility->buffer_size,
897 &input_facility->overlapped))
898 {/* async event processed immediately*/
900 /* reset event manually*/
901 if (! SetEvent (input_facility->overlapped.hEvent))
904 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
906 /* we successfully read something from the TAP and now need to
907 * send it our via STDOUT. Is that possible at the moment? */
908 if ((IOSTATE_READY == output_facility->facility_state ||
909 IOSTATE_WAITING == output_facility->facility_state)
910 && (0 < input_facility->buffer_size))
911 { /* hand over this buffers content and apply message header for gnunet */
912 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
913 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
915 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
916 input_facility->buffer,
917 input_facility->buffer_size);
919 output_facility->buffer_size = size;
920 hdr->size = htons (size);
921 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
922 output_facility->facility_state = IOSTATE_READY;
924 else if (0 < input_facility->buffer_size)
925 /* If we have have read our buffer, wait for our write-partner*/
926 input_facility->facility_state = IOSTATE_WAITING;
928 else /* operation was either queued or failed*/
930 int err = GetLastError ();
931 if (ERROR_IO_PENDING == err)
932 { /* operation queued */
933 input_facility->facility_state = IOSTATE_QUEUED;
936 { /* error occurred, let the rest of the elements finish */
937 input_facility->path_open = FALSE;
938 input_facility->facility_state = IOSTATE_FAILED;
939 if (IOSTATE_WAITING == output_facility->facility_state)
940 output_facility->path_open = FALSE;
942 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
947 // We are queued and should check if the read has finished
950 // there was an operation going on already, check if that has completed now.
952 if (GetOverlappedResult (input_facility->handle,
953 &input_facility->overlapped,
954 &input_facility->buffer_size,
956 {/* successful return for a queued operation */
957 if (! ResetEvent (input_facility->overlapped.hEvent))
960 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
962 /* we successfully read something from the TAP and now need to
963 * send it our via STDOUT. Is that possible at the moment? */
964 if ((IOSTATE_READY == output_facility->facility_state ||
965 IOSTATE_WAITING == output_facility->facility_state)
966 && 0 < input_facility->buffer_size)
967 { /* hand over this buffers content and apply message header for gnunet */
968 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
969 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
971 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
972 input_facility->buffer,
973 input_facility->buffer_size);
975 output_facility->buffer_size = size;
976 hdr->size = htons(size);
977 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
978 output_facility->facility_state = IOSTATE_READY;
979 input_facility->facility_state = IOSTATE_READY;
981 else if (0 < input_facility->buffer_size)
982 { /* If we have have read our buffer, wait for our write-partner*/
983 input_facility->facility_state = IOSTATE_WAITING;
984 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
988 { /* operation still pending/queued or failed? */
989 int err = GetLastError ();
990 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
991 { /* error occurred, let the rest of the elements finish */
992 input_facility->path_open = FALSE;
993 input_facility->facility_state = IOSTATE_FAILED;
994 if (IOSTATE_WAITING == output_facility->facility_state)
995 output_facility->path_open = FALSE;
996 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1001 case IOSTATE_RESUME:
1002 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1003 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1005 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1006 input_facility->buffer,
1007 input_facility->buffer_size);
1009 output_facility->buffer_size = size;
1010 hdr->size = htons (size);
1011 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1012 output_facility->facility_state = IOSTATE_READY;
1013 input_facility->facility_state = IOSTATE_READY;
1022 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1025 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1026 * input handle. Then it goes into IOSTATE_QUEUED state.
1027 * In case the read succeeded instantly the input facility enters 3.
1030 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1031 * If it has finished, go to state 3.
1032 * If it has failed, set IOSTATE_FAILED
1035 * If the facility is finished with ready
1036 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1037 * The input facility enters state IOSTATE_READY
1038 * The output facility enters state IOSTATE_READY
1039 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1041 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1043 * @param input_facility input named pipe or file to work with.
1044 * @param output_facility output pipe or file to hand over data to.
1045 * @return false if an event reset was impossible (OS error), else true
1048 attempt_read_stdin (struct io_facility * input_facility,
1049 struct io_facility * output_facility)
1051 struct GNUNET_MessageHeader * hdr;
1053 switch (input_facility->facility_state)
1057 input_facility->buffer_size = 0;
1059 partial_read_iostate_ready:
1060 if (! ResetEvent (input_facility->overlapped.hEvent))
1063 /* Check how the task is handled */
1064 if (ReadFile (input_facility->handle,
1065 input_facility->buffer + input_facility->buffer_size,
1066 sizeof (input_facility->buffer) - input_facility->buffer_size,
1067 &input_facility->buffer_size_processed,
1068 &input_facility->overlapped))
1069 {/* async event processed immediately*/
1070 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1072 /* reset event manually*/
1073 if (!SetEvent (input_facility->overlapped.hEvent))
1076 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1077 input_facility->buffer_size += input_facility->buffer_size_processed;
1079 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1080 ntohs (hdr->size) > sizeof (input_facility->buffer))
1082 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1083 input_facility->facility_state = IOSTATE_READY;
1086 /* we got the a part of a packet */
1087 if (ntohs (hdr->size) > input_facility->buffer_size)
1088 goto partial_read_iostate_ready;
1090 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1091 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1092 ((IOSTATE_READY == output_facility->facility_state) ||
1093 (IOSTATE_WAITING == output_facility->facility_state)))
1094 {/* we successfully read something from the TAP and now need to
1095 * send it our via STDOUT. Is that possible at the moment? */
1097 /* hand over this buffers content and strip gnunet message header */
1098 memcpy (output_facility->buffer,
1099 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1100 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1101 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1102 output_facility->facility_state = IOSTATE_READY;
1103 input_facility->facility_state = IOSTATE_READY;
1105 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1106 /* If we have have read our buffer, wait for our write-partner*/
1107 input_facility->facility_state = IOSTATE_WAITING;
1108 else /* we read nothing */
1109 input_facility->facility_state = IOSTATE_READY;
1111 else /* operation was either queued or failed*/
1113 int err = GetLastError ();
1114 if (ERROR_IO_PENDING == err) /* operation queued */
1115 input_facility->facility_state = IOSTATE_QUEUED;
1117 { /* error occurred, let the rest of the elements finish */
1118 input_facility->path_open = FALSE;
1119 input_facility->facility_state = IOSTATE_FAILED;
1120 if (IOSTATE_WAITING == output_facility->facility_state)
1121 output_facility->path_open = FALSE;
1123 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1128 // We are queued and should check if the read has finished
1129 case IOSTATE_QUEUED:
1131 // there was an operation going on already, check if that has completed now.
1132 if (GetOverlappedResult (input_facility->handle,
1133 &input_facility->overlapped,
1134 &input_facility->buffer_size_processed,
1136 {/* successful return for a queued operation */
1137 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1139 if (! ResetEvent (input_facility->overlapped.hEvent))
1142 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1143 input_facility->buffer_size += input_facility->buffer_size_processed;
1145 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1146 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1148 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1149 input_facility->facility_state = IOSTATE_READY;
1152 /* we got the a part of a packet */
1153 if (ntohs (hdr->size) > input_facility->buffer_size );
1154 goto partial_read_iostate_ready;
1156 /* we successfully read something from the TAP and now need to
1157 * send it our via STDOUT. Is that possible at the moment? */
1158 if ((IOSTATE_READY == output_facility->facility_state ||
1159 IOSTATE_WAITING == output_facility->facility_state)
1160 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1161 { /* hand over this buffers content and strip gnunet message header */
1162 memcpy (output_facility->buffer,
1163 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1164 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1165 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1166 output_facility->facility_state = IOSTATE_READY;
1167 input_facility->facility_state = IOSTATE_READY;
1169 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1170 input_facility->facility_state = IOSTATE_WAITING;
1172 input_facility->facility_state = IOSTATE_READY;
1175 { /* operation still pending/queued or failed? */
1176 int err = GetLastError ();
1177 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1178 { /* error occurred, let the rest of the elements finish */
1179 input_facility->path_open = FALSE;
1180 input_facility->facility_state = IOSTATE_FAILED;
1181 if (IOSTATE_WAITING == output_facility->facility_state)
1182 output_facility->path_open = FALSE;
1183 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1188 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1189 memcpy (output_facility->buffer,
1190 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1191 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1192 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1193 output_facility->facility_state = IOSTATE_READY;
1194 input_facility->facility_state = IOSTATE_READY;
1203 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1205 * TODO: high level description
1207 * @param output_facility output pipe or file to hand over data to.
1208 * @param input_facility input named pipe or file to work with.
1209 * @return false if an event reset was impossible (OS error), else true
1212 attempt_write (struct io_facility * output_facility,
1213 struct io_facility * input_facility)
1215 switch (output_facility->facility_state)
1218 output_facility->buffer_size_written = 0;
1220 continue_partial_write:
1221 if (! ResetEvent (output_facility->overlapped.hEvent))
1224 /* Check how the task was handled */
1225 if (WriteFile (output_facility->handle,
1226 output_facility->buffer + output_facility->buffer_size_written,
1227 output_facility->buffer_size - output_facility->buffer_size_written,
1228 &output_facility->buffer_size_processed,
1229 &output_facility->overlapped))
1230 {/* async event processed immediately*/
1232 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1233 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1235 /* reset event manually*/
1236 if (! SetEvent (output_facility->overlapped.hEvent))
1240 if (output_facility->buffer_size_written < output_facility->buffer_size)
1241 goto continue_partial_write;
1243 /* we are now waiting for our buffer to be filled*/
1244 output_facility->facility_state = IOSTATE_WAITING;
1246 /* we successfully wrote something and now need to reset our reader */
1247 if (IOSTATE_WAITING == input_facility->facility_state)
1248 input_facility->facility_state = IOSTATE_RESUME;
1249 else if (IOSTATE_FAILED == input_facility->facility_state)
1250 output_facility->path_open = FALSE;
1252 else /* operation was either queued or failed*/
1254 int err = GetLastError ();
1255 if (ERROR_IO_PENDING == err)
1256 { /* operation queued */
1257 output_facility->facility_state = IOSTATE_QUEUED;
1260 { /* error occurred, close this path */
1261 output_facility->path_open = FALSE;
1262 output_facility->facility_state = IOSTATE_FAILED;
1263 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1267 case IOSTATE_QUEUED:
1268 // there was an operation going on already, check if that has completed now.
1270 if (GetOverlappedResult (output_facility->handle,
1271 &output_facility->overlapped,
1272 &output_facility->buffer_size_processed,
1274 {/* successful return for a queued operation */
1275 if (! ResetEvent (output_facility->overlapped.hEvent))
1278 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1279 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1282 if (output_facility->buffer_size_written < output_facility->buffer_size)
1283 goto continue_partial_write;
1285 /* we are now waiting for our buffer to be filled*/
1286 output_facility->facility_state = IOSTATE_WAITING;
1288 /* we successfully wrote something and now need to reset our reader */
1289 if (IOSTATE_WAITING == input_facility->facility_state)
1290 input_facility->facility_state = IOSTATE_RESUME;
1291 else if (IOSTATE_FAILED == input_facility->facility_state)
1292 output_facility->path_open = FALSE;
1295 { /* operation still pending/queued or failed? */
1296 int err = GetLastError ();
1297 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1298 { /* error occurred, close this path */
1299 output_facility->path_open = FALSE;
1300 output_facility->facility_state = IOSTATE_FAILED;
1301 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1311 * Initialize a overlapped structure
1313 * @param elem the element to initilize
1314 * @param initial_state the initial state for this instance
1315 * @param signaled if the hEvent created should default to signaled or not
1316 * @return true on success, else false
1319 initialize_io_facility (struct io_facility * elem,
1323 elem->path_open = TRUE;
1324 elem->handle = INVALID_HANDLE_VALUE;
1325 elem->facility_state = initial_state;
1326 elem->buffer_size = 0;
1327 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1328 if (NULL == elem->overlapped.hEvent)
1336 * Start forwarding to and from the tunnel.
1338 * @param fd_tun tunnel FD
1341 run (HANDLE tap_handle)
1343 /* IO-Facility for reading from our virtual interface */
1344 struct io_facility tap_read;
1345 /* IO-Facility for writing to our virtual interface */
1346 struct io_facility tap_write;
1347 /* IO-Facility for reading from stdin */
1348 struct io_facility std_in;
1349 /* IO-Facility for writing to stdout */
1350 struct io_facility std_out;
1352 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1353 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1356 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1357 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1359 * DHCP and such are all features we will never use in gnunet afaik.
1360 * But for openvpn those are essential.
1362 if (! tun_up (tap_handle))
1365 /* Initialize our overlapped IO structures*/
1366 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1367 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1368 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1369 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1370 goto teardown_final;
1372 /* Handles for STDIN and STDOUT */
1373 tap_read.handle = tap_handle;
1374 tap_write.handle = tap_handle;
1376 #ifdef DEBUG_TO_CONSOLE
1377 /* Debug output to console STDIN/STDOUT*/
1378 std_in.handle = parent_std_in_handle;
1379 std_out.handle = parent_std_out_handle;
1382 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1384 * Find out the types of our handles.
1385 * This part is a problem, because in windows we need to handle files,
1386 * pipes and the console differently.
1388 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1389 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1391 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1395 std_in.handle = ReOpenFile (parent_std_in_handle,
1397 FILE_SHARE_WRITE | FILE_SHARE_READ,
1398 FILE_FLAG_OVERLAPPED);
1400 if (INVALID_HANDLE_VALUE == std_in.handle)
1402 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1406 std_out.handle = ReOpenFile (parent_std_out_handle,
1409 FILE_FLAG_OVERLAPPED);
1411 if (INVALID_HANDLE_VALUE == std_out.handle)
1413 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1418 fprintf (stderr, "DEBUG: mainloop has begun\n");
1420 while (std_out.path_open || tap_write.path_open)
1422 /* perform READ from stdin if possible */
1423 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1426 /* perform READ from tap if possible */
1427 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1430 /* perform WRITE to tap if possible */
1431 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1434 /* perform WRITE to STDOUT if possible */
1435 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1441 fprintf (stderr, "DEBUG: teardown initiated\n");
1443 CancelIo (tap_handle);
1444 CancelIo (std_in.handle);
1445 CancelIo (std_out.handle);
1449 CloseHandle (tap_handle);
1454 * Open VPN tunnel interface.
1456 * @param argc must be 6
1457 * @param argv 0: binary name (gnunet-helper-vpn)
1458 * 1: tunnel interface prefix (gnunet-vpn)
1459 * 2: IPv6 address (::1), "-" to disable
1460 * 3: IPv6 netmask length in bits (64), ignored if #2 is "-"
1461 * 4: IPv4 address (1.2.3.4), "-" to disable
1462 * 5: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
1465 main (int argc, char **argv)
1467 char hwid[LINE_LEN];
1470 BOOL have_ip4 = FALSE;
1471 BOOL have_ip6 = FALSE;
1475 fprintf (stderr, "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1479 strncpy (hwid, argv[1], LINE_LEN);
1480 hwid[LINE_LEN - 1] = '\0';
1483 * We use our PID for finding/resolving the control-panel name of our virtual
1484 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1485 * as additional hardware-id for our device.
1487 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1491 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1493 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1503 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1504 if (0 != strcmp (argv[2], "-"))
1506 const char *address = argv[2];
1507 long prefix_len = atol (argv[3]);
1509 if ((prefix_len < 1) || (prefix_len > 127))
1511 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1516 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n",address,prefix_len);
1517 if (0 != (global_ret = set_address6 (address, prefix_len)))
1523 if (0 != strcmp (argv[4], "-"))
1525 const char *address = argv[4];
1526 const char *mask = argv[5];
1528 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n",address,mask);
1529 if (0 != (global_ret = set_address4 (address, mask)))
1541 const char *address = argv[4];
1542 fprintf (stderr, "DEBUG: Removing IP4 address\n");
1543 remove_address4 (address);
1547 const char *address = argv[2];
1548 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1549 remove_address6 (address);
1552 fprintf (stderr, "DEBUG: removing interface\n");
1553 remove_interface ();
1554 fprintf (stderr, "DEBUG: graceful exit completed\n");