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.
24 #include <ddk/cfgmgr32.h>
25 #include <ddk/newdev.h>
29 #include "tap-windows.h"
31 * Need 'struct GNUNET_MessageHeader'.
33 #include "gnunet_common.h"
36 * Need VPN message types.
38 #include "gnunet_protocols.h"
41 * Should we print (interesting|debug) messages that can happen during
44 #define DEBUG GNUNET_NO
47 /* FIXME: define with varargs... */
48 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
50 #define LOG_DEBUG(msg) do {} while (0)
55 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
57 #define MAX_SIZE 65536
60 * Name or Path+Name of our win32 driver.
61 * The .sys and .cat files HAVE to be in the same location as this file!
63 #define INF_FILE "share/gnunet/tapw32/OemWin2k.inf"
66 * Name or Path+Name of our win64 driver.
67 * The .sys and .cat files HAVE to be in the same location as this file!
69 #define INF_FILE64 "share/gnunet/tapw64/OemWin2k.inf"
72 * Hardware ID used in the inf-file.
73 * This might change over time, as openvpn advances their driver
75 #define HARDWARE_ID "tap0901"
78 * Minimum major-id of the driver version we can work with
80 #define TAP_WIN_MIN_MAJOR 9
83 * Minimum minor-id of the driver version we can work with.
84 * v <= 7 has buggy IPv6.
85 * v == 8 is broken for small IPv4 Packets
87 #define TAP_WIN_MIN_MINOR 9
90 * Time in seconds to wait for our virtual device to go up after telling it to do so.
92 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
93 * (in fact, 4 was chosen by a fair dice roll...)
95 #define TAP32_POSTUP_WAITTIME 4
98 * Location of the network interface list resides in registry.
100 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
103 * Our local process' PID. Used for creating a sufficiently unique additional
104 * hardware ID for our device.
106 static char secondary_hwid[LINE_LEN / 2];
109 * Device's visible Name, used to identify a network device in netsh.
110 * eg: "Local Area Connection 9"
112 static char device_visible_name[256];
115 * This is our own local instance of a virtual network interface
116 * It is (somewhat) equivalent to using tun/tap in unixoid systems
118 * Upon initialization, we create such an device node.
119 * Upon termination, we remove it again.
121 * If we crash this device might stay around.
123 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
126 * Registry Key we hand over to windows to spawn a new virtual interface
128 static SP_DEVINFO_DATA DeviceNode;
131 * GUID of our virtual device in the form of
132 * {12345678-1234-1234-1234-123456789abc} - in hex
134 static char device_guid[256];
138 * Possible states of an IO facility.
144 * overlapped I/O is ready for work
149 * overlapped I/O has been queued
154 * overlapped I/O has finished, but is waiting for it's write-partner
159 * there is a full buffer waiting
164 * Operlapped IO states for facility objects
165 * overlapped I/O has failed, stop processing
173 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
178 * The mode the state machine associated with this object is in.
180 enum IO_State facility_state;
183 * If the path is open or blocked in general (used for quickly checking)
185 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
188 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
193 * Overlaped IO structure used for asynchronous IO in windows.
195 OVERLAPPED overlapped;
198 * Buffer for reading things to and writing from...
200 unsigned char buffer[MAX_SIZE];
203 * How much of this buffer was used when reading or how much data can be written
208 * Amount of data written, is compared to buffer_size.
210 DWORD buffer_size_written;
214 * ReOpenFile is only available as of XP SP2 and 2003 SP1
216 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
219 * IsWow64Process definition for our is_win64, as this is a kernel function
221 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
224 * Determines if the host OS is win32 or win64
232 //this is a win64 binary,
234 #elif defined(_WIN32)
235 //this is a 32bit binary, and we need to check if we are running in WOW64
236 BOOL success = FALSE;
237 BOOL on_wow64 = FALSE;
238 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
240 if (NULL != IsWow64Process)
241 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
243 return success && on_wow64;
247 * Wrapper for executing a shellcommand in windows.
249 * @param command - the command + parameters to execute
250 * @return * exitcode of the program executed,
251 * * EINVAL (cmd/file not found)
252 * * EPIPE (could not read STDOUT)
255 execute_shellcommand (const char *command)
259 if ( (NULL == command) ||
260 (NULL == (pipe = _popen (command, "rt"))) )
264 fprintf (stderr, "DEBUG: Command output: \n");
265 char output[LINE_LEN];
266 while (NULL != fgets (output, sizeof (output), pipe))
267 fprintf (stderr, "%s", output);
270 return _pclose (pipe);
275 * @brief Sets the IPv6-Address given in address on the interface dev
277 * @param address the IPv6-Address
278 * @param prefix_len the length of the network-prefix
281 set_address6 (const char *address, unsigned long prefix_len)
284 char command[LINE_LEN];
285 struct sockaddr_in6 sa6;
288 * parse the new address
290 memset (&sa6, 0, sizeof (struct sockaddr_in6));
291 sa6.sin6_family = AF_INET6;
292 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
294 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
300 * prepare the command
302 snprintf (command, LINE_LEN,
303 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
304 device_visible_name, address, prefix_len);
308 ret = execute_shellcommand (command);
312 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
318 * @brief Removes the IPv6-Address given in address from the interface dev
320 * @param dev the interface to remove
321 * @param address the IPv4-Address
322 * @param mask the netmask
325 remove_address6 (const char *address)
327 char command[LINE_LEN];
330 // sanity checking was already done in set_address6
332 * prepare the command
334 snprintf (command, LINE_LEN,
335 "netsh interface ipv6 delete address \"%s\" store=persistent",
336 device_visible_name, address);
340 ret = execute_shellcommand (command);
344 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
349 * @brief Sets the IPv4-Address given in address on the interface dev
351 * @param dev the interface to configure
352 * @param address the IPv4-Address
353 * @param mask the netmask
356 set_address4 (const char *address, const char *mask)
359 char command[LINE_LEN];
361 struct sockaddr_in addr;
362 addr.sin_family = AF_INET;
367 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
369 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
373 // Set Device to Subnet-Mode?
374 // do we really need tun.c:2925 ?
377 * prepare the command
379 snprintf (command, LINE_LEN,
380 "netsh interface ipv4 add address \"%s\" %s %s store=active",
381 device_visible_name, address, mask);
385 ret = execute_shellcommand (command);
389 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
395 * @brief Removes the IPv4-Address given in address from the interface dev
397 * @param dev the interface to remove
398 * @param address the IPv4-Address
399 * @param mask the netmask
402 remove_address4 (const char *address)
404 char command[LINE_LEN];
407 // sanity checking was already done in set_address4
410 * prepare the command
412 snprintf (command, LINE_LEN,
413 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
414 device_visible_name, address);
418 ret = execute_shellcommand (command);
422 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
427 * Setup a new virtual interface to use for tunneling.
429 * @return: TRUE if setup was successful, else FALSE
435 * where to find our inf-file. (+ the "full" path, after windows found")
437 * We do not directly input all the props here, because openvpn will update
438 * these details over time.
440 char inf_file_path[MAX_PATH];
441 char * temp_inf_filename;
442 char hwidlist[LINE_LEN + 4];
443 char class_name[128];
448 * Set the device's hardware ID and add it to a list.
449 * This information will later on identify this device in registry.
451 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
453 * this is kind of over-complicated, but allows keeps things independent of
454 * how the openvpn-hwid is actually stored.
456 * A HWID list is double-\0 terminated and \0 separated
458 str_length = strlen (hwidlist) + 1;
459 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
460 str_length += strlen (&hwidlist[str_length]) + 1;
463 * Locate the inf-file, we need to store it somewhere where the system can
464 * find it. We need to pick the correct driver for win32/win64.
467 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
469 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
471 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
473 * Bootstrap our device info using the drivers inf-file
475 if ( ! SetupDiGetINFClassA (inf_file_path,
477 class_name, sizeof (class_name) / sizeof (char),
482 * Collect all the other needed information...
483 * let the system fill our this form
485 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
486 if (DeviceInfo == INVALID_HANDLE_VALUE)
489 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
490 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
499 /* Deploy all the information collected into the registry */
500 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
504 str_length * sizeof (char)))
507 /* Install our new class(=device) into the system */
508 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
513 /* This system call tends to take a while (several seconds!) on
514 "modern" Windoze systems */
515 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
518 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
519 NULL)) //reboot required? NEVER!
522 fprintf (stderr, "DEBUG: successfully created a network device\n");
528 * Remove our new virtual interface to use for tunneling.
529 * This function must be called AFTER setup_interface!
531 * @return: TRUE if destruction was successful, else FALSE
536 SP_REMOVEDEVICE_PARAMS remove;
538 if (INVALID_HANDLE_VALUE == DeviceInfo)
541 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
542 remove.HwProfile = 0;
543 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
544 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
546 * 1. Prepare our existing device information set, and place the
547 * uninstall related information into the structure
549 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
550 (PSP_DEVINFO_DATA) & DeviceNode,
551 &remove.ClassInstallHeader,
555 * 2. Uninstall the virtual interface using the class installer
557 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
559 (PSP_DEVINFO_DATA) & DeviceNode))
562 SetupDiDestroyDeviceInfoList (DeviceInfo);
564 fprintf (stderr, "DEBUG: removed interface successfully\n");
571 * Do all the lookup necessary to retrieve the inteface's actual name
574 * @return: TRUE if we were able to lookup the interface's name, else FALSE
577 resolve_interface_name ()
579 SP_DEVINFO_LIST_DETAIL_DATA device_details;
580 char pnp_instance_id [MAX_DEVICE_ID_LEN];
581 HKEY adapter_key_handle;
587 char adapter[] = INTERFACE_REGISTRY_LOCATION;
589 /* We can obtain the PNP instance ID from our setupapi handle */
590 device_details.cbSize = sizeof (device_details);
591 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
592 (PCHAR) pnp_instance_id,
595 NULL)) //hMachine, we are local
598 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
600 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
601 for (retrys = 0; retrys < 120 && !retval; retrys++)
606 /* Now we can use this ID to locate the correct networks interface in registry */
607 if (ERROR_SUCCESS != RegOpenKeyExA (
612 &adapter_key_handle))
615 /* Of course there is a multitude of entries here, with arbitrary names,
616 * thus we need to iterate through there.
620 char instance_key[256];
621 char query_key [256];
622 HKEY instance_key_handle;
623 char pnpinstanceid_name[] = "PnpInstanceID";
624 char pnpinstanceid_value[256];
625 char adaptername_name[] = "Name";
628 len = 256 * sizeof (char);
629 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
630 status = RegEnumKeyExA (
640 /* this may fail due to one of two reasons:
641 * we are at the end of the list*/
642 if (ERROR_NO_MORE_ITEMS == status)
644 // * we found a broken registry key, continue with the next key.
645 if (ERROR_SUCCESS != status)
648 /* prepare our new query string: */
649 snprintf (query_key, 256, "%s\\%s\\Connection",
653 /* look inside instance_key\\Connection */
654 if (ERROR_SUCCESS != RegOpenKeyExA (
659 &instance_key_handle))
662 /* now, read our PnpInstanceID */
663 len = sizeof (pnpinstanceid_value);
664 status = RegQueryValueExA (instance_key_handle,
666 NULL, //reserved, always NULL according to MSDN
668 (LPBYTE) pnpinstanceid_value,
671 if (status != ERROR_SUCCESS || data_type != REG_SZ)
674 /* compare the value we got to our devices PNPInstanceID*/
675 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
676 sizeof (pnpinstanceid_value) / sizeof (char)))
679 len = sizeof (device_visible_name);
680 status = RegQueryValueExA (
683 NULL, //reserved, always NULL according to MSDN
685 (LPBYTE) device_visible_name,
688 if (status != ERROR_SUCCESS || data_type != REG_SZ)
692 * we have successfully found OUR instance,
693 * save the device GUID before exiting
696 strncpy (device_guid, instance_key, 256);
698 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
701 RegCloseKey (instance_key_handle);
706 RegCloseKey (adapter_key_handle);
713 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
715 * @param handle the handle to our tap device
716 * @return TRUE if the version is sufficient, else FALSE
719 check_tapw32_version (HANDLE handle)
723 memset (&(version), 0, sizeof (version));
725 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
726 &version, sizeof (version),
727 &version, sizeof (version), &len, NULL))
728 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
731 (version[2] ? "(DEBUG)" : ""));
733 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
734 (version[1] < TAP_WIN_MIN_MINOR )){
735 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
746 * Creates a tun-interface called dev;
748 * @return the fd to the tun or -1 on error
753 char device_path[256];
756 if (! setup_interface ())
759 return INVALID_HANDLE_VALUE;
762 if (! resolve_interface_name ())
765 return INVALID_HANDLE_VALUE;
768 /* Open Windows TAP-Windows adapter */
769 snprintf (device_path, sizeof (device_path), "%s%s%s",
774 handle = CreateFile (
776 GENERIC_READ | GENERIC_WRITE,
777 0, /* was: FILE_SHARE_READ */
780 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
784 if (INVALID_HANDLE_VALUE == handle)
786 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
790 /* get driver version info */
791 if (! check_tapw32_version (handle))
793 CloseHandle (handle);
794 return INVALID_HANDLE_VALUE;
797 /* TODO (opt?): get MTU-Size */
799 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
805 * Brings a TAP device up and sets it to connected state.
807 * @param handle the handle to our TAP device
808 * @return True if the operation succeeded, else false
811 tun_up (HANDLE handle)
815 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
816 &status, sizeof (status),
817 &status, sizeof (status), &len, NULL))
819 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
823 /* Wait for the device to go UP, might take some time. */
824 Sleep (TAP32_POSTUP_WAITTIME * 1000);
825 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
832 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
835 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
836 * input handle. Then it goes into IOSTATE_QUEUED state.
837 * In case the read succeeded instantly the input facility enters 3.
840 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
841 * If it has finished, go to state 3.
842 * If it has failed, set IOSTATE_FAILED
845 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
846 * The input facility enters state IOSTATE_READY
847 * The output facility enters state IOSTATE_READY
848 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
850 * IOSTATE_WAITING is reset by the output facility, once it has completed.
852 * @param input_facility input named pipe or file to work with.
853 * @param output_facility output pipe or file to hand over data to.
854 * @return false if an event reset was impossible (OS error), else true
857 attempt_read_tap (struct io_facility * input_facility,
858 struct io_facility * output_facility)
860 struct GNUNET_MessageHeader * hdr;
863 switch (input_facility->facility_state)
867 if (! ResetEvent (input_facility->overlapped.hEvent))
872 input_facility->buffer_size = 0;
874 /* Check how the task is handled */
875 if (ReadFile (input_facility->handle,
876 input_facility->buffer,
877 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
878 &input_facility->buffer_size,
879 &input_facility->overlapped))
880 {/* async event processed immediately*/
882 /* reset event manually*/
883 if (! SetEvent (input_facility->overlapped.hEvent))
886 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
888 /* we successfully read something from the TAP and now need to
889 * send it our via STDOUT. Is that possible at the moment? */
890 if ((IOSTATE_READY == output_facility->facility_state ||
891 IOSTATE_WAITING == output_facility->facility_state)
892 && (0 < input_facility->buffer_size))
893 { /* hand over this buffers content and apply message header for gnunet */
894 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
895 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
897 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
898 input_facility->buffer,
899 input_facility->buffer_size);
901 output_facility->buffer_size = size;
902 hdr->size = htons (size);
903 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
904 output_facility->facility_state = IOSTATE_READY;
906 else if (0 < input_facility->buffer_size)
907 { /* If we have have read our buffer, wait for our write-partner*/
908 input_facility->facility_state = IOSTATE_WAITING;
909 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
912 else /* operation was either queued or failed*/
914 int err = GetLastError ();
915 if (ERROR_IO_PENDING == err)
916 { /* operation queued */
917 input_facility->facility_state = IOSTATE_QUEUED;
920 { /* error occurred, let the rest of the elements finish */
921 input_facility->path_open = FALSE;
922 input_facility->facility_state = IOSTATE_FAILED;
923 if (IOSTATE_WAITING == output_facility->facility_state)
924 output_facility->path_open = FALSE;
926 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
931 // We are queued and should check if the read has finished
934 // there was an operation going on already, check if that has completed now.
936 if (GetOverlappedResult (input_facility->handle,
937 &input_facility->overlapped,
938 &input_facility->buffer_size,
940 {/* successful return for a queued operation */
941 if (! ResetEvent (input_facility->overlapped.hEvent))
944 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
946 /* we successfully read something from the TAP and now need to
947 * send it our via STDOUT. Is that possible at the moment? */
948 if ((IOSTATE_READY == output_facility->facility_state ||
949 IOSTATE_WAITING == output_facility->facility_state)
950 && 0 < input_facility->buffer_size)
951 { /* hand over this buffers content and apply message header for gnunet */
952 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
953 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
955 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
956 input_facility->buffer,
957 input_facility->buffer_size);
959 output_facility->buffer_size = size;
960 hdr->size = htons(size);
961 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
962 output_facility->facility_state = IOSTATE_READY;
963 input_facility->facility_state = IOSTATE_READY;
965 else if (0 < input_facility->buffer_size)
966 { /* If we have have read our buffer, wait for our write-partner*/
967 input_facility->facility_state = IOSTATE_WAITING;
968 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
972 { /* operation still pending/queued or failed? */
973 int err = GetLastError ();
974 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
975 { /* error occurred, let the rest of the elements finish */
976 input_facility->path_open = FALSE;
977 input_facility->facility_state = IOSTATE_FAILED;
978 if (IOSTATE_WAITING == output_facility->facility_state)
979 output_facility->path_open = FALSE;
980 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
986 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
987 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
989 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
990 input_facility->buffer,
991 input_facility->buffer_size);
993 output_facility->buffer_size = size;
994 hdr->size = htons (size);
995 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
996 output_facility->facility_state = IOSTATE_READY;
997 input_facility->facility_state = IOSTATE_READY;
1006 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1009 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1010 * input handle. Then it goes into IOSTATE_QUEUED state.
1011 * In case the read succeeded instantly the input facility enters 3.
1014 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1015 * If it has finished, go to state 3.
1016 * If it has failed, set IOSTATE_FAILED
1019 * If the facility is finished with ready
1020 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1021 * The input facility enters state IOSTATE_READY
1022 * The output facility enters state IOSTATE_READY
1023 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1025 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1027 * @param input_facility input named pipe or file to work with.
1028 * @param output_facility output pipe or file to hand over data to.
1029 * @return false if an event reset was impossible (OS error), else true
1032 attempt_read_stdin (struct io_facility * input_facility,
1033 struct io_facility * output_facility)
1035 struct GNUNET_MessageHeader * hdr;
1037 switch (input_facility->facility_state)
1041 if (! ResetEvent (input_facility->overlapped.hEvent))
1043 input_facility->buffer_size = 0;
1044 status = ReadFile (input_facility->handle,
1045 input_facility->buffer,
1046 sizeof (input_facility->buffer),
1047 &input_facility->buffer_size,
1048 &input_facility->overlapped);
1050 /* Check how the task is handled */
1051 if (status && (sizeof (struct GNUNET_MessageHeader) < input_facility->buffer_size))
1052 {/* async event processed immediately*/
1053 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1055 /* reset event manually*/
1056 if (! SetEvent (input_facility->overlapped.hEvent))
1059 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1061 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1062 ntohs (hdr->size) > sizeof (input_facility->buffer))
1064 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1065 input_facility->facility_state = IOSTATE_READY;
1068 if (ntohs (hdr->size) > input_facility->buffer_size);
1069 // TODO: add support for partial read
1071 /* we successfully read something from the TAP and now need to
1072 * send it our via STDOUT. Is that possible at the moment? */
1073 if (sizeof (struct GNUNET_MessageHeader) < input_facility->buffer_size)
1075 if (IOSTATE_READY == output_facility->facility_state ||
1076 IOSTATE_WAITING == output_facility->facility_state)
1078 /* hand over this buffers content and strip gnunet message header */
1079 memcpy (output_facility->buffer,
1080 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1081 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1082 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1083 output_facility->facility_state = IOSTATE_READY;
1086 else if (IOSTATE_QUEUED == output_facility->facility_state)
1087 /* If we have have read our buffer, wait for our write-partner*/
1088 input_facility->facility_state = IOSTATE_WAITING;
1089 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
1092 else if (status && 0 >= input_facility->buffer_size)
1094 if (! SetEvent (input_facility->overlapped.hEvent))
1097 input_facility->facility_state = IOSTATE_READY;
1099 else /* operation was either queued or failed*/
1101 int err = GetLastError ();
1102 if (ERROR_IO_PENDING == err)
1103 { /* operation queued */
1104 input_facility->facility_state = IOSTATE_QUEUED;
1107 { /* error occurred, let the rest of the elements finish */
1108 input_facility->path_open = FALSE;
1109 input_facility->facility_state = IOSTATE_FAILED;
1110 if (IOSTATE_WAITING == output_facility->facility_state)
1111 output_facility->path_open = FALSE;
1113 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1118 // We are queued and should check if the read has finished
1119 case IOSTATE_QUEUED:
1121 // there was an operation going on already, check if that has completed now.
1122 if (GetOverlappedResult (input_facility->handle,
1123 &input_facility->overlapped,
1124 &input_facility->buffer_size,
1126 {/* successful return for a queued operation */
1127 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1129 if (! ResetEvent (input_facility->overlapped.hEvent))
1132 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1134 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1135 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1137 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1138 input_facility->facility_state = IOSTATE_READY;
1141 if (ntohs (hdr->size) > input_facility->buffer_size );
1142 // TODO: add support for partial read
1144 /* we successfully read something from the TAP and now need to
1145 * send it our via STDOUT. Is that possible at the moment? */
1146 if ((IOSTATE_READY == output_facility->facility_state ||
1147 IOSTATE_WAITING == output_facility->facility_state)
1148 && sizeof(struct GNUNET_MessageHeader) < input_facility->buffer_size)
1149 { /* hand over this buffers content and strip gnunet message header */
1150 memcpy (output_facility->buffer,
1151 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1152 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1153 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1154 output_facility->facility_state = IOSTATE_READY;
1155 input_facility->facility_state = IOSTATE_READY;
1157 else if (sizeof(struct GNUNET_MessageHeader) < input_facility->buffer_size)
1158 { /* If we have have read our buffer, wait for our write-partner*/
1159 input_facility->facility_state = IOSTATE_WAITING;
1160 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
1162 else if (sizeof(struct GNUNET_MessageHeader) >= input_facility->buffer_size)
1163 input_facility->facility_state = IOSTATE_READY;
1166 { /* operation still pending/queued or failed? */
1167 int err = GetLastError ();
1168 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1169 { /* error occurred, let the rest of the elements finish */
1170 input_facility->path_open = FALSE;
1171 input_facility->facility_state = IOSTATE_FAILED;
1172 if (IOSTATE_WAITING == output_facility->facility_state)
1173 output_facility->path_open = FALSE;
1174 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1179 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1180 memcpy (output_facility->buffer,
1181 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1182 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1183 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1184 output_facility->facility_state = IOSTATE_READY;
1185 input_facility->facility_state = IOSTATE_READY;
1194 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1196 * TODO: high level description
1198 * @param output_facility output pipe or file to hand over data to.
1199 * @param input_facility input named pipe or file to work with.
1200 * @return false if an event reset was impossible (OS error), else true
1203 attempt_write (struct io_facility * output_facility,
1204 struct io_facility * input_facility)
1208 switch (output_facility->facility_state)
1212 if (! ResetEvent (output_facility->overlapped.hEvent))
1215 output_facility->buffer_size_written = 0;
1216 status = WriteFile (output_facility->handle,
1217 output_facility->buffer,
1218 output_facility->buffer_size,
1219 &output_facility->buffer_size_written,
1220 &output_facility->overlapped);
1222 /* Check how the task was handled */
1224 output_facility->buffer_size_written == output_facility->buffer_size)
1225 {/* async event processed immediately*/
1227 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1229 /* reset event manually*/
1230 if (! SetEvent (output_facility->overlapped.hEvent))
1233 /* we are now waiting for our buffer to be filled*/
1234 output_facility->facility_state = IOSTATE_WAITING;
1235 output_facility->buffer_size = 0;
1236 output_facility->buffer_size_written = 0;
1238 /* we successfully wrote something and now need to reset our reader */
1239 if (IOSTATE_WAITING == input_facility->facility_state)
1240 input_facility->facility_state = IOSTATE_RESUME;
1241 else if (IOSTATE_FAILED == input_facility->facility_state)
1242 output_facility->path_open = FALSE;
1244 else /* operation was either queued or failed*/
1246 int err = GetLastError ();
1247 if (ERROR_IO_PENDING == err)
1248 { /* operation queued */
1249 output_facility->facility_state = IOSTATE_QUEUED;
1252 { /* error occurred, close this path */
1253 output_facility->path_open = FALSE;
1254 output_facility->facility_state = IOSTATE_FAILED;
1255 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1259 case IOSTATE_QUEUED:
1260 // there was an operation going on already, check if that has completed now.
1261 status = GetOverlappedResult (output_facility->handle,
1262 &output_facility->overlapped,
1263 &output_facility->buffer_size_written,
1266 output_facility->buffer_size_written == output_facility->buffer_size)
1267 {/* successful return for a queued operation */
1268 if (! ResetEvent (output_facility->overlapped.hEvent))
1271 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1273 /* we are now waiting for our buffer to be filled*/
1274 output_facility->facility_state = IOSTATE_WAITING;
1275 output_facility->buffer_size = 0;
1276 output_facility->buffer_size_written = 0;
1278 /* we successfully wrote something and now need to reset our reader */
1279 if (IOSTATE_WAITING == input_facility->facility_state)
1280 input_facility->facility_state = IOSTATE_RESUME;
1281 else if (IOSTATE_FAILED == input_facility->facility_state)
1282 output_facility->path_open = FALSE;
1285 { /* operation still pending/queued or failed? */
1286 int err = GetLastError ();
1287 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1288 { /* error occurred, close this path */
1289 output_facility->path_open = FALSE;
1290 output_facility->facility_state = IOSTATE_FAILED;
1291 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1301 * Initialize a overlapped structure
1303 * @param elem the element to initilize
1304 * @param initial_state the initial state for this instance
1305 * @param signaled if the hEvent created should default to signaled or not
1306 * @return true on success, else false
1309 initialize_io_facility (struct io_facility * elem,
1313 elem->path_open = TRUE;
1314 elem->handle = INVALID_HANDLE_VALUE;
1315 elem->facility_state = initial_state;
1316 elem->buffer_size = 0;
1317 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1318 if (NULL == elem->overlapped.hEvent)
1326 * Start forwarding to and from the tunnel.
1328 * @param fd_tun tunnel FD
1331 run (HANDLE tap_handle)
1333 /* IO-Facility for reading from our virtual interface */
1334 struct io_facility tap_read;
1335 /* IO-Facility for writing to our virtual interface */
1336 struct io_facility tap_write;
1337 /* IO-Facility for reading from stdin */
1338 struct io_facility std_in;
1339 /* IO-Facility for writing to stdout */
1340 struct io_facility std_out;
1342 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1343 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1346 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1347 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1349 * DHCP and such are all features we will never use in gnunet afaik.
1350 * But for openvpn those are essential.
1352 if (! tun_up (tap_handle))
1355 /* Initialize our overlapped IO structures*/
1356 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1357 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1358 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1359 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1360 goto teardown_final;
1362 /* Handles for STDIN and STDOUT */
1363 tap_read.handle = tap_handle;
1364 tap_write.handle = tap_handle;
1366 #ifdef DEBUG_TO_CONSOLE
1367 /* Debug output to console STDIN/STDOUT*/
1368 std_in.handle = parent_std_in_handle;
1369 std_out.handle = parent_std_out_handle;
1372 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1374 * Find out the types of our handles.
1375 * This part is a problem, because in windows we need to handle files,
1376 * pipes and the console differently.
1378 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1379 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1381 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1385 std_in.handle = ReOpenFile (parent_std_in_handle,
1387 FILE_SHARE_WRITE | FILE_SHARE_READ,
1388 FILE_FLAG_OVERLAPPED);
1390 if (INVALID_HANDLE_VALUE == std_in.handle)
1392 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1396 std_out.handle = ReOpenFile (parent_std_out_handle,
1399 FILE_FLAG_OVERLAPPED);
1401 if (INVALID_HANDLE_VALUE == std_out.handle)
1403 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1408 fprintf (stderr, "DEBUG: mainloop has begun\n");
1410 while (std_out.path_open || tap_write.path_open)
1412 /* perform READ from stdin if possible */
1413 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1416 /* perform READ from tap if possible */
1417 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1420 /* perform WRITE to tap if possible */
1421 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1424 /* perform WRITE to STDOUT if possible */
1425 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1431 fprintf (stderr, "DEBUG: teardown initiated\n");
1433 CancelIo (tap_handle);
1434 CancelIo (std_in.handle);
1435 CancelIo (std_out.handle);
1439 CloseHandle (tap_handle);
1444 * Open VPN tunnel interface.
1446 * @param argc must be 6
1447 * @param argv 0: binary name (gnunet-helper-vpn)
1448 * 1: tunnel interface prefix (gnunet-vpn)
1449 * 2: IPv6 address (::1), "-" to disable
1450 * 3: IPv6 netmask length in bits (64), ignored if #2 is "-"
1451 * 4: IPv4 address (1.2.3.4), "-" to disable
1452 * 5: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
1455 main (int argc, char **argv)
1457 char hwid[LINE_LEN];
1460 BOOL have_ip4 = FALSE;
1461 BOOL have_ip6 = FALSE;
1465 fprintf (stderr, "FATAL: must supply 5 arguments\nUsage:\ngnunet-helper-vpn <if name prefix> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1469 strncpy (hwid, argv[1], LINE_LEN);
1470 hwid[LINE_LEN - 1] = '\0';
1473 * We use our PID for finding/resolving the control-panel name of our virtual
1474 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1475 * as additional hardware-id for our device.
1477 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1481 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1483 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1493 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1494 if (0 != strcmp (argv[2], "-"))
1496 const char *address = argv[2];
1497 long prefix_len = atol (argv[3]);
1499 if ((prefix_len < 1) || (prefix_len > 127))
1501 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1506 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n",address,prefix_len);
1507 if (0 != (global_ret = set_address6 (address, prefix_len)))
1513 if (0 != strcmp (argv[4], "-"))
1515 const char *address = argv[4];
1516 const char *mask = argv[5];
1518 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n",address,mask);
1519 if (0 != (global_ret = set_address4 (address, mask)))
1531 const char *address = argv[4];
1532 fprintf (stderr, "DEBUG: Removing IP4 address\n");
1533 remove_address4 (address);
1537 const char *address = argv[2];
1538 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1539 remove_address6 (address);
1542 fprintf (stderr, "DEBUG: removing interface\n");
1543 remove_interface ();
1544 fprintf (stderr, "DEBUG: graceful exit completed\n");