Upgrade to OpenVPN 2.1rc22
[tomato.git] / release / src / router / openvpn / tun.c
blobd82ac49a56d88575cfabc39900d76a5ac0f30eb3
1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
8 * Copyright (C) 2002-2009 OpenVPN Technologies, Inc. <sales@openvpn.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 * Support routines for configuring and accessing TUN/TAP
27 * virtual network adapters.
29 * This file is based on the TUN/TAP driver interface routines
30 * from VTun by Maxim Krasnyansky <max_mk@yahoo.com>.
33 #include "syshead.h"
35 #include "tun.h"
36 #include "fdmisc.h"
37 #include "common.h"
38 #include "misc.h"
39 #include "socket.h"
40 #include "manage.h"
41 #include "route.h"
42 #include "win32.h"
44 #include "memdbg.h"
46 #ifdef WIN32
48 /* #define SIMULATE_DHCP_FAILED */ /* simulate bad DHCP negotiation */
50 #define NI_TEST_FIRST (1<<0)
51 #define NI_IP_NETMASK (1<<1)
52 #define NI_OPTIONS (1<<2)
54 static void netsh_ifconfig (const struct tuntap_options *to,
55 const char *flex_name,
56 const in_addr_t ip,
57 const in_addr_t netmask,
58 unsigned int flags);
60 static const char *netsh_get_id (const char *dev_node, struct gc_arena *gc);
62 #endif
64 #ifdef TARGET_SOLARIS
65 static void solaris_error_close (struct tuntap *tt, const struct env_set *es, const char *actual);
66 #endif
68 bool
69 is_dev_type (const char *dev, const char *dev_type, const char *match_type)
71 ASSERT (match_type);
72 if (!dev)
73 return false;
74 if (dev_type)
75 return !strcmp (dev_type, match_type);
76 else
77 return !strncmp (dev, match_type, strlen (match_type));
80 int
81 dev_type_enum (const char *dev, const char *dev_type)
83 if (is_dev_type (dev, dev_type, "tun"))
84 return DEV_TYPE_TUN;
85 else if (is_dev_type (dev, dev_type, "tap"))
86 return DEV_TYPE_TAP;
87 else if (is_dev_type (dev, dev_type, "null"))
88 return DEV_TYPE_NULL;
89 else
90 return DEV_TYPE_UNDEF;
93 const char *
94 dev_type_string (const char *dev, const char *dev_type)
96 switch (dev_type_enum (dev, dev_type))
98 case DEV_TYPE_TUN:
99 return "tun";
100 case DEV_TYPE_TAP:
101 return "tap";
102 case DEV_TYPE_NULL:
103 return "null";
104 default:
105 return "[unknown-dev-type]";
110 * Try to predict the actual TUN/TAP device instance name,
111 * before the device is actually opened.
113 const char *
114 guess_tuntap_dev (const char *dev,
115 const char *dev_type,
116 const char *dev_node,
117 struct gc_arena *gc)
119 #ifdef WIN32
120 const int dt = dev_type_enum (dev, dev_type);
121 if (dt == DEV_TYPE_TUN || dt == DEV_TYPE_TAP)
123 return netsh_get_id (dev_node, gc);
125 #endif
127 /* default case */
128 return dev;
132 * Called by the open_tun function of OSes to check if we
133 * explicitly support IPv6.
135 * In this context, explicit means that the OS expects us to
136 * do something special to the tun socket in order to support
137 * IPv6, i.e. it is not transparent.
139 * ipv6_explicitly_supported should be set to false if we don't
140 * have any explicit IPv6 code in the tun device handler.
142 * If ipv6_explicitly_supported is true, then we have explicit
143 * OS-specific tun dev code for handling IPv6. If so, tt->ipv6
144 * is set according to the --tun-ipv6 command line option.
146 static void
147 ipv6_support (bool ipv6, bool ipv6_explicitly_supported, struct tuntap* tt)
149 tt->ipv6 = false;
150 if (ipv6_explicitly_supported)
151 tt->ipv6 = ipv6;
152 else if (ipv6)
153 msg (M_WARN, "NOTE: explicit support for IPv6 tun devices is not provided for this OS");
156 /* --ifconfig-nowarn disables some options sanity checking */
157 static const char ifconfig_warn_how_to_silence[] = "(silence this warning with --ifconfig-nowarn)";
160 * If !tun, make sure ifconfig_remote_netmask looks
161 * like a netmask.
163 * If tun, make sure ifconfig_remote_netmask looks
164 * like an IPv4 address.
166 static void
167 ifconfig_sanity_check (bool tun, in_addr_t addr, int topology)
169 struct gc_arena gc = gc_new ();
170 const bool looks_like_netmask = ((addr & 0xFF000000) == 0xFF000000);
171 if (tun)
173 if (looks_like_netmask && (topology == TOP_NET30 || topology == TOP_P2P))
174 msg (M_WARN, "WARNING: Since you are using --dev tun with a point-to-point topology, the second argument to --ifconfig must be an IP address. You are using something (%s) that looks more like a netmask. %s",
175 print_in_addr_t (addr, 0, &gc),
176 ifconfig_warn_how_to_silence);
178 else /* tap */
180 if (!looks_like_netmask)
181 msg (M_WARN, "WARNING: Since you are using --dev tap, the second argument to --ifconfig must be a netmask, for example something like 255.255.255.0. %s",
182 ifconfig_warn_how_to_silence);
184 gc_free (&gc);
188 * For TAP-style devices, generate a broadcast address.
190 static in_addr_t
191 generate_ifconfig_broadcast_addr (in_addr_t local,
192 in_addr_t netmask)
194 return local | ~netmask;
198 * Check that --local and --remote addresses do not
199 * clash with ifconfig addresses or subnet.
201 static void
202 check_addr_clash (const char *name,
203 int type,
204 in_addr_t public,
205 in_addr_t local,
206 in_addr_t remote_netmask)
208 struct gc_arena gc = gc_new ();
209 #if 0
210 msg (M_INFO, "CHECK_ADDR_CLASH type=%d public=%s local=%s, remote_netmask=%s",
211 type,
212 print_in_addr_t (public, 0, &gc),
213 print_in_addr_t (local, 0, &gc),
214 print_in_addr_t (remote_netmask, 0, &gc));
215 #endif
217 if (public)
219 if (type == DEV_TYPE_TUN)
221 const in_addr_t test_netmask = 0xFFFFFF00;
222 const in_addr_t public_net = public & test_netmask;
223 const in_addr_t local_net = local & test_netmask;
224 const in_addr_t remote_net = remote_netmask & test_netmask;
226 if (public == local || public == remote_netmask)
227 msg (M_WARN,
228 "WARNING: --%s address [%s] conflicts with --ifconfig address pair [%s, %s]. %s",
229 name,
230 print_in_addr_t (public, 0, &gc),
231 print_in_addr_t (local, 0, &gc),
232 print_in_addr_t (remote_netmask, 0, &gc),
233 ifconfig_warn_how_to_silence);
235 if (public_net == local_net || public_net == remote_net)
236 msg (M_WARN,
237 "WARNING: potential conflict between --%s address [%s] and --ifconfig address pair [%s, %s] -- this is a warning only that is triggered when local/remote addresses exist within the same /24 subnet as --ifconfig endpoints. %s",
238 name,
239 print_in_addr_t (public, 0, &gc),
240 print_in_addr_t (local, 0, &gc),
241 print_in_addr_t (remote_netmask, 0, &gc),
242 ifconfig_warn_how_to_silence);
244 else if (type == DEV_TYPE_TAP)
246 const in_addr_t public_network = public & remote_netmask;
247 const in_addr_t virtual_network = local & remote_netmask;
248 if (public_network == virtual_network)
249 msg (M_WARN,
250 "WARNING: --%s address [%s] conflicts with --ifconfig subnet [%s, %s] -- local and remote addresses cannot be inside of the --ifconfig subnet. %s",
251 name,
252 print_in_addr_t (public, 0, &gc),
253 print_in_addr_t (local, 0, &gc),
254 print_in_addr_t (remote_netmask, 0, &gc),
255 ifconfig_warn_how_to_silence);
258 gc_free (&gc);
262 * Issue a warning if ip/netmask (on the virtual IP network) conflicts with
263 * the settings on the local LAN. This is designed to flag issues where
264 * (for example) the OpenVPN server LAN is running on 192.168.1.x, but then
265 * an OpenVPN client tries to connect from a public location that is also running
266 * off of a router set to 192.168.1.x.
268 void
269 check_subnet_conflict (const in_addr_t ip,
270 const in_addr_t netmask,
271 const char *prefix)
273 struct gc_arena gc = gc_new ();
274 in_addr_t lan_gw = 0;
275 in_addr_t lan_netmask = 0;
277 if (get_default_gateway (&lan_gw, &lan_netmask))
279 const in_addr_t lan_network = lan_gw & lan_netmask;
280 const in_addr_t network = ip & netmask;
282 /* do the two subnets defined by network/netmask and lan_network/lan_netmask intersect? */
283 if ((network & lan_netmask) == lan_network
284 || (lan_network & netmask) == network)
286 msg (M_WARN, "WARNING: potential %s subnet conflict between local LAN [%s/%s] and remote VPN [%s/%s]",
287 prefix,
288 print_in_addr_t (lan_network, 0, &gc),
289 print_in_addr_t (lan_netmask, 0, &gc),
290 print_in_addr_t (network, 0, &gc),
291 print_in_addr_t (netmask, 0, &gc));
294 gc_free (&gc);
297 void
298 warn_on_use_of_common_subnets (void)
300 struct gc_arena gc = gc_new ();
301 in_addr_t lan_gw = 0;
302 in_addr_t lan_netmask = 0;
304 if (get_default_gateway (&lan_gw, &lan_netmask))
306 const in_addr_t lan_network = lan_gw & lan_netmask;
307 if (lan_network == 0xC0A80000 || lan_network == 0xC0A80100)
308 msg (M_WARN, "NOTE: your local LAN uses the extremely common subnet address 192.168.0.x or 192.168.1.x. Be aware that this might create routing conflicts if you connect to the VPN server from public locations such as internet cafes that use the same subnet.");
310 gc_free (&gc);
314 * Complain if --dev tap and --ifconfig is used on an OS for which
315 * we don't have a custom tap ifconfig template below.
317 static void
318 no_tap_ifconfig ()
320 msg (M_FATAL, "Sorry but you cannot use --dev tap and --ifconfig together on this OS because I have not yet been programmed to understand the appropriate ifconfig syntax to use for TAP-style devices on this OS. Your best alternative is to use an --up script and do the ifconfig command manually.");
324 * Return a string to be used for options compatibility check
325 * between peers.
327 const char *
328 ifconfig_options_string (const struct tuntap* tt, bool remote, bool disable, struct gc_arena *gc)
330 struct buffer out = alloc_buf_gc (256, gc);
331 if (tt->did_ifconfig_setup && !disable)
333 if (tt->type == DEV_TYPE_TAP || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET))
335 buf_printf (&out, "%s %s",
336 print_in_addr_t (tt->local & tt->remote_netmask, 0, gc),
337 print_in_addr_t (tt->remote_netmask, 0, gc));
339 else if (tt->type == DEV_TYPE_TUN)
341 const char *l, *r;
342 if (remote)
344 r = print_in_addr_t (tt->local, 0, gc);
345 l = print_in_addr_t (tt->remote_netmask, 0, gc);
347 else
349 l = print_in_addr_t (tt->local, 0, gc);
350 r = print_in_addr_t (tt->remote_netmask, 0, gc);
352 buf_printf (&out, "%s %s", r, l);
354 else
355 buf_printf (&out, "[undef]");
357 return BSTR (&out);
361 * Return a status string describing wait state.
363 const char *
364 tun_stat (const struct tuntap *tt, unsigned int rwflags, struct gc_arena *gc)
366 struct buffer out = alloc_buf_gc (64, gc);
367 if (tt)
369 if (rwflags & EVENT_READ)
371 buf_printf (&out, "T%s",
372 (tt->rwflags_debug & EVENT_READ) ? "R" : "r");
373 #ifdef WIN32
374 buf_printf (&out, "%s",
375 overlapped_io_state_ascii (&tt->reads));
376 #endif
378 if (rwflags & EVENT_WRITE)
380 buf_printf (&out, "T%s",
381 (tt->rwflags_debug & EVENT_WRITE) ? "W" : "w");
382 #ifdef WIN32
383 buf_printf (&out, "%s",
384 overlapped_io_state_ascii (&tt->writes));
385 #endif
388 else
390 buf_printf (&out, "T?");
392 return BSTR (&out);
396 * Return true for point-to-point topology, false for subnet topology
398 bool
399 is_tun_p2p (const struct tuntap *tt)
401 bool tun = false;
403 if (tt->type == DEV_TYPE_TAP || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET))
404 tun = false;
405 else if (tt->type == DEV_TYPE_TUN)
406 tun = true;
407 else
408 msg (M_FATAL, "Error: problem with tun vs. tap setting"); /* JYFIXME -- needs to be caught earlier, in init_tun? */
410 return tun;
414 * Init tun/tap object.
416 * Set up tuntap structure for ifconfig,
417 * but don't execute yet.
419 struct tuntap *
420 init_tun (const char *dev, /* --dev option */
421 const char *dev_type, /* --dev-type option */
422 int topology, /* one of the TOP_x values */
423 const char *ifconfig_local_parm, /* --ifconfig parm 1 */
424 const char *ifconfig_remote_netmask_parm, /* --ifconfig parm 2 */
425 in_addr_t local_public,
426 in_addr_t remote_public,
427 const bool strict_warn,
428 struct env_set *es)
430 struct gc_arena gc = gc_new ();
431 struct tuntap *tt;
433 ALLOC_OBJ (tt, struct tuntap);
434 clear_tuntap (tt);
436 tt->type = dev_type_enum (dev, dev_type);
437 tt->topology = topology;
439 if (ifconfig_local_parm && ifconfig_remote_netmask_parm)
441 bool tun = false;
442 const char *ifconfig_local = NULL;
443 const char *ifconfig_remote_netmask = NULL;
444 const char *ifconfig_broadcast = NULL;
447 * We only handle TUN/TAP devices here, not --dev null devices.
449 tun = is_tun_p2p (tt);
452 * Convert arguments to binary IPv4 addresses.
455 tt->local = getaddr (
456 GETADDR_RESOLVE
457 | GETADDR_HOST_ORDER
458 | GETADDR_FATAL_ON_SIGNAL
459 | GETADDR_FATAL,
460 ifconfig_local_parm,
462 NULL,
463 NULL);
465 tt->remote_netmask = getaddr (
466 (tun ? GETADDR_RESOLVE : 0)
467 | GETADDR_HOST_ORDER
468 | GETADDR_FATAL_ON_SIGNAL
469 | GETADDR_FATAL,
470 ifconfig_remote_netmask_parm,
472 NULL,
473 NULL);
476 * Look for common errors in --ifconfig parms
478 if (strict_warn)
480 ifconfig_sanity_check (tt->type == DEV_TYPE_TUN, tt->remote_netmask, tt->topology);
483 * If local_public or remote_public addresses are defined,
484 * make sure they do not clash with our virtual subnet.
487 check_addr_clash ("local",
488 tt->type,
489 local_public,
490 tt->local,
491 tt->remote_netmask);
493 check_addr_clash ("remote",
494 tt->type,
495 remote_public,
496 tt->local,
497 tt->remote_netmask);
499 if (tt->type == DEV_TYPE_TAP || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET))
500 check_subnet_conflict (tt->local, tt->remote_netmask, "TUN/TAP adapter");
501 else if (tt->type == DEV_TYPE_TUN)
502 check_subnet_conflict (tt->local, ~0, "TUN/TAP adapter");
506 * Set ifconfig parameters
508 ifconfig_local = print_in_addr_t (tt->local, 0, &gc);
509 ifconfig_remote_netmask = print_in_addr_t (tt->remote_netmask, 0, &gc);
512 * If TAP-style interface, generate broadcast address.
514 if (!tun)
516 tt->broadcast = generate_ifconfig_broadcast_addr (tt->local, tt->remote_netmask);
517 ifconfig_broadcast = print_in_addr_t (tt->broadcast, 0, &gc);
521 * Set environmental variables with ifconfig parameters.
523 if (es)
525 setenv_str (es, "ifconfig_local", ifconfig_local);
526 if (tun)
528 setenv_str (es, "ifconfig_remote", ifconfig_remote_netmask);
530 else
532 setenv_str (es, "ifconfig_netmask", ifconfig_remote_netmask);
533 setenv_str (es, "ifconfig_broadcast", ifconfig_broadcast);
537 tt->did_ifconfig_setup = true;
539 gc_free (&gc);
540 return tt;
544 * Platform specific tun initializations
546 void
547 init_tun_post (struct tuntap *tt,
548 const struct frame *frame,
549 const struct tuntap_options *options)
551 tt->options = *options;
552 #ifdef WIN32
553 overlapped_io_init (&tt->reads, frame, FALSE, true);
554 overlapped_io_init (&tt->writes, frame, TRUE, true);
555 tt->rw_handle.read = tt->reads.overlapped.hEvent;
556 tt->rw_handle.write = tt->writes.overlapped.hEvent;
557 tt->adapter_index = ~0;
558 #endif
561 /* execute the ifconfig command through the shell */
562 void
563 do_ifconfig (struct tuntap *tt,
564 const char *actual, /* actual device name */
565 int tun_mtu,
566 const struct env_set *es)
568 struct gc_arena gc = gc_new ();
570 if (tt->did_ifconfig_setup)
572 bool tun = false;
573 const char *ifconfig_local = NULL;
574 const char *ifconfig_remote_netmask = NULL;
575 const char *ifconfig_broadcast = NULL;
576 struct argv argv;
578 argv_init (&argv);
581 * We only handle TUN/TAP devices here, not --dev null devices.
583 tun = is_tun_p2p (tt);
586 * Set ifconfig parameters
588 ifconfig_local = print_in_addr_t (tt->local, 0, &gc);
589 ifconfig_remote_netmask = print_in_addr_t (tt->remote_netmask, 0, &gc);
592 * If TAP-style device, generate broadcast address.
594 if (!tun)
595 ifconfig_broadcast = print_in_addr_t (tt->broadcast, 0, &gc);
597 #ifdef ENABLE_MANAGEMENT
598 if (management)
600 management_set_state (management,
601 OPENVPN_STATE_ASSIGN_IP,
602 NULL,
603 tt->local,
606 #endif
609 #if defined(TARGET_LINUX)
610 #ifdef CONFIG_FEATURE_IPROUTE
612 * Set the MTU for the device
614 argv_printf (&argv,
615 "%s link set dev %s up mtu %d",
616 iproute_path,
617 actual,
618 tun_mtu
620 argv_msg (M_INFO, &argv);
621 openvpn_execve_check (&argv, es, S_FATAL, "Linux ip link set failed");
623 if (tun) {
626 * Set the address for the device
628 argv_printf (&argv,
629 "%s addr add dev %s local %s peer %s",
630 iproute_path,
631 actual,
632 ifconfig_local,
633 ifconfig_remote_netmask
635 argv_msg (M_INFO, &argv);
636 openvpn_execve_check (&argv, es, S_FATAL, "Linux ip addr add failed");
637 } else {
638 argv_printf (&argv,
639 "%s addr add dev %s %s/%d broadcast %s",
640 iproute_path,
641 actual,
642 ifconfig_local,
643 count_netmask_bits(ifconfig_remote_netmask),
644 ifconfig_broadcast
646 argv_msg (M_INFO, &argv);
647 openvpn_execve_check (&argv, es, S_FATAL, "Linux ip addr add failed");
649 tt->did_ifconfig = true;
650 #else
651 if (tun)
652 argv_printf (&argv,
653 "%s %s %s pointopoint %s mtu %d",
654 IFCONFIG_PATH,
655 actual,
656 ifconfig_local,
657 ifconfig_remote_netmask,
658 tun_mtu
660 else
661 argv_printf (&argv,
662 "%s %s %s netmask %s mtu %d broadcast %s",
663 IFCONFIG_PATH,
664 actual,
665 ifconfig_local,
666 ifconfig_remote_netmask,
667 tun_mtu,
668 ifconfig_broadcast
670 argv_msg (M_INFO, &argv);
671 openvpn_execve_check (&argv, es, S_FATAL, "Linux ifconfig failed");
672 tt->did_ifconfig = true;
674 #endif /*CONFIG_FEATURE_IPROUTE*/
675 #elif defined(TARGET_SOLARIS)
677 /* Solaris 2.6 (and 7?) cannot set all parameters in one go...
678 * example:
679 * ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 up
680 * ifconfig tun2 netmask 255.255.255.255
682 if (tun)
684 argv_printf (&argv,
685 "%s %s %s %s mtu %d up",
686 IFCONFIG_PATH,
687 actual,
688 ifconfig_local,
689 ifconfig_remote_netmask,
690 tun_mtu
693 argv_msg (M_INFO, &argv);
694 if (!openvpn_execve_check (&argv, es, 0, "Solaris ifconfig phase-1 failed"))
695 solaris_error_close (tt, es, actual);
697 argv_printf (&argv,
698 "%s %s netmask 255.255.255.255",
699 IFCONFIG_PATH,
700 actual
703 else
704 no_tap_ifconfig ();
706 argv_msg (M_INFO, &argv);
707 if (!openvpn_execve_check (&argv, es, 0, "Solaris ifconfig phase-2 failed"))
708 solaris_error_close (tt, es, actual);
710 tt->did_ifconfig = true;
712 #elif defined(TARGET_OPENBSD)
715 * OpenBSD tun devices appear to be persistent by default. It seems in order
716 * to make this work correctly, we need to delete the previous instance
717 * (if it exists), and re-ifconfig. Let me know if you know a better way.
720 argv_printf (&argv,
721 "%s %s destroy",
722 IFCONFIG_PATH,
723 actual);
724 argv_msg (M_INFO, &argv);
725 openvpn_execve_check (&argv, es, 0, NULL);
726 argv_printf (&argv,
727 "%s %s create",
728 IFCONFIG_PATH,
729 actual);
730 argv_msg (M_INFO, &argv);
731 openvpn_execve_check (&argv, es, 0, NULL);
732 msg (M_INFO, "NOTE: Tried to delete pre-existing tun/tap instance -- No Problem if failure");
734 /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
735 if (tun)
736 argv_printf (&argv,
737 "%s %s %s %s mtu %d netmask 255.255.255.255 up",
738 IFCONFIG_PATH,
739 actual,
740 ifconfig_local,
741 ifconfig_remote_netmask,
742 tun_mtu
744 else
745 argv_printf (&argv,
746 "%s %s %s netmask %s mtu %d broadcast %s link0",
747 IFCONFIG_PATH,
748 actual,
749 ifconfig_local,
750 ifconfig_remote_netmask,
751 tun_mtu,
752 ifconfig_broadcast
754 argv_msg (M_INFO, &argv);
755 openvpn_execve_check (&argv, es, S_FATAL, "OpenBSD ifconfig failed");
756 tt->did_ifconfig = true;
758 #elif defined(TARGET_NETBSD)
760 if (tun)
761 argv_printf (&argv,
762 "%s %s %s %s mtu %d netmask 255.255.255.255 up",
763 IFCONFIG_PATH,
764 actual,
765 ifconfig_local,
766 ifconfig_remote_netmask,
767 tun_mtu
769 else
771 * NetBSD has distinct tun and tap devices
772 * so we don't need the "link0" extra parameter to specify we want to do
773 * tunneling at the ethernet level
775 argv_printf (&argv,
776 "%s %s %s netmask %s mtu %d broadcast %s",
777 IFCONFIG_PATH,
778 actual,
779 ifconfig_local,
780 ifconfig_remote_netmask,
781 tun_mtu,
782 ifconfig_broadcast
784 argv_msg (M_INFO, &argv);
785 openvpn_execve_check (&argv, es, S_FATAL, "NetBSD ifconfig failed");
786 tt->did_ifconfig = true;
788 #elif defined(TARGET_DARWIN)
791 * Darwin (i.e. Mac OS X) seems to exhibit similar behaviour to OpenBSD...
794 argv_printf (&argv,
795 "%s %s delete",
796 IFCONFIG_PATH,
797 actual);
798 argv_msg (M_INFO, &argv);
799 openvpn_execve_check (&argv, es, 0, NULL);
800 msg (M_INFO, "NOTE: Tried to delete pre-existing tun/tap instance -- No Problem if failure");
803 /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
804 if (tun)
805 argv_printf (&argv,
806 "%s %s %s %s mtu %d netmask 255.255.255.255 up",
807 IFCONFIG_PATH,
808 actual,
809 ifconfig_local,
810 ifconfig_remote_netmask,
811 tun_mtu
813 else
815 if (tt->topology == TOP_SUBNET)
816 argv_printf (&argv,
817 "%s %s %s %s netmask %s mtu %d up",
818 IFCONFIG_PATH,
819 actual,
820 ifconfig_local,
821 ifconfig_local,
822 ifconfig_remote_netmask,
823 tun_mtu
825 else
826 argv_printf (&argv,
827 "%s %s %s netmask %s mtu %d up",
828 IFCONFIG_PATH,
829 actual,
830 ifconfig_local,
831 ifconfig_remote_netmask,
832 tun_mtu
835 argv_msg (M_INFO, &argv);
836 openvpn_execve_check (&argv, es, S_FATAL, "Mac OS X ifconfig failed");
837 tt->did_ifconfig = true;
839 /* Add a network route for the local tun interface */
840 if (!tun && tt->topology == TOP_SUBNET)
842 struct route r;
843 CLEAR (r);
844 r.defined = true;
845 r.network = tt->local & tt->remote_netmask;
846 r.netmask = tt->remote_netmask;
847 r.gateway = tt->local;
848 add_route (&r, tt, 0, es);
851 #elif defined(TARGET_FREEBSD)||defined(TARGET_DRAGONFLY)
853 /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
854 if (tun)
855 argv_printf (&argv,
856 "%s %s %s %s mtu %d netmask 255.255.255.255 up",
857 IFCONFIG_PATH,
858 actual,
859 ifconfig_local,
860 ifconfig_remote_netmask,
861 tun_mtu
863 else {
864 if (tt->topology == TOP_SUBNET)
865 argv_printf (&argv,
866 "%s %s %s netmask %s mtu %d up",
867 IFCONFIG_PATH,
868 actual,
869 ifconfig_local,
870 ifconfig_remote_netmask,
871 tun_mtu
873 else
874 argv_printf (&argv,
875 "%s %s %s netmask %s mtu %d up",
876 IFCONFIG_PATH,
877 actual,
878 ifconfig_local,
879 ifconfig_remote_netmask,
880 tun_mtu
884 argv_msg (M_INFO, &argv);
885 openvpn_execve_check (&argv, es, S_FATAL, "FreeBSD ifconfig failed");
886 tt->did_ifconfig = true;
888 /* Add a network route for the local tun interface */
889 if (!tun && tt->topology == TOP_SUBNET)
891 struct route r;
892 CLEAR (r);
893 r.defined = true;
894 r.network = tt->local & tt->remote_netmask;
895 r.netmask = tt->remote_netmask;
896 r.gateway = tt->local;
897 add_route (&r, tt, 0, es);
900 #elif defined (WIN32)
903 * Make sure that both ifconfig addresses are part of the
904 * same .252 subnet.
906 if (tun)
908 verify_255_255_255_252 (tt->local, tt->remote_netmask);
909 tt->adapter_netmask = ~3;
911 else
913 tt->adapter_netmask = tt->remote_netmask;
916 switch (tt->options.ip_win32_type)
918 case IPW32_SET_MANUAL:
919 msg (M_INFO, "******** NOTE: Please manually set the IP/netmask of '%s' to %s/%s (if it is not already set)",
920 actual,
921 ifconfig_local,
922 print_in_addr_t (tt->adapter_netmask, 0, &gc));
923 break;
924 case IPW32_SET_NETSH:
925 if (!strcmp (actual, "NULL"))
926 msg (M_FATAL, "Error: When using --ip-win32 netsh, if you have more than one TAP-Win32 adapter, you must also specify --dev-node");
928 netsh_ifconfig (&tt->options,
929 actual,
930 tt->local,
931 tt->adapter_netmask,
932 NI_IP_NETMASK|NI_OPTIONS);
934 break;
936 tt->did_ifconfig = true;
939 #else
940 msg (M_FATAL, "Sorry, but I don't know how to do 'ifconfig' commands on this operating system. You should ifconfig your TUN/TAP device manually or use an --up script.");
941 #endif
942 argv_reset (&argv);
944 gc_free (&gc);
947 void
948 clear_tuntap (struct tuntap *tuntap)
950 CLEAR (*tuntap);
951 #ifdef WIN32
952 tuntap->hand = NULL;
953 #else
954 tuntap->fd = -1;
955 #endif
956 #ifdef TARGET_SOLARIS
957 tuntap->ip_fd = -1;
958 #endif
959 tuntap->ipv6 = false;
962 static void
963 open_null (struct tuntap *tt)
965 tt->actual_name = string_alloc ("null", NULL);
968 #ifndef WIN32
969 static void
970 open_tun_generic (const char *dev, const char *dev_type, const char *dev_node,
971 bool ipv6, bool ipv6_explicitly_supported, bool dynamic,
972 struct tuntap *tt)
974 char tunname[256];
975 char dynamic_name[256];
976 bool dynamic_opened = false;
978 ipv6_support (ipv6, ipv6_explicitly_supported, tt);
980 if (tt->type == DEV_TYPE_NULL)
982 open_null (tt);
984 else
987 * --dev-node specified, so open an explicit device node
989 if (dev_node)
991 openvpn_snprintf (tunname, sizeof (tunname), "%s", dev_node);
993 else
996 * dynamic open is indicated by --dev specified without
997 * explicit unit number. Try opening /dev/[dev]n
998 * where n = [0, 255].
1000 if (dynamic && !has_digit((unsigned char *)dev))
1002 int i;
1003 for (i = 0; i < 256; ++i)
1005 openvpn_snprintf (tunname, sizeof (tunname),
1006 "/dev/%s%d", dev, i);
1007 openvpn_snprintf (dynamic_name, sizeof (dynamic_name),
1008 "%s%d", dev, i);
1009 if ((tt->fd = open (tunname, O_RDWR)) > 0)
1011 dynamic_opened = true;
1012 break;
1014 msg (D_READ_WRITE | M_ERRNO, "Tried opening %s (failed)", tunname);
1016 if (!dynamic_opened)
1017 msg (M_FATAL, "Cannot allocate TUN/TAP dev dynamically");
1020 * explicit unit number specified
1022 else
1024 openvpn_snprintf (tunname, sizeof (tunname), "/dev/%s", dev);
1028 if (!dynamic_opened)
1030 if ((tt->fd = open (tunname, O_RDWR)) < 0)
1031 msg (M_ERR, "Cannot open TUN/TAP dev %s", tunname);
1034 set_nonblock (tt->fd);
1035 set_cloexec (tt->fd); /* don't pass fd to scripts */
1036 msg (M_INFO, "TUN/TAP device %s opened", tunname);
1038 /* tt->actual_name is passed to up and down scripts and used as the ifconfig dev name */
1039 tt->actual_name = string_alloc (dynamic_opened ? dynamic_name : dev, NULL);
1043 static void
1044 close_tun_generic (struct tuntap *tt)
1046 if (tt->fd >= 0)
1047 close (tt->fd);
1048 if (tt->actual_name)
1049 free (tt->actual_name);
1050 clear_tuntap (tt);
1053 #endif
1055 #if defined(TARGET_LINUX)
1057 #ifdef HAVE_LINUX_IF_TUN_H /* New driver support */
1059 #ifndef HAVE_LINUX_SOCKIOS_H
1060 #error header file linux/sockios.h required
1061 #endif
1063 #if defined(HAVE_TUN_PI) && defined(HAVE_IPHDR) && defined(HAVE_IOVEC) && defined(ETH_P_IPV6) && defined(ETH_P_IP) && defined(HAVE_READV) && defined(HAVE_WRITEV)
1064 #define LINUX_IPV6 1
1065 /* #warning IPv6 ON */
1066 #else
1067 #define LINUX_IPV6 0
1068 /* #warning IPv6 OFF */
1069 #endif
1071 #if !PEDANTIC
1073 void
1074 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
1076 struct ifreq ifr;
1079 * Set tt->ipv6 to true if
1080 * (a) we have the capability of supporting --tun-ipv6, and
1081 * (b) --tun-ipv6 was specified.
1083 ipv6_support (ipv6, LINUX_IPV6, tt);
1086 * We handle --dev null specially, we do not open /dev/null for this.
1088 if (tt->type == DEV_TYPE_NULL)
1090 open_null (tt);
1092 else
1095 * Process --dev-node
1097 const char *node = dev_node;
1098 if (!node)
1099 node = "/dev/net/tun";
1102 * Open the interface
1104 if ((tt->fd = open (node, O_RDWR)) < 0)
1106 msg (M_WARN | M_ERRNO, "Note: Cannot open TUN/TAP dev %s", node);
1107 goto linux_2_2_fallback;
1111 * Process --tun-ipv6
1113 CLEAR (ifr);
1114 if (!tt->ipv6)
1115 ifr.ifr_flags = IFF_NO_PI;
1117 #if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN)
1118 ifr.ifr_flags |= IFF_ONE_QUEUE;
1119 #endif
1122 * Figure out if tun or tap device
1124 if (tt->type == DEV_TYPE_TUN)
1126 ifr.ifr_flags |= IFF_TUN;
1128 else if (tt->type == DEV_TYPE_TAP)
1130 ifr.ifr_flags |= IFF_TAP;
1132 else
1134 msg (M_FATAL, "I don't recognize device %s as a tun or tap device",
1135 dev);
1139 * Set an explicit name, if --dev is not tun or tap
1141 if (strcmp(dev, "tun") && strcmp(dev, "tap"))
1142 strncpynt (ifr.ifr_name, dev, IFNAMSIZ);
1145 * Use special ioctl that configures tun/tap device with the parms
1146 * we set in ifr
1148 if (ioctl (tt->fd, TUNSETIFF, (void *) &ifr) < 0)
1150 msg (M_WARN | M_ERRNO, "Note: Cannot ioctl TUNSETIFF %s", dev);
1151 goto linux_2_2_fallback;
1154 msg (M_INFO, "TUN/TAP device %s opened", ifr.ifr_name);
1157 * Try making the TX send queue bigger
1159 #if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN)
1161 struct ifreq netifr;
1162 int ctl_fd;
1164 if ((ctl_fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0)
1166 CLEAR (netifr);
1167 strncpynt (netifr.ifr_name, ifr.ifr_name, IFNAMSIZ);
1168 netifr.ifr_qlen = tt->options.txqueuelen;
1169 if (ioctl (ctl_fd, SIOCSIFTXQLEN, (void *) &netifr) >= 0)
1170 msg (D_OSBUF, "TUN/TAP TX queue length set to %d", tt->options.txqueuelen);
1171 else
1172 msg (M_WARN | M_ERRNO, "Note: Cannot set tx queue length on %s", ifr.ifr_name);
1173 close (ctl_fd);
1175 else
1177 msg (M_WARN | M_ERRNO, "Note: Cannot open control socket on %s", ifr.ifr_name);
1180 #endif
1182 set_nonblock (tt->fd);
1183 set_cloexec (tt->fd);
1184 tt->actual_name = string_alloc (ifr.ifr_name, NULL);
1186 return;
1188 linux_2_2_fallback:
1189 msg (M_INFO, "Note: Attempting fallback to kernel 2.2 TUN/TAP interface");
1190 if (tt->fd >= 0)
1192 close (tt->fd);
1193 tt->fd = -1;
1195 open_tun_generic (dev, dev_type, dev_node, ipv6, false, true, tt);
1198 #else
1200 void
1201 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
1203 ASSERT (0);
1206 #endif
1208 #else
1210 void
1211 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
1213 open_tun_generic (dev, dev_type, dev_node, ipv6, false, true, tt);
1216 #endif /* HAVE_LINUX_IF_TUN_H */
1218 #ifdef TUNSETPERSIST
1221 * This can be removed in future
1222 * when all systems will use newer
1223 * linux-headers
1225 #ifndef TUNSETOWNER
1226 #define TUNSETOWNER _IOW('T', 204, int)
1227 #endif
1228 #ifndef TUNSETGROUP
1229 #define TUNSETGROUP _IOW('T', 206, int)
1230 #endif
1232 void
1233 tuncfg (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, int persist_mode, const char *username, const char *groupname, const struct tuntap_options *options)
1235 struct tuntap *tt;
1237 ALLOC_OBJ (tt, struct tuntap);
1238 clear_tuntap (tt);
1239 tt->type = dev_type_enum (dev, dev_type);
1240 tt->options = *options;
1241 open_tun (dev, dev_type, dev_node, ipv6, tt);
1242 if (ioctl (tt->fd, TUNSETPERSIST, persist_mode) < 0)
1243 msg (M_ERR, "Cannot ioctl TUNSETPERSIST(%d) %s", persist_mode, dev);
1244 if (username != NULL)
1246 struct user_state user_state;
1248 if (!get_user (username, &user_state))
1249 msg (M_ERR, "Cannot get user entry for %s", username);
1250 else
1251 if (ioctl (tt->fd, TUNSETOWNER, user_state.pw->pw_uid) < 0)
1252 msg (M_ERR, "Cannot ioctl TUNSETOWNER(%s) %s", username, dev);
1254 if (groupname != NULL)
1256 struct group_state group_state;
1258 if (!get_group (groupname, &group_state))
1259 msg (M_ERR, "Cannot get group entry for %s", groupname);
1260 else
1261 if (ioctl (tt->fd, TUNSETGROUP, group_state.gr->gr_gid) < 0)
1262 msg (M_ERR, "Cannot ioctl TUNSETOWNER(%s) %s", groupname, dev);
1264 close_tun (tt);
1265 msg (M_INFO, "Persist state set to: %s", (persist_mode ? "ON" : "OFF"));
1268 #endif /* TUNSETPERSIST */
1270 void
1271 close_tun (struct tuntap *tt)
1273 if (tt)
1275 if (tt->type != DEV_TYPE_NULL && tt->did_ifconfig)
1277 struct argv argv;
1278 struct gc_arena gc = gc_new ();
1279 argv_init (&argv);
1281 #ifdef CONFIG_FEATURE_IPROUTE
1282 if (is_tun_p2p (tt))
1284 argv_printf (&argv,
1285 "%s addr del dev %s local %s peer %s",
1286 iproute_path,
1287 tt->actual_name,
1288 print_in_addr_t (tt->local, 0, &gc),
1289 print_in_addr_t (tt->remote_netmask, 0, &gc)
1292 else
1294 argv_printf (&argv,
1295 "%s addr del dev %s %s/%d",
1296 iproute_path,
1297 tt->actual_name,
1298 print_in_addr_t (tt->local, 0, &gc),
1299 count_netmask_bits(print_in_addr_t (tt->remote_netmask, 0, &gc))
1302 #else
1303 argv_printf (&argv,
1304 "%s %s 0.0.0.0",
1305 IFCONFIG_PATH,
1306 tt->actual_name
1308 #endif
1310 argv_msg (M_INFO, &argv);
1311 openvpn_execve_check (&argv, NULL, 0, "Linux ip addr del failed");
1313 argv_reset (&argv);
1314 gc_free (&gc);
1316 close_tun_generic (tt);
1317 free (tt);
1322 write_tun (struct tuntap* tt, uint8_t *buf, int len)
1324 #if LINUX_IPV6
1325 if (tt->ipv6)
1327 struct tun_pi pi;
1328 struct iphdr *iph;
1329 struct iovec vect[2];
1330 int ret;
1332 iph = (struct iphdr *)buf;
1334 pi.flags = 0;
1336 if(iph->version == 6)
1337 pi.proto = htons(ETH_P_IPV6);
1338 else
1339 pi.proto = htons(ETH_P_IP);
1341 vect[0].iov_len = sizeof(pi);
1342 vect[0].iov_base = &pi;
1343 vect[1].iov_len = len;
1344 vect[1].iov_base = buf;
1346 ret = writev(tt->fd, vect, 2);
1347 return(ret - sizeof(pi));
1349 else
1350 #endif
1351 return write (tt->fd, buf, len);
1355 read_tun (struct tuntap* tt, uint8_t *buf, int len)
1357 #if LINUX_IPV6
1358 if (tt->ipv6)
1360 struct iovec vect[2];
1361 struct tun_pi pi;
1362 int ret;
1364 vect[0].iov_len = sizeof(pi);
1365 vect[0].iov_base = &pi;
1366 vect[1].iov_len = len;
1367 vect[1].iov_base = buf;
1369 ret = readv(tt->fd, vect, 2);
1370 return(ret - sizeof(pi));
1372 else
1373 #endif
1374 return read (tt->fd, buf, len);
1377 #elif defined(TARGET_SOLARIS)
1379 #ifndef TUNNEWPPA
1380 #error I need the symbol TUNNEWPPA from net/if_tun.h
1381 #endif
1383 void
1384 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
1386 int if_fd, muxid, ppa = -1;
1387 struct ifreq ifr;
1388 const char *ptr;
1389 const char *ip_node;
1390 const char *dev_tuntap_type;
1391 int link_type;
1392 bool is_tun;
1394 ipv6_support (ipv6, false, tt);
1396 if (tt->type == DEV_TYPE_NULL)
1398 open_null (tt);
1399 return;
1402 if (tt->type == DEV_TYPE_TUN)
1404 ip_node = "/dev/udp";
1405 if (!dev_node)
1406 dev_node = "/dev/tun";
1407 dev_tuntap_type = "tun";
1408 link_type = I_PLINK;
1409 is_tun = true;
1411 else if (tt->type == DEV_TYPE_TAP)
1413 ip_node = "/dev/ip";
1414 if (!dev_node)
1415 dev_node = "/dev/tap";
1416 dev_tuntap_type = "tap";
1417 link_type = I_PLINK; /* was: I_LINK */
1418 is_tun = false;
1420 else
1422 msg (M_FATAL, "I don't recognize device %s as a tun or tap device",
1423 dev);
1426 /* get unit number */
1427 if (*dev)
1429 ptr = dev;
1430 while (*ptr && !isdigit ((int) *ptr))
1431 ptr++;
1432 ppa = atoi (ptr);
1435 if ((tt->ip_fd = open (ip_node, O_RDWR, 0)) < 0)
1436 msg (M_ERR, "Can't open %s", ip_node);
1438 if ((tt->fd = open (dev_node, O_RDWR, 0)) < 0)
1439 msg (M_ERR, "Can't open %s", dev_node);
1441 /* Assign a new PPA and get its unit number. */
1442 if ((ppa = ioctl (tt->fd, TUNNEWPPA, ppa)) < 0)
1443 msg (M_ERR, "Can't assign new interface");
1445 if ((if_fd = open (dev_node, O_RDWR, 0)) < 0)
1446 msg (M_ERR, "Can't open %s (2)", dev_node);
1448 if (ioctl (if_fd, I_PUSH, "ip") < 0)
1449 msg (M_ERR, "Can't push IP module");
1451 /* Assign ppa according to the unit number returned by tun device */
1452 if (ioctl (if_fd, IF_UNITSEL, (char *) &ppa) < 0)
1453 msg (M_ERR, "Can't set PPA %d", ppa);
1455 if ((muxid = ioctl (tt->ip_fd, link_type, if_fd)) < 0)
1456 msg (M_ERR, "Can't link %s device to IP", dev_tuntap_type);
1458 close (if_fd);
1460 tt->actual_name = (char *) malloc (32);
1461 check_malloc_return (tt->actual_name);
1463 openvpn_snprintf (tt->actual_name, 32, "%s%d", dev_tuntap_type, ppa);
1465 CLEAR (ifr);
1466 strncpynt (ifr.ifr_name, tt->actual_name, sizeof (ifr.ifr_name));
1467 ifr.ifr_ip_muxid = muxid;
1469 if (ioctl (tt->ip_fd, SIOCSIFMUXID, &ifr) < 0)
1471 ioctl (tt->ip_fd, I_PUNLINK, muxid);
1472 msg (M_ERR, "Can't set multiplexor id");
1475 set_nonblock (tt->fd);
1476 set_cloexec (tt->fd);
1477 set_cloexec (tt->ip_fd);
1479 msg (M_INFO, "TUN/TAP device %s opened", tt->actual_name);
1482 static void
1483 solaris_close_tun (struct tuntap *tt)
1485 if (tt)
1487 if (tt->ip_fd >= 0)
1489 struct ifreq ifr;
1490 CLEAR (ifr);
1491 strncpynt (ifr.ifr_name, tt->actual_name, sizeof (ifr.ifr_name));
1493 if (ioctl (tt->ip_fd, SIOCGIFFLAGS, &ifr) < 0)
1494 msg (M_WARN | M_ERRNO, "Can't get iface flags");
1496 if (ioctl (tt->ip_fd, SIOCGIFMUXID, &ifr) < 0)
1497 msg (M_WARN | M_ERRNO, "Can't get multiplexor id");
1499 if (ioctl (tt->ip_fd, I_PUNLINK, ifr.ifr_ip_muxid) < 0)
1500 msg (M_WARN | M_ERRNO, "Can't unlink interface");
1502 close (tt->ip_fd);
1503 tt->ip_fd = -1;
1506 if (tt->fd >= 0)
1508 close (tt->fd);
1509 tt->fd = -1;
1515 * Close TUN device.
1517 void
1518 close_tun (struct tuntap *tt)
1520 if (tt)
1522 solaris_close_tun (tt);
1524 if (tt->actual_name)
1525 free (tt->actual_name);
1527 clear_tuntap (tt);
1528 free (tt);
1532 static void
1533 solaris_error_close (struct tuntap *tt, const struct env_set *es, const char *actual)
1535 struct argv argv;
1536 argv_init (&argv);
1538 argv_printf (&argv,
1539 "%s %s unplumb",
1540 IFCONFIG_PATH,
1541 actual);
1543 argv_msg (M_INFO, &argv);
1544 openvpn_execve_check (&argv, es, 0, "Solaris ifconfig unplumb failed");
1545 close_tun (tt);
1546 msg (M_FATAL, "Solaris ifconfig failed");
1547 argv_reset (&argv);
1551 write_tun (struct tuntap* tt, uint8_t *buf, int len)
1553 struct strbuf sbuf;
1554 sbuf.len = len;
1555 sbuf.buf = (char *)buf;
1556 return putmsg (tt->fd, NULL, &sbuf, 0) >= 0 ? sbuf.len : -1;
1560 read_tun (struct tuntap* tt, uint8_t *buf, int len)
1562 struct strbuf sbuf;
1563 int f = 0;
1565 sbuf.maxlen = len;
1566 sbuf.buf = (char *)buf;
1567 return getmsg (tt->fd, NULL, &sbuf, &f) >= 0 ? sbuf.len : -1;
1570 #elif defined(TARGET_OPENBSD)
1572 #if !defined(HAVE_READV) || !defined(HAVE_WRITEV)
1573 #error openbsd build requires readv & writev library functions
1574 #endif
1577 * OpenBSD has a slightly incompatible TUN device from
1578 * the rest of the world, in that it prepends a
1579 * uint32 to the beginning of the IP header
1580 * to designate the protocol (why not just
1581 * look at the version field in the IP header to
1582 * determine v4 or v6?).
1584 * We strip off this field on reads and
1585 * put it back on writes.
1587 * I have not tested TAP devices on OpenBSD,
1588 * but I have conditionalized the special
1589 * TUN handling code described above to
1590 * go away for TAP devices.
1593 void
1594 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
1596 open_tun_generic (dev, dev_type, dev_node, ipv6, true, true, tt);
1598 /* Enable multicast on the interface */
1599 if (tt->fd >= 0)
1601 struct tuninfo info;
1603 if (ioctl (tt->fd, TUNGIFINFO, &info) < 0) {
1604 msg (M_WARN | M_ERRNO, "Can't get interface info: %s",
1605 strerror(errno));
1608 info.flags |= IFF_MULTICAST;
1610 if (ioctl (tt->fd, TUNSIFINFO, &info) < 0) {
1611 msg (M_WARN | M_ERRNO, "Can't set interface info: %s",
1612 strerror(errno));
1617 void
1618 close_tun (struct tuntap* tt)
1620 if (tt)
1622 close_tun_generic (tt);
1623 free (tt);
1627 static inline int
1628 openbsd_modify_read_write_return (int len)
1630 if (len > 0)
1631 return len > sizeof (u_int32_t) ? len - sizeof (u_int32_t) : 0;
1632 else
1633 return len;
1637 write_tun (struct tuntap* tt, uint8_t *buf, int len)
1639 if (tt->type == DEV_TYPE_TUN)
1641 u_int32_t type;
1642 struct iovec iv[2];
1643 struct ip *iph;
1645 iph = (struct ip *) buf;
1647 if (tt->ipv6 && iph->ip_v == 6)
1648 type = htonl (AF_INET6);
1649 else
1650 type = htonl (AF_INET);
1652 iv[0].iov_base = &type;
1653 iv[0].iov_len = sizeof (type);
1654 iv[1].iov_base = buf;
1655 iv[1].iov_len = len;
1657 return openbsd_modify_read_write_return (writev (tt->fd, iv, 2));
1659 else
1660 return write (tt->fd, buf, len);
1664 read_tun (struct tuntap* tt, uint8_t *buf, int len)
1666 if (tt->type == DEV_TYPE_TUN)
1668 u_int32_t type;
1669 struct iovec iv[2];
1671 iv[0].iov_base = &type;
1672 iv[0].iov_len = sizeof (type);
1673 iv[1].iov_base = buf;
1674 iv[1].iov_len = len;
1676 return openbsd_modify_read_write_return (readv (tt->fd, iv, 2));
1678 else
1679 return read (tt->fd, buf, len);
1682 #elif defined(TARGET_NETBSD)
1685 * NetBSD does not support IPv6 on tun out of the box,
1686 * but there exists a patch. When this patch is applied,
1687 * only two things are left to openvpn:
1688 * 1. Activate multicasting (this has already been done
1689 * before by the kernel, but we make sure that nobody
1690 * has deactivated multicasting inbetween.
1691 * 2. Deactivate "link layer mode" (otherwise NetBSD
1692 * prepends the address family to the packet, and we
1693 * would run into the same trouble as with OpenBSD.
1696 void
1697 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
1699 open_tun_generic (dev, dev_type, dev_node, ipv6, true, true, tt);
1700 if (tt->fd >= 0)
1702 int i = IFF_POINTOPOINT|IFF_MULTICAST;
1703 ioctl (tt->fd, TUNSIFMODE, &i); /* multicast on */
1704 i = 0;
1705 ioctl (tt->fd, TUNSLMODE, &i); /* link layer mode off */
1709 void
1710 close_tun (struct tuntap *tt)
1712 if (tt)
1714 close_tun_generic (tt);
1715 free (tt);
1720 write_tun (struct tuntap* tt, uint8_t *buf, int len)
1722 return write (tt->fd, buf, len);
1726 read_tun (struct tuntap* tt, uint8_t *buf, int len)
1728 return read (tt->fd, buf, len);
1731 #elif defined(TARGET_FREEBSD)
1733 static inline int
1734 freebsd_modify_read_write_return (int len)
1736 if (len > 0)
1737 return len > sizeof (u_int32_t) ? len - sizeof (u_int32_t) : 0;
1738 else
1739 return len;
1742 void
1743 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
1745 open_tun_generic (dev, dev_type, dev_node, ipv6, true, true, tt);
1747 if (tt->fd >= 0 && tt->type == DEV_TYPE_TUN)
1749 int i = 0;
1751 i = tt->topology == TOP_SUBNET ? IFF_BROADCAST : IFF_POINTOPOINT;
1752 i |= IFF_MULTICAST;
1753 if (ioctl (tt->fd, TUNSIFMODE, &i) < 0) {
1754 msg (M_WARN | M_ERRNO, "ioctl(TUNSIFMODE): %s", strerror(errno));
1756 i = 1;
1757 if (ioctl (tt->fd, TUNSIFHEAD, &i) < 0) {
1758 msg (M_WARN | M_ERRNO, "ioctl(TUNSIFHEAD): %s", strerror(errno));
1763 void
1764 close_tun (struct tuntap *tt)
1766 if (tt)
1768 close_tun_generic (tt);
1769 free (tt);
1774 write_tun (struct tuntap* tt, uint8_t *buf, int len)
1776 if (tt->type == DEV_TYPE_TUN)
1778 u_int32_t type;
1779 struct iovec iv[2];
1780 struct ip *iph;
1782 iph = (struct ip *) buf;
1784 if (tt->ipv6 && iph->ip_v == 6)
1785 type = htonl (AF_INET6);
1786 else
1787 type = htonl (AF_INET);
1789 iv[0].iov_base = (char *)&type;
1790 iv[0].iov_len = sizeof (type);
1791 iv[1].iov_base = buf;
1792 iv[1].iov_len = len;
1794 return freebsd_modify_read_write_return (writev (tt->fd, iv, 2));
1796 else
1797 return write (tt->fd, buf, len);
1801 read_tun (struct tuntap* tt, uint8_t *buf, int len)
1803 if (tt->type == DEV_TYPE_TUN)
1805 u_int32_t type;
1806 struct iovec iv[2];
1808 iv[0].iov_base = (char *)&type;
1809 iv[0].iov_len = sizeof (type);
1810 iv[1].iov_base = buf;
1811 iv[1].iov_len = len;
1813 return freebsd_modify_read_write_return (readv (tt->fd, iv, 2));
1815 else
1816 return read (tt->fd, buf, len);
1819 #elif defined(TARGET_DRAGONFLY)
1821 static inline int
1822 dragonfly_modify_read_write_return (int len)
1824 if (len > 0)
1825 return len > sizeof (u_int32_t) ? len - sizeof (u_int32_t) : 0;
1826 else
1827 return len;
1830 void
1831 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
1833 open_tun_generic (dev, dev_type, dev_node, ipv6, true, true, tt);
1835 if (tt->fd >= 0)
1837 int i = 0;
1839 /* Disable extended modes */
1840 ioctl (tt->fd, TUNSLMODE, &i);
1841 i = 1;
1842 ioctl (tt->fd, TUNSIFHEAD, &i);
1846 void
1847 close_tun (struct tuntap *tt)
1849 if (tt)
1851 close_tun_generic (tt);
1852 free (tt);
1857 write_tun (struct tuntap* tt, uint8_t *buf, int len)
1859 if (tt->type == DEV_TYPE_TUN)
1861 u_int32_t type;
1862 struct iovec iv[2];
1863 struct ip *iph;
1865 iph = (struct ip *) buf;
1867 if (tt->ipv6 && iph->ip_v == 6)
1868 type = htonl (AF_INET6);
1869 else
1870 type = htonl (AF_INET);
1872 iv[0].iov_base = (char *)&type;
1873 iv[0].iov_len = sizeof (type);
1874 iv[1].iov_base = buf;
1875 iv[1].iov_len = len;
1877 return dragonfly_modify_read_write_return (writev (tt->fd, iv, 2));
1879 else
1880 return write (tt->fd, buf, len);
1884 read_tun (struct tuntap* tt, uint8_t *buf, int len)
1886 if (tt->type == DEV_TYPE_TUN)
1888 u_int32_t type;
1889 struct iovec iv[2];
1891 iv[0].iov_base = (char *)&type;
1892 iv[0].iov_len = sizeof (type);
1893 iv[1].iov_base = buf;
1894 iv[1].iov_len = len;
1896 return dragonfly_modify_read_write_return (readv (tt->fd, iv, 2));
1898 else
1899 return read (tt->fd, buf, len);
1902 #elif defined(WIN32)
1905 tun_read_queue (struct tuntap *tt, int maxsize)
1907 if (tt->reads.iostate == IOSTATE_INITIAL)
1909 DWORD len;
1910 BOOL status;
1911 int err;
1913 /* reset buf to its initial state */
1914 tt->reads.buf = tt->reads.buf_init;
1916 len = maxsize ? maxsize : BLEN (&tt->reads.buf);
1917 ASSERT (len <= BLEN (&tt->reads.buf));
1919 /* the overlapped read will signal this event on I/O completion */
1920 ASSERT (ResetEvent (tt->reads.overlapped.hEvent));
1922 status = ReadFile(
1923 tt->hand,
1924 BPTR (&tt->reads.buf),
1925 len,
1926 &tt->reads.size,
1927 &tt->reads.overlapped
1930 if (status) /* operation completed immediately? */
1932 /* since we got an immediate return, we must signal the event object ourselves */
1933 ASSERT (SetEvent (tt->reads.overlapped.hEvent));
1935 tt->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
1936 tt->reads.status = 0;
1938 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Read immediate return [%d,%d]",
1939 (int) len,
1940 (int) tt->reads.size);
1942 else
1944 err = GetLastError ();
1945 if (err == ERROR_IO_PENDING) /* operation queued? */
1947 tt->reads.iostate = IOSTATE_QUEUED;
1948 tt->reads.status = err;
1949 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Read queued [%d]",
1950 (int) len);
1952 else /* error occurred */
1954 struct gc_arena gc = gc_new ();
1955 ASSERT (SetEvent (tt->reads.overlapped.hEvent));
1956 tt->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
1957 tt->reads.status = err;
1958 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Read error [%d] : %s",
1959 (int) len,
1960 strerror_win32 (status, &gc));
1961 gc_free (&gc);
1965 return tt->reads.iostate;
1969 tun_write_queue (struct tuntap *tt, struct buffer *buf)
1971 if (tt->writes.iostate == IOSTATE_INITIAL)
1973 BOOL status;
1974 int err;
1976 /* make a private copy of buf */
1977 tt->writes.buf = tt->writes.buf_init;
1978 tt->writes.buf.len = 0;
1979 ASSERT (buf_copy (&tt->writes.buf, buf));
1981 /* the overlapped write will signal this event on I/O completion */
1982 ASSERT (ResetEvent (tt->writes.overlapped.hEvent));
1984 status = WriteFile(
1985 tt->hand,
1986 BPTR (&tt->writes.buf),
1987 BLEN (&tt->writes.buf),
1988 &tt->writes.size,
1989 &tt->writes.overlapped
1992 if (status) /* operation completed immediately? */
1994 tt->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
1996 /* since we got an immediate return, we must signal the event object ourselves */
1997 ASSERT (SetEvent (tt->writes.overlapped.hEvent));
1999 tt->writes.status = 0;
2001 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Write immediate return [%d,%d]",
2002 BLEN (&tt->writes.buf),
2003 (int) tt->writes.size);
2005 else
2007 err = GetLastError ();
2008 if (err == ERROR_IO_PENDING) /* operation queued? */
2010 tt->writes.iostate = IOSTATE_QUEUED;
2011 tt->writes.status = err;
2012 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Write queued [%d]",
2013 BLEN (&tt->writes.buf));
2015 else /* error occurred */
2017 struct gc_arena gc = gc_new ();
2018 ASSERT (SetEvent (tt->writes.overlapped.hEvent));
2019 tt->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
2020 tt->writes.status = err;
2021 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Write error [%d] : %s",
2022 BLEN (&tt->writes.buf),
2023 strerror_win32 (err, &gc));
2024 gc_free (&gc);
2028 return tt->writes.iostate;
2032 tun_finalize (
2033 HANDLE h,
2034 struct overlapped_io *io,
2035 struct buffer *buf)
2037 int ret = -1;
2038 BOOL status;
2040 switch (io->iostate)
2042 case IOSTATE_QUEUED:
2043 status = GetOverlappedResult(
2045 &io->overlapped,
2046 &io->size,
2047 FALSE
2049 if (status)
2051 /* successful return for a queued operation */
2052 if (buf)
2053 *buf = io->buf;
2054 ret = io->size;
2055 io->iostate = IOSTATE_INITIAL;
2056 ASSERT (ResetEvent (io->overlapped.hEvent));
2057 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Completion success [%d]", ret);
2059 else
2061 /* error during a queued operation */
2062 ret = -1;
2063 if (GetLastError() != ERROR_IO_INCOMPLETE)
2065 /* if no error (i.e. just not finished yet),
2066 then DON'T execute this code */
2067 io->iostate = IOSTATE_INITIAL;
2068 ASSERT (ResetEvent (io->overlapped.hEvent));
2069 msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: TAP Completion error");
2072 break;
2074 case IOSTATE_IMMEDIATE_RETURN:
2075 io->iostate = IOSTATE_INITIAL;
2076 ASSERT (ResetEvent (io->overlapped.hEvent));
2077 if (io->status)
2079 /* error return for a non-queued operation */
2080 SetLastError (io->status);
2081 ret = -1;
2082 msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: TAP Completion non-queued error");
2084 else
2086 /* successful return for a non-queued operation */
2087 if (buf)
2088 *buf = io->buf;
2089 ret = io->size;
2090 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Completion non-queued success [%d]", ret);
2092 break;
2094 case IOSTATE_INITIAL: /* were we called without proper queueing? */
2095 SetLastError (ERROR_INVALID_FUNCTION);
2096 ret = -1;
2097 dmsg (D_WIN32_IO, "WIN32 I/O: TAP Completion BAD STATE");
2098 break;
2100 default:
2101 ASSERT (0);
2104 if (buf)
2105 buf->len = ret;
2106 return ret;
2109 const struct tap_reg *
2110 get_tap_reg (struct gc_arena *gc)
2112 HKEY adapter_key;
2113 LONG status;
2114 DWORD len;
2115 struct tap_reg *first = NULL;
2116 struct tap_reg *last = NULL;
2117 int i = 0;
2119 status = RegOpenKeyEx(
2120 HKEY_LOCAL_MACHINE,
2121 ADAPTER_KEY,
2123 KEY_READ,
2124 &adapter_key);
2126 if (status != ERROR_SUCCESS)
2127 msg (M_FATAL, "Error opening registry key: %s", ADAPTER_KEY);
2129 while (true)
2131 char enum_name[256];
2132 char unit_string[256];
2133 HKEY unit_key;
2134 char component_id_string[] = "ComponentId";
2135 char component_id[256];
2136 char net_cfg_instance_id_string[] = "NetCfgInstanceId";
2137 char net_cfg_instance_id[256];
2138 DWORD data_type;
2140 len = sizeof (enum_name);
2141 status = RegEnumKeyEx(
2142 adapter_key,
2144 enum_name,
2145 &len,
2146 NULL,
2147 NULL,
2148 NULL,
2149 NULL);
2150 if (status == ERROR_NO_MORE_ITEMS)
2151 break;
2152 else if (status != ERROR_SUCCESS)
2153 msg (M_FATAL, "Error enumerating registry subkeys of key: %s",
2154 ADAPTER_KEY);
2156 openvpn_snprintf (unit_string, sizeof(unit_string), "%s\\%s",
2157 ADAPTER_KEY, enum_name);
2159 status = RegOpenKeyEx(
2160 HKEY_LOCAL_MACHINE,
2161 unit_string,
2163 KEY_READ,
2164 &unit_key);
2166 if (status != ERROR_SUCCESS)
2167 dmsg (D_REGISTRY, "Error opening registry key: %s", unit_string);
2168 else
2170 len = sizeof (component_id);
2171 status = RegQueryValueEx(
2172 unit_key,
2173 component_id_string,
2174 NULL,
2175 &data_type,
2176 component_id,
2177 &len);
2179 if (status != ERROR_SUCCESS || data_type != REG_SZ)
2180 dmsg (D_REGISTRY, "Error opening registry key: %s\\%s",
2181 unit_string, component_id_string);
2182 else
2184 len = sizeof (net_cfg_instance_id);
2185 status = RegQueryValueEx(
2186 unit_key,
2187 net_cfg_instance_id_string,
2188 NULL,
2189 &data_type,
2190 net_cfg_instance_id,
2191 &len);
2193 if (status == ERROR_SUCCESS && data_type == REG_SZ)
2195 if (!strcmp (component_id, TAP_COMPONENT_ID))
2197 struct tap_reg *reg;
2198 ALLOC_OBJ_CLEAR_GC (reg, struct tap_reg, gc);
2199 reg->guid = string_alloc (net_cfg_instance_id, gc);
2201 /* link into return list */
2202 if (!first)
2203 first = reg;
2204 if (last)
2205 last->next = reg;
2206 last = reg;
2210 RegCloseKey (unit_key);
2212 ++i;
2215 RegCloseKey (adapter_key);
2216 return first;
2219 const struct panel_reg *
2220 get_panel_reg (struct gc_arena *gc)
2222 LONG status;
2223 HKEY network_connections_key;
2224 DWORD len;
2225 struct panel_reg *first = NULL;
2226 struct panel_reg *last = NULL;
2227 int i = 0;
2229 status = RegOpenKeyEx(
2230 HKEY_LOCAL_MACHINE,
2231 NETWORK_CONNECTIONS_KEY,
2233 KEY_READ,
2234 &network_connections_key);
2236 if (status != ERROR_SUCCESS)
2237 msg (M_FATAL, "Error opening registry key: %s", NETWORK_CONNECTIONS_KEY);
2239 while (true)
2241 char enum_name[256];
2242 char connection_string[256];
2243 HKEY connection_key;
2244 char name_data[256];
2245 DWORD name_type;
2246 const char name_string[] = "Name";
2248 len = sizeof (enum_name);
2249 status = RegEnumKeyEx(
2250 network_connections_key,
2252 enum_name,
2253 &len,
2254 NULL,
2255 NULL,
2256 NULL,
2257 NULL);
2258 if (status == ERROR_NO_MORE_ITEMS)
2259 break;
2260 else if (status != ERROR_SUCCESS)
2261 msg (M_FATAL, "Error enumerating registry subkeys of key: %s",
2262 NETWORK_CONNECTIONS_KEY);
2264 openvpn_snprintf (connection_string, sizeof(connection_string),
2265 "%s\\%s\\Connection",
2266 NETWORK_CONNECTIONS_KEY, enum_name);
2268 status = RegOpenKeyEx(
2269 HKEY_LOCAL_MACHINE,
2270 connection_string,
2272 KEY_READ,
2273 &connection_key);
2275 if (status != ERROR_SUCCESS)
2276 dmsg (D_REGISTRY, "Error opening registry key: %s", connection_string);
2277 else
2279 len = sizeof (name_data);
2280 status = RegQueryValueEx(
2281 connection_key,
2282 name_string,
2283 NULL,
2284 &name_type,
2285 name_data,
2286 &len);
2288 if (status != ERROR_SUCCESS || name_type != REG_SZ)
2289 dmsg (D_REGISTRY, "Error opening registry key: %s\\%s\\%s",
2290 NETWORK_CONNECTIONS_KEY, connection_string, name_string);
2291 else
2293 struct panel_reg *reg;
2295 ALLOC_OBJ_CLEAR_GC (reg, struct panel_reg, gc);
2296 reg->name = string_alloc (name_data, gc);
2297 reg->guid = string_alloc (enum_name, gc);
2299 /* link into return list */
2300 if (!first)
2301 first = reg;
2302 if (last)
2303 last->next = reg;
2304 last = reg;
2306 RegCloseKey (connection_key);
2308 ++i;
2311 RegCloseKey (network_connections_key);
2313 return first;
2317 * Check that two addresses are part of the same 255.255.255.252 subnet.
2319 void
2320 verify_255_255_255_252 (in_addr_t local, in_addr_t remote)
2322 struct gc_arena gc = gc_new ();
2323 const unsigned int mask = 3;
2324 const char *err = NULL;
2326 if (local == remote)
2328 err = "must be different";
2329 goto error;
2331 if ((local & (~mask)) != (remote & (~mask)))
2333 err = "must exist within the same 255.255.255.252 subnet. This is a limitation of --dev tun when used with the TAP-WIN32 driver";
2334 goto error;
2336 if ((local & mask) == 0
2337 || (local & mask) == 3
2338 || (remote & mask) == 0
2339 || (remote & mask) == 3)
2341 err = "cannot use the first or last address within a given 255.255.255.252 subnet. This is a limitation of --dev tun when used with the TAP-WIN32 driver";
2342 goto error;
2345 gc_free (&gc);
2346 return;
2348 error:
2349 msg (M_FATAL, "There is a problem in your selection of --ifconfig endpoints [local=%s, remote=%s]. The local and remote VPN endpoints %s. Try '" PACKAGE " --show-valid-subnets' option for more info.",
2350 print_in_addr_t (local, 0, &gc),
2351 print_in_addr_t (remote, 0, &gc),
2352 err);
2353 gc_free (&gc);
2356 void show_valid_win32_tun_subnets (void)
2358 int i;
2359 int col = 0;
2361 printf ("On Windows, point-to-point IP support (i.e. --dev tun)\n");
2362 printf ("is emulated by the TAP-Win32 driver. The major limitation\n");
2363 printf ("imposed by this approach is that the --ifconfig local and\n");
2364 printf ("remote endpoints must be part of the same 255.255.255.252\n");
2365 printf ("subnet. The following list shows examples of endpoint\n");
2366 printf ("pairs which satisfy this requirement. Only the final\n");
2367 printf ("component of the IP address pairs is at issue.\n\n");
2368 printf ("As an example, the following option would be correct:\n");
2369 printf (" --ifconfig 10.7.0.5 10.7.0.6 (on host A)\n");
2370 printf (" --ifconfig 10.7.0.6 10.7.0.5 (on host B)\n");
2371 printf ("because [5,6] is part of the below list.\n\n");
2373 for (i = 0; i < 256; i += 4)
2375 printf("[%3d,%3d] ", i+1, i+2);
2376 if (++col > 4)
2378 col = 0;
2379 printf ("\n");
2382 if (col)
2383 printf ("\n");
2386 void
2387 show_tap_win32_adapters (int msglev, int warnlev)
2389 struct gc_arena gc = gc_new ();
2391 bool warn_panel_null = false;
2392 bool warn_panel_dup = false;
2393 bool warn_tap_dup = false;
2395 int links;
2397 const struct tap_reg *tr;
2398 const struct tap_reg *tr1;
2399 const struct panel_reg *pr;
2401 const struct tap_reg *tap_reg = get_tap_reg (&gc);
2402 const struct panel_reg *panel_reg = get_panel_reg (&gc);
2404 msg (msglev, "Available TAP-WIN32 adapters [name, GUID]:");
2406 /* loop through each TAP-Win32 adapter registry entry */
2407 for (tr = tap_reg; tr != NULL; tr = tr->next)
2409 links = 0;
2411 /* loop through each network connections entry in the control panel */
2412 for (pr = panel_reg; pr != NULL; pr = pr->next)
2414 if (!strcmp (tr->guid, pr->guid))
2416 msg (msglev, "'%s' %s", pr->name, tr->guid);
2417 ++links;
2421 if (links > 1)
2423 warn_panel_dup = true;
2425 else if (links == 0)
2427 /* a TAP adapter exists without a link from the network
2428 connections control panel */
2429 warn_panel_null = true;
2430 msg (msglev, "[NULL] %s", tr->guid);
2434 /* check for TAP-Win32 adapter duplicated GUIDs */
2435 for (tr = tap_reg; tr != NULL; tr = tr->next)
2437 for (tr1 = tap_reg; tr1 != NULL; tr1 = tr1->next)
2439 if (tr != tr1 && !strcmp (tr->guid, tr1->guid))
2440 warn_tap_dup = true;
2444 /* warn on registry inconsistencies */
2445 if (warn_tap_dup)
2446 msg (warnlev, "WARNING: Some TAP-Win32 adapters have duplicate GUIDs");
2448 if (warn_panel_dup)
2449 msg (warnlev, "WARNING: Some TAP-Win32 adapters have duplicate links from the Network Connections control panel");
2451 if (warn_panel_null)
2452 msg (warnlev, "WARNING: Some TAP-Win32 adapters have no link from the Network Connections control panel");
2454 gc_free (&gc);
2458 * Confirm that GUID is a TAP-Win32 adapter.
2460 static bool
2461 is_tap_win32 (const char *guid, const struct tap_reg *tap_reg)
2463 const struct tap_reg *tr;
2465 for (tr = tap_reg; tr != NULL; tr = tr->next)
2467 if (guid && !strcmp (tr->guid, guid))
2468 return true;
2471 return false;
2474 static const char *
2475 guid_to_name (const char *guid, const struct panel_reg *panel_reg)
2477 const struct panel_reg *pr;
2479 for (pr = panel_reg; pr != NULL; pr = pr->next)
2481 if (guid && !strcmp (pr->guid, guid))
2482 return pr->name;
2485 return NULL;
2488 static const char *
2489 name_to_guid (const char *name, const struct tap_reg *tap_reg, const struct panel_reg *panel_reg)
2491 const struct panel_reg *pr;
2493 for (pr = panel_reg; pr != NULL; pr = pr->next)
2495 if (name && !strcmp (pr->name, name) && is_tap_win32 (pr->guid, tap_reg))
2496 return pr->guid;
2499 return NULL;
2502 static void
2503 at_least_one_tap_win32 (const struct tap_reg *tap_reg)
2505 if (!tap_reg)
2506 msg (M_FATAL, "There are no TAP-Win32 adapters on this system. You should be able to create a TAP-Win32 adapter by going to Start -> All Programs -> " PACKAGE_NAME " -> Add a new TAP-Win32 virtual ethernet adapter.");
2510 * Get an adapter GUID and optional actual_name from the
2511 * registry for the TAP device # = device_number.
2513 static const char *
2514 get_unspecified_device_guid (const int device_number,
2515 char *actual_name,
2516 int actual_name_size,
2517 const struct tap_reg *tap_reg_src,
2518 const struct panel_reg *panel_reg_src,
2519 struct gc_arena *gc)
2521 const struct tap_reg *tap_reg = tap_reg_src;
2522 struct buffer ret = clear_buf ();
2523 struct buffer actual = clear_buf ();
2524 int i;
2526 ASSERT (device_number >= 0);
2528 /* Make sure we have at least one TAP adapter */
2529 if (!tap_reg)
2530 return NULL;
2532 /* The actual_name output buffer may be NULL */
2533 if (actual_name)
2535 ASSERT (actual_name_size > 0);
2536 buf_set_write (&actual, actual_name, actual_name_size);
2539 /* Move on to specified device number */
2540 for (i = 0; i < device_number; i++)
2542 tap_reg = tap_reg->next;
2543 if (!tap_reg)
2544 return NULL;
2547 /* Save Network Panel name (if exists) in actual_name */
2548 if (actual_name)
2550 const char *act = guid_to_name (tap_reg->guid, panel_reg_src);
2551 if (act)
2552 buf_printf (&actual, "%s", act);
2553 else
2554 buf_printf (&actual, "%s", tap_reg->guid);
2557 /* Save GUID for return value */
2558 ret = alloc_buf_gc (256, gc);
2559 buf_printf (&ret, "%s", tap_reg->guid);
2560 return BSTR (&ret);
2564 * Lookup a --dev-node adapter name in the registry
2565 * returning the GUID and optional actual_name.
2567 static const char *
2568 get_device_guid (const char *name,
2569 char *actual_name,
2570 int actual_name_size,
2571 const struct tap_reg *tap_reg,
2572 const struct panel_reg *panel_reg,
2573 struct gc_arena *gc)
2575 struct buffer ret = alloc_buf_gc (256, gc);
2576 struct buffer actual = clear_buf ();
2578 /* Make sure we have at least one TAP adapter */
2579 if (!tap_reg)
2580 return NULL;
2582 /* The actual_name output buffer may be NULL */
2583 if (actual_name)
2585 ASSERT (actual_name_size > 0);
2586 buf_set_write (&actual, actual_name, actual_name_size);
2589 /* Check if GUID was explicitly specified as --dev-node parameter */
2590 if (is_tap_win32 (name, tap_reg))
2592 const char *act = guid_to_name (name, panel_reg);
2593 buf_printf (&ret, "%s", name);
2594 if (act)
2595 buf_printf (&actual, "%s", act);
2596 else
2597 buf_printf (&actual, "%s", name);
2598 return BSTR (&ret);
2601 /* Lookup TAP adapter in network connections list */
2603 const char *guid = name_to_guid (name, tap_reg, panel_reg);
2604 if (guid)
2606 buf_printf (&actual, "%s", name);
2607 buf_printf (&ret, "%s", guid);
2608 return BSTR (&ret);
2612 return NULL;
2616 * Get adapter info list
2618 const IP_ADAPTER_INFO *
2619 get_adapter_info_list (struct gc_arena *gc)
2621 ULONG size = 0;
2622 IP_ADAPTER_INFO *pi = NULL;
2623 DWORD status;
2625 if ((status = GetAdaptersInfo (NULL, &size)) != ERROR_BUFFER_OVERFLOW)
2627 msg (M_INFO, "GetAdaptersInfo #1 failed (status=%u) : %s",
2628 (unsigned int)status,
2629 strerror_win32 (status, gc));
2631 else
2633 pi = (PIP_ADAPTER_INFO) gc_malloc (size, false, gc);
2634 if ((status = GetAdaptersInfo (pi, &size)) == NO_ERROR)
2635 return pi;
2636 else
2638 msg (M_INFO, "GetAdaptersInfo #2 failed (status=%u) : %s",
2639 (unsigned int)status,
2640 strerror_win32 (status, gc));
2643 return pi;
2646 const IP_PER_ADAPTER_INFO *
2647 get_per_adapter_info (const DWORD index, struct gc_arena *gc)
2649 ULONG size = 0;
2650 IP_PER_ADAPTER_INFO *pi = NULL;
2651 DWORD status;
2653 if (index != ~0)
2655 if ((status = GetPerAdapterInfo (index, NULL, &size)) != ERROR_BUFFER_OVERFLOW)
2657 msg (M_INFO, "GetPerAdapterInfo #1 failed (status=%u) : %s",
2658 (unsigned int)status,
2659 strerror_win32 (status, gc));
2661 else
2663 pi = (PIP_PER_ADAPTER_INFO) gc_malloc (size, false, gc);
2664 if ((status = GetPerAdapterInfo ((ULONG)index, pi, &size)) == ERROR_SUCCESS)
2665 return pi;
2666 else
2668 msg (M_INFO, "GetPerAdapterInfo #2 failed (status=%u) : %s",
2669 (unsigned int)status,
2670 strerror_win32 (status, gc));
2674 return pi;
2677 static const IP_INTERFACE_INFO *
2678 get_interface_info_list (struct gc_arena *gc)
2680 ULONG size = 0;
2681 IP_INTERFACE_INFO *ii = NULL;
2682 DWORD status;
2684 if ((status = GetInterfaceInfo (NULL, &size)) != ERROR_INSUFFICIENT_BUFFER)
2686 msg (M_INFO, "GetInterfaceInfo #1 failed (status=%u) : %s",
2687 (unsigned int)status,
2688 strerror_win32 (status, gc));
2690 else
2692 ii = (PIP_INTERFACE_INFO) gc_malloc (size, false, gc);
2693 if ((status = GetInterfaceInfo (ii, &size)) == NO_ERROR)
2694 return ii;
2695 else
2697 msg (M_INFO, "GetInterfaceInfo #2 failed (status=%u) : %s",
2698 (unsigned int)status,
2699 strerror_win32 (status, gc));
2702 return ii;
2705 static const IP_ADAPTER_INDEX_MAP *
2706 get_interface_info (DWORD index, struct gc_arena *gc)
2708 const IP_INTERFACE_INFO *list = get_interface_info_list (gc);
2709 if (list)
2711 int i;
2712 for (i = 0; i < list->NumAdapters; ++i)
2714 const IP_ADAPTER_INDEX_MAP *inter = &list->Adapter[i];
2715 if (index == inter->Index)
2716 return inter;
2719 return NULL;
2723 * Given an adapter index, return a pointer to the
2724 * IP_ADAPTER_INFO structure for that adapter.
2727 const IP_ADAPTER_INFO *
2728 get_adapter (const IP_ADAPTER_INFO *ai, DWORD index)
2730 if (ai && index != (DWORD)~0)
2732 const IP_ADAPTER_INFO *a;
2734 /* find index in the linked list */
2735 for (a = ai; a != NULL; a = a->Next)
2737 if (a->Index == index)
2738 return a;
2741 return NULL;
2744 const IP_ADAPTER_INFO *
2745 get_adapter_info (DWORD index, struct gc_arena *gc)
2747 return get_adapter (get_adapter_info_list (gc), index);
2750 static int
2751 get_adapter_n_ip_netmask (const IP_ADAPTER_INFO *ai)
2753 if (ai)
2755 int n = 0;
2756 const IP_ADDR_STRING *ip = &ai->IpAddressList;
2758 while (ip)
2760 ++n;
2761 ip = ip->Next;
2763 return n;
2765 else
2766 return 0;
2769 static bool
2770 get_adapter_ip_netmask (const IP_ADAPTER_INFO *ai, const int n, in_addr_t *ip, in_addr_t *netmask)
2772 bool ret = false;
2773 *ip = 0;
2774 *netmask = 0;
2776 if (ai)
2778 const IP_ADDR_STRING *iplist = &ai->IpAddressList;
2779 int i = 0;
2781 while (iplist)
2783 if (i == n)
2784 break;
2785 ++i;
2786 iplist = iplist->Next;
2789 if (iplist)
2791 const unsigned int getaddr_flags = GETADDR_HOST_ORDER;
2792 const char *ip_str = iplist->IpAddress.String;
2793 const char *netmask_str = iplist->IpMask.String;
2794 bool succeed1 = false;
2795 bool succeed2 = false;
2797 if (ip_str && netmask_str && strlen (ip_str) && strlen (netmask_str))
2799 *ip = getaddr (getaddr_flags, ip_str, 0, &succeed1, NULL);
2800 *netmask = getaddr (getaddr_flags, netmask_str, 0, &succeed2, NULL);
2801 ret = (succeed1 == true && succeed2 == true);
2806 return ret;
2809 static bool
2810 test_adapter_ip_netmask (const IP_ADAPTER_INFO *ai, const in_addr_t ip, const in_addr_t netmask)
2812 if (ai)
2814 in_addr_t ip_adapter = 0;
2815 in_addr_t netmask_adapter = 0;
2816 const bool status = get_adapter_ip_netmask (ai, 0, &ip_adapter, &netmask_adapter);
2817 return (status && ip_adapter == ip && netmask_adapter == netmask);
2819 else
2820 return false;
2823 const IP_ADAPTER_INFO *
2824 get_tun_adapter (const struct tuntap *tt, const IP_ADAPTER_INFO *list)
2826 if (list && tt)
2827 return get_adapter (list, tt->adapter_index);
2828 else
2829 return NULL;
2832 bool
2833 is_adapter_up (const struct tuntap *tt, const IP_ADAPTER_INFO *list)
2835 int i;
2836 bool ret = false;
2838 const IP_ADAPTER_INFO *ai = get_tun_adapter (tt, list);
2840 if (ai)
2842 const int n = get_adapter_n_ip_netmask (ai);
2844 /* loop once for every IP/netmask assigned to adapter */
2845 for (i = 0; i < n; ++i)
2847 in_addr_t ip, netmask;
2848 if (get_adapter_ip_netmask (ai, i, &ip, &netmask))
2850 if (tt->local && tt->adapter_netmask)
2852 /* wait for our --ifconfig parms to match the actual adapter parms */
2853 if (tt->local == ip && tt->adapter_netmask == netmask)
2854 ret = true;
2856 else
2858 /* --ifconfig was not defined, maybe using a real DHCP server */
2859 if (ip && netmask)
2860 ret = true;
2865 else
2866 ret = true; /* this can occur when TAP adapter is bridged */
2868 return ret;
2871 bool
2872 is_ip_in_adapter_subnet (const IP_ADAPTER_INFO *ai, const in_addr_t ip, in_addr_t *highest_netmask)
2874 int i;
2875 bool ret = false;
2877 if (highest_netmask)
2878 *highest_netmask = 0;
2880 if (ai)
2882 const int n = get_adapter_n_ip_netmask (ai);
2883 for (i = 0; i < n; ++i)
2885 in_addr_t adapter_ip, adapter_netmask;
2886 if (get_adapter_ip_netmask (ai, i, &adapter_ip, &adapter_netmask))
2888 if (adapter_ip && adapter_netmask && (ip & adapter_netmask) == (adapter_ip & adapter_netmask))
2890 if (highest_netmask && adapter_netmask > *highest_netmask)
2891 *highest_netmask = adapter_netmask;
2892 ret = true;
2897 return ret;
2900 DWORD
2901 adapter_index_of_ip (const IP_ADAPTER_INFO *list,
2902 const in_addr_t ip,
2903 int *count,
2904 in_addr_t *netmask)
2906 struct gc_arena gc = gc_new ();
2907 DWORD ret = ~0;
2908 in_addr_t highest_netmask = 0;
2909 bool first = true;
2911 if (count)
2912 *count = 0;
2914 while (list)
2916 in_addr_t hn;
2918 if (is_ip_in_adapter_subnet (list, ip, &hn))
2920 if (first || hn > highest_netmask)
2922 highest_netmask = hn;
2923 if (count)
2924 *count = 1;
2925 ret = list->Index;
2926 first = false;
2928 else if (hn == highest_netmask)
2930 if (count)
2931 ++*count;
2934 list = list->Next;
2937 dmsg (D_ROUTE_DEBUG, "DEBUG: IP Locate: ip=%s nm=%s index=%d count=%d",
2938 print_in_addr_t (ip, 0, &gc),
2939 print_in_addr_t (highest_netmask, 0, &gc),
2940 (int)ret,
2941 count ? *count : -1);
2943 if (ret == ~0 && count)
2944 *count = 0;
2946 if (netmask)
2947 *netmask = highest_netmask;
2949 gc_free (&gc);
2950 return ret;
2954 * Given an adapter index, return true if the adapter
2955 * is DHCP disabled.
2958 #define DHCP_STATUS_UNDEF 0
2959 #define DHCP_STATUS_ENABLED 1
2960 #define DHCP_STATUS_DISABLED 2
2962 static int
2963 dhcp_status (DWORD index)
2965 struct gc_arena gc = gc_new ();
2966 int ret = DHCP_STATUS_UNDEF;
2967 if (index != ~0)
2969 const IP_ADAPTER_INFO *ai = get_adapter_info (index, &gc);
2971 if (ai)
2973 if (ai->DhcpEnabled)
2974 ret = DHCP_STATUS_ENABLED;
2975 else
2976 ret = DHCP_STATUS_DISABLED;
2979 gc_free (&gc);
2980 return ret;
2984 * Delete all temporary address/netmask pairs which were added
2985 * to adapter (given by index) by previous calls to AddIPAddress.
2987 static void
2988 delete_temp_addresses (DWORD index)
2990 struct gc_arena gc = gc_new ();
2991 const IP_ADAPTER_INFO *a = get_adapter_info (index, &gc);
2993 if (a)
2995 const IP_ADDR_STRING *ip = &a->IpAddressList;
2996 while (ip)
2998 DWORD status;
2999 const DWORD context = ip->Context;
3001 if ((status = DeleteIPAddress ((ULONG) context)) == NO_ERROR)
3003 msg (M_INFO, "Successfully deleted previously set dynamic IP/netmask: %s/%s",
3004 ip->IpAddress.String,
3005 ip->IpMask.String);
3007 else
3009 const char *empty = "0.0.0.0";
3010 if (strcmp (ip->IpAddress.String, empty)
3011 || strcmp (ip->IpMask.String, empty))
3012 msg (M_INFO, "NOTE: could not delete previously set dynamic IP/netmask: %s/%s (status=%u)",
3013 ip->IpAddress.String,
3014 ip->IpMask.String,
3015 (unsigned int)status);
3017 ip = ip->Next;
3020 gc_free (&gc);
3024 * Get interface index for use with IP Helper API functions.
3026 static DWORD
3027 get_adapter_index_method_1 (const char *guid)
3029 struct gc_arena gc = gc_new ();
3030 ULONG index = ~0;
3031 DWORD status;
3032 wchar_t wbuf[256];
3033 snwprintf (wbuf, SIZE (wbuf), L"\\DEVICE\\TCPIP_%S", guid);
3034 wbuf [SIZE(wbuf) - 1] = 0;
3035 if ((status = GetAdapterIndex (wbuf, &index)) != NO_ERROR)
3036 index = ~0;
3037 gc_free (&gc);
3038 return index;
3041 static DWORD
3042 get_adapter_index_method_2 (const char *guid)
3044 struct gc_arena gc = gc_new ();
3045 DWORD index = ~0;
3047 const IP_ADAPTER_INFO *list = get_adapter_info_list (&gc);
3049 while (list)
3051 if (!strcmp (guid, list->AdapterName))
3053 index = list->Index;
3054 break;
3056 list = list->Next;
3059 gc_free (&gc);
3060 return index;
3063 static DWORD
3064 get_adapter_index (const char *guid)
3066 DWORD index;
3067 index = get_adapter_index_method_1 (guid);
3068 if (index == ~0)
3069 index = get_adapter_index_method_2 (guid);
3070 if (index == ~0)
3071 msg (M_INFO, "NOTE: could not get adapter index for %s", guid);
3072 return index;
3075 static DWORD
3076 get_adapter_index_flexible (const char *name) /* actual name or GUID */
3078 struct gc_arena gc = gc_new ();
3079 DWORD index;
3080 index = get_adapter_index_method_1 (name);
3081 if (index == ~0)
3082 index = get_adapter_index_method_2 (name);
3083 if (index == ~0)
3085 const struct tap_reg *tap_reg = get_tap_reg (&gc);
3086 const struct panel_reg *panel_reg = get_panel_reg (&gc);
3087 const char *guid = name_to_guid (name, tap_reg, panel_reg);
3088 index = get_adapter_index_method_1 (guid);
3089 if (index == ~0)
3090 index = get_adapter_index_method_2 (guid);
3092 if (index == ~0)
3093 msg (M_INFO, "NOTE: could not get adapter index for name/GUID '%s'", name);
3094 gc_free (&gc);
3095 return index;
3099 * Return a string representing a PIP_ADDR_STRING
3101 static const char *
3102 format_ip_addr_string (const IP_ADDR_STRING *ip, struct gc_arena *gc)
3104 struct buffer out = alloc_buf_gc (256, gc);
3105 while (ip)
3107 buf_printf (&out, "%s", ip->IpAddress.String);
3108 if (strlen (ip->IpMask.String))
3110 buf_printf (&out, "/");
3111 buf_printf (&out, "%s", ip->IpMask.String);
3113 buf_printf (&out, " ");
3114 ip = ip->Next;
3116 return BSTR (&out);
3120 * Show info for a single adapter
3122 static void
3123 show_adapter (int msglev, const IP_ADAPTER_INFO *a, struct gc_arena *gc)
3125 msg (msglev, "%s", a->Description);
3126 msg (msglev, " Index = %d", (int)a->Index);
3127 msg (msglev, " GUID = %s", a->AdapterName);
3128 msg (msglev, " IP = %s", format_ip_addr_string (&a->IpAddressList, gc));
3129 msg (msglev, " MAC = %s", format_hex_ex (a->Address, a->AddressLength, 0, 1, ":", gc));
3130 msg (msglev, " GATEWAY = %s", format_ip_addr_string (&a->GatewayList, gc));
3131 if (a->DhcpEnabled)
3133 msg (msglev, " DHCP SERV = %s", format_ip_addr_string (&a->DhcpServer, gc));
3134 msg (msglev, " DHCP LEASE OBTAINED = %s", time_string (a->LeaseObtained, 0, false, gc));
3135 msg (msglev, " DHCP LEASE EXPIRES = %s", time_string (a->LeaseExpires, 0, false, gc));
3137 if (a->HaveWins)
3139 msg (msglev, " PRI WINS = %s", format_ip_addr_string (&a->PrimaryWinsServer, gc));
3140 msg (msglev, " SEC WINS = %s", format_ip_addr_string (&a->SecondaryWinsServer, gc));
3144 const IP_PER_ADAPTER_INFO *pai = get_per_adapter_info (a->Index, gc);
3145 if (pai)
3147 msg (msglev, " DNS SERV = %s", format_ip_addr_string (&pai->DnsServerList, gc));
3153 * Show current adapter list
3155 void
3156 show_adapters (int msglev)
3158 struct gc_arena gc = gc_new ();
3159 const IP_ADAPTER_INFO *ai = get_adapter_info_list (&gc);
3161 msg (msglev, "SYSTEM ADAPTER LIST");
3162 if (ai)
3164 const IP_ADAPTER_INFO *a;
3166 /* find index in the linked list */
3167 for (a = ai; a != NULL; a = a->Next)
3169 show_adapter (msglev, a, &gc);
3172 gc_free (&gc);
3176 * Set a particular TAP-Win32 adapter (or all of them if
3177 * adapter_name == NULL) to allow it to be opened from
3178 * a non-admin account. This setting will only persist
3179 * for the lifetime of the device object.
3182 static void
3183 tap_allow_nonadmin_access_handle (const char *device_path, HANDLE hand)
3185 struct security_attributes sa;
3186 BOOL status;
3188 if (!init_security_attributes_allow_all (&sa))
3189 msg (M_ERR, "Error: init SA failed");
3191 status = SetKernelObjectSecurity (hand, DACL_SECURITY_INFORMATION, &sa.sd);
3192 if (!status)
3194 msg (M_ERRNO, "Error: SetKernelObjectSecurity failed on %s", device_path);
3196 else
3198 msg (M_INFO|M_NOPREFIX, "TAP-Win32 device: %s [Non-admin access allowed]", device_path);
3202 void
3203 tap_allow_nonadmin_access (const char *dev_node)
3205 struct gc_arena gc = gc_new ();
3206 const struct tap_reg *tap_reg = get_tap_reg (&gc);
3207 const struct panel_reg *panel_reg = get_panel_reg (&gc);
3208 const char *device_guid = NULL;
3209 HANDLE hand;
3210 char actual_buffer[256];
3211 char device_path[256];
3213 at_least_one_tap_win32 (tap_reg);
3215 if (dev_node)
3217 /* Get the device GUID for the device specified with --dev-node. */
3218 device_guid = get_device_guid (dev_node, actual_buffer, sizeof (actual_buffer), tap_reg, panel_reg, &gc);
3220 if (!device_guid)
3221 msg (M_FATAL, "TAP-Win32 adapter '%s' not found", dev_node);
3223 /* Open Windows TAP-Win32 adapter */
3224 openvpn_snprintf (device_path, sizeof(device_path), "%s%s%s",
3225 USERMODEDEVICEDIR,
3226 device_guid,
3227 TAPSUFFIX);
3229 hand = CreateFile (
3230 device_path,
3231 MAXIMUM_ALLOWED,
3232 0, /* was: FILE_SHARE_READ */
3234 OPEN_EXISTING,
3235 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
3239 if (hand == INVALID_HANDLE_VALUE)
3240 msg (M_ERR, "CreateFile failed on TAP device: %s", device_path);
3242 tap_allow_nonadmin_access_handle (device_path, hand);
3243 CloseHandle (hand);
3245 else
3247 int device_number = 0;
3249 /* Try opening all TAP devices */
3250 while (true)
3252 device_guid = get_unspecified_device_guid (device_number,
3253 actual_buffer,
3254 sizeof (actual_buffer),
3255 tap_reg,
3256 panel_reg,
3257 &gc);
3259 if (!device_guid)
3260 break;
3262 /* Open Windows TAP-Win32 adapter */
3263 openvpn_snprintf (device_path, sizeof(device_path), "%s%s%s",
3264 USERMODEDEVICEDIR,
3265 device_guid,
3266 TAPSUFFIX);
3268 hand = CreateFile (
3269 device_path,
3270 MAXIMUM_ALLOWED,
3271 0, /* was: FILE_SHARE_READ */
3273 OPEN_EXISTING,
3274 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
3278 if (hand == INVALID_HANDLE_VALUE)
3279 msg (M_WARN, "CreateFile failed on TAP device: %s", device_path);
3280 else
3282 tap_allow_nonadmin_access_handle (device_path, hand);
3283 CloseHandle (hand);
3286 device_number++;
3289 gc_free (&gc);
3293 * DHCP release/renewal
3295 bool
3296 dhcp_release_by_adapter_index(const DWORD adapter_index)
3298 struct gc_arena gc = gc_new ();
3299 bool ret = false;
3300 const IP_ADAPTER_INDEX_MAP *inter = get_interface_info (adapter_index, &gc);
3302 if (inter)
3304 DWORD status = IpReleaseAddress ((IP_ADAPTER_INDEX_MAP *)inter);
3305 if (status == NO_ERROR)
3307 msg (D_TUNTAP_INFO, "TAP: DHCP address released");
3308 ret = true;
3310 else
3311 msg (M_WARN, "NOTE: Release of DHCP-assigned IP address lease on TAP-Win32 adapter failed: %s (code=%u)",
3312 strerror_win32 (status, &gc),
3313 (unsigned int)status);
3316 gc_free (&gc);
3317 return ret;
3320 static bool
3321 dhcp_release (const struct tuntap *tt)
3323 if (tt && tt->options.ip_win32_type == IPW32_SET_DHCP_MASQ && tt->adapter_index != ~0)
3324 return dhcp_release_by_adapter_index (tt->adapter_index);
3325 else
3326 return false;
3329 bool
3330 dhcp_renew_by_adapter_index (const DWORD adapter_index)
3332 struct gc_arena gc = gc_new ();
3333 bool ret = false;
3334 const IP_ADAPTER_INDEX_MAP *inter = get_interface_info (adapter_index, &gc);
3336 if (inter)
3338 DWORD status = IpRenewAddress ((IP_ADAPTER_INDEX_MAP *)inter);
3339 if (status == NO_ERROR)
3341 msg (D_TUNTAP_INFO, "TAP: DHCP address renewal succeeded");
3342 ret = true;
3344 else
3345 msg (M_WARN, "WARNING: Failed to renew DHCP IP address lease on TAP-Win32 adapter: %s (code=%u)",
3346 strerror_win32 (status, &gc),
3347 (unsigned int)status);
3349 gc_free (&gc);
3350 return ret;
3353 static bool
3354 dhcp_renew (const struct tuntap *tt)
3356 if (tt && tt->options.ip_win32_type == IPW32_SET_DHCP_MASQ && tt->adapter_index != ~0)
3357 return dhcp_renew_by_adapter_index (tt->adapter_index);
3358 else
3359 return false;
3363 * netsh functions
3366 static void
3367 netsh_command (const struct argv *a, int n)
3369 int i;
3370 for (i = 0; i < n; ++i)
3372 bool status;
3373 openvpn_sleep (1);
3374 netcmd_semaphore_lock ();
3375 argv_msg_prefix (M_INFO, a, "NETSH");
3376 status = openvpn_execve_check (a, NULL, 0, "ERROR: netsh command failed");
3377 netcmd_semaphore_release ();
3378 if (status)
3379 return;
3380 openvpn_sleep (4);
3382 msg (M_FATAL, "NETSH: command failed");
3385 void
3386 ip_addr_string_to_array (in_addr_t *dest, int *dest_len, const IP_ADDR_STRING *src)
3388 int i = 0;
3389 while (src)
3391 const unsigned int getaddr_flags = GETADDR_HOST_ORDER;
3392 const char *ip_str = src->IpAddress.String;
3393 in_addr_t ip = 0;
3394 bool succeed = false;
3396 if (i >= *dest_len)
3397 break;
3398 if (!ip_str || !strlen (ip_str))
3399 break;
3401 ip = getaddr (getaddr_flags, ip_str, 0, &succeed, NULL);
3402 if (!succeed)
3403 break;
3404 dest[i++] = ip;
3406 src = src->Next;
3408 *dest_len = i;
3410 #if 0
3412 struct gc_arena gc = gc_new ();
3413 msg (M_INFO, "ip_addr_string_to_array [%d]", *dest_len);
3414 for (i = 0; i < *dest_len; ++i)
3416 msg (M_INFO, "%s", print_in_addr_t (dest[i], 0, &gc));
3418 gc_free (&gc);
3420 #endif
3423 static bool
3424 ip_addr_one_to_one (const in_addr_t *a1, const int a1len, const IP_ADDR_STRING *ias)
3426 in_addr_t a2[8];
3427 int a2len = SIZE(a2);
3428 int i;
3430 ip_addr_string_to_array (a2, &a2len, ias);
3431 /*msg (M_INFO, "a1len=%d a2len=%d", a1len, a2len);*/
3432 if (a1len != a2len)
3433 return false;
3435 for (i = 0; i < a1len; ++i)
3437 if (a1[i] != a2[i])
3438 return false;
3440 return true;
3443 static bool
3444 ip_addr_member_of (const in_addr_t addr, const IP_ADDR_STRING *ias)
3446 in_addr_t aa[8];
3447 int len = SIZE(aa);
3448 int i;
3450 ip_addr_string_to_array (aa, &len, ias);
3451 for (i = 0; i < len; ++i)
3453 if (addr == aa[i])
3454 return true;
3456 return false;
3459 static void
3460 netsh_ifconfig_options (const char *type,
3461 const in_addr_t *addr_list,
3462 const int addr_len,
3463 const IP_ADDR_STRING *current,
3464 const char *flex_name,
3465 const bool test_first)
3467 struct gc_arena gc = gc_new ();
3468 struct argv argv = argv_new ();
3469 bool delete_first = false;
3471 /* first check if we should delete existing DNS/WINS settings from TAP interface */
3472 if (test_first)
3474 if (!ip_addr_one_to_one (addr_list, addr_len, current))
3475 delete_first = true;
3477 else
3478 delete_first = true;
3480 /* delete existing DNS/WINS settings from TAP interface */
3481 if (delete_first)
3483 argv_printf (&argv, "%s%sc interface ip delete %s %s all",
3484 get_win_sys_path(),
3485 NETSH_PATH_SUFFIX,
3486 type,
3487 flex_name);
3488 netsh_command (&argv, 2);
3491 /* add new DNS/WINS settings to TAP interface */
3493 int count = 0;
3494 int i;
3495 for (i = 0; i < addr_len; ++i)
3497 if (delete_first || !test_first || !ip_addr_member_of (addr_list[i], current))
3499 const char *fmt = count ?
3500 "%s%sc interface ip add %s %s %s"
3501 : "%s%sc interface ip set %s %s static %s";
3503 argv_printf (&argv, fmt,
3504 get_win_sys_path(),
3505 NETSH_PATH_SUFFIX,
3506 type,
3507 flex_name,
3508 print_in_addr_t (addr_list[i], 0, &gc));
3509 netsh_command (&argv, 2);
3511 ++count;
3513 else
3515 msg (M_INFO, "NETSH: \"%s\" %s %s [already set]",
3516 flex_name,
3517 type,
3518 print_in_addr_t (addr_list[i], 0, &gc));
3523 argv_reset (&argv);
3524 gc_free (&gc);
3527 static void
3528 init_ip_addr_string2 (IP_ADDR_STRING *dest, const IP_ADDR_STRING *src1, const IP_ADDR_STRING *src2)
3530 CLEAR (dest[0]);
3531 CLEAR (dest[1]);
3532 if (src1)
3534 dest[0] = *src1;
3535 dest[0].Next = NULL;
3537 if (src2)
3539 dest[1] = *src2;
3540 dest[0].Next = &dest[1];
3541 dest[1].Next = NULL;
3545 static void
3546 netsh_ifconfig (const struct tuntap_options *to,
3547 const char *flex_name,
3548 const in_addr_t ip,
3549 const in_addr_t netmask,
3550 const unsigned int flags)
3552 struct gc_arena gc = gc_new ();
3553 struct argv argv = argv_new ();
3554 const IP_ADAPTER_INFO *ai = NULL;
3555 const IP_PER_ADAPTER_INFO *pai = NULL;
3557 if (flags & NI_TEST_FIRST)
3559 const IP_ADAPTER_INFO *list = get_adapter_info_list (&gc);
3560 const int index = get_adapter_index_flexible (flex_name);
3561 ai = get_adapter (list, index);
3562 pai = get_per_adapter_info (index, &gc);
3565 if (flags & NI_IP_NETMASK)
3567 if (test_adapter_ip_netmask (ai, ip, netmask))
3569 msg (M_INFO, "NETSH: \"%s\" %s/%s [already set]",
3570 flex_name,
3571 print_in_addr_t (ip, 0, &gc),
3572 print_in_addr_t (netmask, 0, &gc));
3574 else
3576 /* example: netsh interface ip set address my-tap static 10.3.0.1 255.255.255.0 */
3577 argv_printf (&argv, "%s%sc interface ip set address %s static %s %s",
3578 get_win_sys_path(),
3579 NETSH_PATH_SUFFIX,
3580 flex_name,
3581 print_in_addr_t (ip, 0, &gc),
3582 print_in_addr_t (netmask, 0, &gc));
3584 netsh_command (&argv, 4);
3588 /* set WINS/DNS options */
3589 if (flags & NI_OPTIONS)
3591 IP_ADDR_STRING wins[2];
3592 CLEAR (wins[0]);
3593 CLEAR (wins[1]);
3595 netsh_ifconfig_options ("dns",
3596 to->dns,
3597 to->dns_len,
3598 pai ? &pai->DnsServerList : NULL,
3599 flex_name,
3600 BOOL_CAST (flags & NI_TEST_FIRST));
3601 if (ai && ai->HaveWins)
3602 init_ip_addr_string2 (wins, &ai->PrimaryWinsServer, &ai->SecondaryWinsServer);
3604 netsh_ifconfig_options ("wins",
3605 to->wins,
3606 to->wins_len,
3607 ai ? wins : NULL,
3608 flex_name,
3609 BOOL_CAST (flags & NI_TEST_FIRST));
3612 argv_reset (&argv);
3613 gc_free (&gc);
3616 static void
3617 netsh_enable_dhcp (const struct tuntap_options *to,
3618 const char *actual_name)
3620 struct argv argv;
3621 argv_init (&argv);
3623 /* example: netsh interface ip set address my-tap dhcp */
3624 argv_printf (&argv,
3625 "%s%sc interface ip set address %s dhcp",
3626 get_win_sys_path(),
3627 NETSH_PATH_SUFFIX,
3628 actual_name);
3630 netsh_command (&argv, 4);
3632 argv_reset (&argv);
3636 * Return a TAP name for netsh commands.
3638 static const char *
3639 netsh_get_id (const char *dev_node, struct gc_arena *gc)
3641 const struct tap_reg *tap_reg = get_tap_reg (gc);
3642 const struct panel_reg *panel_reg = get_panel_reg (gc);
3643 struct buffer actual = alloc_buf_gc (256, gc);
3644 const char *guid;
3646 at_least_one_tap_win32 (tap_reg);
3648 if (dev_node)
3650 guid = get_device_guid (dev_node, BPTR (&actual), BCAP (&actual), tap_reg, panel_reg, gc);
3652 else
3654 guid = get_unspecified_device_guid (0, BPTR (&actual), BCAP (&actual), tap_reg, panel_reg, gc);
3656 if (get_unspecified_device_guid (1, NULL, 0, tap_reg, panel_reg, gc)) /* ambiguous if more than one TAP-Win32 adapter */
3657 guid = NULL;
3660 if (!guid)
3661 return "NULL"; /* not found */
3662 else if (strcmp (BPTR (&actual), "NULL"))
3663 return BPTR (&actual); /* control panel name */
3664 else
3665 return guid; /* no control panel name, return GUID instead */
3669 * Called iteratively on TAP-Win32 wait-for-initialization polling loop
3671 void
3672 tun_standby_init (struct tuntap *tt)
3674 tt->standby_iter = 0;
3677 bool
3678 tun_standby (struct tuntap *tt)
3680 bool ret = true;
3681 ++tt->standby_iter;
3682 if (tt->options.ip_win32_type == IPW32_SET_ADAPTIVE)
3684 if (tt->standby_iter == IPW32_SET_ADAPTIVE_TRY_NETSH)
3686 msg (M_INFO, "NOTE: now trying netsh (this may take some time)");
3687 netsh_ifconfig (&tt->options,
3688 tt->actual_name,
3689 tt->local,
3690 tt->adapter_netmask,
3691 NI_TEST_FIRST|NI_IP_NETMASK|NI_OPTIONS);
3693 else if (tt->standby_iter >= IPW32_SET_ADAPTIVE_TRY_NETSH*2)
3695 ret = false;
3698 return ret;
3702 * Convert DHCP options from the command line / config file
3703 * into a raw DHCP-format options string.
3706 static void
3707 write_dhcp_u8 (struct buffer *buf, const int type, const int data, bool *error)
3709 if (!buf_safe (buf, 3))
3711 *error = true;
3712 msg (M_WARN, "write_dhcp_u8: buffer overflow building DHCP options");
3713 return;
3715 buf_write_u8 (buf, type);
3716 buf_write_u8 (buf, 1);
3717 buf_write_u8 (buf, data);
3720 static void
3721 write_dhcp_u32_array (struct buffer *buf, const int type, const uint32_t *data, const unsigned int len, bool *error)
3723 if (len > 0)
3725 int i;
3726 const int size = len * sizeof (uint32_t);
3728 if (!buf_safe (buf, 2 + size))
3730 *error = true;
3731 msg (M_WARN, "write_dhcp_u32_array: buffer overflow building DHCP options");
3732 return;
3734 if (size < 1 || size > 255)
3736 *error = true;
3737 msg (M_WARN, "write_dhcp_u32_array: size (%d) must be > 0 and <= 255", size);
3738 return;
3740 buf_write_u8 (buf, type);
3741 buf_write_u8 (buf, size);
3742 for (i = 0; i < len; ++i)
3743 buf_write_u32 (buf, data[i]);
3747 static void
3748 write_dhcp_str (struct buffer *buf, const int type, const char *str, bool *error)
3750 const int len = strlen (str);
3751 if (!buf_safe (buf, 2 + len))
3753 *error = true;
3754 msg (M_WARN, "write_dhcp_str: buffer overflow building DHCP options");
3755 return;
3757 if (len < 1 || len > 255)
3759 *error = true;
3760 msg (M_WARN, "write_dhcp_str: string '%s' must be > 0 bytes and <= 255 bytes", str);
3761 return;
3763 buf_write_u8 (buf, type);
3764 buf_write_u8 (buf, len);
3765 buf_write (buf, str, len);
3768 static bool
3769 build_dhcp_options_string (struct buffer *buf, const struct tuntap_options *o)
3771 bool error = false;
3772 if (o->domain)
3773 write_dhcp_str (buf, 15, o->domain, &error);
3775 if (o->netbios_scope)
3776 write_dhcp_str (buf, 47, o->netbios_scope, &error);
3778 if (o->netbios_node_type)
3779 write_dhcp_u8 (buf, 46, o->netbios_node_type, &error);
3781 write_dhcp_u32_array (buf, 6, (uint32_t*)o->dns, o->dns_len, &error);
3782 write_dhcp_u32_array (buf, 44, (uint32_t*)o->wins, o->wins_len, &error);
3783 write_dhcp_u32_array (buf, 42, (uint32_t*)o->ntp, o->ntp_len, &error);
3784 write_dhcp_u32_array (buf, 45, (uint32_t*)o->nbdd, o->nbdd_len, &error);
3786 /* the MS DHCP server option 'Disable Netbios-over-TCP/IP
3787 is implemented as vendor option 001, value 002.
3788 A value of 001 means 'leave NBT alone' which is the default */
3789 if (o->disable_nbt)
3791 if (!buf_safe (buf, 8))
3793 msg (M_WARN, "build_dhcp_options_string: buffer overflow building DHCP options");
3794 return false;
3796 buf_write_u8 (buf, 43);
3797 buf_write_u8 (buf, 6); /* total length field */
3798 buf_write_u8 (buf, 0x001);
3799 buf_write_u8 (buf, 4); /* length of the vendor specified field */
3800 buf_write_u32 (buf, 0x002);
3802 return !error;
3805 static void
3806 fork_dhcp_action (struct tuntap *tt)
3808 if (tt->options.dhcp_pre_release || tt->options.dhcp_renew)
3810 struct gc_arena gc = gc_new ();
3811 struct buffer cmd = alloc_buf_gc (256, &gc);
3812 const int verb = 3;
3813 const int pre_sleep = 1;
3815 buf_printf (&cmd, "openvpn --verb %d --tap-sleep %d", verb, pre_sleep);
3816 if (tt->options.dhcp_pre_release)
3817 buf_printf (&cmd, " --dhcp-pre-release");
3818 if (tt->options.dhcp_renew)
3819 buf_printf (&cmd, " --dhcp-renew");
3820 buf_printf (&cmd, " --dhcp-rr %u", (unsigned int)tt->adapter_index);
3822 fork_to_self (BSTR (&cmd));
3823 gc_free (&gc);
3827 void
3828 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
3830 struct gc_arena gc = gc_new ();
3831 char device_path[256];
3832 const char *device_guid = NULL;
3833 DWORD len;
3834 bool dhcp_masq = false;
3835 bool dhcp_masq_post = false;
3837 /*netcmd_semaphore_lock ();*/
3839 ipv6_support (ipv6, false, tt);
3841 if (tt->type == DEV_TYPE_NULL)
3843 open_null (tt);
3844 gc_free (&gc);
3845 return;
3847 else if (tt->type == DEV_TYPE_TAP || tt->type == DEV_TYPE_TUN)
3851 else
3853 msg (M_FATAL|M_NOPREFIX, "Unknown virtual device type: '%s'", dev);
3857 * Lookup the device name in the registry, using the --dev-node high level name.
3860 const struct tap_reg *tap_reg = get_tap_reg (&gc);
3861 const struct panel_reg *panel_reg = get_panel_reg (&gc);
3862 char actual_buffer[256];
3864 at_least_one_tap_win32 (tap_reg);
3866 if (dev_node)
3868 /* Get the device GUID for the device specified with --dev-node. */
3869 device_guid = get_device_guid (dev_node, actual_buffer, sizeof (actual_buffer), tap_reg, panel_reg, &gc);
3871 if (!device_guid)
3872 msg (M_FATAL, "TAP-Win32 adapter '%s' not found", dev_node);
3874 /* Open Windows TAP-Win32 adapter */
3875 openvpn_snprintf (device_path, sizeof(device_path), "%s%s%s",
3876 USERMODEDEVICEDIR,
3877 device_guid,
3878 TAPSUFFIX);
3880 tt->hand = CreateFile (
3881 device_path,
3882 GENERIC_READ | GENERIC_WRITE,
3883 0, /* was: FILE_SHARE_READ */
3885 OPEN_EXISTING,
3886 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
3890 if (tt->hand == INVALID_HANDLE_VALUE)
3891 msg (M_ERR, "CreateFile failed on TAP device: %s", device_path);
3893 else
3895 int device_number = 0;
3897 /* Try opening all TAP devices until we find one available */
3898 while (true)
3900 device_guid = get_unspecified_device_guid (device_number,
3901 actual_buffer,
3902 sizeof (actual_buffer),
3903 tap_reg,
3904 panel_reg,
3905 &gc);
3907 if (!device_guid)
3908 msg (M_FATAL, "All TAP-Win32 adapters on this system are currently in use.");
3910 /* Open Windows TAP-Win32 adapter */
3911 openvpn_snprintf (device_path, sizeof(device_path), "%s%s%s",
3912 USERMODEDEVICEDIR,
3913 device_guid,
3914 TAPSUFFIX);
3916 tt->hand = CreateFile (
3917 device_path,
3918 GENERIC_READ | GENERIC_WRITE,
3919 0, /* was: FILE_SHARE_READ */
3921 OPEN_EXISTING,
3922 FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
3926 if (tt->hand == INVALID_HANDLE_VALUE)
3927 msg (D_TUNTAP_INFO, "CreateFile failed on TAP device: %s", device_path);
3928 else
3929 break;
3931 device_number++;
3935 /* translate high-level device name into a device instance
3936 GUID using the registry */
3937 tt->actual_name = string_alloc (actual_buffer, NULL);
3940 msg (M_INFO, "TAP-WIN32 device [%s] opened: %s", tt->actual_name, device_path);
3941 tt->adapter_index = get_adapter_index (device_guid);
3943 /* get driver version info */
3945 ULONG info[3];
3946 CLEAR (info);
3947 if (DeviceIoControl (tt->hand, TAP_IOCTL_GET_VERSION,
3948 &info, sizeof (info),
3949 &info, sizeof (info), &len, NULL))
3951 msg (D_TUNTAP_INFO, "TAP-Win32 Driver Version %d.%d %s",
3952 (int) info[0],
3953 (int) info[1],
3954 (info[2] ? "(DEBUG)" : ""));
3957 if (!(info[0] == TAP_WIN32_MIN_MAJOR && info[1] >= TAP_WIN32_MIN_MINOR))
3958 msg (M_FATAL, "ERROR: This version of " PACKAGE_NAME " requires a TAP-Win32 driver that is at least version %d.%d -- If you recently upgraded your " PACKAGE_NAME " distribution, a reboot is probably required at this point to get Windows to see the new driver.",
3959 TAP_WIN32_MIN_MAJOR,
3960 TAP_WIN32_MIN_MINOR);
3963 /* get driver MTU */
3965 ULONG mtu;
3966 if (DeviceIoControl (tt->hand, TAP_IOCTL_GET_MTU,
3967 &mtu, sizeof (mtu),
3968 &mtu, sizeof (mtu), &len, NULL))
3970 tt->post_open_mtu = (int) mtu;
3971 msg (D_MTU_INFO, "TAP-Win32 MTU=%d", (int) mtu);
3976 * Preliminaries for setting TAP-Win32 adapter TCP/IP
3977 * properties via --ip-win32 dynamic or --ip-win32 adaptive.
3979 if (tt->did_ifconfig_setup)
3981 if (tt->options.ip_win32_type == IPW32_SET_DHCP_MASQ)
3984 * If adapter is set to non-DHCP, set to DHCP mode.
3986 if (dhcp_status (tt->adapter_index) == DHCP_STATUS_DISABLED)
3987 netsh_enable_dhcp (&tt->options, tt->actual_name);
3988 dhcp_masq = true;
3989 dhcp_masq_post = true;
3991 else if (tt->options.ip_win32_type == IPW32_SET_ADAPTIVE)
3994 * If adapter is set to non-DHCP, use netsh right away.
3996 if (dhcp_status (tt->adapter_index) != DHCP_STATUS_ENABLED)
3998 netsh_ifconfig (&tt->options,
3999 tt->actual_name,
4000 tt->local,
4001 tt->adapter_netmask,
4002 NI_TEST_FIRST|NI_IP_NETMASK|NI_OPTIONS);
4004 else
4006 dhcp_masq = true;
4011 /* set point-to-point mode if TUN device */
4013 if (tt->type == DEV_TYPE_TUN)
4015 if (!tt->did_ifconfig_setup)
4017 msg (M_FATAL, "ERROR: --dev tun also requires --ifconfig");
4020 if (tt->topology == TOP_SUBNET)
4022 in_addr_t ep[3];
4023 BOOL status;
4025 ep[0] = htonl (tt->local);
4026 ep[1] = htonl (tt->local & tt->remote_netmask);
4027 ep[2] = htonl (tt->remote_netmask);
4029 status = DeviceIoControl (tt->hand, TAP_IOCTL_CONFIG_TUN,
4030 ep, sizeof (ep),
4031 ep, sizeof (ep), &len, NULL);
4033 msg (status ? M_INFO : M_FATAL, "Set TAP-Win32 TUN subnet mode network/local/netmask = %s/%s/%s [%s]",
4034 print_in_addr_t (ep[1], IA_NET_ORDER, &gc),
4035 print_in_addr_t (ep[0], IA_NET_ORDER, &gc),
4036 print_in_addr_t (ep[2], IA_NET_ORDER, &gc),
4037 status ? "SUCCEEDED" : "FAILED");
4039 } else {
4041 in_addr_t ep[2];
4042 ep[0] = htonl (tt->local);
4043 ep[1] = htonl (tt->remote_netmask);
4045 if (!DeviceIoControl (tt->hand, TAP_IOCTL_CONFIG_POINT_TO_POINT,
4046 ep, sizeof (ep),
4047 ep, sizeof (ep), &len, NULL))
4048 msg (M_FATAL, "ERROR: The TAP-Win32 driver rejected a DeviceIoControl call to set Point-to-Point mode, which is required for --dev tun");
4052 /* should we tell the TAP-Win32 driver to masquerade as a DHCP server as a means
4053 of setting the adapter address? */
4054 if (dhcp_masq)
4056 uint32_t ep[4];
4058 /* We will answer DHCP requests with a reply to set IP/subnet to these values */
4059 ep[0] = htonl (tt->local);
4060 ep[1] = htonl (tt->adapter_netmask);
4062 /* At what IP address should the DHCP server masquerade at? */
4063 if (tt->type == DEV_TYPE_TUN)
4065 if (tt->topology == TOP_SUBNET)
4067 const in_addr_t netmask_inv = ~tt->remote_netmask;
4068 ep[2] = netmask_inv ? htonl ((tt->local | netmask_inv) - 1) : 0;
4070 else
4071 ep[2] = htonl (tt->remote_netmask);
4073 if (tt->options.dhcp_masq_custom_offset)
4074 msg (M_WARN, "WARNING: because you are using '--dev tun' mode, the '--ip-win32 dynamic [offset]' option is ignoring the offset parameter");
4076 else
4078 in_addr_t dsa; /* DHCP server addr */
4080 ASSERT (tt->type == DEV_TYPE_TAP);
4082 if (tt->options.dhcp_masq_offset < 0)
4083 dsa = (tt->local | (~tt->adapter_netmask)) + tt->options.dhcp_masq_offset;
4084 else
4085 dsa = (tt->local & tt->adapter_netmask) + tt->options.dhcp_masq_offset;
4087 if (dsa == tt->local)
4088 msg (M_FATAL, "ERROR: There is a clash between the --ifconfig local address and the internal DHCP server address -- both are set to %s -- please use the --ip-win32 dynamic option to choose a different free address from the --ifconfig subnet for the internal DHCP server", print_in_addr_t (dsa, 0, &gc));
4090 if ((tt->local & tt->adapter_netmask) != (dsa & tt->adapter_netmask))
4091 msg (M_FATAL, "ERROR: --tap-win32 dynamic [offset] : offset is outside of --ifconfig subnet");
4093 ep[2] = htonl (dsa);
4096 /* lease time in seconds */
4097 ep[3] = (uint32_t) tt->options.dhcp_lease_time;
4099 ASSERT (ep[3] > 0);
4101 #ifndef SIMULATE_DHCP_FAILED /* this code is disabled to simulate bad DHCP negotiation */
4102 if (!DeviceIoControl (tt->hand, TAP_IOCTL_CONFIG_DHCP_MASQ,
4103 ep, sizeof (ep),
4104 ep, sizeof (ep), &len, NULL))
4105 msg (M_FATAL, "ERROR: The TAP-Win32 driver rejected a DeviceIoControl call to set TAP_IOCTL_CONFIG_DHCP_MASQ mode");
4107 msg (M_INFO, "Notified TAP-Win32 driver to set a DHCP IP/netmask of %s/%s on interface %s [DHCP-serv: %s, lease-time: %d]",
4108 print_in_addr_t (tt->local, 0, &gc),
4109 print_in_addr_t (tt->adapter_netmask, 0, &gc),
4110 device_guid,
4111 print_in_addr_t (ep[2], IA_NET_ORDER, &gc),
4112 ep[3]
4115 /* user-supplied DHCP options capability */
4116 if (tt->options.dhcp_options)
4118 struct buffer buf = alloc_buf (256);
4119 if (build_dhcp_options_string (&buf, &tt->options))
4121 msg (D_DHCP_OPT, "DHCP option string: %s", format_hex (BPTR (&buf), BLEN (&buf), 0, &gc));
4122 if (!DeviceIoControl (tt->hand, TAP_IOCTL_CONFIG_DHCP_SET_OPT,
4123 BPTR (&buf), BLEN (&buf),
4124 BPTR (&buf), BLEN (&buf), &len, NULL))
4125 msg (M_FATAL, "ERROR: The TAP-Win32 driver rejected a TAP_IOCTL_CONFIG_DHCP_SET_OPT DeviceIoControl call");
4127 else
4128 msg (M_WARN, "DHCP option string not set due to error");
4129 free_buf (&buf);
4131 #endif
4134 /* set driver media status to 'connected' */
4136 ULONG status = TRUE;
4137 if (!DeviceIoControl (tt->hand, TAP_IOCTL_SET_MEDIA_STATUS,
4138 &status, sizeof (status),
4139 &status, sizeof (status), &len, NULL))
4140 msg (M_WARN, "WARNING: The TAP-Win32 driver rejected a TAP_IOCTL_SET_MEDIA_STATUS DeviceIoControl call.");
4143 /* possible wait for adapter to come up */
4145 int s = tt->options.tap_sleep;
4146 if (s > 0)
4148 msg (M_INFO, "Sleeping for %d seconds...", s);
4149 openvpn_sleep (s);
4153 /* possibly use IP Helper API to set IP address on adapter */
4155 const DWORD index = tt->adapter_index;
4157 /* flush arp cache */
4158 if (index != (DWORD)~0)
4160 DWORD status;
4162 if ((status = FlushIpNetTable (index)) == NO_ERROR)
4163 msg (M_INFO, "Successful ARP Flush on interface [%u] %s",
4164 (unsigned int)index,
4165 device_guid);
4166 else
4167 msg (D_TUNTAP_INFO, "NOTE: FlushIpNetTable failed on interface [%u] %s (status=%u) : %s",
4168 (unsigned int)index,
4169 device_guid,
4170 (unsigned int)status,
4171 strerror_win32 (status, &gc));
4175 * If the TAP-Win32 driver is masquerading as a DHCP server
4176 * make sure the TCP/IP properties for the adapter are
4177 * set correctly.
4179 if (dhcp_masq_post)
4181 /* check dhcp enable status */
4182 if (dhcp_status (index) == DHCP_STATUS_DISABLED)
4183 msg (M_WARN, "WARNING: You have selected '--ip-win32 dynamic', which will not work unless the TAP-Win32 TCP/IP properties are set to 'Obtain an IP address automatically'");
4185 /* force an explicit DHCP lease renewal on TAP adapter? */
4186 if (tt->options.dhcp_pre_release)
4187 dhcp_release (tt);
4188 if (tt->options.dhcp_renew)
4189 dhcp_renew (tt);
4191 else
4192 fork_dhcp_action (tt);
4194 if (tt->did_ifconfig_setup && tt->options.ip_win32_type == IPW32_SET_IPAPI)
4196 DWORD status;
4197 const char *error_suffix = "I am having trouble using the Windows 'IP helper API' to automatically set the IP address -- consider using other --ip-win32 methods (not 'ipapi')";
4199 /* couldn't get adapter index */
4200 if (index == (DWORD)~0)
4202 msg (M_FATAL, "ERROR: unable to get adapter index for interface %s -- %s",
4203 device_guid,
4204 error_suffix);
4207 /* check dhcp enable status */
4208 if (dhcp_status (index) == DHCP_STATUS_DISABLED)
4209 msg (M_WARN, "NOTE: You have selected (explicitly or by default) '--ip-win32 ipapi', which has a better chance of working correctly if the TAP-Win32 TCP/IP properties are set to 'Obtain an IP address automatically'");
4211 /* delete previously added IP addresses which were not
4212 correctly deleted */
4213 delete_temp_addresses (index);
4215 /* add a new IP address */
4216 if ((status = AddIPAddress (htonl(tt->local),
4217 htonl(tt->adapter_netmask),
4218 index,
4219 &tt->ipapi_context,
4220 &tt->ipapi_instance)) == NO_ERROR)
4221 msg (M_INFO, "Succeeded in adding a temporary IP/netmask of %s/%s to interface %s using the Win32 IP Helper API",
4222 print_in_addr_t (tt->local, 0, &gc),
4223 print_in_addr_t (tt->adapter_netmask, 0, &gc),
4224 device_guid
4226 else
4227 msg (M_FATAL, "ERROR: AddIPAddress %s/%s failed on interface %s, index=%d, status=%u (windows error: '%s') -- %s",
4228 print_in_addr_t (tt->local, 0, &gc),
4229 print_in_addr_t (tt->adapter_netmask, 0, &gc),
4230 device_guid,
4231 (int)index,
4232 (unsigned int)status,
4233 strerror_win32 (status, &gc),
4234 error_suffix);
4235 tt->ipapi_context_defined = true;
4238 /*netcmd_semaphore_release ();*/
4239 gc_free (&gc);
4242 const char *
4243 tap_win32_getinfo (const struct tuntap *tt, struct gc_arena *gc)
4245 if (tt && tt->hand != NULL)
4247 struct buffer out = alloc_buf_gc (256, gc);
4248 DWORD len;
4249 if (DeviceIoControl (tt->hand, TAP_IOCTL_GET_INFO,
4250 BSTR (&out), BCAP (&out),
4251 BSTR (&out), BCAP (&out),
4252 &len, NULL))
4254 return BSTR (&out);
4257 return NULL;
4260 void
4261 tun_show_debug (struct tuntap *tt)
4263 if (tt && tt->hand != NULL)
4265 struct buffer out = alloc_buf (1024);
4266 DWORD len;
4267 while (DeviceIoControl (tt->hand, TAP_IOCTL_GET_LOG_LINE,
4268 BSTR (&out), BCAP (&out),
4269 BSTR (&out), BCAP (&out),
4270 &len, NULL))
4272 msg (D_TAP_WIN32_DEBUG, "TAP-Win32: %s", BSTR (&out));
4274 free_buf (&out);
4278 void
4279 close_tun (struct tuntap *tt)
4281 struct gc_arena gc = gc_new ();
4283 if (tt)
4285 #if 1
4286 if (tt->ipapi_context_defined)
4288 DWORD status;
4289 if ((status = DeleteIPAddress (tt->ipapi_context)) != NO_ERROR)
4291 msg (M_WARN, "Warning: DeleteIPAddress[%u] failed on TAP-Win32 adapter, status=%u : %s",
4292 (unsigned int)tt->ipapi_context,
4293 (unsigned int)status,
4294 strerror_win32 (status, &gc));
4297 #endif
4299 if (tt->options.dhcp_release)
4300 dhcp_release (tt);
4302 if (tt->hand != NULL)
4304 dmsg (D_WIN32_IO_LOW, "Attempting CancelIO on TAP-Win32 adapter");
4305 if (!CancelIo (tt->hand))
4306 msg (M_WARN | M_ERRNO, "Warning: CancelIO failed on TAP-Win32 adapter");
4309 dmsg (D_WIN32_IO_LOW, "Attempting close of overlapped read event on TAP-Win32 adapter");
4310 overlapped_io_close (&tt->reads);
4312 dmsg (D_WIN32_IO_LOW, "Attempting close of overlapped write event on TAP-Win32 adapter");
4313 overlapped_io_close (&tt->writes);
4315 if (tt->hand != NULL)
4317 dmsg (D_WIN32_IO_LOW, "Attempting CloseHandle on TAP-Win32 adapter");
4318 if (!CloseHandle (tt->hand))
4319 msg (M_WARN | M_ERRNO, "Warning: CloseHandle failed on TAP-Win32 adapter");
4322 if (tt->actual_name)
4323 free (tt->actual_name);
4325 clear_tuntap (tt);
4326 free (tt);
4328 gc_free (&gc);
4332 * Convert --ip-win32 constants between index and ascii form.
4335 struct ipset_names {
4336 const char *short_form;
4339 /* Indexed by IPW32_SET_x */
4340 static const struct ipset_names ipset_names[] = {
4341 {"manual"},
4342 {"netsh"},
4343 {"ipapi"},
4344 {"dynamic"},
4345 {"adaptive"}
4349 ascii2ipset (const char* name)
4351 int i;
4352 ASSERT (IPW32_SET_N == SIZE (ipset_names));
4353 for (i = 0; i < IPW32_SET_N; ++i)
4354 if (!strcmp (name, ipset_names[i].short_form))
4355 return i;
4356 return -1;
4359 const char *
4360 ipset2ascii (int index)
4362 ASSERT (IPW32_SET_N == SIZE (ipset_names));
4363 if (index < 0 || index >= IPW32_SET_N)
4364 return "[unknown --ip-win32 type]";
4365 else
4366 return ipset_names[index].short_form;
4369 const char *
4370 ipset2ascii_all (struct gc_arena *gc)
4372 struct buffer out = alloc_buf_gc (256, gc);
4373 int i;
4375 ASSERT (IPW32_SET_N == SIZE (ipset_names));
4376 for (i = 0; i < IPW32_SET_N; ++i)
4378 if (i)
4379 buf_printf(&out, " ");
4380 buf_printf(&out, "[%s]", ipset2ascii(i));
4382 return BSTR (&out);
4385 #else /* generic */
4387 void
4388 open_tun (const char *dev, const char *dev_type, const char *dev_node, bool ipv6, struct tuntap *tt)
4390 open_tun_generic (dev, dev_type, dev_node, ipv6, false, true, tt);
4393 void
4394 close_tun (struct tuntap* tt)
4396 if (tt)
4398 close_tun_generic (tt);
4399 free (tt);
4404 write_tun (struct tuntap* tt, uint8_t *buf, int len)
4406 return write (tt->fd, buf, len);
4410 read_tun (struct tuntap* tt, uint8_t *buf, int len)
4412 return read (tt->fd, buf, len);
4415 #endif