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/openvpn-tap32/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/openvpn-tap32/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 address the IPv4-Address
339 remove_address6 (const char *address)
341 char command[LINE_LEN];
344 // sanity checking was already done in set_address6
346 * prepare the command
348 snprintf (command, LINE_LEN,
349 "netsh interface ipv6 delete address \"%s\" store=persistent",
350 device_visible_name, address);
354 ret = execute_shellcommand (command);
358 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
363 * @brief Sets the IPv4-Address given in address on the interface dev
365 * @param address the IPv4-Address
366 * @param mask the netmask
369 set_address4 (const char *address, const char *mask)
372 char command[LINE_LEN];
374 struct sockaddr_in addr;
375 addr.sin_family = AF_INET;
380 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
382 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
386 // Set Device to Subnet-Mode?
387 // do we really need tun.c:2925 ?
390 * prepare the command
392 snprintf (command, LINE_LEN,
393 "netsh interface ipv4 add address \"%s\" %s %s store=active",
394 device_visible_name, address, mask);
398 ret = execute_shellcommand (command);
402 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
408 * @brief Removes the IPv4-Address given in address from the interface dev
410 * @param address the IPv4-Address
413 remove_address4 (const char *address)
415 char command[LINE_LEN];
418 // sanity checking was already done in set_address4
421 * prepare the command
423 snprintf (command, LINE_LEN,
424 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
425 device_visible_name, address);
429 ret = execute_shellcommand (command);
433 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
438 * Setup a new virtual interface to use for tunneling.
440 * @return: TRUE if setup was successful, else FALSE
446 * where to find our inf-file. (+ the "full" path, after windows found")
448 * We do not directly input all the props here, because openvpn will update
449 * these details over time.
451 char inf_file_path[MAX_PATH];
452 char * temp_inf_filename;
453 char hwidlist[LINE_LEN + 4];
454 char class_name[128];
459 * Set the device's hardware ID and add it to a list.
460 * This information will later on identify this device in registry.
462 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
464 * this is kind of over-complicated, but allows keeps things independent of
465 * how the openvpn-hwid is actually stored.
467 * A HWID list is double-\0 terminated and \0 separated
469 str_length = strlen (hwidlist) + 1;
470 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
471 str_length += strlen (&hwidlist[str_length]) + 1;
474 * Locate the inf-file, we need to store it somewhere where the system can
475 * find it. We need to pick the correct driver for win32/win64.
478 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
480 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
482 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
484 * Bootstrap our device info using the drivers inf-file
486 if ( ! SetupDiGetINFClassA (inf_file_path,
488 class_name, sizeof (class_name) / sizeof (char),
493 * Collect all the other needed information...
494 * let the system fill our this form
496 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
497 if (DeviceInfo == INVALID_HANDLE_VALUE)
500 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
501 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
510 /* Deploy all the information collected into the registry */
511 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
515 str_length * sizeof (char)))
518 /* Install our new class(=device) into the system */
519 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
524 /* This system call tends to take a while (several seconds!) on
525 "modern" Windoze systems */
526 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
529 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
530 NULL)) //reboot required? NEVER!
533 fprintf (stderr, "DEBUG: successfully created a network device\n");
539 * Remove our new virtual interface to use for tunneling.
540 * This function must be called AFTER setup_interface!
542 * @return: TRUE if destruction was successful, else FALSE
547 SP_REMOVEDEVICE_PARAMS remove;
549 if (INVALID_HANDLE_VALUE == DeviceInfo)
552 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
553 remove.HwProfile = 0;
554 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
555 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
557 * 1. Prepare our existing device information set, and place the
558 * uninstall related information into the structure
560 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
561 (PSP_DEVINFO_DATA) & DeviceNode,
562 &remove.ClassInstallHeader,
566 * 2. Uninstall the virtual interface using the class installer
568 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
570 (PSP_DEVINFO_DATA) & DeviceNode))
573 SetupDiDestroyDeviceInfoList (DeviceInfo);
575 fprintf (stderr, "DEBUG: removed interface successfully\n");
582 * Do all the lookup necessary to retrieve the inteface's actual name
585 * @return: TRUE if we were able to lookup the interface's name, else FALSE
588 resolve_interface_name ()
590 SP_DEVINFO_LIST_DETAIL_DATA device_details;
591 char pnp_instance_id [MAX_DEVICE_ID_LEN];
592 HKEY adapter_key_handle;
598 char adapter[] = INTERFACE_REGISTRY_LOCATION;
600 /* We can obtain the PNP instance ID from our setupapi handle */
601 device_details.cbSize = sizeof (device_details);
602 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
603 (PCHAR) pnp_instance_id,
606 NULL)) //hMachine, we are local
609 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
611 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
612 for (retrys = 0; retrys < 120 && !retval; retrys++)
617 /* Now we can use this ID to locate the correct networks interface in registry */
618 if (ERROR_SUCCESS != RegOpenKeyExA (
623 &adapter_key_handle))
626 /* Of course there is a multitude of entries here, with arbitrary names,
627 * thus we need to iterate through there.
631 char instance_key[256];
632 char query_key [256];
633 HKEY instance_key_handle;
634 char pnpinstanceid_name[] = "PnpInstanceID";
635 char pnpinstanceid_value[256];
636 char adaptername_name[] = "Name";
639 len = 256 * sizeof (char);
640 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
641 status = RegEnumKeyExA (
651 /* this may fail due to one of two reasons:
652 * we are at the end of the list*/
653 if (ERROR_NO_MORE_ITEMS == status)
655 // * we found a broken registry key, continue with the next key.
656 if (ERROR_SUCCESS != status)
659 /* prepare our new query string: */
660 snprintf (query_key, 256, "%s\\%s\\Connection",
664 /* look inside instance_key\\Connection */
665 if (ERROR_SUCCESS != RegOpenKeyExA (
670 &instance_key_handle))
673 /* now, read our PnpInstanceID */
674 len = sizeof (pnpinstanceid_value);
675 status = RegQueryValueExA (instance_key_handle,
677 NULL, //reserved, always NULL according to MSDN
679 (LPBYTE) pnpinstanceid_value,
682 if (status != ERROR_SUCCESS || data_type != REG_SZ)
685 /* compare the value we got to our devices PNPInstanceID*/
686 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
687 sizeof (pnpinstanceid_value) / sizeof (char)))
690 len = sizeof (device_visible_name);
691 status = RegQueryValueExA (
694 NULL, //reserved, always NULL according to MSDN
696 (LPBYTE) device_visible_name,
699 if (status != ERROR_SUCCESS || data_type != REG_SZ)
703 * we have successfully found OUR instance,
704 * save the device GUID before exiting
707 strncpy (device_guid, instance_key, 256);
709 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
712 RegCloseKey (instance_key_handle);
717 RegCloseKey (adapter_key_handle);
724 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
726 * @param handle the handle to our tap device
727 * @return TRUE if the version is sufficient, else FALSE
730 check_tapw32_version (HANDLE handle)
734 memset (&(version), 0, sizeof (version));
736 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
737 &version, sizeof (version),
738 &version, sizeof (version), &len, NULL))
739 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
742 (version[2] ? "(DEBUG)" : ""));
744 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
745 (version[1] < TAP_WIN_MIN_MINOR )){
746 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
757 * Creates a tun-interface called dev;
759 * @return the fd to the tun or -1 on error
764 char device_path[256];
767 if (! setup_interface ())
770 return INVALID_HANDLE_VALUE;
773 if (! resolve_interface_name ())
776 return INVALID_HANDLE_VALUE;
779 /* Open Windows TAP-Windows adapter */
780 snprintf (device_path, sizeof (device_path), "%s%s%s",
785 handle = CreateFile (
787 GENERIC_READ | GENERIC_WRITE,
788 0, /* was: FILE_SHARE_READ */
791 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
795 if (INVALID_HANDLE_VALUE == handle)
797 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
801 /* get driver version info */
802 if (! check_tapw32_version (handle))
804 CloseHandle (handle);
805 return INVALID_HANDLE_VALUE;
808 /* TODO (opt?): get MTU-Size */
810 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
816 * Brings a TAP device up and sets it to connected state.
818 * @param handle the handle to our TAP device
819 * @return True if the operation succeeded, else false
822 tun_up (HANDLE handle)
826 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
827 &status, sizeof (status),
828 &status, sizeof (status), &len, NULL))
830 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
834 /* Wait for the device to go UP, might take some time. */
835 Sleep (TAP32_POSTUP_WAITTIME * 1000);
836 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
843 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
846 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
847 * input handle. Then it goes into IOSTATE_QUEUED state.
848 * In case the read succeeded instantly the input facility enters 3.
851 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
852 * If it has finished, go to state 3.
853 * If it has failed, set IOSTATE_FAILED
856 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
857 * The input facility enters state IOSTATE_READY
858 * The output facility enters state IOSTATE_READY
859 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
861 * IOSTATE_WAITING is reset by the output facility, once it has completed.
863 * @param input_facility input named pipe or file to work with.
864 * @param output_facility output pipe or file to hand over data to.
865 * @return false if an event reset was impossible (OS error), else true
868 attempt_read_tap (struct io_facility * input_facility,
869 struct io_facility * output_facility)
871 struct GNUNET_MessageHeader * hdr;
874 switch (input_facility->facility_state)
878 if (! ResetEvent (input_facility->overlapped.hEvent))
883 input_facility->buffer_size = 0;
885 /* Check how the task is handled */
886 if (ReadFile (input_facility->handle,
887 input_facility->buffer,
888 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
889 &input_facility->buffer_size,
890 &input_facility->overlapped))
891 {/* async event processed immediately*/
893 /* reset event manually*/
894 if (! SetEvent (input_facility->overlapped.hEvent))
897 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
899 /* we successfully read something from the TAP and now need to
900 * send it our via STDOUT. Is that possible at the moment? */
901 if ((IOSTATE_READY == output_facility->facility_state ||
902 IOSTATE_WAITING == output_facility->facility_state)
903 && (0 < input_facility->buffer_size))
904 { /* hand over this buffers content and apply message header for gnunet */
905 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
906 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
908 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
909 input_facility->buffer,
910 input_facility->buffer_size);
912 output_facility->buffer_size = size;
913 hdr->size = htons (size);
914 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
915 output_facility->facility_state = IOSTATE_READY;
917 else if (0 < input_facility->buffer_size)
918 /* If we have have read our buffer, wait for our write-partner*/
919 input_facility->facility_state = IOSTATE_WAITING;
921 else /* operation was either queued or failed*/
923 int err = GetLastError ();
924 if (ERROR_IO_PENDING == err)
925 { /* operation queued */
926 input_facility->facility_state = IOSTATE_QUEUED;
929 { /* error occurred, let the rest of the elements finish */
930 input_facility->path_open = FALSE;
931 input_facility->facility_state = IOSTATE_FAILED;
932 if (IOSTATE_WAITING == output_facility->facility_state)
933 output_facility->path_open = FALSE;
935 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
940 // We are queued and should check if the read has finished
943 // there was an operation going on already, check if that has completed now.
945 if (GetOverlappedResult (input_facility->handle,
946 &input_facility->overlapped,
947 &input_facility->buffer_size,
949 {/* successful return for a queued operation */
950 if (! ResetEvent (input_facility->overlapped.hEvent))
953 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
955 /* we successfully read something from the TAP and now need to
956 * send it our via STDOUT. Is that possible at the moment? */
957 if ((IOSTATE_READY == output_facility->facility_state ||
958 IOSTATE_WAITING == output_facility->facility_state)
959 && 0 < input_facility->buffer_size)
960 { /* hand over this buffers content and apply message header for gnunet */
961 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
962 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
964 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
965 input_facility->buffer,
966 input_facility->buffer_size);
968 output_facility->buffer_size = size;
969 hdr->size = htons(size);
970 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
971 output_facility->facility_state = IOSTATE_READY;
972 input_facility->facility_state = IOSTATE_READY;
974 else if (0 < input_facility->buffer_size)
975 { /* If we have have read our buffer, wait for our write-partner*/
976 input_facility->facility_state = IOSTATE_WAITING;
977 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
981 { /* operation still pending/queued or failed? */
982 int err = GetLastError ();
983 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
984 { /* error occurred, let the rest of the elements finish */
985 input_facility->path_open = FALSE;
986 input_facility->facility_state = IOSTATE_FAILED;
987 if (IOSTATE_WAITING == output_facility->facility_state)
988 output_facility->path_open = FALSE;
989 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
995 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
996 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
998 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
999 input_facility->buffer,
1000 input_facility->buffer_size);
1002 output_facility->buffer_size = size;
1003 hdr->size = htons (size);
1004 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1005 output_facility->facility_state = IOSTATE_READY;
1006 input_facility->facility_state = IOSTATE_READY;
1015 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1018 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1019 * input handle. Then it goes into IOSTATE_QUEUED state.
1020 * In case the read succeeded instantly the input facility enters 3.
1023 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1024 * If it has finished, go to state 3.
1025 * If it has failed, set IOSTATE_FAILED
1028 * If the facility is finished with ready
1029 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1030 * The input facility enters state IOSTATE_READY
1031 * The output facility enters state IOSTATE_READY
1032 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1034 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1036 * @param input_facility input named pipe or file to work with.
1037 * @param output_facility output pipe or file to hand over data to.
1038 * @return false if an event reset was impossible (OS error), else true
1041 attempt_read_stdin (struct io_facility * input_facility,
1042 struct io_facility * output_facility)
1044 struct GNUNET_MessageHeader * hdr;
1046 switch (input_facility->facility_state)
1050 input_facility->buffer_size = 0;
1052 partial_read_iostate_ready:
1053 if (! ResetEvent (input_facility->overlapped.hEvent))
1056 /* Check how the task is handled */
1057 if (ReadFile (input_facility->handle,
1058 input_facility->buffer + input_facility->buffer_size,
1059 sizeof (input_facility->buffer) - input_facility->buffer_size,
1060 &input_facility->buffer_size_processed,
1061 &input_facility->overlapped))
1062 {/* async event processed immediately*/
1063 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1065 /* reset event manually*/
1066 if (!SetEvent (input_facility->overlapped.hEvent))
1069 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1070 input_facility->buffer_size += input_facility->buffer_size_processed;
1072 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1073 ntohs (hdr->size) > sizeof (input_facility->buffer))
1075 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1076 input_facility->facility_state = IOSTATE_READY;
1079 /* we got the a part of a packet */
1080 if (ntohs (hdr->size) > input_facility->buffer_size)
1081 goto partial_read_iostate_ready;
1083 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1084 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1085 ((IOSTATE_READY == output_facility->facility_state) ||
1086 (IOSTATE_WAITING == output_facility->facility_state)))
1087 {/* we successfully read something from the TAP and now need to
1088 * send it our via STDOUT. Is that possible at the moment? */
1090 /* hand over this buffers content and strip gnunet message header */
1091 memcpy (output_facility->buffer,
1092 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1093 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1094 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1095 output_facility->facility_state = IOSTATE_READY;
1096 input_facility->facility_state = IOSTATE_READY;
1098 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1099 /* If we have have read our buffer, wait for our write-partner*/
1100 input_facility->facility_state = IOSTATE_WAITING;
1101 else /* we read nothing */
1102 input_facility->facility_state = IOSTATE_READY;
1104 else /* operation was either queued or failed*/
1106 int err = GetLastError ();
1107 if (ERROR_IO_PENDING == err) /* operation queued */
1108 input_facility->facility_state = IOSTATE_QUEUED;
1110 { /* error occurred, let the rest of the elements finish */
1111 input_facility->path_open = FALSE;
1112 input_facility->facility_state = IOSTATE_FAILED;
1113 if (IOSTATE_WAITING == output_facility->facility_state)
1114 output_facility->path_open = FALSE;
1116 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1121 // We are queued and should check if the read has finished
1122 case IOSTATE_QUEUED:
1124 // there was an operation going on already, check if that has completed now.
1125 if (GetOverlappedResult (input_facility->handle,
1126 &input_facility->overlapped,
1127 &input_facility->buffer_size_processed,
1129 {/* successful return for a queued operation */
1130 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1132 if (! ResetEvent (input_facility->overlapped.hEvent))
1135 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1136 input_facility->buffer_size += input_facility->buffer_size_processed;
1138 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1139 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1141 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1142 input_facility->facility_state = IOSTATE_READY;
1145 /* we got the a part of a packet */
1146 if (ntohs (hdr->size) > input_facility->buffer_size );
1147 goto partial_read_iostate_ready;
1149 /* we successfully read something from the TAP and now need to
1150 * send it our via STDOUT. Is that possible at the moment? */
1151 if ((IOSTATE_READY == output_facility->facility_state ||
1152 IOSTATE_WAITING == output_facility->facility_state)
1153 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1154 { /* hand over this buffers content and strip gnunet message header */
1155 memcpy (output_facility->buffer,
1156 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1157 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1158 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1159 output_facility->facility_state = IOSTATE_READY;
1160 input_facility->facility_state = IOSTATE_READY;
1162 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1163 input_facility->facility_state = IOSTATE_WAITING;
1165 input_facility->facility_state = IOSTATE_READY;
1168 { /* operation still pending/queued or failed? */
1169 int err = GetLastError ();
1170 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1171 { /* error occurred, let the rest of the elements finish */
1172 input_facility->path_open = FALSE;
1173 input_facility->facility_state = IOSTATE_FAILED;
1174 if (IOSTATE_WAITING == output_facility->facility_state)
1175 output_facility->path_open = FALSE;
1176 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1181 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1182 memcpy (output_facility->buffer,
1183 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1184 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1185 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1186 output_facility->facility_state = IOSTATE_READY;
1187 input_facility->facility_state = IOSTATE_READY;
1196 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1198 * TODO: high level description
1200 * @param output_facility output pipe or file to hand over data to.
1201 * @param input_facility input named pipe or file to work with.
1202 * @return false if an event reset was impossible (OS error), else true
1205 attempt_write (struct io_facility * output_facility,
1206 struct io_facility * input_facility)
1208 switch (output_facility->facility_state)
1211 output_facility->buffer_size_written = 0;
1213 continue_partial_write:
1214 if (! ResetEvent (output_facility->overlapped.hEvent))
1217 /* Check how the task was handled */
1218 if (WriteFile (output_facility->handle,
1219 output_facility->buffer + output_facility->buffer_size_written,
1220 output_facility->buffer_size - output_facility->buffer_size_written,
1221 &output_facility->buffer_size_processed,
1222 &output_facility->overlapped))
1223 {/* async event processed immediately*/
1225 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1226 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1228 /* reset event manually*/
1229 if (! SetEvent (output_facility->overlapped.hEvent))
1233 if (output_facility->buffer_size_written < output_facility->buffer_size)
1234 goto continue_partial_write;
1236 /* we are now waiting for our buffer to be filled*/
1237 output_facility->facility_state = IOSTATE_WAITING;
1239 /* we successfully wrote something and now need to reset our reader */
1240 if (IOSTATE_WAITING == input_facility->facility_state)
1241 input_facility->facility_state = IOSTATE_RESUME;
1242 else if (IOSTATE_FAILED == input_facility->facility_state)
1243 output_facility->path_open = FALSE;
1245 else /* operation was either queued or failed*/
1247 int err = GetLastError ();
1248 if (ERROR_IO_PENDING == err)
1249 { /* operation queued */
1250 output_facility->facility_state = IOSTATE_QUEUED;
1253 { /* error occurred, close this path */
1254 output_facility->path_open = FALSE;
1255 output_facility->facility_state = IOSTATE_FAILED;
1256 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1260 case IOSTATE_QUEUED:
1261 // there was an operation going on already, check if that has completed now.
1263 if (GetOverlappedResult (output_facility->handle,
1264 &output_facility->overlapped,
1265 &output_facility->buffer_size_processed,
1267 {/* successful return for a queued operation */
1268 if (! ResetEvent (output_facility->overlapped.hEvent))
1271 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1272 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1275 if (output_facility->buffer_size_written < output_facility->buffer_size)
1276 goto continue_partial_write;
1278 /* we are now waiting for our buffer to be filled*/
1279 output_facility->facility_state = IOSTATE_WAITING;
1281 /* we successfully wrote something and now need to reset our reader */
1282 if (IOSTATE_WAITING == input_facility->facility_state)
1283 input_facility->facility_state = IOSTATE_RESUME;
1284 else if (IOSTATE_FAILED == input_facility->facility_state)
1285 output_facility->path_open = FALSE;
1288 { /* operation still pending/queued or failed? */
1289 int err = GetLastError ();
1290 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1291 { /* error occurred, close this path */
1292 output_facility->path_open = FALSE;
1293 output_facility->facility_state = IOSTATE_FAILED;
1294 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1304 * Initialize a overlapped structure
1306 * @param elem the element to initilize
1307 * @param initial_state the initial state for this instance
1308 * @param signaled if the hEvent created should default to signaled or not
1309 * @return true on success, else false
1312 initialize_io_facility (struct io_facility * elem,
1316 elem->path_open = TRUE;
1317 elem->handle = INVALID_HANDLE_VALUE;
1318 elem->facility_state = initial_state;
1319 elem->buffer_size = 0;
1320 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1321 if (NULL == elem->overlapped.hEvent)
1329 * Start forwarding to and from the tunnel.
1331 * @param tap_handle device handle for interacting with the Virtual interface
1334 run (HANDLE tap_handle)
1336 /* IO-Facility for reading from our virtual interface */
1337 struct io_facility tap_read;
1338 /* IO-Facility for writing to our virtual interface */
1339 struct io_facility tap_write;
1340 /* IO-Facility for reading from stdin */
1341 struct io_facility std_in;
1342 /* IO-Facility for writing to stdout */
1343 struct io_facility std_out;
1345 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1346 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1349 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1350 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1352 * DHCP and such are all features we will never use in gnunet afaik.
1353 * But for openvpn those are essential.
1355 if (! tun_up (tap_handle))
1358 /* Initialize our overlapped IO structures*/
1359 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1360 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1361 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1362 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1363 goto teardown_final;
1365 /* Handles for STDIN and STDOUT */
1366 tap_read.handle = tap_handle;
1367 tap_write.handle = tap_handle;
1369 #ifdef DEBUG_TO_CONSOLE
1370 /* Debug output to console STDIN/STDOUT*/
1371 std_in.handle = parent_std_in_handle;
1372 std_out.handle = parent_std_out_handle;
1375 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1377 * Find out the types of our handles.
1378 * This part is a problem, because in windows we need to handle files,
1379 * pipes and the console differently.
1381 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1382 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1384 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1388 std_in.handle = ReOpenFile (parent_std_in_handle,
1390 FILE_SHARE_WRITE | FILE_SHARE_READ,
1391 FILE_FLAG_OVERLAPPED);
1393 if (INVALID_HANDLE_VALUE == std_in.handle)
1395 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1399 std_out.handle = ReOpenFile (parent_std_out_handle,
1402 FILE_FLAG_OVERLAPPED);
1404 if (INVALID_HANDLE_VALUE == std_out.handle)
1406 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1411 fprintf (stderr, "DEBUG: mainloop has begun\n");
1413 while (std_out.path_open || tap_write.path_open)
1415 /* perform READ from stdin if possible */
1416 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1419 /* perform READ from tap if possible */
1420 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1423 /* perform WRITE to tap if possible */
1424 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1427 /* perform WRITE to STDOUT if possible */
1428 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1434 fprintf (stderr, "DEBUG: teardown initiated\n");
1436 CancelIo (tap_handle);
1437 CancelIo (std_in.handle);
1438 CancelIo (std_out.handle);
1442 CloseHandle (tap_handle);
1445 * Open VPN tunnel interface.
1447 * @param argc must be 6
1448 * @param argv 0: binary name ("gnunet-helper-exit")
1449 * 1: tunnel interface name ("gnunet-exit")
1450 * 2: IPv4 "physical" interface name ("eth0"), or "-" to not do IPv4 NAT
1451 * 3: IPv6 address ("::1"), or "-" to skip IPv6
1452 * 4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1453 * 5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1454 * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1457 main (int argc, char **argv)
1459 char hwid[LINE_LEN];
1462 int local_ret = EINVAL;
1463 BOOL have_ip4 = FALSE;
1464 BOOL have_ip6 = FALSE;
1465 BOOL have_nat44 = FALSE;
1469 fprintf (stderr, "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit <if name prefix> <uplink-interface name> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1473 strncpy (hwid, argv[1], LINE_LEN);
1474 hwid[LINE_LEN - 1] = '\0';
1477 * We use our PID for finding/resolving the control-panel name of our virtual
1478 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1479 * as additional hardware-id for our device.
1481 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1485 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1487 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1497 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1498 if (0 != strcmp (argv[3], "-"))
1500 char command[LINE_LEN];
1501 const char *address = argv[3];
1502 long prefix_len = atol (argv[4]);
1504 if ((prefix_len < 1) || (prefix_len > 127))
1506 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1511 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1512 if (0 != (global_ret = set_address6 (address, prefix_len)))
1517 /* install our the windows NAT module*/
1518 fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n");
1519 /* outside interface (maybe that's already set) */
1520 snprintf (command, LINE_LEN,
1521 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active",
1523 local_ret = execute_shellcommand (command);
1526 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1529 /* internal interface */
1530 snprintf (command, LINE_LEN,
1531 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active",
1532 device_visible_name);
1533 local_ret = execute_shellcommand (command);
1536 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1539 /* we can keep IPv6 forwarding around, as all interfaces have
1540 * their forwarding mode reset to false at bootup. */
1543 if (0 != strcmp (argv[5], "-"))
1545 const char *address = argv[5];
1546 const char *mask = argv[6];
1548 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1549 if (0 != (global_ret = set_address4 (address, mask)))
1552 // setup NAPT, if possible
1553 /* MS has REMOVED the routing/nat capabilities from Vista+, thus
1554 * we can not setup NAT like in XP or on the server. Actually the
1555 * the only feasible solution seems to be to use
1556 * Internet Connection Sharing, which introduces a horde of problems
1557 * such as sending out rogue-RAs on the external interface in an ipv6
1559 * Thus, below stuff ONLY works on
1561 * Win Server 2003 SP1+
1566 if (0 != strcmp (argv[2], "-"))
1568 char command[LINE_LEN];
1570 /* install our the windows NAT module*/
1571 fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]);
1572 local_ret = execute_shellcommand ("netsh routing ip nat install");
1575 fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret));
1579 snprintf (command, LINE_LEN,
1580 "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/
1582 local_ret = execute_shellcommand (command);
1585 fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret));
1588 /* private/internal/virtual IF */
1589 snprintf (command, LINE_LEN,
1590 "netsh routing ip nat add interface \"%s\" private",
1591 device_visible_name);
1592 local_ret = execute_shellcommand (command);
1595 fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret));
1608 const char *address = argv[5];
1610 char command[LINE_LEN];
1611 fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n");
1612 snprintf(command, LINE_LEN,
1613 "netsh routing ip nat del interface \"%s\"",
1614 device_visible_name);
1615 local_ret = execute_shellcommand(command);
1617 fprintf(stderr, "WARNING: Could not remove IPv4-NAPT from internal interface, hopefully this will have no effect in future runs: %s\n", strerror(local_ret));
1620 fprintf(stderr, "DEBUG: Removing IP4 address\n");
1621 remove_address4 (address);
1625 const char *address = argv[3];
1626 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1627 remove_address6 (address);
1630 fprintf (stderr, "DEBUG: removing interface\n");
1631 remove_interface ();
1632 fprintf (stderr, "DEBUG: graceful exit completed\n");