2 This file is part of GNUnet.
3 (C) 2010, 2012 Christian Grothoff
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file vpn/gnunet-helper-vpn-windows.c
23 * @brief the helper for the VPN service in win32 builds.
24 * Opens a virtual network-interface, sends data received on the if to stdout,
25 * sends data received on stdin to the interface
26 * @author Christian M. Fuchs
28 * The following list of people have reviewed this code and considered
29 * it safe since the last modification (if you reviewed it, please
30 * have your name added to the list):
37 #include <ddk/cfgmgr32.h>
39 #include "tap-windows.h"
43 * Need 'struct GNUNET_MessageHeader'.
45 #include "gnunet_common.h"
48 * Need VPN message types.
50 #include "gnunet_protocols.h"
53 * Should we print (interesting|debug) messages that can happen during
56 #define DEBUG GNUNET_NO
59 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
61 #define MAX_SIZE 65536
64 * Name or Path+Name of our driver in Unicode.
65 * The .sys and .cat files HAVE to be in the same location as this file!
67 #define INF_FILE "tapw32.inf"
70 * Hardware ID used in the inf-file.
71 * This might change over time, as openvpn advances their driver
73 #define HARDWARE_ID "TAP0901"
76 * Component ID if our driver
78 #define TAP_WIN_COMPONENT_ID "tap0901"
81 * Minimum major-id of the driver version we can work with
83 #define TAP_WIN_MIN_MAJOR 9
86 * Minimum minor-id of the driver version we can work with.
87 * v <= 7 has buggy IPv6.
88 * v == 8 is broken for small IPv4 Packets
90 #define TAP_WIN_MIN_MINOR 9
93 * Time in seconds to wait for our virtual device to go up after telling it to do so.
95 * openvpn doesn't specify a value, 4 seems sane for testing, even for openwrt
96 * (in fact, 4 was chosen by a fair dice roll...)
98 #define TAP32_POSTUP_WAITTIME 4
101 * Location of the network interface list resides in registry.
102 * TODO: is this fixed on all version of windows? Checked with XP and 7
104 #define INTERFACE_REGISTRY_LOCATION "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}"
107 * Our local process' PID. Used for creating a sufficiently unique additional
108 * hardware ID for our device.
110 static char secondary_hwid[LINE_LEN / 2];
113 * Device's visible Name, used to identify a network device in netsh.
114 * eg: "Local Area Connection 9"
116 static char device_visible_name[256];
119 * This is our own local instance of a virtual network interface
120 * It is (somewhat) equivalent to using tun/tap in unixoid systems
122 * Upon initialization, we create such an device node.
123 * Upon termination, we remove it again.
125 * If we crash this device might stay around.
127 static HDEVINFO DeviceInfo = INVALID_HANDLE_VALUE;
130 * Registry Key we hand over to windows to spawn a new virtual interface
132 static SP_DEVINFO_DATA DeviceNode;
135 * GUID of our virtual device in the form of
136 * {12345678-1234-1234-1234-123456789abc} - in hex
138 static char device_guid[256];
140 /* Overlapped IO Begins here (warning: nasty!) */
143 * A overlapped-IO Object + read/writebuffer + buffer-size for windows asynchronous IO handling
145 struct overlapped_facility
148 BOOL status; // BOOL is winbool, NOT boolean!
152 OVERLAPPED overlapped;
155 unsigned char buffer[MAX_SIZE];
159 * Operlapped IO states for facility objects
161 #define IOSTATE_FAILED -1 /* overlapped I/O has failed, stop processing */
162 #define IOSTATE_READY 0 /* overlapped I/O is ready for work */
163 #define IOSTATE_QUEUED 1 /* overlapped I/O has been queued */
164 #define IOSTATE_WAITING 3 /* overlapped I/O has finished, but is waiting for it's write-partner */
169 * inet_pton() wrapper for WSAStringToAddress()
171 * this is needed as long as we support WinXP, because only Vista+ support
172 * inet_pton at all, and mingw does not yet offer inet_pton/ntop at all
174 * @param af - IN - the aftype this address is supposed to be (v4/v6)
175 * @param src - IN - the presentation form of the address
176 * @param dst - OUT - the numerical form of the address
177 * @return 0 on success, 1 on failure
180 inet_pton (int af, const char *src, void *dst)
182 struct sockaddr_storage addr;
183 int size = sizeof (addr);
184 char local_copy[INET6_ADDRSTRLEN + 1];
186 ZeroMemory (&addr, sizeof (addr));
187 /* stupid non-const API */
188 strncpy (local_copy, src, INET6_ADDRSTRLEN + 1);
189 local_copy[INET6_ADDRSTRLEN] = 0;
191 if (WSAStringToAddressA (local_copy, af, NULL, (struct sockaddr *) &addr, &size) == 0)
196 *(struct in_addr *) dst = ((struct sockaddr_in *) &addr)->sin_addr;
199 *(struct in6_addr *) dst = ((struct sockaddr_in6 *) &addr)->sin6_addr;
208 * Wrapper for executing a shellcommand in windows.
210 * @param command - the command + parameters to execute
211 * @return * exitcode of the program executed,
212 * * EINVAL (cmd/file not found)
213 * * EPIPE (could not read STDOUT)
216 execute_shellcommand (char * command)
220 if (NULL == command ||
221 NULL == (pipe = _popen (command, "rt")))
226 char output[LINE_LEN];
228 printf ("executed command: %s", command);
229 while (NULL != fgets (output, sizeof (output), pipe))
237 return _pclose (pipe);
241 * @brief Sets the IPv6-Address given in address on the interface dev
243 * @param address the IPv6-Address
244 * @param prefix_len the length of the network-prefix
247 set_address6 (const char *address, unsigned long prefix_len)
250 char command[LINE_LEN];
251 struct sockaddr_in6 sa6;
254 * parse the new address
256 memset (&sa6, 0, sizeof (struct sockaddr_in6));
257 sa6.sin6_family = AF_INET6;
258 if (1 != inet_pton (AF_INET6, address, &sa6.sin6_addr.s6_addr))
260 fprintf (stderr, "Failed to parse address `%s': %s\n", address,
266 * prepare the command
268 snprintf (command, LINE_LEN,
269 "netsh interface ipv6 add address \"%s\" %s/%d",
270 device_visible_name, address, prefix_len);
274 ret = execute_shellcommand (command);
279 fprintf (stderr, "Setting IPv6 address failed: %s\n", strerror (ret));
280 exit (1); // FIXME: return error code, shut down interface / unload driver
285 * @brief Sets the IPv4-Address given in address on the interface dev
287 * @param dev the interface to configure
288 * @param address the IPv4-Address
289 * @param mask the netmask
292 set_address4 (const char *address, const char *mask)
295 char command[LINE_LEN];
297 struct sockaddr_in addr;
298 addr.sin_family = AF_INET;
303 if (1 != inet_pton (AF_INET, address, &addr.sin_addr.s_addr))
305 fprintf (stderr, "Failed to parse address `%s': %s\n", address,
311 * prepare the command
313 snprintf (command, LINE_LEN,
314 "netsh interface ipv4 add address \"%s\" %s %s",
315 device_visible_name, address, mask);
319 ret = execute_shellcommand (command);
324 fprintf (stderr, "Setting IPv4 address failed: %s\n", strerror (ret));
325 exit (1); // FIXME: return error code, shut down interface / unload driver
330 * Setup a new virtual interface to use for tunneling.
332 * @return: TRUE if setup was successful, else FALSE
338 * where to find our inf-file. (+ the "full" path, after windows found")
340 * We do not directly input all the props here, because openvpn will update
341 * these details over time.
343 char inf_file_path[MAX_PATH];
344 char hwidlist[LINE_LEN + 4];
345 char class_name[128];
350 * Set the device's hardware ID and add it to a list.
351 * This information will later on identify this device in registry.
353 * TODO: Currently we just use TAP0901 as HWID,
354 * but we might want to add additional information
356 strncpy (hwidlist, HARDWARE_ID, LINE_LEN);
358 * this is kind of over-complicated, but allows keeps things independent of
359 * how the openvpn-hwid is actually stored.
361 * A HWID list is double-\0 terminated and \0 separated
363 str_lenth = strlen (hwidlist) + 1;
364 strncpy (&hwidlist[str_lenth], secondary_hwid, LINE_LEN - str_lenth);
367 * Locate the inf-file, we need to store it somewhere where the system can
368 * find it. A good choice would be CWD/PDW or %WINDIR$\system32\
370 * TODO: How about win64 in the future?
371 * We need to use a different driver for amd64/i386 !
373 GetFullPathNameA (INF_FILE, MAX_PATH, inf_file_path, NULL);
376 * Bootstrap our device info using the drivers inf-file
378 if (!SetupDiGetINFClassA (inf_file_path,
380 class_name, sizeof (class_name) / sizeof (char),
385 * Collect all the other needed information...
386 * let the system fill our this form
388 DeviceInfo = SetupDiCreateDeviceInfoList (&class_guid, NULL);
389 if (DeviceInfo == INVALID_HANDLE_VALUE)
392 DeviceNode.cbSize = sizeof (SP_DEVINFO_DATA);
393 if (!SetupDiCreateDeviceInfoA (DeviceInfo,
402 /* Deploy all the information collected into the registry */
403 if (!SetupDiSetDeviceRegistryPropertyA (DeviceInfo,
407 (strlen (hwidlist) + 2) * sizeof (char)))
410 /* Install our new class(=device) into the system */
411 if (!SetupDiCallClassInstaller (DIF_REGISTERDEVICE,
420 * Remove our new virtual interface to use for tunneling.
421 * This function must be called AFTER setup_interface!
423 * @return: TRUE if destruction was successful, else FALSE
428 SP_REMOVEDEVICE_PARAMS remove;
430 if (INVALID_HANDLE_VALUE == DeviceInfo)
433 remove.ClassInstallHeader.cbSize = sizeof (SP_CLASSINSTALL_HEADER);
434 remove.HwProfile = 0;
435 remove.Scope = DI_REMOVEDEVICE_GLOBAL;
436 remove.ClassInstallHeader.InstallFunction = DIF_REMOVE;
438 * 1. Prepare our existing device information set, and place the
439 * uninstall related information into the structure
441 if (!SetupDiSetClassInstallParamsA (DeviceInfo,
442 (PSP_DEVINFO_DATA) & DeviceNode,
443 &remove.ClassInstallHeader,
447 * 2. Uninstall the virtual interface using the class installer
449 if (!SetupDiCallClassInstaller (DIF_REMOVE,
451 (PSP_DEVINFO_DATA) & DeviceNode))
454 SetupDiDestroyDeviceInfoList (DeviceInfo);
460 * Do all the lookup necessary to retrieve the inteface's actual name
463 * @return: TRUE if we were able to lookup the interface's name, else FALSE
466 resolve_interface_name ()
469 SP_DEVINFO_LIST_DETAIL_DATA device_details;
470 char pnp_instance_id [MAX_DEVICE_ID_LEN];
471 HKEY adapter_key_handle;
475 boolean retval = FALSE;
476 char adapter[] = INTERFACE_REGISTRY_LOCATION;
478 /* We can obtain the PNP instance ID from our setupapi handle */
479 device_details.cbSize = sizeof (device_details);
480 if (CR_SUCCESS != CM_Get_Device_ID_ExA (DeviceNode.DevInst,
481 (PCHAR) pnp_instance_id,
484 NULL)) //hMachine, we are local
487 /* Now we can use this ID to locate the correct networks interface in registry */
488 if (ERROR_SUCCESS != RegOpenKeyExA (
493 &adapter_key_handle))
496 /* Of course there is a multitude of entries here, with arbitrary names,
497 * thus we need to iterate through there.
501 char instance_key[256];
502 char query_key [256];
503 HKEY instance_key_handle;
504 char pnpinstanceid_name[] = "PnpInstanceID";
505 char pnpinstanceid_value[256];
506 char adaptername_name[] = "Name";
509 len = sizeof (adapter_key_handle);
510 /* optain a subkey of {4D36E972-E325-11CE-BFC1-08002BE10318} */
511 status = RegEnumKeyExA (
521 /* this may fail due to one of two reasons:
522 * we are at the end of the list*/
523 if (ERROR_NO_MORE_ITEMS == status)
525 // * we found a broken registry key, continue with the next key.
526 if (ERROR_SUCCESS != status)
529 /* prepare our new query string: */
530 snprintf (query_key, 256, "%s\\%s\\Connection",
531 INTERFACE_REGISTRY_LOCATION,
534 /* look inside instance_key\\Connection */
535 status = RegOpenKeyExA (
540 &instance_key_handle);
542 if (status != ERROR_SUCCESS)
545 /* now, read our PnpInstanceID */
546 len = sizeof (pnpinstanceid_value);
547 status = RegQueryValueExA (instance_key_handle,
549 NULL, //reserved, always NULL according to MSDN
551 (LPBYTE) pnpinstanceid_value,
554 if (status != ERROR_SUCCESS || data_type != REG_SZ)
557 /* compare the value we got to our devices PNPInstanceID*/
558 if (0 != strncmp (pnpinstanceid_value, pnp_instance_id,
559 sizeof (pnpinstanceid_value) / sizeof (char)))
562 len = sizeof (device_visible_name);
563 status = RegQueryValueExA (
566 NULL, //reserved, always NULL according to MSDN
568 (LPBYTE) device_visible_name,
571 if (status != ERROR_SUCCESS || data_type != REG_SZ)
575 * we have successfully found OUR instance,
576 * save the device GUID before exiting
579 strncpy (device_guid, instance_key, 256);
583 RegCloseKey (instance_key_handle);
588 RegCloseKey (adapter_key_handle);
594 check_tapw32_version (HANDLE handle)
599 memset (&(version), 0, sizeof (version));
602 if (DeviceIoControl (handle, TAP_WIN_IOCTL_GET_VERSION,
603 &version, sizeof (version),
604 &version, sizeof (version), &len, NULL))
607 fprintf (stderr, "TAP-Windows Driver Version %d.%d %s",
610 (version[2] ? "(DEBUG)" : ""));
614 if (version[0] != TAP_WIN_MIN_MAJOR || version[1] < TAP_WIN_MIN_MINOR)
616 fprintf (stderr, "ERROR: This version of gnunet requires a TAP-Windows driver that is at least version %d.%d!\n",
626 * Creates a tun-interface called dev;
628 * @return the fd to the tun or -1 on error
633 char device_path[256];
636 if (!setup_interface ())
639 return INVALID_HANDLE_VALUE;
642 if (!resolve_interface_name ())
645 return INVALID_HANDLE_VALUE;
648 /* Open Windows TAP-Windows adapter */
649 snprintf (device_path, sizeof (device_path), "%s%s%s",
654 handle = CreateFile (
656 GENERIC_READ | GENERIC_WRITE,
657 0, /* was: FILE_SHARE_READ */
660 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
664 if (handle == INVALID_HANDLE_VALUE)
666 fprintf (stderr, "CreateFile failed on TAP device: %s\n", device_path);
670 /* get driver version info */
671 if (!check_tapw32_version (handle))
673 CloseHandle (handle);
674 return INVALID_HANDLE_VALUE;
677 /* TODO (opt?): get MTU-Size */
683 tun_up (HANDLE handle)
687 if (DeviceIoControl (handle, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
688 &status, sizeof (status),
689 &status, sizeof (status), &len, NULL))
691 fprintf (stderr, "The TAP-Windows driver ignored our request to set the interface UP (TAP_WIN_IOCTL_SET_MEDIA_STATUS DeviceIoControl call)!\n");
695 /* Wait for the device to go UP, might take some time. */
696 Sleep ((TAP32_POSTUP_WAITTIME)*1000);
703 attempt_std_in ( struct overlapped_facility * std_in,
704 struct overlapped_facility * tap_write)
710 attempt_tap_read (HANDLE tap_handle,
711 struct overlapped_facility * tap_read,
712 struct overlapped_facility * std_out)
715 if (IOSTATE_READY == tap_read->iostate)
717 if (!ResetEvent (tap_read->overlapped.hEvent))
721 tap_read->status = ReadFile (tap_handle,
722 &tap_read->buffer[MAX_SIZE],
724 &tap_read->buffer_size,
725 &tap_read->overlapped);
727 /* Check how the task is handled */
728 if (tap_read->status)
729 {/* async event processed immediately*/
731 /* reset event manually*/
732 if (!SetEvent (tap_read->overlapped.hEvent))
735 /* we successfully read something from the TAP and now need to
736 * send it our via STDOUT. Is that possible at the moment? */
737 if (IOSTATE_READY == std_out->iostate && 0 < tap_read->buffer_size)
738 { /* hand over this buffers content */
739 memcpy (std_out->buffer,
742 std_out->buffer_size = tap_read->buffer_size;
743 std_out->iostate = IOSTATE_READY;
745 else if (0 < tap_read->buffer_size)
746 { /* If we have have read our buffer, wait for our write-partner*/
747 tap_read->iostate = IOSTATE_WAITING;
748 // TODO: shall we attempt to fill our bufferm or should we wait for our write-partner to finish?
751 else /* operation was either queued or failed*/
753 int err = GetLastError ();
754 if (ERROR_IO_PENDING == err)
755 { /* operation queued */
756 tap_read->iostate = IOSTATE_QUEUED;
759 { /* error occurred, let the rest of the elements finish */
760 tap_read->path_open = FALSE;
761 tap_read->iostate = IOSTATE_FAILED;
765 // We are queued and should check if the read has finished
766 else if (IOSTATE_QUEUED == tap_read->iostate )
768 // there was an operation going on already, check if that has completed now.
769 tap_read->status = GetOverlappedResult (tap_handle,
770 &tap_read->overlapped,
771 &tap_read->buffer_size,
773 if (tap_read->status)
774 {/* successful return for a queued operation */
775 if (!ResetEvent (tap_read->overlapped.hEvent))
778 /* we successfully read something from the TAP and now need to
779 * send it our via STDOUT. Is that possible at the moment? */
780 if (IOSTATE_READY == std_out->iostate && 0 < tap_read->buffer_size )
781 { /* hand over this buffers content */
782 memcpy (std_out->buffer,
785 std_out->buffer_size = tap_read->buffer_size;
786 std_out->iostate = IOSTATE_READY;
787 tap_read->iostate = IOSTATE_READY;
789 else if (0 < tap_read->buffer_size)
790 { /* If we have have read our buffer, wait for our write-partner*/
791 tap_read->iostate = IOSTATE_WAITING;
792 // TODO: shall we attempt to fill our bufferm or should we wait for our write-partner to finish?
796 { /* operation still pending/queued or failed? */
797 int err = GetLastError ();
798 if (ERROR_IO_INCOMPLETE != err && ERROR_IO_PENDING != err )
799 { /* error occurred, let the rest of the elements finish */
800 tap_read->path_open = FALSE;
801 tap_read->iostate = IOSTATE_FAILED;
809 attempt_tap_write (HANDLE tap_handle,
810 struct overlapped_facility * tap_write,
811 struct overlapped_facility * std_in)
817 attempt_std_out ( struct overlapped_facility * std_out,
818 struct overlapped_facility * tap_read)
824 * Initialize a overlapped structure
826 * @param elem the element to initilize
827 * @param initial_state the initial state for this instance
828 * @param signaled if the hEvent created should default to signaled or not
829 * @return true on success, else false
832 initialize_overlapped_facility (struct overlapped_facility * elem,
837 elem->path_open = TRUE;
838 elem->status = initial_state;
840 elem->buffer_size = 0;
841 elem->overlapped.hEvent = CreateEvent (NULL, TRUE, signaled, NULL);
842 if (NULL == elem->overlapped.hEvent)
849 * Start forwarding to and from the tunnel.
851 * @param fd_tun tunnel FD
854 run (HANDLE tap_handle)
856 /* IO-Facility for reading from our virtual interface */
857 struct overlapped_facility tap_read;
858 /* IO-Facility for writing to our virtual interface */
859 struct overlapped_facility tap_write;
860 /* IO-Facility for reading from stdin */
861 struct overlapped_facility std_in;
862 /* IO-Facility for writing to stdout */
863 struct overlapped_facility std_out;
866 /* we do this HERE and not beforehand (in init_tun()), in contrast to openvpn
867 * to remove the need to flush the arp cache, handle DHCP and wrong IPs.
869 * DHCP and such are all features we will never use in gnunet afaik.
870 * But for openvpn those are essential.
872 if (!tun_up (tap_handle))
875 /* Initialize our overlapped IO structures*/
876 if (initialize_overlapped_facility (&tap_read, TRUE, FALSE)
877 && initialize_overlapped_facility (&tap_write, FALSE, TRUE)
878 && initialize_overlapped_facility (&std_in, TRUE, FALSE)
879 && initialize_overlapped_facility (&std_out, FALSE, TRUE))
884 // Set Device to Subnet-Mode?
885 // do we really need tun.c:2925 ?
886 // Why does openvpn assign IPv4's there??? Foobar??
888 // Setup should be complete here.
889 // If something is missing, check init.c:3400+
892 // tunnel_point_to_point
895 while (std_in.path_open
897 || tap_read.path_open
898 || tap_write.path_open)
900 /* perform READ from stdin if possible */
901 if ((std_in.path_open && tap_write.path_open)
902 || IOSTATE_QUEUED == std_in.iostate)
903 if (!attempt_std_in (&std_in, &tap_write))
906 /* perform READ from tap if possible */
907 if ((tap_read.path_open && std_out.path_open)
908 || IOSTATE_QUEUED == tap_read.iostate )
909 if (!attempt_tap_read (tap_handle, &tap_read, &std_out))
912 /* perform WRITE to tap if possible */
913 if ( IOSTATE_READY == tap_write.iostate && tap_write.path_open )
914 if (!attempt_tap_write (tap_handle, &tap_write, &std_in))
917 /* perform WRITE to STDOUT if possible */
918 if ( IOSTATE_READY == std_out.iostate && std_out.path_open)
919 if (!attempt_std_out (&std_out, &tap_read))
922 // check if any path is blocked
930 * Open VPN tunnel interface.
932 * @param argc must be 6
933 * @param argv 0: binary name (gnunet-helper-vpn)
934 * 1: tunnel interface name (gnunet-vpn)
935 * 2: IPv6 address (::1), "-" to disable
936 * 3: IPv6 netmask length in bits (64), ignored if #2 is "-"
937 * 4: IPv4 address (1.2.3.4), "-" to disable
938 * 5: IPv4 netmask (255.255.0.0), ignored if #4 is "-"
941 main (int argc, char **argv)
949 fprintf (stderr, "Fatal: must supply 5 arguments!\n");
953 strncpy (hwid, argv[1], LINE_LEN);
954 hwid[LINE_LEN - 1] = '\0';
957 * We use our PID for finding/resolving the control-panel name of our virtual
958 * device. PIDs are (of course) unique at runtime, thus we can safely use it
959 * as additional hardware-id for our device.
961 snprintf (secondary_hwid, LINE_LEN / 2, "%s-%d",
965 if (INVALID_HANDLE_VALUE == (handle = init_tun ()))
967 fprintf (stderr, "Fatal: could not initialize virtual-interface %s with IPv6 %s/%s and IPv4 %s/%s\n",
976 if (0 != strcmp (argv[2], "-"))
978 const char *address = argv[2];
979 long prefix_len = atol (argv[3]);
981 if ((prefix_len < 1) || (prefix_len > 127))
983 fprintf (stderr, "Fatal: prefix_len out of range\n");
988 set_address6 (address, prefix_len);
991 if (0 != strcmp (argv[4], "-"))
993 const char *address = argv[4];
994 const char *mask = argv[5];
996 set_address4 (address, mask);
1000 // tap_allow_nonadmin_access
1006 remove_interface ();