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):
36 #include <ddk/cfgmgr32.h>
37 #include <ddk/newdev.h>
41 #include "tap-windows.h"
43 * Need 'struct GNUNET_MessageHeader'.
45 #include "gnunet_common.h"
48 * Need VPN message types.
50 #include "gnunet_protocols.h"
53 * Should we print (interesting|debug) messages that can happen during
56 #define DEBUG GNUNET_NO
59 /* FIXME: define with varargs... */
60 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
62 #define LOG_DEBUG(msg) do {} while (0)
66 * Will this binary be run in permissions testing mode?
68 static boolean privilege_testing = FALSE;
71 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
73 #define MAX_SIZE 65536
76 * Name or Path+Name of our win32 driver.
77 * The .sys and .cat files HAVE to be in the same location as this file!
79 #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
82 * Name or Path+Name of our win64 driver.
83 * The .sys and .cat files HAVE to be in the same location as this file!
85 #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
88 * Hardware ID used in the inf-file.
89 * This might change over time, as openvpn advances their driver
91 #define HARDWARE_ID "tap0901"
94 * Minimum major-id of the driver version we can work with
96 #define TAP_WIN_MIN_MAJOR 9
99 * Minimum minor-id of the driver version we can work with.
100 * v <= 7 has buggy IPv6.
101 * v == 8 is broken for small IPv4 Packets
103 #define TAP_WIN_MIN_MINOR 9
106 * Time in seconds to wait for our virtual device to go up after telling it to do so.
108 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
109 * (in fact, 4 was chosen by a fair dice roll...)
111 #define TAP32_POSTUP_WAITTIME 4
114 * Location of the network interface list resides in registry.
116 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
119 * Our local process' PID. Used for creating a sufficiently unique additional
120 * hardware ID for our device.
122 static char secondary_hwid[LINE_LEN / 2];
125 * Device's visible Name, used to identify a network device in netsh.
126 * eg: "Local Area Connection 9"
128 static char device_visible_name[256];
131 * This is our own local instance of a virtual network interface
132 * It is (somewhat) equivalent to using tun/tap in unixoid systems
134 * Upon initialization, we create such an device node.
135 * Upon termination, we remove it again.
137 * If we crash this device might stay around.
139 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
142 * Registry Key we hand over to windows to spawn a new virtual interface
144 static SP_DEVINFO_DATA DeviceNode;
147 * GUID of our virtual device in the form of
148 * {12345678-1234-1234-1234-123456789abc} - in hex
150 static char device_guid[256];
154 * Possible states of an IO facility.
160 * overlapped I/O is ready for work
165 * overlapped I/O has been queued
170 * overlapped I/O has finished, but is waiting for it's write-partner
175 * there is a full buffer waiting
180 * Operlapped IO states for facility objects
181 * overlapped I/O has failed, stop processing
189 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
194 * The mode the state machine associated with this object is in.
196 enum IO_State facility_state;
199 * If the path is open or blocked in general (used for quickly checking)
201 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
204 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
209 * Overlaped IO structure used for asynchronous IO in windows.
211 OVERLAPPED overlapped;
214 * Buffer for reading things to and writing from...
216 unsigned char buffer[MAX_SIZE];
219 * How much of this buffer was used when reading or how much data can be written
224 * Amount of data actually written or read by readfile/writefile.
226 DWORD buffer_size_processed;
229 * How much of this buffer we have written in total
231 DWORD buffer_size_written;
235 * ReOpenFile is only available as of XP SP2 and 2003 SP1
237 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
240 * IsWow64Process definition for our is_win64, as this is a kernel function
242 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
245 * Determines if the host OS is win32 or win64
253 //this is a win64 binary,
255 #elif defined(_WIN32)
256 //this is a 32bit binary, and we need to check if we are running in WOW64
257 BOOL success = FALSE;
258 BOOL on_wow64 = FALSE;
259 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
261 if (NULL != IsWow64Process)
262 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
264 return success && on_wow64;
268 * Wrapper for executing a shellcommand in windows.
270 * @param command - the command + parameters to execute
271 * @return * exitcode of the program executed,
272 * * EINVAL (cmd/file not found)
273 * * EPIPE (could not read STDOUT)
276 execute_shellcommand (const char *command)
280 if ( (NULL == command) ||
281 (NULL == (pipe = _popen (command, "rt"))) )
285 fprintf (stderr, "DEBUG: Command output: \n");
286 char output[LINE_LEN];
287 while (NULL != fgets (output, sizeof (output), pipe))
288 fprintf (stderr, "%s", output);
291 return _pclose (pipe);
296 * @brief Sets the IPv6-Address given in address on the interface dev
298 * @param address the IPv6-Address
299 * @param prefix_len the length of the network-prefix
302 set_address6 (const char *address, unsigned long prefix_len)
305 char command[LINE_LEN];
306 struct sockaddr_in6 sa6;
309 * parse the new address
311 memset (&sa6, 0, sizeof (struct sockaddr_in6));
312 sa6.sin6_family = AF_INET6;
313 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
315 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
321 * prepare the command
323 snprintf (command, LINE_LEN,
324 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
325 device_visible_name, address, prefix_len);
329 ret = execute_shellcommand (command);
333 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
339 * @brief Removes the IPv6-Address given in address from the interface dev
341 * @param address the IPv4-Address
344 remove_address6 (const char *address)
346 char command[LINE_LEN];
349 // sanity checking was already done in set_address6
351 * prepare the command
353 snprintf (command, LINE_LEN,
354 "netsh interface ipv6 delete address \"%s\" store=persistent",
355 device_visible_name, address);
359 ret = execute_shellcommand (command);
363 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
368 * @brief Sets the IPv4-Address given in address on the interface dev
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 address the IPv4-Address
418 remove_address4 (const char *address)
420 char command[LINE_LEN];
423 // sanity checking was already done in set_address4
426 * prepare the command
428 snprintf (command, LINE_LEN,
429 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
430 device_visible_name, address);
434 ret = execute_shellcommand (command);
438 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
443 * Setup a new virtual interface to use for tunneling.
445 * @return: TRUE if setup was successful, else FALSE
451 * where to find our inf-file. (+ the "full" path, after windows found")
453 * We do not directly input all the props here, because openvpn will update
454 * these details over time.
456 char inf_file_path[MAX_PATH];
457 char * temp_inf_filename;
458 char hwidlist[LINE_LEN + 4];
459 char class_name[128];
464 * Set the device's hardware ID and add it to a list.
465 * This information will later on identify this device in registry.
467 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
469 * this is kind of over-complicated, but allows keeps things independent of
470 * how the openvpn-hwid is actually stored.
472 * A HWID list is double-\0 terminated and \0 separated
474 str_length = strlen (hwidlist) + 1;
475 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
476 str_length += strlen (&hwidlist[str_length]) + 1;
479 * Locate the inf-file, we need to store it somewhere where the system can
480 * find it. We need to pick the correct driver for win32/win64.
483 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
485 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
487 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
489 * Bootstrap our device info using the drivers inf-file
491 if ( ! SetupDiGetINFClassA (inf_file_path,
493 class_name, sizeof (class_name) / sizeof (char),
498 * Collect all the other needed information...
499 * let the system fill our this form
501 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
502 if (DeviceInfo == INVALID_HANDLE_VALUE)
505 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
506 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
515 /* Deploy all the information collected into the registry */
516 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
520 str_length * sizeof (char)))
523 /* Install our new class(=device) into the system */
524 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
529 /* This system call tends to take a while (several seconds!) on
530 "modern" Windoze systems */
531 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
534 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
535 NULL)) //reboot required? NEVER!
538 fprintf (stderr, "DEBUG: successfully created a network device\n");
544 * Remove our new virtual interface to use for tunneling.
545 * This function must be called AFTER setup_interface!
547 * @return: TRUE if destruction was successful, else FALSE
552 SP_REMOVEDEVICE_PARAMS remove;
554 if (INVALID_HANDLE_VALUE == DeviceInfo)
557 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
558 remove.HwProfile = 0;
559 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
560 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
562 * 1. Prepare our existing device information set, and place the
563 * uninstall related information into the structure
565 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
566 (PSP_DEVINFO_DATA) & DeviceNode,
567 &remove.ClassInstallHeader,
571 * 2. Uninstall the virtual interface using the class installer
573 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
575 (PSP_DEVINFO_DATA) & DeviceNode))
578 SetupDiDestroyDeviceInfoList (DeviceInfo);
580 fprintf (stderr, "DEBUG: removed interface successfully\n");
587 * Do all the lookup necessary to retrieve the inteface's actual name
590 * @return: TRUE if we were able to lookup the interface's name, else FALSE
593 resolve_interface_name ()
595 SP_DEVINFO_LIST_DETAIL_DATA device_details;
596 char pnp_instance_id [MAX_DEVICE_ID_LEN];
597 HKEY adapter_key_handle;
603 char adapter[] = INTERFACE_REGISTRY_LOCATION;
605 /* We can obtain the PNP instance ID from our setupapi handle */
606 device_details.cbSize = sizeof (device_details);
607 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
608 (PCHAR) pnp_instance_id,
611 NULL)) //hMachine, we are local
614 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
616 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
617 for (retrys = 0; retrys < 120 && !retval; retrys++)
622 /* Now we can use this ID to locate the correct networks interface in registry */
623 if (ERROR_SUCCESS != RegOpenKeyExA (
628 &adapter_key_handle))
631 /* Of course there is a multitude of entries here, with arbitrary names,
632 * thus we need to iterate through there.
636 char instance_key[256];
637 char query_key [256];
638 HKEY instance_key_handle;
639 char pnpinstanceid_name[] = "PnpInstanceID";
640 char pnpinstanceid_value[256];
641 char adaptername_name[] = "Name";
644 len = 256 * sizeof (char);
645 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
646 status = RegEnumKeyExA (
656 /* this may fail due to one of two reasons:
657 * we are at the end of the list*/
658 if (ERROR_NO_MORE_ITEMS == status)
660 // * we found a broken registry key, continue with the next key.
661 if (ERROR_SUCCESS != status)
664 /* prepare our new query string: */
665 snprintf (query_key, 256, "%s\\%s\\Connection",
669 /* look inside instance_key\\Connection */
670 if (ERROR_SUCCESS != RegOpenKeyExA (
675 &instance_key_handle))
678 /* now, read our PnpInstanceID */
679 len = sizeof (pnpinstanceid_value);
680 status = RegQueryValueExA (instance_key_handle,
682 NULL, //reserved, always NULL according to MSDN
684 (LPBYTE) pnpinstanceid_value,
687 if (status != ERROR_SUCCESS || data_type != REG_SZ)
690 /* compare the value we got to our devices PNPInstanceID*/
691 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
692 sizeof (pnpinstanceid_value) / sizeof (char)))
695 len = sizeof (device_visible_name);
696 status = RegQueryValueExA (
699 NULL, //reserved, always NULL according to MSDN
701 (LPBYTE) device_visible_name,
704 if (status != ERROR_SUCCESS || data_type != REG_SZ)
708 * we have successfully found OUR instance,
709 * save the device GUID before exiting
712 strncpy (device_guid, instance_key, 256);
714 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
717 RegCloseKey (instance_key_handle);
722 RegCloseKey (adapter_key_handle);
729 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
731 * @param handle the handle to our tap device
732 * @return TRUE if the version is sufficient, else FALSE
735 check_tapw32_version (HANDLE handle)
739 memset (&(version), 0, sizeof (version));
741 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
742 &version, sizeof (version),
743 &version, sizeof (version), &len, NULL))
744 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
747 (version[2] ? "(DEBUG)" : ""));
749 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
750 (version[1] < TAP_WIN_MIN_MINOR )){
751 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
762 * Creates a tun-interface called dev;
764 * @return the fd to the tun or -1 on error
769 char device_path[256];
772 if (! setup_interface ())
775 return INVALID_HANDLE_VALUE;
778 if (! resolve_interface_name ())
781 return INVALID_HANDLE_VALUE;
784 /* Open Windows TAP-Windows adapter */
785 snprintf (device_path, sizeof (device_path), "%s%s%s",
790 handle = CreateFile (
792 GENERIC_READ | GENERIC_WRITE,
793 0, /* was: FILE_SHARE_READ */
796 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
800 if (INVALID_HANDLE_VALUE == handle)
802 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
806 /* get driver version info */
807 if (! check_tapw32_version (handle))
809 CloseHandle (handle);
810 return INVALID_HANDLE_VALUE;
813 /* TODO (opt?): get MTU-Size */
815 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
821 * Brings a TAP device up and sets it to connected state.
823 * @param handle the handle to our TAP device
824 * @return True if the operation succeeded, else false
827 tun_up (HANDLE handle)
831 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
832 &status, sizeof (status),
833 &status, sizeof (status), &len, NULL))
835 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
839 /* Wait for the device to go UP, might take some time. */
840 Sleep (TAP32_POSTUP_WAITTIME * 1000);
841 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
848 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
851 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
852 * input handle. Then it goes into IOSTATE_QUEUED state.
853 * In case the read succeeded instantly the input facility enters 3.
856 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
857 * If it has finished, go to state 3.
858 * If it has failed, set IOSTATE_FAILED
861 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
862 * The input facility enters state IOSTATE_READY
863 * The output facility enters state IOSTATE_READY
864 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
866 * IOSTATE_WAITING is reset by the output facility, once it has completed.
868 * @param input_facility input named pipe or file to work with.
869 * @param output_facility output pipe or file to hand over data to.
870 * @return false if an event reset was impossible (OS error), else true
873 attempt_read_tap (struct io_facility * input_facility,
874 struct io_facility * output_facility)
876 struct GNUNET_MessageHeader * hdr;
879 switch (input_facility->facility_state)
883 if (! ResetEvent (input_facility->overlapped.hEvent))
888 input_facility->buffer_size = 0;
890 /* Check how the task is handled */
891 if (ReadFile (input_facility->handle,
892 input_facility->buffer,
893 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
894 &input_facility->buffer_size,
895 &input_facility->overlapped))
896 {/* async event processed immediately*/
898 /* reset event manually*/
899 if (! SetEvent (input_facility->overlapped.hEvent))
902 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
904 /* we successfully read something from the TAP and now need to
905 * send it our via STDOUT. Is that possible at the moment? */
906 if ((IOSTATE_READY == output_facility->facility_state ||
907 IOSTATE_WAITING == output_facility->facility_state)
908 && (0 < input_facility->buffer_size))
909 { /* hand over this buffers content and apply message header for gnunet */
910 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
911 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
913 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
914 input_facility->buffer,
915 input_facility->buffer_size);
917 output_facility->buffer_size = size;
918 hdr->size = htons (size);
919 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
920 output_facility->facility_state = IOSTATE_READY;
922 else if (0 < input_facility->buffer_size)
923 /* If we have have read our buffer, wait for our write-partner*/
924 input_facility->facility_state = IOSTATE_WAITING;
926 else /* operation was either queued or failed*/
928 int err = GetLastError ();
929 if (ERROR_IO_PENDING == err)
930 { /* operation queued */
931 input_facility->facility_state = IOSTATE_QUEUED;
934 { /* error occurred, let the rest of the elements finish */
935 input_facility->path_open = FALSE;
936 input_facility->facility_state = IOSTATE_FAILED;
937 if (IOSTATE_WAITING == output_facility->facility_state)
938 output_facility->path_open = FALSE;
940 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
945 // We are queued and should check if the read has finished
948 // there was an operation going on already, check if that has completed now.
950 if (GetOverlappedResult (input_facility->handle,
951 &input_facility->overlapped,
952 &input_facility->buffer_size,
954 {/* successful return for a queued operation */
955 if (! ResetEvent (input_facility->overlapped.hEvent))
958 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
960 /* we successfully read something from the TAP and now need to
961 * send it our via STDOUT. Is that possible at the moment? */
962 if ((IOSTATE_READY == output_facility->facility_state ||
963 IOSTATE_WAITING == output_facility->facility_state)
964 && 0 < input_facility->buffer_size)
965 { /* hand over this buffers content and apply message header for gnunet */
966 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
967 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
969 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
970 input_facility->buffer,
971 input_facility->buffer_size);
973 output_facility->buffer_size = size;
974 hdr->size = htons(size);
975 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
976 output_facility->facility_state = IOSTATE_READY;
977 input_facility->facility_state = IOSTATE_READY;
979 else if (0 < input_facility->buffer_size)
980 { /* If we have have read our buffer, wait for our write-partner*/
981 input_facility->facility_state = IOSTATE_WAITING;
982 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
986 { /* operation still pending/queued or failed? */
987 int err = GetLastError ();
988 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
989 { /* error occurred, let the rest of the elements finish */
990 input_facility->path_open = FALSE;
991 input_facility->facility_state = IOSTATE_FAILED;
992 if (IOSTATE_WAITING == output_facility->facility_state)
993 output_facility->path_open = FALSE;
994 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1000 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1001 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1003 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1004 input_facility->buffer,
1005 input_facility->buffer_size);
1007 output_facility->buffer_size = size;
1008 hdr->size = htons (size);
1009 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1010 output_facility->facility_state = IOSTATE_READY;
1011 input_facility->facility_state = IOSTATE_READY;
1020 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1023 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1024 * input handle. Then it goes into IOSTATE_QUEUED state.
1025 * In case the read succeeded instantly the input facility enters 3.
1028 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1029 * If it has finished, go to state 3.
1030 * If it has failed, set IOSTATE_FAILED
1033 * If the facility is finished with ready
1034 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1035 * The input facility enters state IOSTATE_READY
1036 * The output facility enters state IOSTATE_READY
1037 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1039 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1041 * @param input_facility input named pipe or file to work with.
1042 * @param output_facility output pipe or file to hand over data to.
1043 * @return false if an event reset was impossible (OS error), else true
1046 attempt_read_stdin (struct io_facility * input_facility,
1047 struct io_facility * output_facility)
1049 struct GNUNET_MessageHeader * hdr;
1051 switch (input_facility->facility_state)
1055 input_facility->buffer_size = 0;
1057 partial_read_iostate_ready:
1058 if (! ResetEvent (input_facility->overlapped.hEvent))
1061 /* Check how the task is handled */
1062 if (ReadFile (input_facility->handle,
1063 input_facility->buffer + input_facility->buffer_size,
1064 sizeof (input_facility->buffer) - input_facility->buffer_size,
1065 &input_facility->buffer_size_processed,
1066 &input_facility->overlapped))
1067 {/* async event processed immediately*/
1068 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1070 /* reset event manually*/
1071 if (!SetEvent (input_facility->overlapped.hEvent))
1074 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1075 input_facility->buffer_size += input_facility->buffer_size_processed;
1077 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1078 ntohs (hdr->size) > sizeof (input_facility->buffer))
1080 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1081 input_facility->facility_state = IOSTATE_READY;
1084 /* we got the a part of a packet */
1085 if (ntohs (hdr->size) > input_facility->buffer_size)
1086 goto partial_read_iostate_ready;
1088 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1089 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1090 ((IOSTATE_READY == output_facility->facility_state) ||
1091 (IOSTATE_WAITING == output_facility->facility_state)))
1092 {/* we successfully read something from the TAP and now need to
1093 * send it our via STDOUT. Is that possible at the moment? */
1095 /* hand over this buffers content and strip gnunet message header */
1096 memcpy (output_facility->buffer,
1097 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1098 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1099 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1100 output_facility->facility_state = IOSTATE_READY;
1101 input_facility->facility_state = IOSTATE_READY;
1103 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1104 /* If we have have read our buffer, wait for our write-partner*/
1105 input_facility->facility_state = IOSTATE_WAITING;
1106 else /* we read nothing */
1107 input_facility->facility_state = IOSTATE_READY;
1109 else /* operation was either queued or failed*/
1111 int err = GetLastError ();
1112 if (ERROR_IO_PENDING == err) /* operation queued */
1113 input_facility->facility_state = IOSTATE_QUEUED;
1115 { /* error occurred, let the rest of the elements finish */
1116 input_facility->path_open = FALSE;
1117 input_facility->facility_state = IOSTATE_FAILED;
1118 if (IOSTATE_WAITING == output_facility->facility_state)
1119 output_facility->path_open = FALSE;
1121 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1126 // We are queued and should check if the read has finished
1127 case IOSTATE_QUEUED:
1129 // there was an operation going on already, check if that has completed now.
1130 if (GetOverlappedResult (input_facility->handle,
1131 &input_facility->overlapped,
1132 &input_facility->buffer_size_processed,
1134 {/* successful return for a queued operation */
1135 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1137 if (! ResetEvent (input_facility->overlapped.hEvent))
1140 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1141 input_facility->buffer_size += input_facility->buffer_size_processed;
1143 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1144 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1146 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1147 input_facility->facility_state = IOSTATE_READY;
1150 /* we got the a part of a packet */
1151 if (ntohs (hdr->size) > input_facility->buffer_size );
1152 goto partial_read_iostate_ready;
1154 /* we successfully read something from the TAP and now need to
1155 * send it our via STDOUT. Is that possible at the moment? */
1156 if ((IOSTATE_READY == output_facility->facility_state ||
1157 IOSTATE_WAITING == output_facility->facility_state)
1158 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1159 { /* hand over this buffers content and strip gnunet message header */
1160 memcpy (output_facility->buffer,
1161 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1162 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1163 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1164 output_facility->facility_state = IOSTATE_READY;
1165 input_facility->facility_state = IOSTATE_READY;
1167 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1168 input_facility->facility_state = IOSTATE_WAITING;
1170 input_facility->facility_state = IOSTATE_READY;
1173 { /* operation still pending/queued or failed? */
1174 int err = GetLastError ();
1175 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1176 { /* error occurred, let the rest of the elements finish */
1177 input_facility->path_open = FALSE;
1178 input_facility->facility_state = IOSTATE_FAILED;
1179 if (IOSTATE_WAITING == output_facility->facility_state)
1180 output_facility->path_open = FALSE;
1181 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1186 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1187 memcpy (output_facility->buffer,
1188 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1189 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1190 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1191 output_facility->facility_state = IOSTATE_READY;
1192 input_facility->facility_state = IOSTATE_READY;
1201 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1203 * TODO: high level description
1205 * @param output_facility output pipe or file to hand over data to.
1206 * @param input_facility input named pipe or file to work with.
1207 * @return false if an event reset was impossible (OS error), else true
1210 attempt_write (struct io_facility * output_facility,
1211 struct io_facility * input_facility)
1213 switch (output_facility->facility_state)
1216 output_facility->buffer_size_written = 0;
1218 continue_partial_write:
1219 if (! ResetEvent (output_facility->overlapped.hEvent))
1222 /* Check how the task was handled */
1223 if (WriteFile (output_facility->handle,
1224 output_facility->buffer + output_facility->buffer_size_written,
1225 output_facility->buffer_size - output_facility->buffer_size_written,
1226 &output_facility->buffer_size_processed,
1227 &output_facility->overlapped))
1228 {/* async event processed immediately*/
1230 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1231 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1233 /* reset event manually*/
1234 if (! SetEvent (output_facility->overlapped.hEvent))
1238 if (output_facility->buffer_size_written < output_facility->buffer_size)
1239 goto continue_partial_write;
1241 /* we are now waiting for our buffer to be filled*/
1242 output_facility->facility_state = IOSTATE_WAITING;
1244 /* we successfully wrote something and now need to reset our reader */
1245 if (IOSTATE_WAITING == input_facility->facility_state)
1246 input_facility->facility_state = IOSTATE_RESUME;
1247 else if (IOSTATE_FAILED == input_facility->facility_state)
1248 output_facility->path_open = FALSE;
1250 else /* operation was either queued or failed*/
1252 int err = GetLastError ();
1253 if (ERROR_IO_PENDING == err)
1254 { /* operation queued */
1255 output_facility->facility_state = IOSTATE_QUEUED;
1258 { /* error occurred, close this path */
1259 output_facility->path_open = FALSE;
1260 output_facility->facility_state = IOSTATE_FAILED;
1261 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1265 case IOSTATE_QUEUED:
1266 // there was an operation going on already, check if that has completed now.
1268 if (GetOverlappedResult (output_facility->handle,
1269 &output_facility->overlapped,
1270 &output_facility->buffer_size_processed,
1272 {/* successful return for a queued operation */
1273 if (! ResetEvent (output_facility->overlapped.hEvent))
1276 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1277 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1280 if (output_facility->buffer_size_written < output_facility->buffer_size)
1281 goto continue_partial_write;
1283 /* we are now waiting for our buffer to be filled*/
1284 output_facility->facility_state = IOSTATE_WAITING;
1286 /* we successfully wrote something and now need to reset our reader */
1287 if (IOSTATE_WAITING == input_facility->facility_state)
1288 input_facility->facility_state = IOSTATE_RESUME;
1289 else if (IOSTATE_FAILED == input_facility->facility_state)
1290 output_facility->path_open = FALSE;
1293 { /* operation still pending/queued or failed? */
1294 int err = GetLastError ();
1295 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1296 { /* error occurred, close this path */
1297 output_facility->path_open = FALSE;
1298 output_facility->facility_state = IOSTATE_FAILED;
1299 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1309 * Initialize a overlapped structure
1311 * @param elem the element to initilize
1312 * @param initial_state the initial state for this instance
1313 * @param signaled if the hEvent created should default to signaled or not
1314 * @return true on success, else false
1317 initialize_io_facility (struct io_facility * elem,
1321 elem->path_open = TRUE;
1322 elem->handle = INVALID_HANDLE_VALUE;
1323 elem->facility_state = initial_state;
1324 elem->buffer_size = 0;
1325 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1326 if (NULL == elem->overlapped.hEvent)
1334 * Start forwarding to and from the tunnel.
1336 * @param tap_handle device handle for interacting with the Virtual interface
1339 run (HANDLE tap_handle)
1341 /* IO-Facility for reading from our virtual interface */
1342 struct io_facility tap_read;
1343 /* IO-Facility for writing to our virtual interface */
1344 struct io_facility tap_write;
1345 /* IO-Facility for reading from stdin */
1346 struct io_facility std_in;
1347 /* IO-Facility for writing to stdout */
1348 struct io_facility std_out;
1350 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1351 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1354 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1355 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1357 * DHCP and such are all features we will never use in gnunet afaik.
1358 * But for openvpn those are essential.
1360 if ((privilege_testing) || (! tun_up (tap_handle) ))
1361 goto teardown_final;
1363 /* Initialize our overlapped IO structures*/
1364 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1365 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1366 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1367 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1368 goto teardown_final;
1370 /* Handles for STDIN and STDOUT */
1371 tap_read.handle = tap_handle;
1372 tap_write.handle = tap_handle;
1374 #ifdef DEBUG_TO_CONSOLE
1375 /* Debug output to console STDIN/STDOUT*/
1376 std_in.handle = parent_std_in_handle;
1377 std_out.handle = parent_std_out_handle;
1380 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1382 * Find out the types of our handles.
1383 * This part is a problem, because in windows we need to handle files,
1384 * pipes and the console differently.
1386 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1387 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1389 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1393 std_in.handle = ReOpenFile (parent_std_in_handle,
1395 FILE_SHARE_WRITE | FILE_SHARE_READ,
1396 FILE_FLAG_OVERLAPPED);
1398 if (INVALID_HANDLE_VALUE == std_in.handle)
1400 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1404 std_out.handle = ReOpenFile (parent_std_out_handle,
1407 FILE_FLAG_OVERLAPPED);
1409 if (INVALID_HANDLE_VALUE == std_out.handle)
1411 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1416 fprintf (stderr, "DEBUG: mainloop has begun\n");
1418 while (std_out.path_open || tap_write.path_open)
1420 /* perform READ from stdin if possible */
1421 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1424 /* perform READ from tap if possible */
1425 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1428 /* perform WRITE to tap if possible */
1429 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1432 /* perform WRITE to STDOUT if possible */
1433 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1436 fprintf (stderr, "DEBUG: teardown initiated\n");
1440 CancelIo (tap_handle);
1441 CancelIo (std_in.handle);
1442 CancelIo (std_out.handle);
1446 CloseHandle (tap_handle);
1449 * Open VPN tunnel interface.
1451 * @param argc must be 6
1452 * @param argv 0: binary name ("gnunet-helper-exit")
1453 * 1: tunnel interface name ("gnunet-exit")
1454 * 2: IPv4 "physical" interface name ("eth0"), or "-" to not do IPv4 NAT
1455 * 3: IPv6 address ("::1"), or "-" to skip IPv6
1456 * 4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1457 * 5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1458 * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1461 main (int argc, char **argv)
1463 char hwid[LINE_LEN];
1466 int local_ret = EINVAL;
1467 BOOL have_ip4 = FALSE;
1468 BOOL have_ip6 = FALSE;
1469 BOOL have_nat44 = FALSE;
1471 if ( (1 < argc) && (0 != strcmp (argv[1], "-d"))){
1472 privilege_testing = TRUE;
1473 fprintf (stderr, "DEBUG: Running binary in privilege testing mode.", argv[0]);
1480 fprintf (stderr, "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit [-d] <if name prefix> <uplink-interface name> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n", argv[0]);
1484 strncpy (hwid, argv[1], LINE_LEN);
1485 hwid[LINE_LEN - 1] = '\0';
1488 * We use our PID for finding/resolving the control-panel name of our virtual
1489 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1490 * as additional hardware-id for our device.
1492 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1496 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1498 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1508 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1509 if (0 != strcmp (argv[3], "-"))
1511 char command[LINE_LEN];
1512 const char *address = argv[3];
1513 long prefix_len = atol (argv[4]);
1515 if ((prefix_len < 1) || (prefix_len > 127))
1517 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1522 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1523 if (0 != (global_ret = set_address6 (address, prefix_len)))
1528 /* install our the windows NAT module*/
1529 fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n");
1530 /* outside interface (maybe that's already set) */
1531 snprintf (command, LINE_LEN,
1532 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active",
1534 local_ret = execute_shellcommand (command);
1537 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1540 /* internal interface */
1541 snprintf (command, LINE_LEN,
1542 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active",
1543 device_visible_name);
1544 local_ret = execute_shellcommand (command);
1547 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1550 /* we can keep IPv6 forwarding around, as all interfaces have
1551 * their forwarding mode reset to false at bootup. */
1554 if (0 != strcmp (argv[5], "-"))
1556 const char *address = argv[5];
1557 const char *mask = argv[6];
1559 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1560 if (0 != (global_ret = set_address4 (address, mask)))
1563 // setup NAPT, if possible
1564 /* MS has REMOVED the routing/nat capabilities from Vista+, thus
1565 * we can not setup NAT like in XP or on the server. Actually the
1566 * the only feasible solution seems to be to use
1567 * Internet Connection Sharing, which introduces a horde of problems
1568 * such as sending out rogue-RAs on the external interface in an ipv6
1570 * Thus, below stuff ONLY works on
1572 * Win Server 2003 SP1+
1577 if (0 != strcmp (argv[2], "-"))
1579 char command[LINE_LEN];
1581 /* install our the windows NAT module*/
1582 fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]);
1583 local_ret = execute_shellcommand ("netsh routing ip nat install");
1586 fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret));
1590 snprintf (command, LINE_LEN,
1591 "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/
1593 local_ret = execute_shellcommand (command);
1596 fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret));
1599 /* private/internal/virtual IF */
1600 snprintf (command, LINE_LEN,
1601 "netsh routing ip nat add interface \"%s\" private",
1602 device_visible_name);
1603 local_ret = execute_shellcommand (command);
1606 fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret));
1618 const char *address = argv[5];
1620 char command[LINE_LEN];
1621 fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n");
1622 snprintf(command, LINE_LEN,
1623 "netsh routing ip nat del interface \"%s\"",
1624 device_visible_name);
1625 local_ret = execute_shellcommand(command);
1627 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));
1630 fprintf(stderr, "DEBUG: Removing IP4 address\n");
1631 remove_address4 (address);
1635 const char *address = argv[3];
1636 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1637 remove_address6 (address);
1640 fprintf (stderr, "DEBUG: removing interface\n");
1641 remove_interface ();
1642 fprintf (stderr, "DEBUG: graceful exit completed\n");