2 This file is part of GNUnet.
3 Copyright (C) 2010, 2012 Christian Grothoff
5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License,
8 or (at your 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 Affero General Public License for more details.
15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 * @file exit/gnunet-helper-exit-windows.c
20 * @brief the helper for the EXIT service in win32 builds.
21 * Opens a virtual network-interface, sends data received on the if to stdout,
22 * sends data received on stdin to the interface
23 * @author Christian M. Fuchs
25 * The following list of people have reviewed this code and considered
26 * it safe since the last modification (if you reviewed it, please
27 * have your name added to the list):
35 #ifndef __MINGW64_VERSION_MAJOR
36 #include <ddk/cfgmgr32.h>
37 #include <ddk/newdev.h>
44 #include "tap-windows.h"
46 * Need 'struct GNUNET_HashCode' and 'struct GNUNET_PeerIdentity'.
48 #include "gnunet_crypto_lib.h"
50 * Need 'struct GNUNET_MessageHeader'.
52 #include "gnunet_common.h"
55 * Need VPN message types.
57 #include "gnunet_protocols.h"
60 * Should we print (interesting|debug) messages that can happen during
63 #define DEBUG GNUNET_NO
66 /* FIXME: define with varargs... */
67 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
69 #define LOG_DEBUG(msg) do {} while (0)
73 * Will this binary be run in permissions testing mode?
75 static boolean privilege_testing = FALSE;
78 * Maximum size of a GNUnet message (GNUNET_MAX_MESSAGE_SIZE)
80 #define MAX_SIZE 65536
83 * Name or Path+Name of our win32 driver.
84 * The .sys and .cat files HAVE to be in the same location as this file!
86 #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
89 * Name or Path+Name of our win64 driver.
90 * The .sys and .cat files HAVE to be in the same location as this file!
92 #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
95 * Hardware ID used in the inf-file.
96 * This might change over time, as openvpn advances their driver
98 #define HARDWARE_ID "tap0901"
101 * Minimum major-id of the driver version we can work with
103 #define TAP_WIN_MIN_MAJOR 9
106 * Minimum minor-id of the driver version we can work with.
107 * v <= 7 has buggy IPv6.
108 * v == 8 is broken for small IPv4 Packets
110 #define TAP_WIN_MIN_MINOR 9
113 * Time in seconds to wait for our virtual device to go up after telling it to do so.
115 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
116 * (in fact, 4 was chosen by a fair dice roll...)
118 #define TAP32_POSTUP_WAITTIME 4
121 * Location of the network interface list resides in registry.
123 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
126 * Our local process' PID. Used for creating a sufficiently unique additional
127 * hardware ID for our device.
129 static char secondary_hwid[LINE_LEN / 2];
132 * Device's visible Name, used to identify a network device in netsh.
133 * eg: "Local Area Connection 9"
135 static char device_visible_name[256];
138 * This is our own local instance of a virtual network interface
139 * It is (somewhat) equivalent to using tun/tap in unixoid systems
141 * Upon initialization, we create such an device node.
142 * Upon termination, we remove it again.
144 * If we crash this device might stay around.
146 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
149 * Registry Key we hand over to windows to spawn a new virtual interface
151 static SP_DEVINFO_DATA DeviceNode;
154 * GUID of our virtual device in the form of
155 * {12345678-1234-1234-1234-123456789abc} - in hex
157 static char device_guid[256];
161 * Possible states of an IO facility.
167 * overlapped I/O is ready for work
172 * overlapped I/O has been queued
177 * overlapped I/O has finished, but is waiting for it's write-partner
182 * there is a full buffer waiting
187 * Operlapped IO states for facility objects
188 * overlapped I/O has failed, stop processing
196 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
201 * The mode the state machine associated with this object is in.
203 enum IO_State facility_state;
206 * If the path is open or blocked in general (used for quickly checking)
208 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
211 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
216 * Overlaped IO structure used for asynchronous IO in windows.
218 OVERLAPPED overlapped;
221 * Buffer for reading things to and writing from...
223 unsigned char buffer[MAX_SIZE];
226 * How much of this buffer was used when reading or how much data can be written
231 * Amount of data actually written or read by readfile/writefile.
233 DWORD buffer_size_processed;
236 * How much of this buffer we have written in total
238 DWORD buffer_size_written;
242 * ReOpenFile is only available as of XP SP2 and 2003 SP1
244 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
247 * IsWow64Process definition for our is_win64, as this is a kernel function
249 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
252 * Determines if the host OS is win32 or win64
260 //this is a win64 binary,
262 #elif defined(_WIN32)
263 //this is a 32bit binary, and we need to check if we are running in WOW64
264 BOOL success = FALSE;
265 BOOL on_wow64 = FALSE;
266 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
268 if (NULL != IsWow64Process)
269 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
271 return success && on_wow64;
275 * Wrapper for executing a shellcommand in windows.
277 * @param command - the command + parameters to execute
278 * @return * exitcode of the program executed,
279 * * EINVAL (cmd/file not found)
280 * * EPIPE (could not read STDOUT)
283 execute_shellcommand (const char *command)
287 if ( (NULL == command) ||
288 (NULL == (pipe = _popen (command, "rt"))) )
292 fprintf (stderr, "DEBUG: Command output: \n");
293 char output[LINE_LEN];
294 while (NULL != fgets (output, sizeof (output), pipe))
295 fprintf (stderr, "%s", output);
298 return _pclose (pipe);
303 * @brief Sets the IPv6-Address given in address on the interface dev
305 * @param address the IPv6-Address
306 * @param prefix_len the length of the network-prefix
309 set_address6 (const char *address, unsigned long prefix_len)
312 char command[LINE_LEN];
313 struct sockaddr_in6 sa6;
316 * parse the new address
318 memset (&sa6, 0, sizeof (struct sockaddr_in6));
319 sa6.sin6_family = AF_INET6;
320 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
322 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
328 * prepare the command
330 snprintf (command, LINE_LEN,
331 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
332 device_visible_name, address, prefix_len);
336 ret = execute_shellcommand (command);
340 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
346 * @brief Removes the IPv6-Address given in address from the interface dev
348 * @param address the IPv4-Address
351 remove_address6 (const char *address)
353 char command[LINE_LEN];
356 // sanity checking was already done in set_address6
358 * prepare the command
360 snprintf (command, LINE_LEN,
361 "netsh interface ipv6 delete address \"%s\" store=persistent",
362 device_visible_name);
366 ret = execute_shellcommand (command);
370 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
375 * @brief Sets the IPv4-Address given in address on the interface dev
377 * @param address the IPv4-Address
378 * @param mask the netmask
381 set_address4 (const char *address, const char *mask)
384 char command[LINE_LEN];
386 struct sockaddr_in addr;
387 addr.sin_family = AF_INET;
392 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
394 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
398 // Set Device to Subnet-Mode?
399 // do we really need tun.c:2925 ?
402 * prepare the command
404 snprintf (command, LINE_LEN,
405 "netsh interface ipv4 add address \"%s\" %s %s store=active",
406 device_visible_name, address, mask);
410 ret = execute_shellcommand (command);
414 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
420 * @brief Removes the IPv4-Address given in address from the interface dev
422 * @param address the IPv4-Address
425 remove_address4 (const char *address)
427 char command[LINE_LEN];
430 // sanity checking was already done in set_address4
433 * prepare the command
435 snprintf (command, LINE_LEN,
436 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
437 device_visible_name);
441 ret = execute_shellcommand (command);
445 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
450 * Setup a new virtual interface to use for tunneling.
452 * @return: TRUE if setup was successful, else FALSE
458 * where to find our inf-file. (+ the "full" path, after windows found")
460 * We do not directly input all the props here, because openvpn will update
461 * these details over time.
463 char inf_file_path[MAX_PATH];
464 char * temp_inf_filename;
465 char hwidlist[LINE_LEN + 4];
466 char class_name[128];
471 * Set the device's hardware ID and add it to a list.
472 * This information will later on identify this device in registry.
474 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
476 * this is kind of over-complicated, but allows keeps things independent of
477 * how the openvpn-hwid is actually stored.
479 * A HWID list is double-\0 terminated and \0 separated
481 str_length = strlen (hwidlist) + 1;
482 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
483 str_length += strlen (&hwidlist[str_length]) + 1;
486 * Locate the inf-file, we need to store it somewhere where the system can
487 * find it. We need to pick the correct driver for win32/win64.
490 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
492 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
494 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
496 * Bootstrap our device info using the drivers inf-file
498 if ( ! SetupDiGetINFClassA (inf_file_path,
500 class_name, sizeof (class_name) / sizeof (char),
505 * Collect all the other needed information...
506 * let the system fill our this form
508 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
509 if (DeviceInfo == INVALID_HANDLE_VALUE)
512 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
513 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
522 /* Deploy all the information collected into the registry */
523 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
527 str_length * sizeof (char)))
530 /* Install our new class(=device) into the system */
531 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
536 /* This system call tends to take a while (several seconds!) on
537 "modern" Windoze systems */
538 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
541 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
542 NULL)) //reboot required? NEVER!
545 fprintf (stderr, "DEBUG: successfully created a network device\n");
551 * Remove our new virtual interface to use for tunneling.
552 * This function must be called AFTER setup_interface!
554 * @return: TRUE if destruction was successful, else FALSE
559 SP_REMOVEDEVICE_PARAMS remove;
561 if (INVALID_HANDLE_VALUE == DeviceInfo)
564 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
565 remove.HwProfile = 0;
566 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
567 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
569 * 1. Prepare our existing device information set, and place the
570 * uninstall related information into the structure
572 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
573 (PSP_DEVINFO_DATA) & DeviceNode,
574 &remove.ClassInstallHeader,
578 * 2. Uninstall the virtual interface using the class installer
580 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
582 (PSP_DEVINFO_DATA) & DeviceNode))
585 SetupDiDestroyDeviceInfoList (DeviceInfo);
587 fprintf (stderr, "DEBUG: removed interface successfully\n");
594 * Do all the lookup necessary to retrieve the inteface's actual name
597 * @return: TRUE if we were able to lookup the interface's name, else FALSE
600 resolve_interface_name ()
602 SP_DEVINFO_LIST_DETAIL_DATA device_details;
603 char pnp_instance_id [MAX_DEVICE_ID_LEN];
604 HKEY adapter_key_handle;
610 char adapter[] = INTERFACE_REGISTRY_LOCATION;
612 /* We can obtain the PNP instance ID from our setupapi handle */
613 device_details.cbSize = sizeof (device_details);
614 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
615 (PCHAR) pnp_instance_id,
618 NULL)) //hMachine, we are local
621 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
623 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
624 for (retrys = 0; retrys < 120 && !retval; retrys++)
629 /* Now we can use this ID to locate the correct networks interface in registry */
630 if (ERROR_SUCCESS != RegOpenKeyExA (
635 &adapter_key_handle))
638 /* Of course there is a multitude of entries here, with arbitrary names,
639 * thus we need to iterate through there.
643 char instance_key[256];
644 char query_key [256];
645 HKEY instance_key_handle;
646 char pnpinstanceid_name[] = "PnpInstanceID";
647 char pnpinstanceid_value[256];
648 char adaptername_name[] = "Name";
651 len = 256 * sizeof (char);
652 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
653 status = RegEnumKeyExA (
663 /* this may fail due to one of two reasons:
664 * we are at the end of the list*/
665 if (ERROR_NO_MORE_ITEMS == status)
667 // * we found a broken registry key, continue with the next key.
668 if (ERROR_SUCCESS != status)
671 /* prepare our new query string: */
672 snprintf (query_key, 256, "%s\\%s\\Connection",
676 /* look inside instance_key\\Connection */
677 if (ERROR_SUCCESS != RegOpenKeyExA (
682 &instance_key_handle))
685 /* now, read our PnpInstanceID */
686 len = sizeof (pnpinstanceid_value);
687 status = RegQueryValueExA (instance_key_handle,
689 NULL, //reserved, always NULL according to MSDN
691 (LPBYTE) pnpinstanceid_value,
694 if (status != ERROR_SUCCESS || data_type != REG_SZ)
697 /* compare the value we got to our devices PNPInstanceID*/
698 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
699 sizeof (pnpinstanceid_value) / sizeof (char)))
702 len = sizeof (device_visible_name);
703 status = RegQueryValueExA (
706 NULL, //reserved, always NULL according to MSDN
708 (LPBYTE) device_visible_name,
711 if (status != ERROR_SUCCESS || data_type != REG_SZ)
715 * we have successfully found OUR instance,
716 * save the device GUID before exiting
719 strncpy (device_guid, instance_key, 256);
721 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
724 RegCloseKey (instance_key_handle);
729 RegCloseKey (adapter_key_handle);
736 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
738 * @param handle the handle to our tap device
739 * @return TRUE if the version is sufficient, else FALSE
742 check_tapw32_version (HANDLE handle)
746 memset (&(version), 0, sizeof (version));
748 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
749 &version, sizeof (version),
750 &version, sizeof (version), &len, NULL))
751 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
754 (version[2] ? "(DEBUG)" : ""));
756 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
757 (version[1] < TAP_WIN_MIN_MINOR )){
758 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
769 * Creates a tun-interface called dev;
771 * @return the fd to the tun or -1 on error
776 char device_path[256];
779 if (! setup_interface ())
782 return INVALID_HANDLE_VALUE;
785 if (! resolve_interface_name ())
788 return INVALID_HANDLE_VALUE;
791 /* Open Windows TAP-Windows adapter */
792 snprintf (device_path, sizeof (device_path), "%s%s%s",
797 handle = CreateFile (
799 GENERIC_READ | GENERIC_WRITE,
800 0, /* was: FILE_SHARE_READ */
803 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
807 if (INVALID_HANDLE_VALUE == handle)
809 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
813 /* get driver version info */
814 if (! check_tapw32_version (handle))
816 CloseHandle (handle);
817 return INVALID_HANDLE_VALUE;
820 /* TODO (opt?): get MTU-Size */
822 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
828 * Brings a TAP device up and sets it to connected state.
830 * @param handle the handle to our TAP device
831 * @return True if the operation succeeded, else false
834 tun_up (HANDLE handle)
838 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
839 &status, sizeof (status),
840 &status, sizeof (status), &len, NULL))
842 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
846 /* Wait for the device to go UP, might take some time. */
847 Sleep (TAP32_POSTUP_WAITTIME * 1000);
848 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
855 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
858 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
859 * input handle. Then it goes into IOSTATE_QUEUED state.
860 * In case the read succeeded instantly the input facility enters 3.
863 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
864 * If it has finished, go to state 3.
865 * If it has failed, set IOSTATE_FAILED
868 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
869 * The input facility enters state IOSTATE_READY
870 * The output facility enters state IOSTATE_READY
871 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
873 * IOSTATE_WAITING is reset by the output facility, once it has completed.
875 * @param input_facility input named pipe or file to work with.
876 * @param output_facility output pipe or file to hand over data to.
877 * @return false if an event reset was impossible (OS error), else true
880 attempt_read_tap (struct io_facility * input_facility,
881 struct io_facility * output_facility)
883 struct GNUNET_MessageHeader * hdr;
886 switch (input_facility->facility_state)
890 if (! ResetEvent (input_facility->overlapped.hEvent))
895 input_facility->buffer_size = 0;
897 /* Check how the task is handled */
898 if (ReadFile (input_facility->handle,
899 input_facility->buffer,
900 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
901 &input_facility->buffer_size,
902 &input_facility->overlapped))
903 {/* async event processed immediately*/
905 /* reset event manually*/
906 if (! SetEvent (input_facility->overlapped.hEvent))
909 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
911 /* we successfully read something from the TAP and now need to
912 * send it our via STDOUT. Is that possible at the moment? */
913 if ((IOSTATE_READY == output_facility->facility_state ||
914 IOSTATE_WAITING == output_facility->facility_state)
915 && (0 < input_facility->buffer_size))
916 { /* hand over this buffers content and apply message header for gnunet */
917 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
918 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
920 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
921 input_facility->buffer,
922 input_facility->buffer_size);
924 output_facility->buffer_size = size;
925 hdr->size = htons (size);
926 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
927 output_facility->facility_state = IOSTATE_READY;
929 else if (0 < input_facility->buffer_size)
930 /* If we have have read our buffer, wait for our write-partner*/
931 input_facility->facility_state = IOSTATE_WAITING;
933 else /* operation was either queued or failed*/
935 int err = GetLastError ();
936 if (ERROR_IO_PENDING == err)
937 { /* operation queued */
938 input_facility->facility_state = IOSTATE_QUEUED;
941 { /* error occurred, let the rest of the elements finish */
942 input_facility->path_open = FALSE;
943 input_facility->facility_state = IOSTATE_FAILED;
944 if (IOSTATE_WAITING == output_facility->facility_state)
945 output_facility->path_open = FALSE;
947 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
952 // We are queued and should check if the read has finished
955 // there was an operation going on already, check if that has completed now.
957 if (GetOverlappedResult (input_facility->handle,
958 &input_facility->overlapped,
959 &input_facility->buffer_size,
961 {/* successful return for a queued operation */
962 if (! ResetEvent (input_facility->overlapped.hEvent))
965 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
967 /* we successfully read something from the TAP and now need to
968 * send it our via STDOUT. Is that possible at the moment? */
969 if ((IOSTATE_READY == output_facility->facility_state ||
970 IOSTATE_WAITING == output_facility->facility_state)
971 && 0 < input_facility->buffer_size)
972 { /* hand over this buffers content and apply message header for gnunet */
973 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
974 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
976 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
977 input_facility->buffer,
978 input_facility->buffer_size);
980 output_facility->buffer_size = size;
981 hdr->size = htons(size);
982 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
983 output_facility->facility_state = IOSTATE_READY;
984 input_facility->facility_state = IOSTATE_READY;
986 else if (0 < input_facility->buffer_size)
987 { /* If we have have read our buffer, wait for our write-partner*/
988 input_facility->facility_state = IOSTATE_WAITING;
989 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
993 { /* operation still pending/queued or failed? */
994 int err = GetLastError ();
995 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
996 { /* error occurred, let the rest of the elements finish */
997 input_facility->path_open = FALSE;
998 input_facility->facility_state = IOSTATE_FAILED;
999 if (IOSTATE_WAITING == output_facility->facility_state)
1000 output_facility->path_open = FALSE;
1001 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1006 case IOSTATE_RESUME:
1007 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1008 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1010 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1011 input_facility->buffer,
1012 input_facility->buffer_size);
1014 output_facility->buffer_size = size;
1015 hdr->size = htons (size);
1016 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1017 output_facility->facility_state = IOSTATE_READY;
1018 input_facility->facility_state = IOSTATE_READY;
1027 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1030 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1031 * input handle. Then it goes into IOSTATE_QUEUED state.
1032 * In case the read succeeded instantly the input facility enters 3.
1035 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1036 * If it has finished, go to state 3.
1037 * If it has failed, set IOSTATE_FAILED
1040 * If the facility is finished with ready
1041 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1042 * The input facility enters state IOSTATE_READY
1043 * The output facility enters state IOSTATE_READY
1044 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1046 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1048 * @param input_facility input named pipe or file to work with.
1049 * @param output_facility output pipe or file to hand over data to.
1050 * @return false if an event reset was impossible (OS error), else true
1053 attempt_read_stdin (struct io_facility * input_facility,
1054 struct io_facility * output_facility)
1056 struct GNUNET_MessageHeader * hdr;
1058 switch (input_facility->facility_state)
1062 input_facility->buffer_size = 0;
1064 partial_read_iostate_ready:
1065 if (! ResetEvent (input_facility->overlapped.hEvent))
1068 /* Check how the task is handled */
1069 if (ReadFile (input_facility->handle,
1070 input_facility->buffer + input_facility->buffer_size,
1071 sizeof (input_facility->buffer) - input_facility->buffer_size,
1072 &input_facility->buffer_size_processed,
1073 &input_facility->overlapped))
1074 {/* async event processed immediately*/
1075 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1077 /* reset event manually*/
1078 if (!SetEvent (input_facility->overlapped.hEvent))
1081 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1082 input_facility->buffer_size += input_facility->buffer_size_processed;
1084 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1085 ntohs (hdr->size) > sizeof (input_facility->buffer))
1087 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1088 input_facility->facility_state = IOSTATE_READY;
1091 /* we got the a part of a packet */
1092 if (ntohs (hdr->size) > input_facility->buffer_size)
1093 goto partial_read_iostate_ready;
1095 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1096 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1097 ((IOSTATE_READY == output_facility->facility_state) ||
1098 (IOSTATE_WAITING == output_facility->facility_state)))
1099 {/* we successfully read something from the TAP and now need to
1100 * send it our via STDOUT. Is that possible at the moment? */
1102 /* hand over this buffers content and strip gnunet message header */
1103 GNUNET_memcpy (output_facility->buffer,
1104 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1105 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1106 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1107 output_facility->facility_state = IOSTATE_READY;
1108 input_facility->facility_state = IOSTATE_READY;
1110 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1111 /* If we have have read our buffer, wait for our write-partner*/
1112 input_facility->facility_state = IOSTATE_WAITING;
1113 else /* we read nothing */
1114 input_facility->facility_state = IOSTATE_READY;
1116 else /* operation was either queued or failed*/
1118 int err = GetLastError ();
1119 if (ERROR_IO_PENDING == err) /* operation queued */
1120 input_facility->facility_state = IOSTATE_QUEUED;
1122 { /* error occurred, let the rest of the elements finish */
1123 input_facility->path_open = FALSE;
1124 input_facility->facility_state = IOSTATE_FAILED;
1125 if (IOSTATE_WAITING == output_facility->facility_state)
1126 output_facility->path_open = FALSE;
1128 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1133 // We are queued and should check if the read has finished
1134 case IOSTATE_QUEUED:
1136 // there was an operation going on already, check if that has completed now.
1137 if (GetOverlappedResult (input_facility->handle,
1138 &input_facility->overlapped,
1139 &input_facility->buffer_size_processed,
1141 {/* successful return for a queued operation */
1142 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1144 if (! ResetEvent (input_facility->overlapped.hEvent))
1147 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1148 input_facility->buffer_size += input_facility->buffer_size_processed;
1150 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1151 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1153 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1154 input_facility->facility_state = IOSTATE_READY;
1157 /* we got the a part of a packet */
1158 if (ntohs (hdr->size) > input_facility->buffer_size );
1159 goto partial_read_iostate_ready;
1161 /* we successfully read something from the TAP and now need to
1162 * send it our via STDOUT. Is that possible at the moment? */
1163 if ((IOSTATE_READY == output_facility->facility_state ||
1164 IOSTATE_WAITING == output_facility->facility_state)
1165 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1166 { /* hand over this buffers content and strip gnunet message header */
1167 GNUNET_memcpy (output_facility->buffer,
1168 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1169 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1170 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1171 output_facility->facility_state = IOSTATE_READY;
1172 input_facility->facility_state = IOSTATE_READY;
1174 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1175 input_facility->facility_state = IOSTATE_WAITING;
1177 input_facility->facility_state = IOSTATE_READY;
1180 { /* operation still pending/queued or failed? */
1181 int err = GetLastError ();
1182 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1183 { /* error occurred, let the rest of the elements finish */
1184 input_facility->path_open = FALSE;
1185 input_facility->facility_state = IOSTATE_FAILED;
1186 if (IOSTATE_WAITING == output_facility->facility_state)
1187 output_facility->path_open = FALSE;
1188 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1193 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1194 GNUNET_memcpy (output_facility->buffer,
1195 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1196 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1197 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1198 output_facility->facility_state = IOSTATE_READY;
1199 input_facility->facility_state = IOSTATE_READY;
1208 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1210 * TODO: high level description
1212 * @param output_facility output pipe or file to hand over data to.
1213 * @param input_facility input named pipe or file to work with.
1214 * @return false if an event reset was impossible (OS error), else true
1217 attempt_write (struct io_facility * output_facility,
1218 struct io_facility * input_facility)
1220 switch (output_facility->facility_state)
1223 output_facility->buffer_size_written = 0;
1225 continue_partial_write:
1226 if (! ResetEvent (output_facility->overlapped.hEvent))
1229 /* Check how the task was handled */
1230 if (WriteFile (output_facility->handle,
1231 output_facility->buffer + output_facility->buffer_size_written,
1232 output_facility->buffer_size - output_facility->buffer_size_written,
1233 &output_facility->buffer_size_processed,
1234 &output_facility->overlapped))
1235 {/* async event processed immediately*/
1237 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1238 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1240 /* reset event manually*/
1241 if (! SetEvent (output_facility->overlapped.hEvent))
1245 if (output_facility->buffer_size_written < output_facility->buffer_size)
1246 goto continue_partial_write;
1248 /* we are now waiting for our buffer to be filled*/
1249 output_facility->facility_state = IOSTATE_WAITING;
1251 /* we successfully wrote something and now need to reset our reader */
1252 if (IOSTATE_WAITING == input_facility->facility_state)
1253 input_facility->facility_state = IOSTATE_RESUME;
1254 else if (IOSTATE_FAILED == input_facility->facility_state)
1255 output_facility->path_open = FALSE;
1257 else /* operation was either queued or failed*/
1259 int err = GetLastError ();
1260 if (ERROR_IO_PENDING == err)
1261 { /* operation queued */
1262 output_facility->facility_state = IOSTATE_QUEUED;
1265 { /* error occurred, close this path */
1266 output_facility->path_open = FALSE;
1267 output_facility->facility_state = IOSTATE_FAILED;
1268 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1272 case IOSTATE_QUEUED:
1273 // there was an operation going on already, check if that has completed now.
1275 if (GetOverlappedResult (output_facility->handle,
1276 &output_facility->overlapped,
1277 &output_facility->buffer_size_processed,
1279 {/* successful return for a queued operation */
1280 if (! ResetEvent (output_facility->overlapped.hEvent))
1283 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1284 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1287 if (output_facility->buffer_size_written < output_facility->buffer_size)
1288 goto continue_partial_write;
1290 /* we are now waiting for our buffer to be filled*/
1291 output_facility->facility_state = IOSTATE_WAITING;
1293 /* we successfully wrote something and now need to reset our reader */
1294 if (IOSTATE_WAITING == input_facility->facility_state)
1295 input_facility->facility_state = IOSTATE_RESUME;
1296 else if (IOSTATE_FAILED == input_facility->facility_state)
1297 output_facility->path_open = FALSE;
1300 { /* operation still pending/queued or failed? */
1301 int err = GetLastError ();
1302 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1303 { /* error occurred, close this path */
1304 output_facility->path_open = FALSE;
1305 output_facility->facility_state = IOSTATE_FAILED;
1306 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1316 * Initialize a overlapped structure
1318 * @param elem the element to initilize
1319 * @param initial_state the initial state for this instance
1320 * @param signaled if the hEvent created should default to signaled or not
1321 * @return true on success, else false
1324 initialize_io_facility (struct io_facility * elem,
1328 elem->path_open = TRUE;
1329 elem->handle = INVALID_HANDLE_VALUE;
1330 elem->facility_state = initial_state;
1331 elem->buffer_size = 0;
1332 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1333 if (NULL == elem->overlapped.hEvent)
1341 * Start forwarding to and from the tunnel.
1343 * @param tap_handle device handle for interacting with the Virtual interface
1346 run (HANDLE tap_handle)
1348 /* IO-Facility for reading from our virtual interface */
1349 struct io_facility tap_read;
1350 /* IO-Facility for writing to our virtual interface */
1351 struct io_facility tap_write;
1352 /* IO-Facility for reading from stdin */
1353 struct io_facility std_in;
1354 /* IO-Facility for writing to stdout */
1355 struct io_facility std_out;
1357 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1358 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1361 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1362 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1364 * DHCP and such are all features we will never use in gnunet afaik.
1365 * But for openvpn those are essential.
1367 if ((privilege_testing) || (! tun_up (tap_handle) ))
1368 goto teardown_final;
1370 /* Initialize our overlapped IO structures*/
1371 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1372 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1373 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1374 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1375 goto teardown_final;
1377 /* Handles for STDIN and STDOUT */
1378 tap_read.handle = tap_handle;
1379 tap_write.handle = tap_handle;
1381 #ifdef DEBUG_TO_CONSOLE
1382 /* Debug output to console STDIN/STDOUT*/
1383 std_in.handle = parent_std_in_handle;
1384 std_out.handle = parent_std_out_handle;
1387 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1389 * Find out the types of our handles.
1390 * This part is a problem, because in windows we need to handle files,
1391 * pipes and the console differently.
1393 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1394 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1396 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1400 std_in.handle = ReOpenFile (parent_std_in_handle,
1402 FILE_SHARE_WRITE | FILE_SHARE_READ,
1403 FILE_FLAG_OVERLAPPED);
1405 if (INVALID_HANDLE_VALUE == std_in.handle)
1407 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1411 std_out.handle = ReOpenFile (parent_std_out_handle,
1414 FILE_FLAG_OVERLAPPED);
1416 if (INVALID_HANDLE_VALUE == std_out.handle)
1418 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1423 fprintf (stderr, "DEBUG: mainloop has begun\n");
1425 while (std_out.path_open || tap_write.path_open)
1427 /* perform READ from stdin if possible */
1428 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1431 /* perform READ from tap if possible */
1432 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1435 /* perform WRITE to tap if possible */
1436 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1439 /* perform WRITE to STDOUT if possible */
1440 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1443 fprintf (stderr, "DEBUG: teardown initiated\n");
1447 CancelIo (tap_handle);
1448 CancelIo (std_in.handle);
1449 CancelIo (std_out.handle);
1453 CloseHandle (tap_handle);
1458 * Open VPN tunnel interface.
1460 * @param argc must be 6
1461 * @param argv 0: binary name ("gnunet-helper-exit")
1462 * 1: tunnel interface name ("gnunet-exit")
1463 * 2: IPv4 "physical" interface name ("eth0"), or "-" to not do IPv4 NAT
1464 * 3: IPv6 address ("::1"), or "-" to skip IPv6
1465 * 4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1466 * 5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1467 * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1470 main (int argc, char **argv)
1472 char hwid[LINE_LEN];
1475 int local_ret = EINVAL;
1476 BOOL have_ip4 = FALSE;
1477 BOOL have_ip6 = FALSE;
1478 BOOL have_nat44 = FALSE;
1480 if ( (1 < argc) && (0 != strcmp (argv[1], "-d"))){
1481 privilege_testing = TRUE;
1484 "DEBUG: Running binary in privilege testing mode.");
1493 "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit [-d] <if name prefix> <uplink-interface name> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n");
1497 strncpy (hwid, argv[1], LINE_LEN);
1498 hwid[LINE_LEN - 1] = '\0';
1501 * We use our PID for finding/resolving the control-panel name of our virtual
1502 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1503 * as additional hardware-id for our device.
1505 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1509 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1511 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1521 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1522 if (0 != strcmp (argv[3], "-"))
1524 char command[LINE_LEN];
1525 const char *address = argv[3];
1526 long prefix_len = atol (argv[4]);
1528 if ((prefix_len < 1) || (prefix_len > 127))
1530 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1535 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1536 if (0 != (global_ret = set_address6 (address, prefix_len)))
1541 /* install our the windows NAT module*/
1542 fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n");
1543 /* outside interface (maybe that's already set) */
1544 snprintf (command, LINE_LEN,
1545 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active",
1547 local_ret = execute_shellcommand (command);
1550 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1553 /* internal interface */
1554 snprintf (command, LINE_LEN,
1555 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active",
1556 device_visible_name);
1557 local_ret = execute_shellcommand (command);
1560 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1563 /* we can keep IPv6 forwarding around, as all interfaces have
1564 * their forwarding mode reset to false at bootup. */
1567 if (0 != strcmp (argv[5], "-"))
1569 const char *address = argv[5];
1570 const char *mask = argv[6];
1572 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1573 if (0 != (global_ret = set_address4 (address, mask)))
1576 // setup NAPT, if possible
1577 /* MS has REMOVED the routing/nat capabilities from Vista+, thus
1578 * we can not setup NAT like in XP or on the server. Actually the
1579 * the only feasible solution seems to be to use
1580 * Internet Connection Sharing, which introduces a horde of problems
1581 * such as sending out rogue-RAs on the external interface in an ipv6
1583 * Thus, below stuff ONLY works on
1585 * Win Server 2003 SP1+
1590 if (0 != strcmp (argv[2], "-"))
1592 char command[LINE_LEN];
1594 /* install our the windows NAT module*/
1595 fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]);
1596 local_ret = execute_shellcommand ("netsh routing ip nat install");
1599 fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret));
1603 snprintf (command, LINE_LEN,
1604 "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/
1606 local_ret = execute_shellcommand (command);
1609 fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret));
1612 /* private/internal/virtual IF */
1613 snprintf (command, LINE_LEN,
1614 "netsh routing ip nat add interface \"%s\" private",
1615 device_visible_name);
1616 local_ret = execute_shellcommand (command);
1619 fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret));
1631 const char *address = argv[5];
1633 char command[LINE_LEN];
1634 fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n");
1635 snprintf(command, LINE_LEN,
1636 "netsh routing ip nat del interface \"%s\"",
1637 device_visible_name);
1638 local_ret = execute_shellcommand(command);
1640 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));
1643 fprintf(stderr, "DEBUG: Removing IP4 address\n");
1644 remove_address4 (address);
1648 const char *address = argv[3];
1649 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1650 remove_address6 (address);
1653 fprintf (stderr, "DEBUG: removing interface\n");
1654 remove_interface ();
1655 fprintf (stderr, "DEBUG: graceful exit completed\n");