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
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):
37 #ifndef __MINGW64_VERSION_MAJOR
38 #include <ddk/cfgmgr32.h>
39 #include <ddk/newdev.h>
46 #include "tap-windows.h"
48 * Need 'struct GNUNET_HashCode' and 'struct GNUNET_PeerIdentity'.
50 #include "gnunet_crypto_lib.h"
52 * Need 'struct GNUNET_MessageHeader'.
54 #include "gnunet_common.h"
57 * Need VPN message types.
59 #include "gnunet_protocols.h"
62 * Should we print (interesting|debug) messages that can happen during
65 #define DEBUG GNUNET_NO
68 /* FIXME: define with varargs... */
69 #define LOG_DEBUG(msg) fprintf (stderr, "%s", msg);
71 #define LOG_DEBUG(msg) do {} while (0)
75 * Will this binary be run in permissions testing mode?
77 static boolean privilege_testing = FALSE;
80 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
82 #define MAX_SIZE 65536
85 * Name or Path+Name of our win32 driver.
86 * The .sys and .cat files HAVE to be in the same location as this file!
88 #define INF_FILE "share/gnunet/openvpn-tap32/tapw32/OemWin2k.inf"
91 * Name or Path+Name of our win64 driver.
92 * The .sys and .cat files HAVE to be in the same location as this file!
94 #define INF_FILE64 "share/gnunet/openvpn-tap32/tapw64/OemWin2k.inf"
97 * Hardware ID used in the inf-file.
98 * This might change over time, as openvpn advances their driver
100 #define HARDWARE_ID "tap0901"
103 * Minimum major-id of the driver version we can work with
105 #define TAP_WIN_MIN_MAJOR 9
108 * Minimum minor-id of the driver version we can work with.
109 * v <= 7 has buggy IPv6.
110 * v == 8 is broken for small IPv4 Packets
112 #define TAP_WIN_MIN_MINOR 9
115 * Time in seconds to wait for our virtual device to go up after telling it to do so.
117 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
118 * (in fact, 4 was chosen by a fair dice roll...)
120 #define TAP32_POSTUP_WAITTIME 4
123 * Location of the network interface list resides in registry.
125 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
128 * Our local process' PID. Used for creating a sufficiently unique additional
129 * hardware ID for our device.
131 static char secondary_hwid[LINE_LEN / 2];
134 * Device's visible Name, used to identify a network device in netsh.
135 * eg: "Local Area Connection 9"
137 static char device_visible_name[256];
140 * This is our own local instance of a virtual network interface
141 * It is (somewhat) equivalent to using tun/tap in unixoid systems
143 * Upon initialization, we create such an device node.
144 * Upon termination, we remove it again.
146 * If we crash this device might stay around.
148 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
151 * Registry Key we hand over to windows to spawn a new virtual interface
153 static SP_DEVINFO_DATA DeviceNode;
156 * GUID of our virtual device in the form of
157 * {12345678-1234-1234-1234-123456789abc} - in hex
159 static char device_guid[256];
163 * Possible states of an IO facility.
169 * overlapped I/O is ready for work
174 * overlapped I/O has been queued
179 * overlapped I/O has finished, but is waiting for it's write-partner
184 * there is a full buffer waiting
189 * Operlapped IO states for facility objects
190 * overlapped I/O has failed, stop processing
198 * A IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
203 * The mode the state machine associated with this object is in.
205 enum IO_State facility_state;
208 * If the path is open or blocked in general (used for quickly checking)
210 BOOL path_open; // BOOL is winbool (int), NOT boolean (unsigned char)!
213 * Windows Object-Handle (used for accessing TAP and STDIN/STDOUT)
218 * Overlaped IO structure used for asynchronous IO in windows.
220 OVERLAPPED overlapped;
223 * Buffer for reading things to and writing from...
225 unsigned char buffer[MAX_SIZE];
228 * How much of this buffer was used when reading or how much data can be written
233 * Amount of data actually written or read by readfile/writefile.
235 DWORD buffer_size_processed;
238 * How much of this buffer we have written in total
240 DWORD buffer_size_written;
244 * ReOpenFile is only available as of XP SP2 and 2003 SP1
246 WINBASEAPI HANDLE WINAPI ReOpenFile (HANDLE, DWORD, DWORD, DWORD);
249 * IsWow64Process definition for our is_win64, as this is a kernel function
251 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
254 * Determines if the host OS is win32 or win64
262 //this is a win64 binary,
264 #elif defined(_WIN32)
265 //this is a 32bit binary, and we need to check if we are running in WOW64
266 BOOL success = FALSE;
267 BOOL on_wow64 = FALSE;
268 LPFN_ISWOW64PROCESS IsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle ("kernel32"), "IsWow64Process");
270 if (NULL != IsWow64Process)
271 success = IsWow64Process (GetCurrentProcess (), &on_wow64);
273 return success && on_wow64;
277 * Wrapper for executing a shellcommand in windows.
279 * @param command - the command + parameters to execute
280 * @return * exitcode of the program executed,
281 * * EINVAL (cmd/file not found)
282 * * EPIPE (could not read STDOUT)
285 execute_shellcommand (const char *command)
289 if ( (NULL == command) ||
290 (NULL == (pipe = _popen (command, "rt"))) )
294 fprintf (stderr, "DEBUG: Command output: \n");
295 char output[LINE_LEN];
296 while (NULL != fgets (output, sizeof (output), pipe))
297 fprintf (stderr, "%s", output);
300 return _pclose (pipe);
305 * @brief Sets the IPv6-Address given in address on the interface dev
307 * @param address the IPv6-Address
308 * @param prefix_len the length of the network-prefix
311 set_address6 (const char *address, unsigned long prefix_len)
314 char command[LINE_LEN];
315 struct sockaddr_in6 sa6;
318 * parse the new address
320 memset (&sa6, 0, sizeof (struct sockaddr_in6));
321 sa6.sin6_family = AF_INET6;
322 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
324 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
330 * prepare the command
332 snprintf (command, LINE_LEN,
333 "netsh interface ipv6 add address \"%s\" %s/%d store=active",
334 device_visible_name, address, prefix_len);
338 ret = execute_shellcommand (command);
342 fprintf (stderr, "FATAL: Setting IPv6 address failed: %s\n", strerror (ret));
348 * @brief Removes the IPv6-Address given in address from the interface dev
350 * @param address the IPv4-Address
353 remove_address6 (const char *address)
355 char command[LINE_LEN];
358 // sanity checking was already done in set_address6
360 * prepare the command
362 snprintf (command, LINE_LEN,
363 "netsh interface ipv6 delete address \"%s\" store=persistent",
364 device_visible_name);
368 ret = execute_shellcommand (command);
372 fprintf (stderr, "FATAL: removing IPv6 address failed: %s\n", strerror (ret));
377 * @brief Sets the IPv4-Address given in address on the interface dev
379 * @param address the IPv4-Address
380 * @param mask the netmask
383 set_address4 (const char *address, const char *mask)
386 char command[LINE_LEN];
388 struct sockaddr_in addr;
389 addr.sin_family = AF_INET;
394 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
396 fprintf (stderr, "ERROR: Failed to parse address `%s': %s\n", address,
400 // Set Device to Subnet-Mode?
401 // do we really need tun.c:2925 ?
404 * prepare the command
406 snprintf (command, LINE_LEN,
407 "netsh interface ipv4 add address \"%s\" %s %s store=active",
408 device_visible_name, address, mask);
412 ret = execute_shellcommand (command);
416 fprintf (stderr, "FATAL: Setting IPv4 address failed: %s\n", strerror (ret));
422 * @brief Removes the IPv4-Address given in address from the interface dev
424 * @param address the IPv4-Address
427 remove_address4 (const char *address)
429 char command[LINE_LEN];
432 // sanity checking was already done in set_address4
435 * prepare the command
437 snprintf (command, LINE_LEN,
438 "netsh interface ipv4 delete address \"%s\" gateway=all store=persistent",
439 device_visible_name);
443 ret = execute_shellcommand (command);
447 fprintf (stderr, "FATAL: removing IPv4 address failed: %s\n", strerror (ret));
452 * Setup a new virtual interface to use for tunneling.
454 * @return: TRUE if setup was successful, else FALSE
460 * where to find our inf-file. (+ the "full" path, after windows found")
462 * We do not directly input all the props here, because openvpn will update
463 * these details over time.
465 char inf_file_path[MAX_PATH];
466 char * temp_inf_filename;
467 char hwidlist[LINE_LEN + 4];
468 char class_name[128];
473 * Set the device's hardware ID and add it to a list.
474 * This information will later on identify this device in registry.
476 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
478 * this is kind of over-complicated, but allows keeps things independent of
479 * how the openvpn-hwid is actually stored.
481 * A HWID list is double-\0 terminated and \0 separated
483 str_length = strlen (hwidlist) + 1;
484 strncpy (&hwidlist[str_length], secondary_hwid, LINE_LEN);
485 str_length += strlen (&hwidlist[str_length]) + 1;
488 * Locate the inf-file, we need to store it somewhere where the system can
489 * find it. We need to pick the correct driver for win32/win64.
492 GetFullPathNameA (INF_FILE64, MAX_PATH, inf_file_path, &temp_inf_filename);
494 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, &temp_inf_filename);
496 fprintf (stderr, "INFO: Located our driver's .inf file at %s\n", inf_file_path);
498 * Bootstrap our device info using the drivers inf-file
500 if ( ! SetupDiGetINFClassA (inf_file_path,
502 class_name, sizeof (class_name) / sizeof (char),
507 * Collect all the other needed information...
508 * let the system fill our this form
510 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
511 if (DeviceInfo == INVALID_HANDLE_VALUE)
514 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
515 if ( ! SetupDiCreateDeviceInfoA (DeviceInfo,
524 /* Deploy all the information collected into the registry */
525 if ( ! SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
529 str_length * sizeof (char)))
532 /* Install our new class(=device) into the system */
533 if ( ! SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
538 /* This system call tends to take a while (several seconds!) on
539 "modern" Windoze systems */
540 if ( ! UpdateDriverForPlugAndPlayDevicesA (NULL,
543 INSTALLFLAG_FORCE | INSTALLFLAG_NONINTERACTIVE,
544 NULL)) //reboot required? NEVER!
547 fprintf (stderr, "DEBUG: successfully created a network device\n");
553 * Remove our new virtual interface to use for tunneling.
554 * This function must be called AFTER setup_interface!
556 * @return: TRUE if destruction was successful, else FALSE
561 SP_REMOVEDEVICE_PARAMS remove;
563 if (INVALID_HANDLE_VALUE == DeviceInfo)
566 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
567 remove.HwProfile = 0;
568 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
569 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
571 * 1. Prepare our existing device information set, and place the
572 * uninstall related information into the structure
574 if ( ! SetupDiSetClassInstallParamsA (DeviceInfo,
575 (PSP_DEVINFO_DATA) & DeviceNode,
576 &remove.ClassInstallHeader,
580 * 2. Uninstall the virtual interface using the class installer
582 if ( ! SetupDiCallClassInstaller (DIF_REMOVE,
584 (PSP_DEVINFO_DATA) & DeviceNode))
587 SetupDiDestroyDeviceInfoList (DeviceInfo);
589 fprintf (stderr, "DEBUG: removed interface successfully\n");
596 * Do all the lookup necessary to retrieve the inteface's actual name
599 * @return: TRUE if we were able to lookup the interface's name, else FALSE
602 resolve_interface_name ()
604 SP_DEVINFO_LIST_DETAIL_DATA device_details;
605 char pnp_instance_id [MAX_DEVICE_ID_LEN];
606 HKEY adapter_key_handle;
612 char adapter[] = INTERFACE_REGISTRY_LOCATION;
614 /* We can obtain the PNP instance ID from our setupapi handle */
615 device_details.cbSize = sizeof (device_details);
616 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
617 (PCHAR) pnp_instance_id,
620 NULL)) //hMachine, we are local
623 fprintf (stderr, "DEBUG: Resolving interface name for network device %s\n",pnp_instance_id);
625 /* Registry is incredibly slow, retry for up to 30 seconds to allow registry to refresh */
626 for (retrys = 0; retrys < 120 && !retval; retrys++)
631 /* Now we can use this ID to locate the correct networks interface in registry */
632 if (ERROR_SUCCESS != RegOpenKeyExA (
637 &adapter_key_handle))
640 /* Of course there is a multitude of entries here, with arbitrary names,
641 * thus we need to iterate through there.
645 char instance_key[256];
646 char query_key [256];
647 HKEY instance_key_handle;
648 char pnpinstanceid_name[] = "PnpInstanceID";
649 char pnpinstanceid_value[256];
650 char adaptername_name[] = "Name";
653 len = 256 * sizeof (char);
654 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
655 status = RegEnumKeyExA (
665 /* this may fail due to one of two reasons:
666 * we are at the end of the list*/
667 if (ERROR_NO_MORE_ITEMS == status)
669 // * we found a broken registry key, continue with the next key.
670 if (ERROR_SUCCESS != status)
673 /* prepare our new query string: */
674 snprintf (query_key, 256, "%s\\%s\\Connection",
678 /* look inside instance_key\\Connection */
679 if (ERROR_SUCCESS != RegOpenKeyExA (
684 &instance_key_handle))
687 /* now, read our PnpInstanceID */
688 len = sizeof (pnpinstanceid_value);
689 status = RegQueryValueExA (instance_key_handle,
691 NULL, //reserved, always NULL according to MSDN
693 (LPBYTE) pnpinstanceid_value,
696 if (status != ERROR_SUCCESS || data_type != REG_SZ)
699 /* compare the value we got to our devices PNPInstanceID*/
700 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
701 sizeof (pnpinstanceid_value) / sizeof (char)))
704 len = sizeof (device_visible_name);
705 status = RegQueryValueExA (
708 NULL, //reserved, always NULL according to MSDN
710 (LPBYTE) device_visible_name,
713 if (status != ERROR_SUCCESS || data_type != REG_SZ)
717 * we have successfully found OUR instance,
718 * save the device GUID before exiting
721 strncpy (device_guid, instance_key, 256);
723 fprintf (stderr, "DEBUG: Interface Name lookup succeeded on retry %d, got \"%s\" %s\n", retrys, device_visible_name, device_guid);
726 RegCloseKey (instance_key_handle);
731 RegCloseKey (adapter_key_handle);
738 * Determines the version of the installed TAP32 driver and checks if it's sufficiently new for GNUNET
740 * @param handle the handle to our tap device
741 * @return TRUE if the version is sufficient, else FALSE
744 check_tapw32_version (HANDLE handle)
748 memset (&(version), 0, sizeof (version));
750 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
751 &version, sizeof (version),
752 &version, sizeof (version), &len, NULL))
753 fprintf (stderr, "INFO: TAP-Windows Driver Version %d.%d %s\n",
756 (version[2] ? "(DEBUG)" : ""));
758 if ((version[0] != TAP_WIN_MIN_MAJOR) ||
759 (version[1] < TAP_WIN_MIN_MINOR )){
760 fprintf (stderr, "FATAL: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d\n",
771 * Creates a tun-interface called dev;
773 * @return the fd to the tun or -1 on error
778 char device_path[256];
781 if (! setup_interface ())
784 return INVALID_HANDLE_VALUE;
787 if (! resolve_interface_name ())
790 return INVALID_HANDLE_VALUE;
793 /* Open Windows TAP-Windows adapter */
794 snprintf (device_path, sizeof (device_path), "%s%s%s",
799 handle = CreateFile (
801 GENERIC_READ | GENERIC_WRITE,
802 0, /* was: FILE_SHARE_READ */
805 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
809 if (INVALID_HANDLE_VALUE == handle)
811 fprintf (stderr, "FATAL: CreateFile failed on TAP device: %s\n", device_path);
815 /* get driver version info */
816 if (! check_tapw32_version (handle))
818 CloseHandle (handle);
819 return INVALID_HANDLE_VALUE;
822 /* TODO (opt?): get MTU-Size */
824 fprintf (stderr, "DEBUG: successfully opened TAP device\n");
830 * Brings a TAP device up and sets it to connected state.
832 * @param handle the handle to our TAP device
833 * @return True if the operation succeeded, else false
836 tun_up (HANDLE handle)
840 if (! DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
841 &status, sizeof (status),
842 &status, sizeof (status), &len, NULL))
844 fprintf (stderr, "FATAL: TAP driver ignored request to UP interface (DeviceIoControl call)\n");
848 /* Wait for the device to go UP, might take some time. */
849 Sleep (TAP32_POSTUP_WAITTIME * 1000);
850 fprintf (stderr, "DEBUG: successfully set TAP device to UP\n");
857 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
860 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
861 * input handle. Then it goes into IOSTATE_QUEUED state.
862 * In case the read succeeded instantly the input facility enters 3.
865 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
866 * If it has finished, go to state 3.
867 * If it has failed, set IOSTATE_FAILED
870 * If the output facility is in state IOSTATE_READY, the read-buffer is copied to the output buffer.
871 * The input facility enters state IOSTATE_READY
872 * The output facility enters state IOSTATE_READY
873 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
875 * IOSTATE_WAITING is reset by the output facility, once it has completed.
877 * @param input_facility input named pipe or file to work with.
878 * @param output_facility output pipe or file to hand over data to.
879 * @return false if an event reset was impossible (OS error), else true
882 attempt_read_tap (struct io_facility * input_facility,
883 struct io_facility * output_facility)
885 struct GNUNET_MessageHeader * hdr;
888 switch (input_facility->facility_state)
892 if (! ResetEvent (input_facility->overlapped.hEvent))
897 input_facility->buffer_size = 0;
899 /* Check how the task is handled */
900 if (ReadFile (input_facility->handle,
901 input_facility->buffer,
902 sizeof (input_facility->buffer) - sizeof (struct GNUNET_MessageHeader),
903 &input_facility->buffer_size,
904 &input_facility->overlapped))
905 {/* async event processed immediately*/
907 /* reset event manually*/
908 if (! SetEvent (input_facility->overlapped.hEvent))
911 fprintf (stderr, "DEBUG: tap read succeeded immediately\n");
913 /* we successfully read something from the TAP and now need to
914 * send it our via STDOUT. Is that possible at the moment? */
915 if ((IOSTATE_READY == output_facility->facility_state ||
916 IOSTATE_WAITING == output_facility->facility_state)
917 && (0 < input_facility->buffer_size))
918 { /* hand over this buffers content and apply message header for gnunet */
919 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
920 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
922 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
923 input_facility->buffer,
924 input_facility->buffer_size);
926 output_facility->buffer_size = size;
927 hdr->size = htons (size);
928 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
929 output_facility->facility_state = IOSTATE_READY;
931 else if (0 < input_facility->buffer_size)
932 /* If we have have read our buffer, wait for our write-partner*/
933 input_facility->facility_state = IOSTATE_WAITING;
935 else /* operation was either queued or failed*/
937 int err = GetLastError ();
938 if (ERROR_IO_PENDING == err)
939 { /* operation queued */
940 input_facility->facility_state = IOSTATE_QUEUED;
943 { /* error occurred, let the rest of the elements finish */
944 input_facility->path_open = FALSE;
945 input_facility->facility_state = IOSTATE_FAILED;
946 if (IOSTATE_WAITING == output_facility->facility_state)
947 output_facility->path_open = FALSE;
949 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
954 // We are queued and should check if the read has finished
957 // there was an operation going on already, check if that has completed now.
959 if (GetOverlappedResult (input_facility->handle,
960 &input_facility->overlapped,
961 &input_facility->buffer_size,
963 {/* successful return for a queued operation */
964 if (! ResetEvent (input_facility->overlapped.hEvent))
967 fprintf (stderr, "DEBUG: tap read succeeded delayed\n");
969 /* we successfully read something from the TAP and now need to
970 * send it our via STDOUT. Is that possible at the moment? */
971 if ((IOSTATE_READY == output_facility->facility_state ||
972 IOSTATE_WAITING == output_facility->facility_state)
973 && 0 < input_facility->buffer_size)
974 { /* hand over this buffers content and apply message header for gnunet */
975 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
976 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
978 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
979 input_facility->buffer,
980 input_facility->buffer_size);
982 output_facility->buffer_size = size;
983 hdr->size = htons(size);
984 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
985 output_facility->facility_state = IOSTATE_READY;
986 input_facility->facility_state = IOSTATE_READY;
988 else if (0 < input_facility->buffer_size)
989 { /* If we have have read our buffer, wait for our write-partner*/
990 input_facility->facility_state = IOSTATE_WAITING;
991 // TODO: shall we attempt to fill our buffer or should we wait for our write-partner to finish?
995 { /* operation still pending/queued or failed? */
996 int err = GetLastError ();
997 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
998 { /* error occurred, let the rest of the elements finish */
999 input_facility->path_open = FALSE;
1000 input_facility->facility_state = IOSTATE_FAILED;
1001 if (IOSTATE_WAITING == output_facility->facility_state)
1002 output_facility->path_open = FALSE;
1003 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1008 case IOSTATE_RESUME:
1009 hdr = (struct GNUNET_MessageHeader *) output_facility->buffer;
1010 size = input_facility->buffer_size + sizeof (struct GNUNET_MessageHeader);
1012 memcpy (output_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1013 input_facility->buffer,
1014 input_facility->buffer_size);
1016 output_facility->buffer_size = size;
1017 hdr->size = htons (size);
1018 hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
1019 output_facility->facility_state = IOSTATE_READY;
1020 input_facility->facility_state = IOSTATE_READY;
1029 * Attempts to read off an input facility (tap or named pipe) in overlapped mode.
1032 * If the input facility is in IOSTATE_READY, it will issue a new read operation to the
1033 * input handle. Then it goes into IOSTATE_QUEUED state.
1034 * In case the read succeeded instantly the input facility enters 3.
1037 * If the input facility is in IOSTATE_QUEUED state, it will check if the queued read has finished already.
1038 * If it has finished, go to state 3.
1039 * If it has failed, set IOSTATE_FAILED
1042 * If the facility is finished with ready
1043 * The read-buffer is copied to the output buffer, except for the GNUNET_MessageHeader.
1044 * The input facility enters state IOSTATE_READY
1045 * The output facility enters state IOSTATE_READY
1046 * If the output facility is in state IOSTATE_QUEUED, the input facility enters IOSTATE_WAITING
1048 * IOSTATE_WAITING is reset by the output facility, once it has completed.
1050 * @param input_facility input named pipe or file to work with.
1051 * @param output_facility output pipe or file to hand over data to.
1052 * @return false if an event reset was impossible (OS error), else true
1055 attempt_read_stdin (struct io_facility * input_facility,
1056 struct io_facility * output_facility)
1058 struct GNUNET_MessageHeader * hdr;
1060 switch (input_facility->facility_state)
1064 input_facility->buffer_size = 0;
1066 partial_read_iostate_ready:
1067 if (! ResetEvent (input_facility->overlapped.hEvent))
1070 /* Check how the task is handled */
1071 if (ReadFile (input_facility->handle,
1072 input_facility->buffer + input_facility->buffer_size,
1073 sizeof (input_facility->buffer) - input_facility->buffer_size,
1074 &input_facility->buffer_size_processed,
1075 &input_facility->overlapped))
1076 {/* async event processed immediately*/
1077 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1079 /* reset event manually*/
1080 if (!SetEvent (input_facility->overlapped.hEvent))
1083 fprintf (stderr, "DEBUG: stdin read succeeded immediately\n");
1084 input_facility->buffer_size += input_facility->buffer_size_processed;
1086 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER ||
1087 ntohs (hdr->size) > sizeof (input_facility->buffer))
1089 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1090 input_facility->facility_state = IOSTATE_READY;
1093 /* we got the a part of a packet */
1094 if (ntohs (hdr->size) > input_facility->buffer_size)
1095 goto partial_read_iostate_ready;
1097 /* have we read more than 0 bytes of payload? (sizeread > header)*/
1098 if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader) &&
1099 ((IOSTATE_READY == output_facility->facility_state) ||
1100 (IOSTATE_WAITING == output_facility->facility_state)))
1101 {/* we successfully read something from the TAP and now need to
1102 * send it our via STDOUT. Is that possible at the moment? */
1104 /* hand over this buffers content and strip gnunet message header */
1105 memcpy (output_facility->buffer,
1106 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1107 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1108 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1109 output_facility->facility_state = IOSTATE_READY;
1110 input_facility->facility_state = IOSTATE_READY;
1112 else if (input_facility->buffer_size > sizeof (struct GNUNET_MessageHeader))
1113 /* If we have have read our buffer, wait for our write-partner*/
1114 input_facility->facility_state = IOSTATE_WAITING;
1115 else /* we read nothing */
1116 input_facility->facility_state = IOSTATE_READY;
1118 else /* operation was either queued or failed*/
1120 int err = GetLastError ();
1121 if (ERROR_IO_PENDING == err) /* operation queued */
1122 input_facility->facility_state = IOSTATE_QUEUED;
1124 { /* error occurred, let the rest of the elements finish */
1125 input_facility->path_open = FALSE;
1126 input_facility->facility_state = IOSTATE_FAILED;
1127 if (IOSTATE_WAITING == output_facility->facility_state)
1128 output_facility->path_open = FALSE;
1130 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1135 // We are queued and should check if the read has finished
1136 case IOSTATE_QUEUED:
1138 // there was an operation going on already, check if that has completed now.
1139 if (GetOverlappedResult (input_facility->handle,
1140 &input_facility->overlapped,
1141 &input_facility->buffer_size_processed,
1143 {/* successful return for a queued operation */
1144 hdr = (struct GNUNET_MessageHeader *) input_facility->buffer;
1146 if (! ResetEvent (input_facility->overlapped.hEvent))
1149 fprintf (stderr, "DEBUG: stdin read succeeded delayed\n");
1150 input_facility->buffer_size += input_facility->buffer_size_processed;
1152 if ((ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER) ||
1153 (ntohs (hdr->size) > sizeof (input_facility->buffer)))
1155 fprintf (stderr, "WARNING: Protocol violation, got GNUnet Message type %h, size %h\n", ntohs (hdr->type), ntohs (hdr->size));
1156 input_facility->facility_state = IOSTATE_READY;
1159 /* we got the a part of a packet */
1160 if (ntohs (hdr->size) > input_facility->buffer_size );
1161 goto partial_read_iostate_ready;
1163 /* we successfully read something from the TAP and now need to
1164 * send it our via STDOUT. Is that possible at the moment? */
1165 if ((IOSTATE_READY == output_facility->facility_state ||
1166 IOSTATE_WAITING == output_facility->facility_state)
1167 && input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1168 { /* hand over this buffers content and strip gnunet message header */
1169 memcpy (output_facility->buffer,
1170 input_facility->buffer + sizeof(struct GNUNET_MessageHeader),
1171 input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader));
1172 output_facility->buffer_size = input_facility->buffer_size - sizeof(struct GNUNET_MessageHeader);
1173 output_facility->facility_state = IOSTATE_READY;
1174 input_facility->facility_state = IOSTATE_READY;
1176 else if (input_facility->buffer_size > sizeof(struct GNUNET_MessageHeader))
1177 input_facility->facility_state = IOSTATE_WAITING;
1179 input_facility->facility_state = IOSTATE_READY;
1182 { /* operation still pending/queued or failed? */
1183 int err = GetLastError ();
1184 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1185 { /* error occurred, let the rest of the elements finish */
1186 input_facility->path_open = FALSE;
1187 input_facility->facility_state = IOSTATE_FAILED;
1188 if (IOSTATE_WAITING == output_facility->facility_state)
1189 output_facility->path_open = FALSE;
1190 fprintf (stderr, "FATAL: Read from handle failed, allowing write to finish\n");
1195 case IOSTATE_RESUME: /* Our buffer was filled already but our write facility was busy. */
1196 memcpy (output_facility->buffer,
1197 input_facility->buffer + sizeof (struct GNUNET_MessageHeader),
1198 input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader));
1199 output_facility->buffer_size = input_facility->buffer_size - sizeof (struct GNUNET_MessageHeader);
1200 output_facility->facility_state = IOSTATE_READY;
1201 input_facility->facility_state = IOSTATE_READY;
1210 * Attempts to write to an output facility (tap or named pipe) in overlapped mode.
1212 * TODO: high level description
1214 * @param output_facility output pipe or file to hand over data to.
1215 * @param input_facility input named pipe or file to work with.
1216 * @return false if an event reset was impossible (OS error), else true
1219 attempt_write (struct io_facility * output_facility,
1220 struct io_facility * input_facility)
1222 switch (output_facility->facility_state)
1225 output_facility->buffer_size_written = 0;
1227 continue_partial_write:
1228 if (! ResetEvent (output_facility->overlapped.hEvent))
1231 /* Check how the task was handled */
1232 if (WriteFile (output_facility->handle,
1233 output_facility->buffer + output_facility->buffer_size_written,
1234 output_facility->buffer_size - output_facility->buffer_size_written,
1235 &output_facility->buffer_size_processed,
1236 &output_facility->overlapped))
1237 {/* async event processed immediately*/
1239 fprintf (stderr, "DEBUG: write succeeded immediately\n");
1240 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1242 /* reset event manually*/
1243 if (! SetEvent (output_facility->overlapped.hEvent))
1247 if (output_facility->buffer_size_written < output_facility->buffer_size)
1248 goto continue_partial_write;
1250 /* we are now waiting for our buffer to be filled*/
1251 output_facility->facility_state = IOSTATE_WAITING;
1253 /* we successfully wrote something and now need to reset our reader */
1254 if (IOSTATE_WAITING == input_facility->facility_state)
1255 input_facility->facility_state = IOSTATE_RESUME;
1256 else if (IOSTATE_FAILED == input_facility->facility_state)
1257 output_facility->path_open = FALSE;
1259 else /* operation was either queued or failed*/
1261 int err = GetLastError ();
1262 if (ERROR_IO_PENDING == err)
1263 { /* operation queued */
1264 output_facility->facility_state = IOSTATE_QUEUED;
1267 { /* error occurred, close this path */
1268 output_facility->path_open = FALSE;
1269 output_facility->facility_state = IOSTATE_FAILED;
1270 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1274 case IOSTATE_QUEUED:
1275 // there was an operation going on already, check if that has completed now.
1277 if (GetOverlappedResult (output_facility->handle,
1278 &output_facility->overlapped,
1279 &output_facility->buffer_size_processed,
1281 {/* successful return for a queued operation */
1282 if (! ResetEvent (output_facility->overlapped.hEvent))
1285 fprintf (stderr, "DEBUG: write succeeded delayed\n");
1286 output_facility->buffer_size_written += output_facility->buffer_size_processed;
1289 if (output_facility->buffer_size_written < output_facility->buffer_size)
1290 goto continue_partial_write;
1292 /* we are now waiting for our buffer to be filled*/
1293 output_facility->facility_state = IOSTATE_WAITING;
1295 /* we successfully wrote something and now need to reset our reader */
1296 if (IOSTATE_WAITING == input_facility->facility_state)
1297 input_facility->facility_state = IOSTATE_RESUME;
1298 else if (IOSTATE_FAILED == input_facility->facility_state)
1299 output_facility->path_open = FALSE;
1302 { /* operation still pending/queued or failed? */
1303 int err = GetLastError ();
1304 if ((ERROR_IO_INCOMPLETE != err) && (ERROR_IO_PENDING != err))
1305 { /* error occurred, close this path */
1306 output_facility->path_open = FALSE;
1307 output_facility->facility_state = IOSTATE_FAILED;
1308 fprintf (stderr, "FATAL: Write to handle failed, exiting\n");
1318 * Initialize a overlapped structure
1320 * @param elem the element to initilize
1321 * @param initial_state the initial state for this instance
1322 * @param signaled if the hEvent created should default to signaled or not
1323 * @return true on success, else false
1326 initialize_io_facility (struct io_facility * elem,
1330 elem->path_open = TRUE;
1331 elem->handle = INVALID_HANDLE_VALUE;
1332 elem->facility_state = initial_state;
1333 elem->buffer_size = 0;
1334 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
1335 if (NULL == elem->overlapped.hEvent)
1343 * Start forwarding to and from the tunnel.
1345 * @param tap_handle device handle for interacting with the Virtual interface
1348 run (HANDLE tap_handle)
1350 /* IO-Facility for reading from our virtual interface */
1351 struct io_facility tap_read;
1352 /* IO-Facility for writing to our virtual interface */
1353 struct io_facility tap_write;
1354 /* IO-Facility for reading from stdin */
1355 struct io_facility std_in;
1356 /* IO-Facility for writing to stdout */
1357 struct io_facility std_out;
1359 HANDLE parent_std_in_handle = GetStdHandle (STD_INPUT_HANDLE);
1360 HANDLE parent_std_out_handle = GetStdHandle (STD_OUTPUT_HANDLE);
1363 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
1364 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
1366 * DHCP and such are all features we will never use in gnunet afaik.
1367 * But for openvpn those are essential.
1369 if ((privilege_testing) || (! tun_up (tap_handle) ))
1370 goto teardown_final;
1372 /* Initialize our overlapped IO structures*/
1373 if (! (initialize_io_facility (&tap_read, IOSTATE_READY, FALSE)
1374 && initialize_io_facility (&tap_write, IOSTATE_WAITING, TRUE)
1375 && initialize_io_facility (&std_in, IOSTATE_READY, FALSE)
1376 && initialize_io_facility (&std_out, IOSTATE_WAITING, TRUE)))
1377 goto teardown_final;
1379 /* Handles for STDIN and STDOUT */
1380 tap_read.handle = tap_handle;
1381 tap_write.handle = tap_handle;
1383 #ifdef DEBUG_TO_CONSOLE
1384 /* Debug output to console STDIN/STDOUT*/
1385 std_in.handle = parent_std_in_handle;
1386 std_out.handle = parent_std_out_handle;
1389 fprintf (stderr, "DEBUG: reopening stdin/out for overlapped IO\n");
1391 * Find out the types of our handles.
1392 * This part is a problem, because in windows we need to handle files,
1393 * pipes and the console differently.
1395 if ((FILE_TYPE_PIPE != GetFileType (parent_std_in_handle)) ||
1396 (FILE_TYPE_PIPE != GetFileType (parent_std_out_handle)))
1398 fprintf (stderr, "ERROR: stdin/stdout must be named pipes\n");
1402 std_in.handle = ReOpenFile (parent_std_in_handle,
1404 FILE_SHARE_WRITE | FILE_SHARE_READ,
1405 FILE_FLAG_OVERLAPPED);
1407 if (INVALID_HANDLE_VALUE == std_in.handle)
1409 fprintf (stderr, "FATAL: Could not reopen stdin for in overlapped mode, has to be a named pipe\n");
1413 std_out.handle = ReOpenFile (parent_std_out_handle,
1416 FILE_FLAG_OVERLAPPED);
1418 if (INVALID_HANDLE_VALUE == std_out.handle)
1420 fprintf (stderr, "FATAL: Could not reopen stdout for in overlapped mode, has to be a named pipe\n");
1425 fprintf (stderr, "DEBUG: mainloop has begun\n");
1427 while (std_out.path_open || tap_write.path_open)
1429 /* perform READ from stdin if possible */
1430 if (std_in.path_open && (! attempt_read_stdin (&std_in, &tap_write)))
1433 /* perform READ from tap if possible */
1434 if (tap_read.path_open && (! attempt_read_tap (&tap_read, &std_out)))
1437 /* perform WRITE to tap if possible */
1438 if (tap_write.path_open && (! attempt_write (&tap_write, &std_in)))
1441 /* perform WRITE to STDOUT if possible */
1442 if (std_out.path_open && (! attempt_write (&std_out, &tap_read)))
1445 fprintf (stderr, "DEBUG: teardown initiated\n");
1449 CancelIo (tap_handle);
1450 CancelIo (std_in.handle);
1451 CancelIo (std_out.handle);
1455 CloseHandle (tap_handle);
1460 * Open VPN tunnel interface.
1462 * @param argc must be 6
1463 * @param argv 0: binary name ("gnunet-helper-exit")
1464 * 1: tunnel interface name ("gnunet-exit")
1465 * 2: IPv4 "physical" interface name ("eth0"), or "-" to not do IPv4 NAT
1466 * 3: IPv6 address ("::1"), or "-" to skip IPv6
1467 * 4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
1468 * 5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
1469 * 6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
1472 main (int argc, char **argv)
1474 char hwid[LINE_LEN];
1477 int local_ret = EINVAL;
1478 BOOL have_ip4 = FALSE;
1479 BOOL have_ip6 = FALSE;
1480 BOOL have_nat44 = FALSE;
1482 if ( (1 < argc) && (0 != strcmp (argv[1], "-d"))){
1483 privilege_testing = TRUE;
1486 "DEBUG: Running binary in privilege testing mode.");
1495 "FATAL: must supply 6 arguments\nUsage:\ngnunet-helper-exit [-d] <if name prefix> <uplink-interface name> <address6 or \"-\"> <netbits6> <address4 or \"-\"> <netmask4>\n");
1499 strncpy (hwid, argv[1], LINE_LEN);
1500 hwid[LINE_LEN - 1] = '\0';
1503 * We use our PID for finding/resolving the control-panel name of our virtual
1504 * device. PIDs are (of course) unique at runtime, thus we can safely use it
1505 * as additional hardware-id for our device.
1507 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
1511 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
1513 fprintf (stderr, "FATAL: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
1523 fprintf (stderr, "DEBUG: Setting IPs, if needed\n");
1524 if (0 != strcmp (argv[3], "-"))
1526 char command[LINE_LEN];
1527 const char *address = argv[3];
1528 long prefix_len = atol (argv[4]);
1530 if ((prefix_len < 1) || (prefix_len > 127))
1532 fprintf (stderr, "FATAL: ipv6 prefix_len out of range\n");
1537 fprintf (stderr, "DEBUG: Setting IP6 address: %s/%d\n", address, prefix_len);
1538 if (0 != (global_ret = set_address6 (address, prefix_len)))
1543 /* install our the windows NAT module*/
1544 fprintf (stderr, "DEBUG: Setting IPv6 Forwarding for internal and external interface.\n");
1545 /* outside interface (maybe that's already set) */
1546 snprintf (command, LINE_LEN,
1547 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled store=active",
1549 local_ret = execute_shellcommand (command);
1552 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1555 /* internal interface */
1556 snprintf (command, LINE_LEN,
1557 "netsh interface ipv6 set interface interface=\"%s\" metric=1 forwarding=enabled advertise=enabled store=active",
1558 device_visible_name);
1559 local_ret = execute_shellcommand (command);
1562 fprintf (stderr, "FATAL: Could not enable forwarding via netsh: %s\n", strerror (local_ret));
1565 /* we can keep IPv6 forwarding around, as all interfaces have
1566 * their forwarding mode reset to false at bootup. */
1569 if (0 != strcmp (argv[5], "-"))
1571 const char *address = argv[5];
1572 const char *mask = argv[6];
1574 fprintf (stderr, "DEBUG: Setting IP4 address: %s/%s\n", address, mask);
1575 if (0 != (global_ret = set_address4 (address, mask)))
1578 // setup NAPT, if possible
1579 /* MS has REMOVED the routing/nat capabilities from Vista+, thus
1580 * we can not setup NAT like in XP or on the server. Actually the
1581 * the only feasible solution seems to be to use
1582 * Internet Connection Sharing, which introduces a horde of problems
1583 * such as sending out rogue-RAs on the external interface in an ipv6
1585 * Thus, below stuff ONLY works on
1587 * Win Server 2003 SP1+
1592 if (0 != strcmp (argv[2], "-"))
1594 char command[LINE_LEN];
1596 /* install our the windows NAT module*/
1597 fprintf (stderr, "DEBUG: Adding NAPT/Masquerading between external IF %s and mine.\n", argv[2]);
1598 local_ret = execute_shellcommand ("netsh routing ip nat install");
1601 fprintf (stderr, "FATAL: Could not install NAPT support via Netsh: %s\n", strerror (local_ret));
1605 snprintf (command, LINE_LEN,
1606 "netsh routing ip nat add interface \"%s\" full", /*full = NAPT (addr+port)*/
1608 local_ret = execute_shellcommand (command);
1611 fprintf (stderr, "FATAL: IPv4-NAPT on external interface failed: %s\n", strerror (local_ret));
1614 /* private/internal/virtual IF */
1615 snprintf (command, LINE_LEN,
1616 "netsh routing ip nat add interface \"%s\" private",
1617 device_visible_name);
1618 local_ret = execute_shellcommand (command);
1621 fprintf (stderr, "FATAL: IPv4-NAPT on internal interface failed: %s\n", strerror (local_ret));
1633 const char *address = argv[5];
1635 char command[LINE_LEN];
1636 fprintf(stderr, "DEBUG: removing IP4 NAPT from virtual interface \n");
1637 snprintf(command, LINE_LEN,
1638 "netsh routing ip nat del interface \"%s\"",
1639 device_visible_name);
1640 local_ret = execute_shellcommand(command);
1642 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));
1645 fprintf(stderr, "DEBUG: Removing IP4 address\n");
1646 remove_address4 (address);
1650 const char *address = argv[3];
1651 fprintf (stderr, "DEBUG: Removing IP6 address\n");
1652 remove_address6 (address);
1655 fprintf (stderr, "DEBUG: removing interface\n");
1656 remove_interface ();
1657 fprintf (stderr, "DEBUG: graceful exit completed\n");