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 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.
16 * @file exit/gnunet-helper-exit-windows.c
17 * @brief the helper for the EXIT service in win32 builds.
18 * Opens a virtual network-interface, sends data received on the if to stdout,
19 * sends data received on stdin to the interface
20 * @author Christian M. Fuchs
22 * The following list of people have reviewed this code and considered
23 * it safe since the last modification (if you reviewed it, please
24 * have your name added to the list):
32 #ifndef __MINGW64_VERSION_MAJOR
33 #include <ddk/cfgmgr32.h>
34 #include <ddk/newdev.h>
41 #include "tap-windows.h"
43 * Need 'struct GNUNET_HashCode' and 'struct GNUNET_PeerIdentity'.
45 #include "gnunet_crypto_lib.h"
47 * Need 'struct GNUNET_MessageHeader'.
49 #include "gnunet_common.h"
52 * Need VPN message types.
54 #include "gnunet_protocols.h"
57 * Should we print (interesting|debug) messages that can happen during
60 #define DEBUG GNUNET_NO
63 /* FIXME: define with varargs... */
64 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
66 #define LOG_DEBUG(msg) do {} while (0)
70 * Will this binary be run in permissions testing mode?
72 static boolean privilege_testing = FALSE;
75 * Maximum size of a GNUnet message (GNUNET_MAX_MESSAGE_SIZE)
77 #define MAX_SIZE 65536
80 * Name or Path+Name of our win32 driver.
81 * The .sys and .cat files HAVE to be in the same location as this file!
83 #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
86 * Name or Path+Name of our win64 driver.
87 * The .sys and .cat files HAVE to be in the same location as this file!
89 #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
92 * Hardware ID used in the inf-file.
93 * This might change over time, as openvpn advances their driver
95 #define HARDWARE_ID "tap0901"
98 * Minimum major-id of the driver version we can work with
100 #define TAP_WIN_MIN_MAJOR 9
103 * Minimum minor-id of the driver version we can work with.
104 * v <= 7 has buggy IPv6.
105 * v == 8 is broken for small IPv4 Packets
107 #define TAP_WIN_MIN_MINOR 9
110 * Time in seconds to wait for our virtual device to go up after telling it to do so.
112 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
113 * (in fact, 4 was chosen by a fair dice roll...)
115 #define TAP32_POSTUP_WAITTIME 4
118 * Location of the network interface list resides in registry.
120 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
123 * Our local process' PID. Used for creating a sufficiently unique additional
124 * hardware ID for our device.
126 static char secondary_hwid[LINE_LEN / 2];
129 * Device's visible Name, used to identify a network device in netsh.
130 * eg: "Local Area Connection 9"
132 static char device_visible_name[256];
135 * This is our own local instance of a virtual network interface
136 * It is (somewhat) equivalent to using tun/tap in unixoid systems
138 * Upon initialization, we create such an device node.
139 * Upon termination, we remove it again.
141 * If we crash this device might stay around.
143 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
146 * Registry Key we hand over to windows to spawn a new virtual interface
148 static SP_DEVINFO_DATA DeviceNode;
151 * GUID of our virtual device in the form of
152 * {12345678-1234-1234-1234-123456789abc} - in hex
154 static char device_guid[256];
158 * Possible states of an IO facility.
164 * overlapped I/O is ready for work
169 * overlapped I/O has been queued
174 * overlapped I/O has finished, but is waiting for it's write-partner
179 * there is a full buffer waiting
184 * Operlapped IO states for facility objects
185 * overlapped I/O has failed, stop processing
193 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
198 * The mode the state machine associated with this object is in.
200 enum IO_State facility_state;
203 * If the path is open or blocked in general (used for quickly checking)
205 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
208 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
213 * Overlaped IO structure used for asynchronous IO in windows.
215 OVERLAPPED overlapped;
218 * Buffer for reading things to and writing from...
220 unsigned char buffer[MAX_SIZE];
223 * How much of this buffer was used when reading or how much data can be written
228 * Amount of data actually written or read by readfile/writefile.
230 DWORD buffer_size_processed;
233 * How much of this buffer we have written in total
235 DWORD buffer_size_written;
239 * ReOpenFile is only available as of XP SP2 and 2003 SP1
241 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
244 * IsWow64Process definition for our is_win64, as this is a kernel function
246 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
249 * Determines if the host OS is win32 or win64
257 //this is a win64 binary,
259 #elif defined(_WIN32)
260 //this is a 32bit binary, and we need to check if we are running in WOW64
261 BOOL success = FALSE;
262 BOOL on_wow64 = FALSE;
263 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
265 if (NULL != IsWow64Process)
266 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
268 return success && on_wow64;
272 * Wrapper for executing a shellcommand in windows.
274 * @param command - the command + parameters to execute
275 * @return * exitcode of the program executed,
276 * * EINVAL (cmd/file not found)
277 * * EPIPE (could not read STDOUT)
280 execute_shellcommand (const char *command)
284 if ( (NULL == command) ||
285 (NULL == (pipe = _popen (command, "rt"))) )
289 fprintf (stderr, "DEBUG: Command output: \n");
290 char output[LINE_LEN];
291 while (NULL != fgets (output, sizeof (output), pipe))
292 fprintf (stderr, "%s", output);
295 return _pclose (pipe);
300 * @brief Sets the IPv6-Address given in address on the interface dev
302 * @param address the IPv6-Address
303 * @param prefix_len the length of the network-prefix
306 set_address6 (const char *address, unsigned long prefix_len)
309 char command[LINE_LEN];
310 struct sockaddr_in6 sa6;
313 * parse the new address
315 memset (&sa6, 0, sizeof (struct sockaddr_in6));
316 sa6.sin6_family = AF_INET6;
317 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
319 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
325 * prepare the command
327 snprintf (command, LINE_LEN,
328 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
329 device_visible_name, address, prefix_len);
333 ret = execute_shellcommand (command);
337 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
343 * @brief Removes the IPv6-Address given in address from the interface dev
345 * @param address the IPv4-Address
348 remove_address6 (const char *address)
350 char command[LINE_LEN];
353 // sanity checking was already done in set_address6
355 * prepare the command
357 snprintf (command, LINE_LEN,
358 "netsh interface ipv6 delete address \"%s\" store=persistent",
359 device_visible_name);
363 ret = execute_shellcommand (command);
367 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
372 * @brief Sets the IPv4-Address given in address on the interface dev
374 * @param address the IPv4-Address
375 * @param mask the netmask
378 set_address4 (const char *address, const char *mask)
381 char command[LINE_LEN];
383 struct sockaddr_in addr;
384 addr.sin_family = AF_INET;
389 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
391 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
395 // Set Device to Subnet-Mode?
396 // do we really need tun.c:2925 ?
399 * prepare the command
401 snprintf (command, LINE_LEN,
402 "netsh interface ipv4 add address \"%s\" %s %s store=active",
403 device_visible_name, address, mask);
407 ret = execute_shellcommand (command);
411 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
417 * @brief Removes the IPv4-Address given in address from the interface dev
419 * @param address the IPv4-Address
422 remove_address4 (const char *address)
424 char command[LINE_LEN];
427 // sanity checking was already done in set_address4
430 * prepare the command
432 snprintf (command, LINE_LEN,
433 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
434 device_visible_name);
438 ret = execute_shellcommand (command);
442 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
447 * Setup a new virtual interface to use for tunneling.
449 * @return: TRUE if setup was successful, else FALSE
455 * where to find our inf-file. (+ the "full" path, after windows found")
457 * We do not directly input all the props here, because openvpn will update
458 * these details over time.
460 char inf_file_path[MAX_PATH];
461 char * temp_inf_filename;
462 char hwidlist[LINE_LEN + 4];
463 char class_name[128];
468 * Set the device's hardware ID and add it to a list.
469 * This information will later on identify this device in registry.
471 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
473 * this is kind of over-complicated, but allows keeps things independent of
474 * how the openvpn-hwid is actually stored.
476 * A HWID list is double-\0 terminated and \0 separated
478 str_length = strlen (hwidlist) + 1;
479 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
480 str_length += strlen (&hwidlist[str_length]) + 1;
483 * Locate the inf-file, we need to store it somewhere where the system can
484 * find it. We need to pick the correct driver for win32/win64.
487 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
489 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
491 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
493 * Bootstrap our device info using the drivers inf-file
495 if ( ! SetupDiGetINFClassA (inf_file_path,
497 class_name, sizeof (class_name) / sizeof (char),
502 * Collect all the other needed information...
503 * let the system fill our this form
505 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
506 if (DeviceInfo == INVALID_HANDLE_VALUE)
509 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
510 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
519 /* Deploy all the information collected into the registry */
520 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
524 str_length * sizeof (char)))
527 /* Install our new class(=device) into the system */
528 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
533 /* This system call tends to take a while (several seconds!) on
534 "modern" Windoze systems */
535 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
538 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
539 NULL)) //reboot required? NEVER!
542 fprintf (stderr, "DEBUG: successfully created a network device\n");
548 * Remove our new virtual interface to use for tunneling.
549 * This function must be called AFTER setup_interface!
551 * @return: TRUE if destruction was successful, else FALSE
556 SP_REMOVEDEVICE_PARAMS remove;
558 if (INVALID_HANDLE_VALUE == DeviceInfo)
561 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
562 remove.HwProfile = 0;
563 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
564 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
566 * 1. Prepare our existing device information set, and place the
567 * uninstall related information into the structure
569 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
570 (PSP_DEVINFO_DATA) & DeviceNode,
571 &remove.ClassInstallHeader,
575 * 2. Uninstall the virtual interface using the class installer
577 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
579 (PSP_DEVINFO_DATA) & DeviceNode))
582 SetupDiDestroyDeviceInfoList (DeviceInfo);
584 fprintf (stderr, "DEBUG: removed interface successfully\n");
591 * Do all the lookup necessary to retrieve the inteface's actual name
594 * @return: TRUE if we were able to lookup the interface's name, else FALSE
597 resolve_interface_name ()
599 SP_DEVINFO_LIST_DETAIL_DATA device_details;
600 char pnp_instance_id [MAX_DEVICE_ID_LEN];
601 HKEY adapter_key_handle;
607 char adapter[] = INTERFACE_REGISTRY_LOCATION;
609 /* We can obtain the PNP instance ID from our setupapi handle */
610 device_details.cbSize = sizeof (device_details);
611 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
612 (PCHAR) pnp_instance_id,
615 NULL)) //hMachine, we are local
618 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
620 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
621 for (retrys = 0; retrys < 120 && !retval; retrys++)
626 /* Now we can use this ID to locate the correct networks interface in registry */
627 if (ERROR_SUCCESS != RegOpenKeyExA (
632 &adapter_key_handle))
635 /* Of course there is a multitude of entries here, with arbitrary names,
636 * thus we need to iterate through there.
640 char instance_key[256];
641 char query_key [256];
642 HKEY instance_key_handle;
643 char pnpinstanceid_name[] = "PnpInstanceID";
644 char pnpinstanceid_value[256];
645 char adaptername_name[] = "Name";
648 len = 256 * sizeof (char);
649 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
650 status = RegEnumKeyExA (
660 /* this may fail due to one of two reasons:
661 * we are at the end of the list*/
662 if (ERROR_NO_MORE_ITEMS == status)
664 // * we found a broken registry key, continue with the next key.
665 if (ERROR_SUCCESS != status)
668 /* prepare our new query string: */
669 snprintf (query_key, 256, "%s\\%s\\Connection",
673 /* look inside instance_key\\Connection */
674 if (ERROR_SUCCESS != RegOpenKeyExA (
679 &instance_key_handle))
682 /* now, read our PnpInstanceID */
683 len = sizeof (pnpinstanceid_value);
684 status = RegQueryValueExA (instance_key_handle,
686 NULL, //reserved, always NULL according to MSDN
688 (LPBYTE) pnpinstanceid_value,
691 if (status != ERROR_SUCCESS || data_type != REG_SZ)
694 /* compare the value we got to our devices PNPInstanceID*/
695 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
696 sizeof (pnpinstanceid_value) / sizeof (char)))
699 len = sizeof (device_visible_name);
700 status = RegQueryValueExA (
703 NULL, //reserved, always NULL according to MSDN
705 (LPBYTE) device_visible_name,
708 if (status != ERROR_SUCCESS || data_type != REG_SZ)
712 * we have successfully found OUR instance,
713 * save the device GUID before exiting
716 strncpy (device_guid, instance_key, 256);
718 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
721 RegCloseKey (instance_key_handle);
726 RegCloseKey (adapter_key_handle);
733 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
735 * @param handle the handle to our tap device
736 * @return TRUE if the version is sufficient, else FALSE
739 check_tapw32_version (HANDLE handle)
743 memset (&(version), 0, sizeof (version));
745 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
746 &version, sizeof (version),
747 &version, sizeof (version), &len, NULL))
748 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
751 (version[2] ? "(DEBUG)" : ""));
753 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
754 (version[1] < TAP_WIN_MIN_MINOR )){
755 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
766 * Creates a tun-interface called dev;
768 * @return the fd to the tun or -1 on error
773 char device_path[256];
776 if (! setup_interface ())
779 return INVALID_HANDLE_VALUE;
782 if (! resolve_interface_name ())
785 return INVALID_HANDLE_VALUE;
788 /* Open Windows TAP-Windows adapter */
789 snprintf (device_path, sizeof (device_path), "%s%s%s",
794 handle = CreateFile (
796 GENERIC_READ | GENERIC_WRITE,
797 0, /* was: FILE_SHARE_READ */
800 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
804 if (INVALID_HANDLE_VALUE == handle)
806 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
810 /* get driver version info */
811 if (! check_tapw32_version (handle))
813 CloseHandle (handle);
814 return INVALID_HANDLE_VALUE;
817 /* TODO (opt?): get MTU-Size */
819 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
825 * Brings a TAP device up and sets it to connected state.
827 * @param handle the handle to our TAP device
828 * @return True if the operation succeeded, else false
831 tun_up (HANDLE handle)
835 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
836 &status, sizeof (status),
837 &status, sizeof (status), &len, NULL))
839 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
843 /* Wait for the device to go UP, might take some time. */
844 Sleep (TAP32_POSTUP_WAITTIME * 1000);
845 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
852 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
855 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
856 * input handle. Then it goes into IOSTATE_QUEUED state.
857 * In case the read succeeded instantly the input facility enters 3.
860 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
861 * If it has finished, go to state 3.
862 * If it has failed, set IOSTATE_FAILED
865 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
866 * The input facility enters state IOSTATE_READY
867 * The output facility enters state IOSTATE_READY
868 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
870 * IOSTATE_WAITING is reset by the output facility, once it has completed.
872 * @param input_facility input named pipe or file to work with.
873 * @param output_facility output pipe or file to hand over data to.
874 * @return false if an event reset was impossible (OS error), else true
877 attempt_read_tap (struct io_facility * input_facility,
878 struct io_facility * output_facility)
880 struct GNUNET_MessageHeader * hdr;
883 switch (input_facility->facility_state)
887 if (! ResetEvent (input_facility->overlapped.hEvent))
892 input_facility->buffer_size = 0;
894 /* Check how the task is handled */
895 if (ReadFile (input_facility->handle,
896 input_facility->buffer,
897 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
898 &input_facility->buffer_size,
899 &input_facility->overlapped))
900 {/* async event processed immediately*/
902 /* reset event manually*/
903 if (! SetEvent (input_facility->overlapped.hEvent))
906 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
908 /* we successfully read something from the TAP and now need to
909 * send it our via STDOUT. Is that possible at the moment? */
910 if ((IOSTATE_READY == output_facility->facility_state ||
911 IOSTATE_WAITING == output_facility->facility_state)
912 && (0 < input_facility->buffer_size))
913 { /* hand over this buffers content and apply message header for gnunet */
914 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
915 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
917 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
918 input_facility->buffer,
919 input_facility->buffer_size);
921 output_facility->buffer_size = size;
922 hdr->size = htons (size);
923 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
924 output_facility->facility_state = IOSTATE_READY;
926 else if (0 < input_facility->buffer_size)
927 /* If we have have read our buffer, wait for our write-partner*/
928 input_facility->facility_state = IOSTATE_WAITING;
930 else /* operation was either queued or failed*/
932 int err = GetLastError ();
933 if (ERROR_IO_PENDING == err)
934 { /* operation queued */
935 input_facility->facility_state = IOSTATE_QUEUED;
938 { /* error occurred, let the rest of the elements finish */
939 input_facility->path_open = FALSE;
940 input_facility->facility_state = IOSTATE_FAILED;
941 if (IOSTATE_WAITING == output_facility->facility_state)
942 output_facility->path_open = FALSE;
944 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
949 // We are queued and should check if the read has finished
952 // there was an operation going on already, check if that has completed now.
954 if (GetOverlappedResult (input_facility->handle,
955 &input_facility->overlapped,
956 &input_facility->buffer_size,
958 {/* successful return for a queued operation */
959 if (! ResetEvent (input_facility->overlapped.hEvent))
962 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
964 /* we successfully read something from the TAP and now need to
965 * send it our via STDOUT. Is that possible at the moment? */
966 if ((IOSTATE_READY == output_facility->facility_state ||
967 IOSTATE_WAITING == output_facility->facility_state)
968 && 0 < input_facility->buffer_size)
969 { /* hand over this buffers content and apply message header for gnunet */
970 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
971 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
973 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
974 input_facility->buffer,
975 input_facility->buffer_size);
977 output_facility->buffer_size = size;
978 hdr->size = htons(size);
979 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
980 output_facility->facility_state = IOSTATE_READY;
981 input_facility->facility_state = IOSTATE_READY;
983 else if (0 < input_facility->buffer_size)
984 { /* If we have have read our buffer, wait for our write-partner*/
985 input_facility->facility_state = IOSTATE_WAITING;
986 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
990 { /* operation still pending/queued or failed? */
991 int err = GetLastError ();
992 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
993 { /* error occurred, let the rest of the elements finish */
994 input_facility->path_open = FALSE;
995 input_facility->facility_state = IOSTATE_FAILED;
996 if (IOSTATE_WAITING == output_facility->facility_state)
997 output_facility->path_open = FALSE;
998 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1003 case IOSTATE_RESUME:
1004 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1005 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1007 GNUNET_memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1008 input_facility->buffer,
1009 input_facility->buffer_size);
1011 output_facility->buffer_size = size;
1012 hdr->size = htons (size);
1013 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1014 output_facility->facility_state = IOSTATE_READY;
1015 input_facility->facility_state = IOSTATE_READY;
1024 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1027 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1028 * input handle. Then it goes into IOSTATE_QUEUED state.
1029 * In case the read succeeded instantly the input facility enters 3.
1032 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1033 * If it has finished, go to state 3.
1034 * If it has failed, set IOSTATE_FAILED
1037 * If the facility is finished with ready
1038 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1039 * The input facility enters state IOSTATE_READY
1040 * The output facility enters state IOSTATE_READY
1041 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1043 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1045 * @param input_facility input named pipe or file to work with.
1046 * @param output_facility output pipe or file to hand over data to.
1047 * @return false if an event reset was impossible (OS error), else true
1050 attempt_read_stdin (struct io_facility * input_facility,
1051 struct io_facility * output_facility)
1053 struct GNUNET_MessageHeader * hdr;
1055 switch (input_facility->facility_state)
1059 input_facility->buffer_size = 0;
1061 partial_read_iostate_ready:
1062 if (! ResetEvent (input_facility->overlapped.hEvent))
1065 /* Check how the task is handled */
1066 if (ReadFile (input_facility->handle,
1067 input_facility->buffer + input_facility->buffer_size,
1068 sizeof (input_facility->buffer) - input_facility->buffer_size,
1069 &input_facility->buffer_size_processed,
1070 &input_facility->overlapped))
1071 {/* async event processed immediately*/
1072 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1074 /* reset event manually*/
1075 if (!SetEvent (input_facility->overlapped.hEvent))
1078 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1079 input_facility->buffer_size += input_facility->buffer_size_processed;
1081 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1082 ntohs (hdr->size) > sizeof (input_facility->buffer))
1084 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1085 input_facility->facility_state = IOSTATE_READY;
1088 /* we got the a part of a packet */
1089 if (ntohs (hdr->size) > input_facility->buffer_size)
1090 goto partial_read_iostate_ready;
1092 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1093 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1094 ((IOSTATE_READY == output_facility->facility_state) ||
1095 (IOSTATE_WAITING == output_facility->facility_state)))
1096 {/* we successfully read something from the TAP and now need to
1097 * send it our via STDOUT. Is that possible at the moment? */
1099 /* hand over this buffers content and strip gnunet message header */
1100 GNUNET_memcpy (output_facility->buffer,
1101 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1102 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1103 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1104 output_facility->facility_state = IOSTATE_READY;
1105 input_facility->facility_state = IOSTATE_READY;
1107 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1108 /* If we have have read our buffer, wait for our write-partner*/
1109 input_facility->facility_state = IOSTATE_WAITING;
1110 else /* we read nothing */
1111 input_facility->facility_state = IOSTATE_READY;
1113 else /* operation was either queued or failed*/
1115 int err = GetLastError ();
1116 if (ERROR_IO_PENDING == err) /* operation queued */
1117 input_facility->facility_state = IOSTATE_QUEUED;
1119 { /* error occurred, let the rest of the elements finish */
1120 input_facility->path_open = FALSE;
1121 input_facility->facility_state = IOSTATE_FAILED;
1122 if (IOSTATE_WAITING == output_facility->facility_state)
1123 output_facility->path_open = FALSE;
1125 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1130 // We are queued and should check if the read has finished
1131 case IOSTATE_QUEUED:
1133 // there was an operation going on already, check if that has completed now.
1134 if (GetOverlappedResult (input_facility->handle,
1135 &input_facility->overlapped,
1136 &input_facility->buffer_size_processed,
1138 {/* successful return for a queued operation */
1139 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1141 if (! ResetEvent (input_facility->overlapped.hEvent))
1144 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1145 input_facility->buffer_size += input_facility->buffer_size_processed;
1147 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1148 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1150 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1151 input_facility->facility_state = IOSTATE_READY;
1154 /* we got the a part of a packet */
1155 if (ntohs (hdr->size) > input_facility->buffer_size );
1156 goto partial_read_iostate_ready;
1158 /* we successfully read something from the TAP and now need to
1159 * send it our via STDOUT. Is that possible at the moment? */
1160 if ((IOSTATE_READY == output_facility->facility_state ||
1161 IOSTATE_WAITING == output_facility->facility_state)
1162 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1163 { /* hand over this buffers content and strip gnunet message header */
1164 GNUNET_memcpy (output_facility->buffer,
1165 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1166 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1167 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1168 output_facility->facility_state = IOSTATE_READY;
1169 input_facility->facility_state = IOSTATE_READY;
1171 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1172 input_facility->facility_state = IOSTATE_WAITING;
1174 input_facility->facility_state = IOSTATE_READY;
1177 { /* operation still pending/queued or failed? */
1178 int err = GetLastError ();
1179 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1180 { /* error occurred, let the rest of the elements finish */
1181 input_facility->path_open = FALSE;
1182 input_facility->facility_state = IOSTATE_FAILED;
1183 if (IOSTATE_WAITING == output_facility->facility_state)
1184 output_facility->path_open = FALSE;
1185 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1190 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1191 GNUNET_memcpy (output_facility->buffer,
1192 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1193 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1194 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1195 output_facility->facility_state = IOSTATE_READY;
1196 input_facility->facility_state = IOSTATE_READY;
1205 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1207 * TODO: high level description
1209 * @param output_facility output pipe or file to hand over data to.
1210 * @param input_facility input named pipe or file to work with.
1211 * @return false if an event reset was impossible (OS error), else true
1214 attempt_write (struct io_facility * output_facility,
1215 struct io_facility * input_facility)
1217 switch (output_facility->facility_state)
1220 output_facility->buffer_size_written = 0;
1222 continue_partial_write:
1223 if (! ResetEvent (output_facility->overlapped.hEvent))
1226 /* Check how the task was handled */
1227 if (WriteFile (output_facility->handle,
1228 output_facility->buffer + output_facility->buffer_size_written,
1229 output_facility->buffer_size - output_facility->buffer_size_written,
1230 &output_facility->buffer_size_processed,
1231 &output_facility->overlapped))
1232 {/* async event processed immediately*/
1234 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1235 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1237 /* reset event manually*/
1238 if (! SetEvent (output_facility->overlapped.hEvent))
1242 if (output_facility->buffer_size_written < output_facility->buffer_size)
1243 goto continue_partial_write;
1245 /* we are now waiting for our buffer to be filled*/
1246 output_facility->facility_state = IOSTATE_WAITING;
1248 /* we successfully wrote something and now need to reset our reader */
1249 if (IOSTATE_WAITING == input_facility->facility_state)
1250 input_facility->facility_state = IOSTATE_RESUME;
1251 else if (IOSTATE_FAILED == input_facility->facility_state)
1252 output_facility->path_open = FALSE;
1254 else /* operation was either queued or failed*/
1256 int err = GetLastError ();
1257 if (ERROR_IO_PENDING == err)
1258 { /* operation queued */
1259 output_facility->facility_state = IOSTATE_QUEUED;
1262 { /* error occurred, close this path */
1263 output_facility->path_open = FALSE;
1264 output_facility->facility_state = IOSTATE_FAILED;
1265 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1269 case IOSTATE_QUEUED:
1270 // there was an operation going on already, check if that has completed now.
1272 if (GetOverlappedResult (output_facility->handle,
1273 &output_facility->overlapped,
1274 &output_facility->buffer_size_processed,
1276 {/* successful return for a queued operation */
1277 if (! ResetEvent (output_facility->overlapped.hEvent))
1280 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1281 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1284 if (output_facility->buffer_size_written < output_facility->buffer_size)
1285 goto continue_partial_write;
1287 /* we are now waiting for our buffer to be filled*/
1288 output_facility->facility_state = IOSTATE_WAITING;
1290 /* we successfully wrote something and now need to reset our reader */
1291 if (IOSTATE_WAITING == input_facility->facility_state)
1292 input_facility->facility_state = IOSTATE_RESUME;
1293 else if (IOSTATE_FAILED == input_facility->facility_state)
1294 output_facility->path_open = FALSE;
1297 { /* operation still pending/queued or failed? */
1298 int err = GetLastError ();
1299 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1300 { /* error occurred, close this path */
1301 output_facility->path_open = FALSE;
1302 output_facility->facility_state = IOSTATE_FAILED;
1303 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1313 * Initialize a overlapped structure
1315 * @param elem the element to initilize
1316 * @param initial_state the initial state for this instance
1317 * @param signaled if the hEvent created should default to signaled or not
1318 * @return true on success, else false
1321 initialize_io_facility (struct io_facility * elem,
1325 elem->path_open = TRUE;
1326 elem->handle = INVALID_HANDLE_VALUE;
1327 elem->facility_state = initial_state;
1328 elem->buffer_size = 0;
1329 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1330 if (NULL == elem->overlapped.hEvent)
1338 * Start forwarding to and from the tunnel.
1340 * @param tap_handle device handle for interacting with the Virtual interface
1343 run (HANDLE tap_handle)
1345 /* IO-Facility for reading from our virtual interface */
1346 struct io_facility tap_read;
1347 /* IO-Facility for writing to our virtual interface */
1348 struct io_facility tap_write;
1349 /* IO-Facility for reading from stdin */
1350 struct io_facility std_in;
1351 /* IO-Facility for writing to stdout */
1352 struct io_facility std_out;
1354 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1355 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1358 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1359 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1361 * DHCP and such are all features we will never use in gnunet afaik.
1362 * But for openvpn those are essential.
1364 if ((privilege_testing) || (! tun_up (tap_handle) ))
1365 goto teardown_final;
1367 /* Initialize our overlapped IO structures*/
1368 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1369 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1370 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1371 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1372 goto teardown_final;
1374 /* Handles for STDIN and STDOUT */
1375 tap_read.handle = tap_handle;
1376 tap_write.handle = tap_handle;
1378 #ifdef DEBUG_TO_CONSOLE
1379 /* Debug output to console STDIN/STDOUT*/
1380 std_in.handle = parent_std_in_handle;
1381 std_out.handle = parent_std_out_handle;
1384 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1386 * Find out the types of our handles.
1387 * This part is a problem, because in windows we need to handle files,
1388 * pipes and the console differently.
1390 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1391 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1393 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1397 std_in.handle = ReOpenFile (parent_std_in_handle,
1399 FILE_SHARE_WRITE | FILE_SHARE_READ,
1400 FILE_FLAG_OVERLAPPED);
1402 if (INVALID_HANDLE_VALUE == std_in.handle)
1404 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1408 std_out.handle = ReOpenFile (parent_std_out_handle,
1411 FILE_FLAG_OVERLAPPED);
1413 if (INVALID_HANDLE_VALUE == std_out.handle)
1415 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1420 fprintf (stderr, "DEBUG: mainloop has begun\n");
1422 while (std_out.path_open || tap_write.path_open)
1424 /* perform READ from stdin if possible */
1425 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1428 /* perform READ from tap if possible */
1429 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1432 /* perform WRITE to tap if possible */
1433 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1436 /* perform WRITE to STDOUT if possible */
1437 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1440 fprintf (stderr, "DEBUG: teardown initiated\n");
1444 CancelIo (tap_handle);
1445 CancelIo (std_in.handle);
1446 CancelIo (std_out.handle);
1450 CloseHandle (tap_handle);
1455 * Open VPN tunnel interface.
1457 * @param argc must be 6
1458 * @param argv 0: binary name ("gnunet-helper-exit")
1459 * 1: tunnel interface name ("gnunet-exit")
1460 * 2: IPv4 "physical" interface name ("eth0"), or "-" to not do IPv4 NAT
1461 * 3: IPv6 address ("::1"), or "-" to skip IPv6
1462 * 4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1463 * 5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1464 * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1467 main (int argc, char **argv)
1469 char hwid[LINE_LEN];
1472 int local_ret = EINVAL;
1473 BOOL have_ip4 = FALSE;
1474 BOOL have_ip6 = FALSE;
1475 BOOL have_nat44 = FALSE;
1477 if ( (1 < argc) && (0 != strcmp (argv[1], "-d"))){
1478 privilege_testing = TRUE;
1481 "DEBUG: Running binary in privilege testing mode.");
1490 "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit [-d] <if name prefix> <uplink-interface name> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n");
1494 strncpy (hwid, argv[1], LINE_LEN);
1495 hwid[LINE_LEN - 1] = '\0';
1498 * We use our PID for finding/resolving the control-panel name of our virtual
1499 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1500 * as additional hardware-id for our device.
1502 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1506 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1508 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1518 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1519 if (0 != strcmp (argv[3], "-"))
1521 char command[LINE_LEN];
1522 const char *address = argv[3];
1523 long prefix_len = atol (argv[4]);
1525 if ((prefix_len < 1) || (prefix_len > 127))
1527 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1532 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1533 if (0 != (global_ret = set_address6 (address, prefix_len)))
1538 /* install our the windows NAT module*/
1539 fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n");
1540 /* outside interface (maybe that's already set) */
1541 snprintf (command, LINE_LEN,
1542 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active",
1544 local_ret = execute_shellcommand (command);
1547 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1550 /* internal interface */
1551 snprintf (command, LINE_LEN,
1552 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active",
1553 device_visible_name);
1554 local_ret = execute_shellcommand (command);
1557 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1560 /* we can keep IPv6 forwarding around, as all interfaces have
1561 * their forwarding mode reset to false at bootup. */
1564 if (0 != strcmp (argv[5], "-"))
1566 const char *address = argv[5];
1567 const char *mask = argv[6];
1569 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1570 if (0 != (global_ret = set_address4 (address, mask)))
1573 // setup NAPT, if possible
1574 /* MS has REMOVED the routing/nat capabilities from Vista+, thus
1575 * we can not setup NAT like in XP or on the server. Actually the
1576 * the only feasible solution seems to be to use
1577 * Internet Connection Sharing, which introduces a horde of problems
1578 * such as sending out rogue-RAs on the external interface in an ipv6
1580 * Thus, below stuff ONLY works on
1582 * Win Server 2003 SP1+
1587 if (0 != strcmp (argv[2], "-"))
1589 char command[LINE_LEN];
1591 /* install our the windows NAT module*/
1592 fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]);
1593 local_ret = execute_shellcommand ("netsh routing ip nat install");
1596 fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret));
1600 snprintf (command, LINE_LEN,
1601 "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/
1603 local_ret = execute_shellcommand (command);
1606 fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret));
1609 /* private/internal/virtual IF */
1610 snprintf (command, LINE_LEN,
1611 "netsh routing ip nat add interface \"%s\" private",
1612 device_visible_name);
1613 local_ret = execute_shellcommand (command);
1616 fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret));
1628 const char *address = argv[5];
1630 char command[LINE_LEN];
1631 fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n");
1632 snprintf(command, LINE_LEN,
1633 "netsh routing ip nat del interface \"%s\"",
1634 device_visible_name);
1635 local_ret = execute_shellcommand(command);
1637 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));
1640 fprintf(stderr, "DEBUG: Removing IP4 address\n");
1641 remove_address4 (address);
1645 const char *address = argv[3];
1646 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1647 remove_address6 (address);
1650 fprintf (stderr, "DEBUG: removing interface\n");
1651 remove_interface ();
1652 fprintf (stderr, "DEBUG: graceful exit completed\n");