OpenVPN
tun.c
Go to the documentation of this file.
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.
7  *
8  * Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
9  *
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.
13  *
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.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 /*
25  * Support routines for configuring and accessing TUN/TAP
26  * virtual network adapters.
27  *
28  * This file is based on the TUN/TAP driver interface routines
29  * from VTun by Maxim Krasnyansky <max_mk@yahoo.com>.
30  */
31 
32 #ifdef HAVE_CONFIG_H
33 #include "config.h"
34 #elif defined(_MSC_VER)
35 #include "config-msvc.h"
36 #endif
37 
38 #include "syshead.h"
39 
40 #include "tun.h"
41 #include "fdmisc.h"
42 #include "common.h"
43 #include "run_command.h"
44 #include "socket.h"
45 #include "manage.h"
46 #include "route.h"
47 #include "win32.h"
48 #include "block_dns.h"
49 
50 #include "memdbg.h"
51 
52 #ifdef _WIN32
53 #include "openvpn-msg.h"
54 #endif
55 
56 #include <string.h>
57 
58 #ifdef _WIN32
59 
60 /* #define SIMULATE_DHCP_FAILED */ /* simulate bad DHCP negotiation */
61 
62 #define NI_TEST_FIRST (1<<0)
63 #define NI_IP_NETMASK (1<<1)
64 #define NI_OPTIONS (1<<2)
65 
66 static void netsh_ifconfig(const struct tuntap_options *to,
67  const char *flex_name,
68  const in_addr_t ip,
69  const in_addr_t netmask,
70  const unsigned int flags);
71 
72 static void netsh_set_dns6_servers(const struct in6_addr *addr_list,
73  const int addr_len,
74  const char *flex_name);
75 
76 static void netsh_command(const struct argv *a, int n, int msglevel);
77 
78 static const char *netsh_get_id(const char *dev_node, struct gc_arena *gc);
79 
80 static DWORD get_adapter_index_flexible(const char *name);
81 
82 static bool
83 do_address_service(const bool add, const short family, const struct tuntap *tt)
84 {
85  bool ret = false;
86  ack_message_t ack;
87  struct gc_arena gc = gc_new();
88  HANDLE pipe = tt->options.msg_channel;
89 
90  address_message_t addr = {
91  .header = {
93  sizeof(address_message_t),
94  0
95  },
96  .family = family,
97  .iface = { .index = tt->adapter_index, .name = "" }
98  };
99 
101  {
102  strncpy(addr.iface.name, tt->actual_name, sizeof(addr.iface.name));
103  addr.iface.name[sizeof(addr.iface.name) - 1] = '\0';
104  }
105 
106  if (addr.family == AF_INET)
107  {
108  addr.address.ipv4.s_addr = tt->local;
109  addr.prefix_len = 32;
110  }
111  else
112  {
113  addr.address.ipv6 = tt->local_ipv6;
114  addr.prefix_len = tt->netbits_ipv6;
115  }
116 
117  if (!send_msg_iservice(pipe, &addr, sizeof(addr), &ack, "TUN"))
118  {
119  goto out;
120  }
121 
122  if (ack.error_number != NO_ERROR)
123  {
124  msg(M_WARN, "TUN: %s address failed using service: %s [status=%u if_index=%d]",
125  (add ? "adding" : "deleting"), strerror_win32(ack.error_number, &gc),
126  ack.error_number, addr.iface.index);
127  goto out;
128  }
129 
130  ret = true;
131 
132 out:
133  gc_free(&gc);
134  return ret;
135 }
136 
137 static bool
138 do_dns6_service(bool add, const struct tuntap *tt)
139 {
140  bool ret = false;
141  ack_message_t ack;
142  struct gc_arena gc = gc_new();
143  HANDLE pipe = tt->options.msg_channel;
144  int addr_len = add ? tt->options.dns6_len : 0;
145 
146  if (addr_len == 0 && add) /* no addresses to add */
147  {
148  return true;
149  }
150 
151  dns_cfg_message_t dns = {
152  .header = {
154  sizeof(dns_cfg_message_t),
155  0
156  },
157  .iface = { .index = tt->adapter_index, .name = "" },
158  .domains = "",
159  .family = AF_INET6,
160  .addr_len = addr_len
161  };
162 
163  /* interface name is required */
164  strncpy(dns.iface.name, tt->actual_name, sizeof(dns.iface.name));
165  dns.iface.name[sizeof(dns.iface.name) - 1] = '\0';
166 
167  if (addr_len > _countof(dns.addr))
168  {
169  addr_len = _countof(dns.addr);
170  dns.addr_len = addr_len;
171  msg(M_WARN, "Number of IPv6 DNS addresses sent to service truncated to %d",
172  addr_len);
173  }
174 
175  for (int i = 0; i < addr_len; ++i)
176  {
177  dns.addr[i].ipv6 = tt->options.dns6[i];
178  }
179 
180  msg(D_LOW, "%s IPv6 dns servers on '%s' (if_index = %d) using service",
181  (add ? "Setting" : "Deleting"), dns.iface.name, dns.iface.index);
182 
183  if (!send_msg_iservice(pipe, &dns, sizeof(dns), &ack, "TUN"))
184  {
185  goto out;
186  }
187 
188  if (ack.error_number != NO_ERROR)
189  {
190  msg(M_WARN, "TUN: %s IPv6 dns failed using service: %s [status=%u if_name=%s]",
191  (add ? "adding" : "deleting"), strerror_win32(ack.error_number, &gc),
192  ack.error_number, dns.iface.name);
193  goto out;
194  }
195 
196  msg(M_INFO, "IPv6 dns servers %s using service", (add ? "set" : "deleted"));
197  ret = true;
198 
199 out:
200  gc_free(&gc);
201  return ret;
202 }
203 
204 #endif /* ifdef _WIN32 */
205 
206 #ifdef TARGET_SOLARIS
207 static void solaris_error_close(struct tuntap *tt, const struct env_set *es, const char *actual, bool unplumb_inet6);
208 
209 #include <stropts.h>
210 #endif
211 
212 #if defined(TARGET_DARWIN) && HAVE_NET_IF_UTUN_H
213 #include <sys/kern_control.h>
214 #include <net/if_utun.h>
215 #include <sys/sys_domain.h>
216 #endif
217 
218 static void clear_tuntap(struct tuntap *tuntap);
219 
220 bool
221 is_dev_type(const char *dev, const char *dev_type, const char *match_type)
222 {
223  ASSERT(match_type);
224  if (!dev)
225  {
226  return false;
227  }
228  if (dev_type)
229  {
230  return !strcmp(dev_type, match_type);
231  }
232  else
233  {
234  return !strncmp(dev, match_type, strlen(match_type));
235  }
236 }
237 
238 int
239 dev_type_enum(const char *dev, const char *dev_type)
240 {
241  if (is_dev_type(dev, dev_type, "tun"))
242  {
243  return DEV_TYPE_TUN;
244  }
245  else if (is_dev_type(dev, dev_type, "tap"))
246  {
247  return DEV_TYPE_TAP;
248  }
249  else if (is_dev_type(dev, dev_type, "null"))
250  {
251  return DEV_TYPE_NULL;
252  }
253  else
254  {
255  return DEV_TYPE_UNDEF;
256  }
257 }
258 
259 const char *
260 dev_type_string(const char *dev, const char *dev_type)
261 {
262  switch (dev_type_enum(dev, dev_type))
263  {
264  case DEV_TYPE_TUN:
265  return "tun";
266 
267  case DEV_TYPE_TAP:
268  return "tap";
269 
270  case DEV_TYPE_NULL:
271  return "null";
272 
273  default:
274  return "[unknown-dev-type]";
275  }
276 }
277 
278 /*
279  * Try to predict the actual TUN/TAP device instance name,
280  * before the device is actually opened.
281  */
282 const char *
283 guess_tuntap_dev(const char *dev,
284  const char *dev_type,
285  const char *dev_node,
286  struct gc_arena *gc)
287 {
288 #ifdef _WIN32
289  const int dt = dev_type_enum(dev, dev_type);
290  if (dt == DEV_TYPE_TUN || dt == DEV_TYPE_TAP)
291  {
292  return netsh_get_id(dev_node, gc);
293  }
294 #endif
295 
296  /* default case */
297  return dev;
298 }
299 
300 
301 /* --ifconfig-nowarn disables some options sanity checking */
302 static const char ifconfig_warn_how_to_silence[] = "(silence this warning with --ifconfig-nowarn)";
303 
304 /*
305  * If !tun, make sure ifconfig_remote_netmask looks
306  * like a netmask.
307  *
308  * If tun, make sure ifconfig_remote_netmask looks
309  * like an IPv4 address.
310  */
311 static void
312 ifconfig_sanity_check(bool tun, in_addr_t addr, int topology)
313 {
314  struct gc_arena gc = gc_new();
315  const bool looks_like_netmask = ((addr & 0xFF000000) == 0xFF000000);
316  if (tun)
317  {
318  if (looks_like_netmask && (topology == TOP_NET30 || topology == TOP_P2P))
319  {
320  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",
321  print_in_addr_t(addr, 0, &gc),
323  }
324  }
325  else /* tap */
326  {
327  if (!looks_like_netmask)
328  {
329  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",
331  }
332  }
333  gc_free(&gc);
334 }
335 
336 /*
337  * For TAP-style devices, generate a broadcast address.
338  */
339 static in_addr_t
341  in_addr_t netmask)
342 {
343  return local | ~netmask;
344 }
345 
346 /*
347  * Check that --local and --remote addresses do not
348  * clash with ifconfig addresses or subnet.
349  */
350 static void
351 check_addr_clash(const char *name,
352  int type,
353  in_addr_t public,
354  in_addr_t local,
355  in_addr_t remote_netmask)
356 {
357  struct gc_arena gc = gc_new();
358 #if 0
359  msg(M_INFO, "CHECK_ADDR_CLASH type=%d public=%s local=%s, remote_netmask=%s",
360  type,
361  print_in_addr_t(public, 0, &gc),
362  print_in_addr_t(local, 0, &gc),
363  print_in_addr_t(remote_netmask, 0, &gc));
364 #endif
365 
366  if (public)
367  {
368  if (type == DEV_TYPE_TUN)
369  {
370  const in_addr_t test_netmask = 0xFFFFFF00;
371  const in_addr_t public_net = public & test_netmask;
372  const in_addr_t local_net = local & test_netmask;
373  const in_addr_t remote_net = remote_netmask & test_netmask;
374 
375  if (public == local || public == remote_netmask)
376  {
377  msg(M_WARN,
378  "WARNING: --%s address [%s] conflicts with --ifconfig address pair [%s, %s]. %s",
379  name,
380  print_in_addr_t(public, 0, &gc),
381  print_in_addr_t(local, 0, &gc),
382  print_in_addr_t(remote_netmask, 0, &gc),
384  }
385 
386  if (public_net == local_net || public_net == remote_net)
387  {
388  msg(M_WARN,
389  "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",
390  name,
391  print_in_addr_t(public, 0, &gc),
392  print_in_addr_t(local, 0, &gc),
393  print_in_addr_t(remote_netmask, 0, &gc),
395  }
396  }
397  else if (type == DEV_TYPE_TAP)
398  {
399  const in_addr_t public_network = public & remote_netmask;
400  const in_addr_t virtual_network = local & remote_netmask;
401  if (public_network == virtual_network)
402  {
403  msg(M_WARN,
404  "WARNING: --%s address [%s] conflicts with --ifconfig subnet [%s, %s] -- local and remote addresses cannot be inside of the --ifconfig subnet. %s",
405  name,
406  print_in_addr_t(public, 0, &gc),
407  print_in_addr_t(local, 0, &gc),
408  print_in_addr_t(remote_netmask, 0, &gc),
410  }
411  }
412  }
413  gc_free(&gc);
414 }
415 
416 /*
417  * Issue a warning if ip/netmask (on the virtual IP network) conflicts with
418  * the settings on the local LAN. This is designed to flag issues where
419  * (for example) the OpenVPN server LAN is running on 192.168.1.x, but then
420  * an OpenVPN client tries to connect from a public location that is also running
421  * off of a router set to 192.168.1.x.
422  */
423 void
425  const in_addr_t netmask,
426  const char *prefix)
427 {
428 #if 0 /* too many false positives */
429  struct gc_arena gc = gc_new();
430  in_addr_t lan_gw = 0;
431  in_addr_t lan_netmask = 0;
432 
433  if (get_default_gateway(&lan_gw, &lan_netmask) && lan_netmask)
434  {
435  const in_addr_t lan_network = lan_gw & lan_netmask;
436  const in_addr_t network = ip & netmask;
437 
438  /* do the two subnets defined by network/netmask and lan_network/lan_netmask intersect? */
439  if ((network & lan_netmask) == lan_network
440  || (lan_network & netmask) == network)
441  {
442  msg(M_WARN, "WARNING: potential %s subnet conflict between local LAN [%s/%s] and remote VPN [%s/%s]",
443  prefix,
444  print_in_addr_t(lan_network, 0, &gc),
445  print_in_addr_t(lan_netmask, 0, &gc),
446  print_in_addr_t(network, 0, &gc),
447  print_in_addr_t(netmask, 0, &gc));
448  }
449  }
450  gc_free(&gc);
451 #endif /* if 0 */
452 }
453 
454 void
456 {
457  struct gc_arena gc = gc_new();
458  struct route_gateway_info rgi;
459  const int needed = (RGI_ADDR_DEFINED|RGI_NETMASK_DEFINED);
460 
461  get_default_gateway(&rgi);
462  if ((rgi.flags & needed) == needed)
463  {
464  const in_addr_t lan_network = rgi.gateway.addr & rgi.gateway.netmask;
465  if (lan_network == 0xC0A80000 || lan_network == 0xC0A80100)
466  {
467  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.");
468  }
469  }
470  gc_free(&gc);
471 }
472 
473 /*
474  * Return a string to be used for options compatibility check
475  * between peers.
476  */
477 const char *
478 ifconfig_options_string(const struct tuntap *tt, bool remote, bool disable, struct gc_arena *gc)
479 {
480  struct buffer out = alloc_buf_gc(256, gc);
481  if (tt->did_ifconfig_setup && !disable)
482  {
483  if (tt->type == DEV_TYPE_TAP || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET))
484  {
485  buf_printf(&out, "%s %s",
486  print_in_addr_t(tt->local & tt->remote_netmask, 0, gc),
487  print_in_addr_t(tt->remote_netmask, 0, gc));
488  }
489  else if (tt->type == DEV_TYPE_TUN)
490  {
491  const char *l, *r;
492  if (remote)
493  {
494  r = print_in_addr_t(tt->local, 0, gc);
495  l = print_in_addr_t(tt->remote_netmask, 0, gc);
496  }
497  else
498  {
499  l = print_in_addr_t(tt->local, 0, gc);
500  r = print_in_addr_t(tt->remote_netmask, 0, gc);
501  }
502  buf_printf(&out, "%s %s", r, l);
503  }
504  else
505  {
506  buf_printf(&out, "[undef]");
507  }
508  }
509  return BSTR(&out);
510 }
511 
512 /*
513  * Return a status string describing wait state.
514  */
515 const char *
516 tun_stat(const struct tuntap *tt, unsigned int rwflags, struct gc_arena *gc)
517 {
518  struct buffer out = alloc_buf_gc(64, gc);
519  if (tt)
520  {
521  if (rwflags & EVENT_READ)
522  {
523  buf_printf(&out, "T%s",
524  (tt->rwflags_debug & EVENT_READ) ? "R" : "r");
525 #ifdef _WIN32
526  buf_printf(&out, "%s",
528 #endif
529  }
530  if (rwflags & EVENT_WRITE)
531  {
532  buf_printf(&out, "T%s",
533  (tt->rwflags_debug & EVENT_WRITE) ? "W" : "w");
534 #ifdef _WIN32
535  buf_printf(&out, "%s",
537 #endif
538  }
539  }
540  else
541  {
542  buf_printf(&out, "T?");
543  }
544  return BSTR(&out);
545 }
546 
547 /*
548  * Return true for point-to-point topology, false for subnet topology
549  */
550 bool
551 is_tun_p2p(const struct tuntap *tt)
552 {
553  bool tun = false;
554 
555  if (tt->type == DEV_TYPE_TAP
556  || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET)
557  || tt->type == DEV_TYPE_NULL)
558  {
559  tun = false;
560  }
561  else if (tt->type == DEV_TYPE_TUN)
562  {
563  tun = true;
564  }
565  else
566  {
567  msg(M_FATAL, "Error: problem with tun vs. tap setting"); /* JYFIXME -- needs to be caught earlier, in init_tun? */
568 
569  }
570  return tun;
571 }
572 
573 /*
574  * Set the ifconfig_* environment variables, both for IPv4 and IPv6
575  */
576 void
577 do_ifconfig_setenv(const struct tuntap *tt, struct env_set *es)
578 {
579  struct gc_arena gc = gc_new();
580  const char *ifconfig_local = print_in_addr_t(tt->local, 0, &gc);
581  const char *ifconfig_remote_netmask = print_in_addr_t(tt->remote_netmask, 0, &gc);
582 
583  /*
584  * Set environmental variables with ifconfig parameters.
585  */
586  if (tt->did_ifconfig_setup)
587  {
588  bool tun = is_tun_p2p(tt);
589 
590  setenv_str(es, "ifconfig_local", ifconfig_local);
591  if (tun)
592  {
593  setenv_str(es, "ifconfig_remote", ifconfig_remote_netmask);
594  }
595  else
596  {
597  const char *ifconfig_broadcast = print_in_addr_t(tt->broadcast, 0, &gc);
598  setenv_str(es, "ifconfig_netmask", ifconfig_remote_netmask);
599  setenv_str(es, "ifconfig_broadcast", ifconfig_broadcast);
600  }
601  }
602 
603  if (tt->did_ifconfig_ipv6_setup)
604  {
605  const char *ifconfig_ipv6_local = print_in6_addr(tt->local_ipv6, 0, &gc);
606  const char *ifconfig_ipv6_remote = print_in6_addr(tt->remote_ipv6, 0, &gc);
607 
608  setenv_str(es, "ifconfig_ipv6_local", ifconfig_ipv6_local);
609  setenv_int(es, "ifconfig_ipv6_netbits", tt->netbits_ipv6);
610  setenv_str(es, "ifconfig_ipv6_remote", ifconfig_ipv6_remote);
611  }
612 
613  gc_free(&gc);
614 }
615 
616 /*
617  * Init tun/tap object.
618  *
619  * Set up tuntap structure for ifconfig,
620  * but don't execute yet.
621  */
622 struct tuntap *
623 init_tun(const char *dev, /* --dev option */
624  const char *dev_type, /* --dev-type option */
625  int topology, /* one of the TOP_x values */
626  const char *ifconfig_local_parm, /* --ifconfig parm 1 */
627  const char *ifconfig_remote_netmask_parm, /* --ifconfig parm 2 */
628  const char *ifconfig_ipv6_local_parm, /* --ifconfig parm 1 IPv6 */
629  int ifconfig_ipv6_netbits_parm,
630  const char *ifconfig_ipv6_remote_parm, /* --ifconfig parm 2 IPv6 */
631  struct addrinfo *local_public,
632  struct addrinfo *remote_public,
633  const bool strict_warn,
634  struct env_set *es)
635 {
636  struct gc_arena gc = gc_new();
637  struct tuntap *tt;
638 
639  ALLOC_OBJ(tt, struct tuntap);
640  clear_tuntap(tt);
641 
642  tt->type = dev_type_enum(dev, dev_type);
643  tt->topology = topology;
644 
645  if (ifconfig_local_parm && ifconfig_remote_netmask_parm)
646  {
647  bool tun = false;
648 
649  /*
650  * We only handle TUN/TAP devices here, not --dev null devices.
651  */
652  tun = is_tun_p2p(tt);
653 
654  /*
655  * Convert arguments to binary IPv4 addresses.
656  */
657 
658  tt->local = getaddr(
662  | GETADDR_FATAL,
663  ifconfig_local_parm,
664  0,
665  NULL,
666  NULL);
667 
668  tt->remote_netmask = getaddr(
669  (tun ? GETADDR_RESOLVE : 0)
672  | GETADDR_FATAL,
673  ifconfig_remote_netmask_parm,
674  0,
675  NULL,
676  NULL);
677 
678  /*
679  * Look for common errors in --ifconfig parms
680  */
681  if (strict_warn)
682  {
683  struct addrinfo *curele;
685 
686  /*
687  * If local_public or remote_public addresses are defined,
688  * make sure they do not clash with our virtual subnet.
689  */
690 
691  for (curele = local_public; curele; curele = curele->ai_next)
692  {
693  if (curele->ai_family == AF_INET)
694  {
695  check_addr_clash("local",
696  tt->type,
697  ((struct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr,
698  tt->local,
699  tt->remote_netmask);
700  }
701  }
702 
703  for (curele = remote_public; curele; curele = curele->ai_next)
704  {
705  if (curele->ai_family == AF_INET)
706  {
707  check_addr_clash("remote",
708  tt->type,
709  ((struct sockaddr_in *)curele->ai_addr)->sin_addr.s_addr,
710  tt->local,
711  tt->remote_netmask);
712  }
713  }
714 
715  if (tt->type == DEV_TYPE_TAP || (tt->type == DEV_TYPE_TUN && tt->topology == TOP_SUBNET))
716  {
717  check_subnet_conflict(tt->local, tt->remote_netmask, "TUN/TAP adapter");
718  }
719  else if (tt->type == DEV_TYPE_TUN)
720  {
721  check_subnet_conflict(tt->local, IPV4_NETMASK_HOST, "TUN/TAP adapter");
722  }
723  }
724 
725  /*
726  * If TAP-style interface, generate broadcast address.
727  */
728  if (!tun)
729  {
731  }
732 
733 #ifdef _WIN32
734  /*
735  * Make sure that both ifconfig addresses are part of the
736  * same .252 subnet.
737  */
738  if (tun)
739  {
741  tt->adapter_netmask = ~3;
742  }
743  else
744  {
746  }
747 #endif
748 
749  tt->did_ifconfig_setup = true;
750  }
751 
752  if (ifconfig_ipv6_local_parm && ifconfig_ipv6_remote_parm)
753  {
754 
755  /*
756  * Convert arguments to binary IPv6 addresses.
757  */
758 
759  if (inet_pton( AF_INET6, ifconfig_ipv6_local_parm, &tt->local_ipv6 ) != 1
760  || inet_pton( AF_INET6, ifconfig_ipv6_remote_parm, &tt->remote_ipv6 ) != 1)
761  {
762  msg( M_FATAL, "init_tun: problem converting IPv6 ifconfig addresses %s and %s to binary", ifconfig_ipv6_local_parm, ifconfig_ipv6_remote_parm );
763  }
764  tt->netbits_ipv6 = ifconfig_ipv6_netbits_parm;
765 
766  tt->did_ifconfig_ipv6_setup = true;
767  }
768 
769  /*
770  * Set environmental variables with ifconfig parameters.
771  */
772  if (es)
773  {
774  do_ifconfig_setenv(tt, es);
775  }
776 
777  gc_free(&gc);
778  return tt;
779 }
780 
781 /*
782  * Platform specific tun initializations
783  */
784 void
785 init_tun_post(struct tuntap *tt,
786  const struct frame *frame,
787  const struct tuntap_options *options)
788 {
789  tt->options = *options;
790 #ifdef _WIN32
791  overlapped_io_init(&tt->reads, frame, FALSE, true);
792  overlapped_io_init(&tt->writes, frame, TRUE, true);
793  tt->rw_handle.read = tt->reads.overlapped.hEvent;
794  tt->rw_handle.write = tt->writes.overlapped.hEvent;
796 #endif
797 }
798 
799 #if defined(_WIN32) \
800  || defined(TARGET_DARWIN) || defined(TARGET_NETBSD) || defined(TARGET_OPENBSD)
801 
802 /* some of the platforms will auto-add a "network route" pointing
803  * to the interface on "ifconfig tunX 2001:db8::1/64", others need
804  * an extra call to "route add..."
805  * -> helper function to simplify code below
806  */
807 void
808 add_route_connected_v6_net(struct tuntap *tt,
809  const struct env_set *es)
810 {
811  struct route_ipv6 r6;
812 
813  CLEAR(r6);
814  r6.network = tt->local_ipv6;
815  r6.netbits = tt->netbits_ipv6;
816  r6.gateway = tt->local_ipv6;
817  r6.metric = 0; /* connected route */
819  add_route_ipv6(&r6, tt, 0, es);
820 }
821 
822 void
824  const struct env_set *es)
825 {
826  struct route_ipv6 r6;
827 
828  CLEAR(r6);
829  r6.network = tt->local_ipv6;
830  r6.netbits = tt->netbits_ipv6;
831  r6.gateway = tt->local_ipv6;
832  r6.metric = 0; /* connected route */
835  delete_route_ipv6(&r6, tt, 0, es);
836 }
837 #endif /* if defined(_WIN32) || defined(TARGET_DARWIN) || defined(TARGET_NETBSD) || defined(TARGET_OPENBSD) */
838 
839 #if defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY) \
840  || defined(TARGET_NETBSD) || defined(TARGET_OPENBSD)
841 /* we can't use true subnet mode on tun on all platforms, as that
842  * conflicts with IPv6 (wants to use ND then, which we don't do),
843  * but the OSes want "a remote address that is different from ours"
844  * - so we construct one, normally the first in the subnet, but if
845  * this is the same as ours, use the second one.
846  * The actual address does not matter at all, as the tun interface
847  * is still point to point and no layer 2 resolution is done...
848  */
849 
850 in_addr_t
851 create_arbitrary_remote( struct tuntap *tt )
852 {
853  in_addr_t remote;
854 
855  remote = (tt->local & tt->remote_netmask) +1;
856 
857  if (remote == tt->local)
858  {
859  remote++;
860  }
861 
862  return remote;
863 }
864 #endif
865 
874 static void
875 do_ifconfig_ipv6(struct tuntap *tt, const char *ifname, int tun_mtu,
876  const struct env_set *es)
877 {
878  const char *ifconfig_ipv6_local = NULL;
879  struct argv argv = argv_new();
880  struct gc_arena gc = gc_new();
881 
882  ifconfig_ipv6_local = print_in6_addr(tt->local_ipv6, 0, &gc);
883 
884 #if defined(TARGET_LINUX)
885 #ifdef ENABLE_IPROUTE
886  /* set the MTU for the device and bring it up */
887  argv_printf(&argv, "%s link set dev %s up mtu %d", iproute_path, ifname,
888  tun_mtu);
889  argv_msg(M_INFO, &argv);
890  openvpn_execve_check(&argv, es, S_FATAL, "Linux ip link set failed");
891 
892  argv_printf(&argv, "%s -6 addr add %s/%d dev %s", iproute_path,
893  ifconfig_ipv6_local, tt->netbits_ipv6, ifname);
894  argv_msg(M_INFO, &argv);
895  openvpn_execve_check(&argv, es, S_FATAL, "Linux ip -6 addr add failed");
896 #else /* ifdef ENABLE_IPROUTE */
897  argv_printf(&argv, "%s %s add %s/%d mtu %d up", IFCONFIG_PATH, ifname,
898  ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
899  argv_msg(M_INFO, &argv);
900  openvpn_execve_check(&argv, es, S_FATAL, "Linux ifconfig inet6 failed");
901 #endif
902 #elif defined(TARGET_ANDROID)
903  char out6[64];
904 
905  openvpn_snprintf(out6, sizeof(out6), "%s/%d %d",
906  ifconfig_ipv6_local,tt->netbits_ipv6, tun_mtu);
907  management_android_control(management, "IFCONFIG6", out6);
908 #elif defined(TARGET_SOLARIS)
909  argv_printf(&argv, "%s %s inet6 unplumb", IFCONFIG_PATH, ifname);
910  argv_msg(M_INFO, &argv);
911  openvpn_execve_check(&argv, es, 0, NULL);
912 
913  if (tt->type == DEV_TYPE_TUN)
914  {
915  const char *ifconfig_ipv6_remote = print_in6_addr(tt->remote_ipv6, 0, &gc);
916 
917  argv_printf(&argv, "%s %s inet6 plumb %s/%d %s mtu %d up",
918  IFCONFIG_PATH, ifname, ifconfig_ipv6_local,
919  tt->netbits_ipv6, ifconfig_ipv6_remote, tun_mtu);
920  }
921  else /* tap mode */
922  {
923  /* base IPv6 tap interface needs to be brought up first */
924  argv_printf(&argv, "%s %s inet6 plumb up", IFCONFIG_PATH, ifname);
925  argv_msg(M_INFO, &argv);
926 
927  if (!openvpn_execve_check(&argv, es, 0,
928  "Solaris ifconfig IPv6 (prepare) failed"))
929  {
930  solaris_error_close(tt, es, ifname, true);
931  }
932 
933  /* we might need to do "ifconfig %s inet6 auto-dhcp drop"
934  * after the system has noticed the interface and fired up
935  * the DHCPv6 client - but this takes quite a while, and the
936  * server will ignore the DHCPv6 packets anyway. So we don't.
937  */
938 
939  /* static IPv6 addresses need to go to a subinterface (tap0:1) */
940  argv_printf(&argv, "%s %s inet6 addif %s/%d mtu %d up", IFCONFIG_PATH,
941  ifname, ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
942  }
943  argv_msg(M_INFO, &argv);
944 
945  if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig IPv6 failed"))
946  {
947  solaris_error_close(tt, es, ifname, true);
948  }
949 #elif defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) \
950  || defined(TARGET_DARWIN) || defined(TARGET_FREEBSD) \
951  || defined(TARGET_DRAGONFLY)
952  argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifname,
953  ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
954  argv_msg(M_INFO, &argv);
955 
956  openvpn_execve_check(&argv, es, S_FATAL,
957  "generic BSD ifconfig inet6 failed");
958 
959 #if defined(TARGET_OPENBSD) || defined(TARGET_NETBSD) \
960  || defined(TARGET_DARWIN)
961  /* and, hooray, we explicitly need to add a route... */
963 #endif
964 #elif defined(TARGET_AIX)
965  argv_printf(&argv, "%s %s inet6 %s/%d mtu %d up", IFCONFIG_PATH, ifname,
966  ifconfig_ipv6_local, tt->netbits_ipv6, tun_mtu);
967  argv_msg(M_INFO, &argv);
968 
969  /* AIX ifconfig will complain if it can't find ODM path in env */
970  es = env_set_create(NULL);
971  env_set_add(es, "ODMDIR=/etc/objrepos");
972 
973  openvpn_execve_check(&argv, es, S_FATAL,
974  "generic BSD ifconfig inet6 failed");
975 
976  env_set_destroy(es);
977 #elif defined (_WIN32)
979  {
980  msg(M_INFO, "******** NOTE: Please manually set the v6 IP of '%s' to %s (if it is not already set)",
981  ifname, ifconfig_ipv6_local);
982  }
983  else if (tt->options.msg_channel)
984  {
985  do_address_service(true, AF_INET6, tt);
986  do_dns6_service(true, tt);
987  }
988  else
989  {
990  /* example: netsh interface ipv6 set address interface=42
991  * 2001:608:8003::d store=active
992  */
993  char iface[64];
994 
995  openvpn_snprintf(iface, sizeof(iface), "interface=%lu",
996  tt->adapter_index);
997  argv_printf(&argv, "%s%sc interface ipv6 set address %s %s store=active",
999  ifconfig_ipv6_local);
1000  netsh_command(&argv, 4, M_FATAL);
1001  /* set ipv6 dns servers if any are specified */
1003  }
1004 
1005  /* explicit route needed */
1007  {
1009  }
1010 #else /* platforms we have no IPv6 code for */
1011  msg(M_FATAL, "Sorry, but I don't know how to do IPv6 'ifconfig' commands on this operating system. You should ifconfig your TUN/TAP device manually or use an --up script.");
1012 #endif /* outer "if defined(TARGET_xxx)" conditional */
1013 
1014  gc_free(&gc);
1015  argv_reset(&argv);
1016 }
1017 
1026 static void
1027 do_ifconfig_ipv4(struct tuntap *tt, const char *ifname, int tun_mtu,
1028  const struct env_set *es)
1029 {
1030  bool tun = false;
1031  const char *ifconfig_local = NULL;
1032  const char *ifconfig_remote_netmask = NULL;
1033  const char *ifconfig_broadcast = NULL;
1034  struct argv argv = argv_new();
1035  struct gc_arena gc = gc_new();
1036 
1037  /*
1038  * We only handle TUN/TAP devices here, not --dev null devices.
1039  */
1040  tun = is_tun_p2p(tt);
1041 
1042  /*
1043  * Set ifconfig parameters
1044  */
1045  ifconfig_local = print_in_addr_t(tt->local, 0, &gc);
1046  ifconfig_remote_netmask = print_in_addr_t(tt->remote_netmask, 0, &gc);
1047 
1048  /*
1049  * If TAP-style device, generate broadcast address.
1050  */
1051  if (!tun)
1052  {
1053  ifconfig_broadcast = print_in_addr_t(tt->broadcast, 0, &gc);
1054  }
1055 
1056 #if defined(TARGET_LINUX)
1057 #ifdef ENABLE_IPROUTE
1058  /*
1059  * Set the MTU for the device
1060  */
1061  argv_printf(&argv, "%s link set dev %s up mtu %d", iproute_path, ifname,
1062  tun_mtu);
1063  argv_msg(M_INFO, &argv);
1064  openvpn_execve_check(&argv, es, S_FATAL, "Linux ip link set failed");
1065 
1066  if (tun)
1067  {
1068 
1069  /*
1070  * Set the address for the device
1071  */
1072  argv_printf(&argv, "%s addr add dev %s local %s peer %s", iproute_path,
1073  ifname, ifconfig_local, ifconfig_remote_netmask);
1074  argv_msg(M_INFO, &argv);
1075  openvpn_execve_check(&argv, es, S_FATAL, "Linux ip addr add failed");
1076  }
1077  else
1078  {
1079  argv_printf(&argv, "%s addr add dev %s %s/%d broadcast %s",
1080  iproute_path, ifname, ifconfig_local,
1082  ifconfig_broadcast);
1083  argv_msg(M_INFO, &argv);
1084  openvpn_execve_check(&argv, es, S_FATAL, "Linux ip addr add failed");
1085  }
1086 #else /* ifdef ENABLE_IPROUTE */
1087  if (tun)
1088  {
1089  argv_printf(&argv, "%s %s %s pointopoint %s mtu %d", IFCONFIG_PATH,
1090  ifname, ifconfig_local, ifconfig_remote_netmask, tun_mtu);
1091  }
1092  else
1093  {
1094  argv_printf(&argv, "%s %s %s netmask %s mtu %d broadcast %s",
1095  IFCONFIG_PATH, ifname, ifconfig_local,
1096  ifconfig_remote_netmask, tun_mtu, ifconfig_broadcast);
1097  }
1098  argv_msg(M_INFO, &argv);
1099  openvpn_execve_check(&argv, es, S_FATAL, "Linux ifconfig failed");
1100 
1101 #endif /*ENABLE_IPROUTE*/
1102 #elif defined(TARGET_ANDROID)
1103  char out[64];
1104 
1105  char *top;
1106  switch (tt->topology)
1107  {
1108  case TOP_NET30:
1109  top = "net30";
1110  break;
1111 
1112  case TOP_P2P:
1113  top = "p2p";
1114  break;
1115 
1116  case TOP_SUBNET:
1117  top = "subnet";
1118  break;
1119 
1120  default:
1121  top = "undef";
1122  }
1123 
1124  openvpn_snprintf(out, sizeof(out), "%s %s %d %s", ifconfig_local,
1125  ifconfig_remote_netmask, tun_mtu, top);
1126  management_android_control(management, "IFCONFIG", out);
1127 
1128 #elif defined(TARGET_SOLARIS)
1129  /* Solaris 2.6 (and 7?) cannot set all parameters in one go...
1130  * example:
1131  * ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 up
1132  * ifconfig tun2 netmask 255.255.255.255
1133  */
1134  if (tun)
1135  {
1136  argv_printf(&argv, "%s %s %s %s mtu %d up", IFCONFIG_PATH, ifname,
1137  ifconfig_local, ifconfig_remote_netmask, tun_mtu);
1138 
1139  argv_msg(M_INFO, &argv);
1140  if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig phase-1 failed"))
1141  {
1142  solaris_error_close(tt, es, ifname, false);
1143  }
1144 
1145  argv_printf(&argv, "%s %s netmask 255.255.255.255", IFCONFIG_PATH,
1146  ifname);
1147  }
1148  else if (tt->topology == TOP_SUBNET)
1149  {
1150  argv_printf(&argv, "%s %s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
1151  ifname, ifconfig_local, ifconfig_local,
1152  ifconfig_remote_netmask, tun_mtu);
1153  }
1154  else
1155  {
1156  argv_printf(&argv, "%s %s %s netmask %s broadcast + up",
1157  IFCONFIG_PATH, ifname, ifconfig_local,
1158  ifconfig_remote_netmask);
1159  }
1160 
1161  argv_msg(M_INFO, &argv);
1162  if (!openvpn_execve_check(&argv, es, 0, "Solaris ifconfig phase-2 failed"))
1163  {
1164  solaris_error_close(tt, es, ifname, false);
1165  }
1166 
1167  if (!tun && tt->topology == TOP_SUBNET)
1168  {
1169  /* Add a network route for the local tun interface */
1170  struct route_ipv4 r;
1171  CLEAR(r);
1173  r.network = tt->local & tt->remote_netmask;
1174  r.netmask = tt->remote_netmask;
1175  r.gateway = tt->local;
1176  r.metric = 0;
1177  add_route(&r, tt, 0, NULL, es);
1178  }
1179 
1180 #elif defined(TARGET_OPENBSD)
1181 
1182  in_addr_t remote_end; /* for "virtual" subnet topology */
1183 
1184  /*
1185  * On OpenBSD, tun interfaces are persistent if created with
1186  * "ifconfig tunX create", and auto-destroyed if created by
1187  * opening "/dev/tunX" (so we just use the /dev/tunX)
1188  */
1189 
1190  /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
1191  if (tun)
1192  {
1193  argv_printf(&argv,
1194  "%s %s %s %s mtu %d netmask 255.255.255.255 up -link0",
1195  IFCONFIG_PATH, ifname, ifconfig_local,
1196  ifconfig_remote_netmask, tun_mtu);
1197  }
1198  else if (tt->topology == TOP_SUBNET)
1199  {
1200  remote_end = create_arbitrary_remote( tt );
1201  argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up -link0",
1202  IFCONFIG_PATH, ifname, ifconfig_local,
1203  print_in_addr_t(remote_end, 0, &gc), tun_mtu,
1204  ifconfig_remote_netmask);
1205  }
1206  else
1207  {
1208  argv_printf(&argv, "%s %s %s netmask %s mtu %d broadcast %s link0",
1209  IFCONFIG_PATH, ifname, ifconfig_local,
1210  ifconfig_remote_netmask, tun_mtu, ifconfig_broadcast);
1211  }
1212  argv_msg(M_INFO, &argv);
1213  openvpn_execve_check(&argv, es, S_FATAL, "OpenBSD ifconfig failed");
1214 
1215  /* Add a network route for the local tun interface */
1216  if (!tun && tt->topology == TOP_SUBNET)
1217  {
1218  struct route_ipv4 r;
1219  CLEAR(r);
1220  r.flags = RT_DEFINED;
1221  r.network = tt->local & tt->remote_netmask;
1222  r.netmask = tt->remote_netmask;
1223  r.gateway = remote_end;
1224  add_route(&r, tt, 0, NULL, es);
1225  }
1226 
1227 #elif defined(TARGET_NETBSD)
1228  in_addr_t remote_end; /* for "virtual" subnet topology */
1229 
1230  if (tun)
1231  {
1232  argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up",
1233  IFCONFIG_PATH, ifname, ifconfig_local,
1234  ifconfig_remote_netmask, tun_mtu);
1235  }
1236  else if (tt->topology == TOP_SUBNET)
1237  {
1238  remote_end = create_arbitrary_remote(tt);
1239  argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up", IFCONFIG_PATH,
1240  ifname, ifconfig_local, print_in_addr_t(remote_end, 0, &gc),
1241  tun_mtu, ifconfig_remote_netmask);
1242  }
1243  else
1244  {
1245  /*
1246  * NetBSD has distinct tun and tap devices
1247  * so we don't need the "link0" extra parameter to specify we want to do
1248  * tunneling at the ethernet level
1249  */
1250  argv_printf(&argv, "%s %s %s netmask %s mtu %d broadcast %s",
1251  IFCONFIG_PATH, ifname, ifconfig_local,
1252  ifconfig_remote_netmask, tun_mtu, ifconfig_broadcast);
1253  }
1254  argv_msg(M_INFO, &argv);
1255  openvpn_execve_check(&argv, es, S_FATAL, "NetBSD ifconfig failed");
1256 
1257  /* Add a network route for the local tun interface */
1258  if (!tun && tt->topology == TOP_SUBNET)
1259  {
1260  struct route_ipv4 r;
1261  CLEAR(r);
1262  r.flags = RT_DEFINED;
1263  r.network = tt->local & tt->remote_netmask;
1264  r.netmask = tt->remote_netmask;
1265  r.gateway = remote_end;
1266  add_route(&r, tt, 0, NULL, es);
1267  }
1268 
1269 #elif defined(TARGET_DARWIN)
1270  /*
1271  * Darwin (i.e. Mac OS X) seems to exhibit similar behaviour to OpenBSD...
1272  */
1273 
1274  argv_printf(&argv, "%s %s delete", IFCONFIG_PATH, ifname);
1275  argv_msg(M_INFO, &argv);
1276  openvpn_execve_check(&argv, es, 0, NULL);
1277  msg(M_INFO,
1278  "NOTE: Tried to delete pre-existing tun/tap instance -- No Problem if failure");
1279 
1280 
1281  /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
1282  if (tun)
1283  {
1284  argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up",
1285  IFCONFIG_PATH, ifname, ifconfig_local,
1286  ifconfig_remote_netmask, tun_mtu);
1287  }
1288  else
1289  {
1290  if (tt->topology == TOP_SUBNET)
1291  {
1292  argv_printf(&argv, "%s %s %s %s netmask %s mtu %d up",
1293  IFCONFIG_PATH, ifname, ifconfig_local, ifconfig_local,
1294  ifconfig_remote_netmask, tun_mtu);
1295  }
1296  else
1297  {
1298  argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
1299  ifname, ifconfig_local, ifconfig_remote_netmask,
1300  tun_mtu);
1301  }
1302  }
1303 
1304  argv_msg(M_INFO, &argv);
1305  openvpn_execve_check(&argv, es, S_FATAL, "Mac OS X ifconfig failed");
1306 
1307  /* Add a network route for the local tun interface */
1308  if (!tun && tt->topology == TOP_SUBNET)
1309  {
1310  struct route_ipv4 r;
1311  CLEAR(r);
1312  r.flags = RT_DEFINED;
1313  r.network = tt->local & tt->remote_netmask;
1314  r.netmask = tt->remote_netmask;
1315  r.gateway = tt->local;
1316  add_route(&r, tt, 0, NULL, es);
1317  }
1318 
1319 #elif defined(TARGET_FREEBSD) || defined(TARGET_DRAGONFLY)
1320 
1321  in_addr_t remote_end; /* for "virtual" subnet topology */
1322 
1323  /* example: ifconfig tun2 10.2.0.2 10.2.0.1 mtu 1450 netmask 255.255.255.255 up */
1324  if (tun)
1325  {
1326  argv_printf(&argv, "%s %s %s %s mtu %d netmask 255.255.255.255 up",
1327  IFCONFIG_PATH, ifname, ifconfig_local,
1328  ifconfig_remote_netmask, tun_mtu);
1329  }
1330  else if (tt->topology == TOP_SUBNET)
1331  {
1332  remote_end = create_arbitrary_remote( tt );
1333  argv_printf(&argv, "%s %s %s %s mtu %d netmask %s up", IFCONFIG_PATH,
1334  ifname, ifconfig_local, print_in_addr_t(remote_end, 0, &gc),
1335  tun_mtu, ifconfig_remote_netmask);
1336  }
1337  else
1338  {
1339  argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
1340  ifname, ifconfig_local, ifconfig_remote_netmask, tun_mtu);
1341  }
1342 
1343  argv_msg(M_INFO, &argv);
1344  openvpn_execve_check(&argv, es, S_FATAL, "FreeBSD ifconfig failed");
1345 
1346  /* Add a network route for the local tun interface */
1347  if (!tun && tt->topology == TOP_SUBNET)
1348  {
1349  struct route_ipv4 r;
1350  CLEAR(r);
1351  r.flags = RT_DEFINED;
1352  r.network = tt->local & tt->remote_netmask;
1353  r.netmask = tt->remote_netmask;
1354  r.gateway = remote_end;
1355  add_route(&r, tt, 0, NULL, es);
1356  }
1357 
1358 #elif defined(TARGET_AIX)
1359  {
1360  /* AIX ifconfig will complain if it can't find ODM path in env */
1361  struct env_set *aix_es = env_set_create(NULL);
1362  env_set_add( aix_es, "ODMDIR=/etc/objrepos" );
1363 
1364  if (tun)
1365  {
1366  msg(M_FATAL, "no tun support on AIX (canthappen)");
1367  }
1368 
1369  /* example: ifconfig tap0 172.30.1.1 netmask 255.255.254.0 up */
1370  argv_printf(&argv, "%s %s %s netmask %s mtu %d up", IFCONFIG_PATH,
1371  ifname, ifconfig_local, ifconfig_remote_netmask, tun_mtu);
1372 
1373  argv_msg(M_INFO, &argv);
1374  openvpn_execve_check(&argv, aix_es, S_FATAL, "AIX ifconfig failed");
1375 
1376  env_set_destroy(aix_es);
1377  }
1378 #elif defined (_WIN32)
1379  {
1380  ASSERT(ifname != NULL);
1381 
1382  switch (tt->options.ip_win32_type)
1383  {
1384  case IPW32_SET_MANUAL:
1385  msg(M_INFO,
1386  "******** NOTE: Please manually set the IP/netmask of '%s' to %s/%s (if it is not already set)",
1387  ifname, ifconfig_local,
1388  print_in_addr_t(tt->adapter_netmask, 0, &gc));
1389  break;
1390 
1391  case IPW32_SET_NETSH:
1392  netsh_ifconfig(&tt->options, ifname, tt->local,
1394 
1395  break;
1396  }
1397  }
1398 
1399 #else /* if defined(TARGET_LINUX) */
1400  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.");
1401 #endif /* if defined(TARGET_LINUX) */
1402 
1403  gc_free(&gc);
1404  argv_reset(&argv);
1405 }
1406 
1407 /* execute the ifconfig command through the shell */
1408 void
1409 do_ifconfig(struct tuntap *tt, const char *ifname, int tun_mtu,
1410  const struct env_set *es)
1411 {
1412  msg(D_LOW, "do_ifconfig, ipv4=%d, ipv6=%d", tt->did_ifconfig_setup,
1414 
1415 #ifdef ENABLE_MANAGEMENT
1416  if (management)
1417  {
1420  NULL,
1421  &tt->local,
1422  &tt->local_ipv6,
1423  NULL,
1424  NULL);
1425  }
1426 #endif
1427 
1428  if (tt->did_ifconfig_setup)
1429  {
1430  do_ifconfig_ipv4(tt, ifname, tun_mtu, es);
1431  }
1432 
1433  if (tt->did_ifconfig_ipv6_setup)
1434  {
1435  do_ifconfig_ipv6(tt, ifname, tun_mtu, es);
1436  }
1437 }
1438 
1439 static void
1440 clear_tuntap(struct tuntap *tuntap)
1441 {
1442  CLEAR(*tuntap);
1443 #ifdef _WIN32
1444  tuntap->hand = NULL;
1445 #else
1446  tuntap->fd = -1;
1447 #endif
1448 #ifdef TARGET_SOLARIS
1449  tuntap->ip_fd = -1;
1450 #endif
1451 }
1452 
1453 static void
1454 open_null(struct tuntap *tt)
1455 {
1456  tt->actual_name = string_alloc("null", NULL);
1457 }
1458 
1459 
1460 #if defined (TARGET_OPENBSD) || (defined(TARGET_DARWIN) && HAVE_NET_IF_UTUN_H)
1461 
1462 /*
1463  * OpenBSD and Mac OS X when using utun
1464  * have a slightly incompatible TUN device from
1465  * the rest of the world, in that it prepends a
1466  * uint32 to the beginning of the IP header
1467  * to designate the protocol (why not just
1468  * look at the version field in the IP header to
1469  * determine v4 or v6?).
1470  *
1471  * We strip off this field on reads and
1472  * put it back on writes.
1473  *
1474  * I have not tested TAP devices on OpenBSD,
1475  * but I have conditionalized the special
1476  * TUN handling code described above to
1477  * go away for TAP devices.
1478  */
1479 
1480 #include <netinet/ip.h>
1481 #include <sys/uio.h>
1482 
1483 static inline int
1484 header_modify_read_write_return(int len)
1485 {
1486  if (len > 0)
1487  {
1488  return len > sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
1489  }
1490  else
1491  {
1492  return len;
1493  }
1494 }
1495 
1496 int
1497 write_tun_header(struct tuntap *tt, uint8_t *buf, int len)
1498 {
1499  if (tt->type == DEV_TYPE_TUN)
1500  {
1501  u_int32_t type;
1502  struct iovec iv[2];
1503  struct openvpn_iphdr *iph;
1504 
1505  iph = (struct openvpn_iphdr *) buf;
1506 
1507  if (OPENVPN_IPH_GET_VER(iph->version_len) == 6)
1508  {
1509  type = htonl(AF_INET6);
1510  }
1511  else
1512  {
1513  type = htonl(AF_INET);
1514  }
1515 
1516  iv[0].iov_base = &type;
1517  iv[0].iov_len = sizeof(type);
1518  iv[1].iov_base = buf;
1519  iv[1].iov_len = len;
1520 
1521  return header_modify_read_write_return(writev(tt->fd, iv, 2));
1522  }
1523  else
1524  {
1525  return write(tt->fd, buf, len);
1526  }
1527 }
1528 
1529 int
1530 read_tun_header(struct tuntap *tt, uint8_t *buf, int len)
1531 {
1532  if (tt->type == DEV_TYPE_TUN)
1533  {
1534  u_int32_t type;
1535  struct iovec iv[2];
1536 
1537  iv[0].iov_base = &type;
1538  iv[0].iov_len = sizeof(type);
1539  iv[1].iov_base = buf;
1540  iv[1].iov_len = len;
1541 
1542  return header_modify_read_write_return(readv(tt->fd, iv, 2));
1543  }
1544  else
1545  {
1546  return read(tt->fd, buf, len);
1547  }
1548 }
1549 #endif /* if defined (TARGET_OPENBSD) || (defined(TARGET_DARWIN) && HAVE_NET_IF_UTUN_H) */
1550 
1551 
1552 #if !(defined(_WIN32) || defined(TARGET_LINUX))
1553 static void
1554 open_tun_generic(const char *dev, const char *dev_type, const char *dev_node,
1555  bool dynamic, struct tuntap *tt)
1556 {
1557  char tunname[256];
1558  char dynamic_name[256];
1559  bool dynamic_opened = false;
1560 
1561  if (tt->type == DEV_TYPE_NULL)
1562  {
1563  open_null(tt);
1564  }
1565  else
1566  {
1567  /*
1568  * --dev-node specified, so open an explicit device node
1569  */
1570  if (dev_node)
1571  {
1572  openvpn_snprintf(tunname, sizeof(tunname), "%s", dev_node);
1573  }
1574  else
1575  {
1576  /*
1577  * dynamic open is indicated by --dev specified without
1578  * explicit unit number. Try opening /dev/[dev]n
1579  * where n = [0, 255].
1580  */
1581 #ifdef TARGET_NETBSD
1582  /* on NetBSD, tap (but not tun) devices are opened by
1583  * opening /dev/tap and then querying the system about the
1584  * actual device name (tap0, tap1, ...) assigned
1585  */
1586  if (dynamic && strcmp( dev, "tap" ) == 0)
1587  {
1588  struct ifreq ifr;
1589  if ((tt->fd = open( "/dev/tap", O_RDWR)) < 0)
1590  {
1591  msg(M_FATAL, "Cannot allocate NetBSD TAP dev dynamically");
1592  }
1593  if (ioctl( tt->fd, TAPGIFNAME, (void *)&ifr ) < 0)
1594  {
1595  msg(M_FATAL, "Cannot query NetBSD TAP device name");
1596  }
1597  CLEAR(dynamic_name);
1598  strncpy( dynamic_name, ifr.ifr_name, sizeof(dynamic_name)-1 );
1599  dynamic_opened = true;
1600  openvpn_snprintf(tunname, sizeof(tunname), "/dev/%s", dynamic_name );
1601  }
1602  else
1603 #endif
1604 
1605  if (dynamic && !has_digit((unsigned char *)dev))
1606  {
1607  int i;
1608  for (i = 0; i < 256; ++i)
1609  {
1610  openvpn_snprintf(tunname, sizeof(tunname),
1611  "/dev/%s%d", dev, i);
1612  openvpn_snprintf(dynamic_name, sizeof(dynamic_name),
1613  "%s%d", dev, i);
1614  if ((tt->fd = open(tunname, O_RDWR)) > 0)
1615  {
1616  dynamic_opened = true;
1617  break;
1618  }
1619  msg(D_READ_WRITE | M_ERRNO, "Tried opening %s (failed)", tunname);
1620  }
1621  if (!dynamic_opened)
1622  {
1623  msg(M_FATAL, "Cannot allocate TUN/TAP dev dynamically");
1624  }
1625  }
1626  /*
1627  * explicit unit number specified
1628  */
1629  else
1630  {
1631  openvpn_snprintf(tunname, sizeof(tunname), "/dev/%s", dev);
1632  }
1633  }
1634 
1635  if (!dynamic_opened)
1636  {
1637  /* has named device existed before? if so, don't destroy at end */
1638  if (if_nametoindex( dev ) > 0)
1639  {
1640  msg(M_INFO, "TUN/TAP device %s exists previously, keep at program end", dev );
1641  tt->persistent_if = true;
1642  }
1643 
1644  if ((tt->fd = open(tunname, O_RDWR)) < 0)
1645  {
1646  msg(M_ERR, "Cannot open TUN/TAP dev %s", tunname);
1647  }
1648  }
1649 
1650  set_nonblock(tt->fd);
1651  set_cloexec(tt->fd); /* don't pass fd to scripts */
1652  msg(M_INFO, "TUN/TAP device %s opened", tunname);
1653 
1654  /* tt->actual_name is passed to up and down scripts and used as the ifconfig dev name */
1655  tt->actual_name = string_alloc(dynamic_opened ? dynamic_name : dev, NULL);
1656  }
1657 }
1658 #endif /* !_WIN32 && !TARGET_LINUX */
1659 
1660 #if !defined(_WIN32)
1661 static void
1662 close_tun_generic(struct tuntap *tt)
1663 {
1664  if (tt->fd >= 0)
1665  {
1666  close(tt->fd);
1667  }
1668  if (tt->actual_name)
1669  {
1670  free(tt->actual_name);
1671  }
1672  clear_tuntap(tt);
1673 }
1674 #endif /* !_WIN32 */
1675 
1676 #if defined (TARGET_ANDROID)
1677 void
1678 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
1679 {
1680 #define ANDROID_TUNNAME "vpnservice-tun"
1681  struct user_pass up;
1682  struct gc_arena gc = gc_new();
1683  bool opentun;
1684 
1685  int oldtunfd = tt->fd;
1686 
1687  /* Prefer IPv6 DNS servers,
1688  * Android will use the DNS server in the order we specify*/
1689  for (int i = 0; i < tt->options.dns6_len; i++)
1690  {
1691  management_android_control(management, "DNS6SERVER",
1692  print_in6_addr(tt->options.dns6[i], 0, &gc));
1693  }
1694 
1695  for (int i = 0; i < tt->options.dns_len; i++)
1696  {
1697  management_android_control(management, "DNSSERVER",
1698  print_in_addr_t(tt->options.dns[i], 0, &gc));
1699  }
1700 
1701  if (tt->options.domain)
1702  {
1703  management_android_control(management, "DNSDOMAIN", tt->options.domain);
1704  }
1705 
1706  int android_method = managment_android_persisttun_action(management);
1707 
1708  /* Android 4.4 workaround */
1709  if (oldtunfd >=0 && android_method == ANDROID_OPEN_AFTER_CLOSE)
1710  {
1711  close(oldtunfd);
1712  management_sleep(2);
1713  }
1714 
1715  if (oldtunfd >=0 && android_method == ANDROID_KEEP_OLD_TUN)
1716  {
1717  /* keep the old fd */
1718  opentun = true;
1719  }
1720  else
1721  {
1722  opentun = management_android_control(management, "OPENTUN", dev);
1723  /* Pick up the fd from management interface after calling the
1724  * OPENTUN command */
1725  tt->fd = management->connection.lastfdreceived;
1726  management->connection.lastfdreceived = -1;
1727  }
1728 
1729  if (oldtunfd>=0 && android_method == ANDROID_OPEN_BEFORE_CLOSE)
1730  {
1731  close(oldtunfd);
1732  }
1733 
1734  /* Set the actual name to a dummy name */
1735  tt->actual_name = string_alloc(ANDROID_TUNNAME, NULL);
1736 
1737  if ((tt->fd < 0) || !opentun)
1738  {
1739  msg(M_ERR, "ERROR: Cannot open TUN");
1740  }
1741 
1742  gc_free(&gc);
1743 }
1744 
1745 void
1746 close_tun(struct tuntap *tt)
1747 {
1748  ASSERT(tt);
1749 
1750  close_tun_generic(tt);
1751  free(tt);
1752 }
1753 
1754 int
1755 write_tun(struct tuntap *tt, uint8_t *buf, int len)
1756 {
1757  return write(tt->fd, buf, len);
1758 }
1759 
1760 int
1761 read_tun(struct tuntap *tt, uint8_t *buf, int len)
1762 {
1763  return read(tt->fd, buf, len);
1764 }
1765 
1766 #elif defined(TARGET_LINUX)
1767 
1768 #ifndef HAVE_LINUX_SOCKIOS_H
1769 #error header file linux/sockios.h required
1770 #endif
1771 
1772 #if !PEDANTIC
1773 
1774 void
1775 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
1776 {
1777  struct ifreq ifr;
1778 
1779  /*
1780  * We handle --dev null specially, we do not open /dev/null for this.
1781  */
1782  if (tt->type == DEV_TYPE_NULL)
1783  {
1784  open_null(tt);
1785  }
1786  else
1787  {
1788  /*
1789  * Process --dev-node
1790  */
1791  const char *node = dev_node;
1792  if (!node)
1793  {
1794  node = "/dev/net/tun";
1795  }
1796 
1797  /*
1798  * Open the interface
1799  */
1800  if ((tt->fd = open(node, O_RDWR)) < 0)
1801  {
1802  msg(M_ERR, "ERROR: Cannot open TUN/TAP dev %s", node);
1803  }
1804 
1805  /*
1806  * Process --tun-ipv6
1807  */
1808  CLEAR(ifr);
1809  ifr.ifr_flags = IFF_NO_PI;
1810 
1811 #if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN)
1812  ifr.ifr_flags |= IFF_ONE_QUEUE;
1813 #endif
1814 
1815  /*
1816  * Figure out if tun or tap device
1817  */
1818  if (tt->type == DEV_TYPE_TUN)
1819  {
1820  ifr.ifr_flags |= IFF_TUN;
1821  }
1822  else if (tt->type == DEV_TYPE_TAP)
1823  {
1824  ifr.ifr_flags |= IFF_TAP;
1825  }
1826  else
1827  {
1828  msg(M_FATAL, "I don't recognize device %s as a tun or tap device",
1829  dev);
1830  }
1831 
1832  /*
1833  * Set an explicit name, if --dev is not tun or tap
1834  */
1835  if (strcmp(dev, "tun") && strcmp(dev, "tap"))
1836  {
1837  strncpynt(ifr.ifr_name, dev, IFNAMSIZ);
1838  }
1839 
1840  /*
1841  * Use special ioctl that configures tun/tap device with the parms
1842  * we set in ifr
1843  */
1844  if (ioctl(tt->fd, TUNSETIFF, (void *) &ifr) < 0)
1845  {
1846  msg(M_ERR, "ERROR: Cannot ioctl TUNSETIFF %s", dev);
1847  }
1848 
1849  msg(M_INFO, "TUN/TAP device %s opened", ifr.ifr_name);
1850 
1851  /*
1852  * Try making the TX send queue bigger
1853  */
1854 #if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN)
1855  if (tt->options.txqueuelen)
1856  {
1857  struct ifreq netifr;
1858  int ctl_fd;
1859 
1860  if ((ctl_fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0)
1861  {
1862  CLEAR(netifr);
1863  strncpynt(netifr.ifr_name, ifr.ifr_name, IFNAMSIZ);
1864  netifr.ifr_qlen = tt->options.txqueuelen;
1865  if (ioctl(ctl_fd, SIOCSIFTXQLEN, (void *) &netifr) >= 0)
1866  {
1867  msg(D_OSBUF, "TUN/TAP TX queue length set to %d", tt->options.txqueuelen);
1868  }
1869  else
1870  {
1871  msg(M_WARN | M_ERRNO, "Note: Cannot set tx queue length on %s", ifr.ifr_name);
1872  }
1873  close(ctl_fd);
1874  }
1875  else
1876  {
1877  msg(M_WARN | M_ERRNO, "Note: Cannot open control socket on %s", ifr.ifr_name);
1878  }
1879  }
1880 #endif /* if defined(IFF_ONE_QUEUE) && defined(SIOCSIFTXQLEN) */
1881 
1882  set_nonblock(tt->fd);
1883  set_cloexec(tt->fd);
1884  tt->actual_name = string_alloc(ifr.ifr_name, NULL);
1885  }
1886  return;
1887 }
1888 
1889 #else /* if !PEDANTIC */
1890 
1891 void
1892 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
1893 {
1894  ASSERT(0);
1895 }
1896 
1897 #endif /* !PEDANTIC */
1898 
1899 #ifdef ENABLE_FEATURE_TUN_PERSIST
1900 
1901 void
1902 tuncfg(const char *dev, const char *dev_type, const char *dev_node, int persist_mode, const char *username, const char *groupname, const struct tuntap_options *options)
1903 {
1904  struct tuntap *tt;
1905 
1906  ALLOC_OBJ(tt, struct tuntap);
1907  clear_tuntap(tt);
1908  tt->type = dev_type_enum(dev, dev_type);
1909  tt->options = *options;
1910  open_tun(dev, dev_type, dev_node, tt);
1911  if (ioctl(tt->fd, TUNSETPERSIST, persist_mode) < 0)
1912  {
1913  msg(M_ERR, "Cannot ioctl TUNSETPERSIST(%d) %s", persist_mode, dev);
1914  }
1915  if (username != NULL)
1916  {
1917  struct platform_state_user platform_state_user;
1918 
1919  if (!platform_user_get(username, &platform_state_user))
1920  {
1921  msg(M_ERR, "Cannot get user entry for %s", username);
1922  }
1923  else if (ioctl(tt->fd, TUNSETOWNER, platform_state_user.pw->pw_uid) < 0)
1924  {
1925  msg(M_ERR, "Cannot ioctl TUNSETOWNER(%s) %s", username, dev);
1926  }
1927  }
1928  if (groupname != NULL)
1929  {
1930  struct platform_state_group platform_state_group;
1931 
1932  if (!platform_group_get(groupname, &platform_state_group))
1933  {
1934  msg(M_ERR, "Cannot get group entry for %s", groupname);
1935  }
1936  else if (ioctl(tt->fd, TUNSETGROUP, platform_state_group.gr->gr_gid) < 0)
1937  {
1938  msg(M_ERR, "Cannot ioctl TUNSETOWNER(%s) %s", groupname, dev);
1939  }
1940  }
1941  close_tun(tt);
1942  msg(M_INFO, "Persist state set to: %s", (persist_mode ? "ON" : "OFF"));
1943 }
1944 
1945 #endif /* ENABLE_FEATURE_TUN_PERSIST */
1946 
1947 void
1948 undo_ifconfig_ipv4(struct tuntap *tt, struct gc_arena *gc)
1949 {
1950  struct argv argv = argv_new();
1951 
1952 #ifdef ENABLE_IPROUTE
1953  if (is_tun_p2p(tt))
1954  {
1955  argv_printf(&argv, "%s addr del dev %s local %s peer %s", iproute_path,
1956  tt->actual_name, print_in_addr_t(tt->local, 0, gc),
1957  print_in_addr_t(tt->remote_netmask, 0, gc));
1958  }
1959  else
1960  {
1961  argv_printf(&argv, "%s addr del dev %s %s/%d", iproute_path,
1962  tt->actual_name, print_in_addr_t(tt->local, 0, gc),
1964  }
1965 #else /* ifdef ENABLE_IPROUTE */
1966  argv_printf(&argv, "%s %s 0.0.0.0", IFCONFIG_PATH, tt->actual_name);
1967 #endif /* ifdef ENABLE_IPROUTE */
1968 
1969  argv_msg(M_INFO, &argv);
1970  openvpn_execve_check(&argv, NULL, 0, "Linux ip addr del failed");
1971 
1972  argv_reset(&argv);
1973 }
1974 
1975 void
1976 undo_ifconfig_ipv6(struct tuntap *tt, struct gc_arena *gc)
1977 {
1978  const char *ifconfig_ipv6_local = print_in6_addr(tt->local_ipv6, 0, gc);
1979  struct argv argv = argv_new();
1980 
1981 #ifdef ENABLE_IPROUTE
1982  argv_printf(&argv, "%s -6 addr del %s/%d dev %s", iproute_path,
1983  ifconfig_ipv6_local, tt->netbits_ipv6, tt->actual_name);
1984 #else /* ifdef ENABLE_IPROUTE */
1985  argv_printf(&argv, "%s %s del %s/%d", IFCONFIG_PATH, tt->actual_name,
1986  ifconfig_ipv6_local, tt->netbits_ipv6);
1987 #endif
1988 
1989  argv_msg(M_INFO, &argv);
1990  openvpn_execve_check(&argv, NULL, 0, "Linux ip -6 addr del failed");
1991 
1992  argv_reset(&argv);
1993 }
1994 
1995 void
1996 close_tun(struct tuntap *tt)
1997 {
1998  ASSERT(tt);
1999 
2000  if (tt->type != DEV_TYPE_NULL)
2001  {
2002  struct gc_arena gc = gc_new();
2003 
2004  if (tt->did_ifconfig_setup)
2005  {
2006  undo_ifconfig_ipv4(tt, &gc);
2007  }
2008 
2009  if (tt->did_ifconfig_ipv6_setup)
2010  {
2011  undo_ifconfig_ipv6(tt, &gc);
2012  }
2013 
2014  gc_free(&gc);
2015  }
2016 
2017  close_tun_generic(tt);
2018  free(tt);
2019 }
2020 
2021 int
2022 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2023 {
2024  return write(tt->fd, buf, len);
2025 }
2026 
2027 int
2028 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2029 {
2030  return read(tt->fd, buf, len);
2031 }
2032 
2033 #elif defined(TARGET_SOLARIS)
2034 
2035 #ifndef TUNNEWPPA
2036 #error I need the symbol TUNNEWPPA from net/if_tun.h
2037 #endif
2038 
2039 void
2040 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2041 {
2042  int if_fd, ip_muxid, arp_muxid, arp_fd, ppa = -1;
2043  struct lifreq ifr;
2044  const char *ptr;
2045  const char *ip_node, *arp_node;
2046  const char *dev_tuntap_type;
2047  int link_type;
2048  bool is_tun;
2049  struct strioctl strioc_if, strioc_ppa;
2050 
2051  /* improved generic TUN/TAP driver from
2052  * http://www.whiteboard.ne.jp/~admin2/tuntap/
2053  * has IPv6 support
2054  */
2055  CLEAR(ifr);
2056 
2057  if (tt->type == DEV_TYPE_NULL)
2058  {
2059  open_null(tt);
2060  return;
2061  }
2062 
2063  if (tt->type == DEV_TYPE_TUN)
2064  {
2065  ip_node = "/dev/udp";
2066  if (!dev_node)
2067  {
2068  dev_node = "/dev/tun";
2069  }
2070  dev_tuntap_type = "tun";
2071  link_type = I_PLINK;
2072  is_tun = true;
2073  }
2074  else if (tt->type == DEV_TYPE_TAP)
2075  {
2076  ip_node = "/dev/udp";
2077  if (!dev_node)
2078  {
2079  dev_node = "/dev/tap";
2080  }
2081  arp_node = dev_node;
2082  dev_tuntap_type = "tap";
2083  link_type = I_PLINK; /* was: I_LINK */
2084  is_tun = false;
2085  }
2086  else
2087  {
2088  msg(M_FATAL, "I don't recognize device %s as a tun or tap device",
2089  dev);
2090  }
2091 
2092  if ((tt->ip_fd = open(ip_node, O_RDWR, 0)) < 0)
2093  {
2094  msg(M_ERR, "Can't open %s", ip_node);
2095  }
2096 
2097  if ((tt->fd = open(dev_node, O_RDWR, 0)) < 0)
2098  {
2099  msg(M_ERR, "Can't open %s", dev_node);
2100  }
2101 
2102  /* get unit number */
2103  if (*dev)
2104  {
2105  ptr = dev;
2106  while (*ptr && !isdigit((int) *ptr))
2107  {
2108  ptr++;
2109  }
2110  ppa = atoi(ptr);
2111  }
2112 
2113  /* Assign a new PPA and get its unit number. */
2114  strioc_ppa.ic_cmd = TUNNEWPPA;
2115  strioc_ppa.ic_timout = 0;
2116  strioc_ppa.ic_len = sizeof(ppa);
2117  strioc_ppa.ic_dp = (char *)&ppa;
2118 
2119  if (*ptr == '\0') /* no number given, try dynamic */
2120  {
2121  bool found_one = false;
2122  while (!found_one && ppa < 64)
2123  {
2124  int new_ppa = ioctl(tt->fd, I_STR, &strioc_ppa);
2125  if (new_ppa >= 0)
2126  {
2127  msg( M_INFO, "open_tun: got dynamic interface '%s%d'", dev_tuntap_type, new_ppa );
2128  ppa = new_ppa;
2129  found_one = true;
2130  break;
2131  }
2132  if (errno != EEXIST)
2133  {
2134  msg(M_ERR, "open_tun: unexpected error trying to find free %s interface", dev_tuntap_type );
2135  }
2136  ppa++;
2137  }
2138  if (!found_one)
2139  {
2140  msg(M_ERR, "open_tun: could not find free %s interface, give up.", dev_tuntap_type );
2141  }
2142  }
2143  else /* try this particular one */
2144  {
2145  if ((ppa = ioctl(tt->fd, I_STR, &strioc_ppa)) < 0)
2146  {
2147  msg(M_ERR, "Can't assign PPA for new interface (%s%d)", dev_tuntap_type, ppa );
2148  }
2149  }
2150 
2151  if ((if_fd = open(dev_node, O_RDWR, 0)) < 0)
2152  {
2153  msg(M_ERR, "Can't open %s (2)", dev_node);
2154  }
2155 
2156  if (ioctl(if_fd, I_PUSH, "ip") < 0)
2157  {
2158  msg(M_ERR, "Can't push IP module");
2159  }
2160 
2161  if (tt->type == DEV_TYPE_TUN)
2162  {
2163  /* Assign ppa according to the unit number returned by tun device */
2164  if (ioctl(if_fd, IF_UNITSEL, (char *) &ppa) < 0)
2165  {
2166  msg(M_ERR, "Can't set PPA %d", ppa);
2167  }
2168  }
2169 
2170  tt->actual_name = (char *) malloc(32);
2172 
2173  openvpn_snprintf(tt->actual_name, 32, "%s%d", dev_tuntap_type, ppa);
2174 
2175  if (tt->type == DEV_TYPE_TAP)
2176  {
2177  if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
2178  {
2179  msg(M_ERR, "Can't get flags\n");
2180  }
2181  strncpynt(ifr.lifr_name, tt->actual_name, sizeof(ifr.lifr_name));
2182  ifr.lifr_ppa = ppa;
2183  /* Assign ppa according to the unit number returned by tun device */
2184  if (ioctl(if_fd, SIOCSLIFNAME, &ifr) < 0)
2185  {
2186  msg(M_ERR, "Can't set PPA %d", ppa);
2187  }
2188  if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
2189  {
2190  msg(M_ERR, "Can't get flags\n");
2191  }
2192  /* Push arp module to if_fd */
2193  if (ioctl(if_fd, I_PUSH, "arp") < 0)
2194  {
2195  msg(M_ERR, "Can't push ARP module");
2196  }
2197 
2198  /* Pop any modules on the stream */
2199  while (true)
2200  {
2201  if (ioctl(tt->ip_fd, I_POP, NULL) < 0)
2202  {
2203  break;
2204  }
2205  }
2206  /* Push arp module to ip_fd */
2207  if (ioctl(tt->ip_fd, I_PUSH, "arp") < 0)
2208  {
2209  msg(M_ERR, "Can't push ARP module\n");
2210  }
2211 
2212  /* Open arp_fd */
2213  if ((arp_fd = open(arp_node, O_RDWR, 0)) < 0)
2214  {
2215  msg(M_ERR, "Can't open %s\n", arp_node);
2216  }
2217  /* Push arp module to arp_fd */
2218  if (ioctl(arp_fd, I_PUSH, "arp") < 0)
2219  {
2220  msg(M_ERR, "Can't push ARP module\n");
2221  }
2222 
2223  /* Set ifname to arp */
2224  strioc_if.ic_cmd = SIOCSLIFNAME;
2225  strioc_if.ic_timout = 0;
2226  strioc_if.ic_len = sizeof(ifr);
2227  strioc_if.ic_dp = (char *)&ifr;
2228  if (ioctl(arp_fd, I_STR, &strioc_if) < 0)
2229  {
2230  msg(M_ERR, "Can't set ifname to arp\n");
2231  }
2232  }
2233 
2234  if ((ip_muxid = ioctl(tt->ip_fd, link_type, if_fd)) < 0)
2235  {
2236  msg(M_ERR, "Can't link %s device to IP", dev_tuntap_type);
2237  }
2238 
2239  if (tt->type == DEV_TYPE_TAP)
2240  {
2241  if ((arp_muxid = ioctl(tt->ip_fd, link_type, arp_fd)) < 0)
2242  {
2243  msg(M_ERR, "Can't link %s device to ARP", dev_tuntap_type);
2244  }
2245  close(arp_fd);
2246  }
2247 
2248  CLEAR(ifr);
2249  strncpynt(ifr.lifr_name, tt->actual_name, sizeof(ifr.lifr_name));
2250  ifr.lifr_ip_muxid = ip_muxid;
2251  if (tt->type == DEV_TYPE_TAP)
2252  {
2253  ifr.lifr_arp_muxid = arp_muxid;
2254  }
2255 
2256  if (ioctl(tt->ip_fd, SIOCSLIFMUXID, &ifr) < 0)
2257  {
2258  if (tt->type == DEV_TYPE_TAP)
2259  {
2260  ioctl(tt->ip_fd, I_PUNLINK, arp_muxid);
2261  }
2262  ioctl(tt->ip_fd, I_PUNLINK, ip_muxid);
2263  msg(M_ERR, "Can't set multiplexor id");
2264  }
2265 
2266  set_nonblock(tt->fd);
2267  set_cloexec(tt->fd);
2268  set_cloexec(tt->ip_fd);
2269 
2270  msg(M_INFO, "TUN/TAP device %s opened", tt->actual_name);
2271 }
2272 
2273 static void
2274 solaris_close_tun(struct tuntap *tt)
2275 {
2276  /* IPv6 interfaces need to be 'manually' de-configured */
2277  if (tt->did_ifconfig_ipv6_setup)
2278  {
2279  struct argv argv = argv_new();
2280  argv_printf( &argv, "%s %s inet6 unplumb",
2281  IFCONFIG_PATH, tt->actual_name );
2282  argv_msg(M_INFO, &argv);
2283  openvpn_execve_check(&argv, NULL, 0, "Solaris ifconfig inet6 unplumb failed");
2284  argv_reset(&argv);
2285  }
2286 
2287  if (tt->ip_fd >= 0)
2288  {
2289  struct lifreq ifr;
2290  CLEAR(ifr);
2291  strncpynt(ifr.lifr_name, tt->actual_name, sizeof(ifr.lifr_name));
2292 
2293  if (ioctl(tt->ip_fd, SIOCGLIFFLAGS, &ifr) < 0)
2294  {
2295  msg(M_WARN | M_ERRNO, "Can't get iface flags");
2296  }
2297 
2298  if (ioctl(tt->ip_fd, SIOCGLIFMUXID, &ifr) < 0)
2299  {
2300  msg(M_WARN | M_ERRNO, "Can't get multiplexor id");
2301  }
2302 
2303  if (tt->type == DEV_TYPE_TAP)
2304  {
2305  if (ioctl(tt->ip_fd, I_PUNLINK, ifr.lifr_arp_muxid) < 0)
2306  {
2307  msg(M_WARN | M_ERRNO, "Can't unlink interface(arp)");
2308  }
2309  }
2310 
2311  if (ioctl(tt->ip_fd, I_PUNLINK, ifr.lifr_ip_muxid) < 0)
2312  {
2313  msg(M_WARN | M_ERRNO, "Can't unlink interface(ip)");
2314  }
2315 
2316  close(tt->ip_fd);
2317  tt->ip_fd = -1;
2318  }
2319 
2320  if (tt->fd >= 0)
2321  {
2322  close(tt->fd);
2323  tt->fd = -1;
2324  }
2325 }
2326 
2327 /*
2328  * Close TUN device.
2329  */
2330 void
2331 close_tun(struct tuntap *tt)
2332 {
2333  ASSERT(tt);
2334 
2335  solaris_close_tun(tt);
2336 
2337  if (tt->actual_name)
2338  {
2339  free(tt->actual_name);
2340  }
2341 
2342  clear_tuntap(tt);
2343  free(tt);
2344 }
2345 
2346 static void
2347 solaris_error_close(struct tuntap *tt, const struct env_set *es,
2348  const char *actual, bool unplumb_inet6 )
2349 {
2350  struct argv argv = argv_new();
2351 
2352  if (unplumb_inet6)
2353  {
2354  argv_printf( &argv, "%s %s inet6 unplumb",
2355  IFCONFIG_PATH, actual );
2356  argv_msg(M_INFO, &argv);
2357  openvpn_execve_check(&argv, es, 0, "Solaris ifconfig inet6 unplumb failed");
2358  }
2359 
2360  argv_printf(&argv,
2361  "%s %s unplumb",
2362  IFCONFIG_PATH,
2363  actual);
2364 
2365  argv_msg(M_INFO, &argv);
2366  openvpn_execve_check(&argv, es, 0, "Solaris ifconfig unplumb failed");
2367  close_tun(tt);
2368  msg(M_FATAL, "Solaris ifconfig failed");
2369  argv_reset(&argv);
2370 }
2371 
2372 int
2373 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2374 {
2375  struct strbuf sbuf;
2376  sbuf.len = len;
2377  sbuf.buf = (char *)buf;
2378  return putmsg(tt->fd, NULL, &sbuf, 0) >= 0 ? sbuf.len : -1;
2379 }
2380 
2381 int
2382 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2383 {
2384  struct strbuf sbuf;
2385  int f = 0;
2386 
2387  sbuf.maxlen = len;
2388  sbuf.buf = (char *)buf;
2389  return getmsg(tt->fd, NULL, &sbuf, &f) >= 0 ? sbuf.len : -1;
2390 }
2391 
2392 #elif defined(TARGET_OPENBSD)
2393 
2394 void
2395 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2396 {
2397  open_tun_generic(dev, dev_type, dev_node, true, tt);
2398 
2399  /* Enable multicast on the interface */
2400  if (tt->fd >= 0)
2401  {
2402  struct tuninfo info;
2403 
2404  if (ioctl(tt->fd, TUNGIFINFO, &info) < 0)
2405  {
2406  msg(M_WARN | M_ERRNO, "Can't get interface info");
2407  }
2408 
2409 #ifdef IFF_MULTICAST /* openbsd 4.x doesn't have this */
2410  info.flags |= IFF_MULTICAST;
2411 #endif
2412 
2413  if (ioctl(tt->fd, TUNSIFINFO, &info) < 0)
2414  {
2415  msg(M_WARN | M_ERRNO, "Can't set interface info");
2416  }
2417  }
2418 }
2419 
2420 /* tun(4): "If the device was created by opening /dev/tunN, it will be
2421  * automatically destroyed. Devices created via ifconfig(8) are
2422  * only marked as not running and traffic will be dropped
2423  * returning EHOSTDOWN."
2424  * --> no special handling should be needed - *but* OpenBSD is misbehaving
2425  * here: if the interface was put in tap mode ("ifconfig tunN link0"), it
2426  * *will* stay around, and needs to be cleaned up manually
2427  */
2428 
2429 void
2430 close_tun(struct tuntap *tt)
2431 {
2432  ASSERT(tt);
2433 
2434  /* only *TAP* devices need destroying, tun devices auto-self-destruct
2435  */
2436  if (tt->type == DEV_TYPE_TUN || tt->persistent_if)
2437  {
2438  close_tun_generic(tt);
2439  free(tt);
2440  return;
2441  }
2442 
2443  struct argv argv = argv_new();
2444 
2445  /* setup command, close tun dev (clears tt->actual_name!), run command
2446  */
2447 
2448  argv_printf(&argv, "%s %s destroy",
2449  IFCONFIG_PATH, tt->actual_name);
2450 
2451  close_tun_generic(tt);
2452 
2453  argv_msg(M_INFO, &argv);
2454  openvpn_execve_check(&argv, NULL, 0, "OpenBSD 'destroy tun interface' failed (non-critical)");
2455 
2456  free(tt);
2457  argv_reset(&argv);
2458 }
2459 
2460 int
2461 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2462 {
2463  return write_tun_header(tt, buf, len);
2464 }
2465 
2466 int
2467 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2468 {
2469  return read_tun_header(tt, buf, len);
2470 }
2471 
2472 #elif defined(TARGET_NETBSD)
2473 
2474 /*
2475  * NetBSD before 4.0 does not support IPv6 on tun out of the box,
2476  * but there exists a patch (sys/net/if_tun.c, 1.79->1.80, see PR 32944).
2477  *
2478  * NetBSD 4.0 and up do, but we need to put the tun interface into
2479  * "multi_af" mode, which will prepend the address family to all packets
2480  * (same as OpenBSD and FreeBSD). If this is not enabled, the kernel
2481  * silently drops all IPv6 packets on output and gets confused on input.
2482  *
2483  * On earlier versions, multi_af is not available at all, so we have
2484  * two different NetBSD code variants here :-(
2485  *
2486  */
2487 
2488 void
2489 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2490 {
2491  open_tun_generic(dev, dev_type, dev_node, true, tt);
2492 
2493  if (tt->fd >= 0)
2494  {
2495  int i = IFF_POINTOPOINT|IFF_MULTICAST;
2496  ioctl(tt->fd, TUNSIFMODE, &i); /* multicast on */
2497  i = 0;
2498  ioctl(tt->fd, TUNSLMODE, &i); /* link layer mode off */
2499 
2500  if (tt->type == DEV_TYPE_TUN)
2501  {
2502  i = 1;
2503  if (ioctl(tt->fd, TUNSIFHEAD, &i) < 0) /* multi-af mode on */
2504  {
2505  msg(M_WARN | M_ERRNO, "ioctl(TUNSIFHEAD)");
2506  }
2507  }
2508  }
2509 }
2510 
2511 /* the current way OpenVPN handles tun devices on NetBSD leads to
2512  * lingering tunX interfaces after close -> for a full cleanup, they
2513  * need to be explicitly destroyed
2514  */
2515 void
2516 close_tun(struct tuntap *tt)
2517 {
2518  ASSERT(tt);
2519 
2520  /* only tun devices need destroying, tap devices auto-self-destruct
2521  */
2522  if (tt->type != DEV_TYPE_TUN || tt->persistent_if)
2523  {
2524  close_tun_generic(tt);
2525  free(tt);
2526  return;
2527  }
2528 
2529  struct argv argv = argv_new();
2530 
2531  /* setup command, close tun dev (clears tt->actual_name!), run command
2532  */
2533 
2534  argv_printf(&argv, "%s %s destroy",
2535  IFCONFIG_PATH, tt->actual_name);
2536 
2537  close_tun_generic(tt);
2538 
2539  argv_msg(M_INFO, &argv);
2540  openvpn_execve_check(&argv, NULL, 0, "NetBSD 'destroy tun interface' failed (non-critical)");
2541 
2542  free(tt);
2543  argv_reset(&argv);
2544 }
2545 
2546 static inline int
2547 netbsd_modify_read_write_return(int len)
2548 {
2549  if (len > 0)
2550  {
2551  return len > sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
2552  }
2553  else
2554  {
2555  return len;
2556  }
2557 }
2558 
2559 int
2560 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2561 {
2562  if (tt->type == DEV_TYPE_TUN)
2563  {
2564  u_int32_t type;
2565  struct iovec iv[2];
2566  struct openvpn_iphdr *iph;
2567 
2568  iph = (struct openvpn_iphdr *) buf;
2569 
2570  if (OPENVPN_IPH_GET_VER(iph->version_len) == 6)
2571  {
2572  type = htonl(AF_INET6);
2573  }
2574  else
2575  {
2576  type = htonl(AF_INET);
2577  }
2578 
2579  iv[0].iov_base = (char *)&type;
2580  iv[0].iov_len = sizeof(type);
2581  iv[1].iov_base = buf;
2582  iv[1].iov_len = len;
2583 
2584  return netbsd_modify_read_write_return(writev(tt->fd, iv, 2));
2585  }
2586  else
2587  {
2588  return write(tt->fd, buf, len);
2589  }
2590 }
2591 
2592 int
2593 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2594 {
2595  if (tt->type == DEV_TYPE_TUN)
2596  {
2597  u_int32_t type;
2598  struct iovec iv[2];
2599 
2600  iv[0].iov_base = (char *)&type;
2601  iv[0].iov_len = sizeof(type);
2602  iv[1].iov_base = buf;
2603  iv[1].iov_len = len;
2604 
2605  return netbsd_modify_read_write_return(readv(tt->fd, iv, 2));
2606  }
2607  else
2608  {
2609  return read(tt->fd, buf, len);
2610  }
2611 }
2612 
2613 #elif defined(TARGET_FREEBSD)
2614 
2615 static inline int
2616 freebsd_modify_read_write_return(int len)
2617 {
2618  if (len > 0)
2619  {
2620  return len > sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
2621  }
2622  else
2623  {
2624  return len;
2625  }
2626 }
2627 
2628 void
2629 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2630 {
2631  open_tun_generic(dev, dev_type, dev_node, true, tt);
2632 
2633  if (tt->fd >= 0 && tt->type == DEV_TYPE_TUN)
2634  {
2635  int i = IFF_POINTOPOINT | IFF_MULTICAST;
2636 
2637  if (ioctl(tt->fd, TUNSIFMODE, &i) < 0)
2638  {
2639  msg(M_WARN | M_ERRNO, "ioctl(TUNSIFMODE)");
2640  }
2641  i = 1;
2642  if (ioctl(tt->fd, TUNSIFHEAD, &i) < 0)
2643  {
2644  msg(M_WARN | M_ERRNO, "ioctl(TUNSIFHEAD)");
2645  }
2646  }
2647 }
2648 
2649 /* tun(4): "These network interfaces persist until the if_tun.ko module is
2650  * unloaded, or until removed with the ifconfig(8) command."
2651  * (verified for FreeBSD 6.3, 7.4, 8.2 and 9, same for tap(4))
2652  *
2653  * so, to avoid lingering tun/tap interfaces after OpenVPN quits,
2654  * we need to call "ifconfig ... destroy" for cleanup
2655  */
2656 void
2657 close_tun(struct tuntap *tt)
2658 {
2659  ASSERT(tt);
2660 
2661  if (tt->persistent_if) /* keep pre-existing if around */
2662  {
2663  close_tun_generic(tt);
2664  free(tt);
2665  return;
2666  }
2667 
2668  /* close and destroy */
2669  struct argv argv = argv_new();
2670 
2671  /* setup command, close tun dev (clears tt->actual_name!), run command
2672  */
2673 
2674  argv_printf(&argv, "%s %s destroy",
2675  IFCONFIG_PATH, tt->actual_name);
2676 
2677  close_tun_generic(tt);
2678 
2679  argv_msg(M_INFO, &argv);
2680  openvpn_execve_check(&argv, NULL, 0,
2681  "FreeBSD 'destroy tun interface' failed (non-critical)");
2682 
2683  free(tt);
2684  argv_reset(&argv);
2685 }
2686 
2687 int
2688 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2689 {
2690  if (tt->type == DEV_TYPE_TUN)
2691  {
2692  u_int32_t type;
2693  struct iovec iv[2];
2694  struct ip *iph;
2695 
2696  iph = (struct ip *) buf;
2697 
2698  if (iph->ip_v == 6)
2699  {
2700  type = htonl(AF_INET6);
2701  }
2702  else
2703  {
2704  type = htonl(AF_INET);
2705  }
2706 
2707  iv[0].iov_base = (char *)&type;
2708  iv[0].iov_len = sizeof(type);
2709  iv[1].iov_base = buf;
2710  iv[1].iov_len = len;
2711 
2712  return freebsd_modify_read_write_return(writev(tt->fd, iv, 2));
2713  }
2714  else
2715  {
2716  return write(tt->fd, buf, len);
2717  }
2718 }
2719 
2720 int
2721 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2722 {
2723  if (tt->type == DEV_TYPE_TUN)
2724  {
2725  u_int32_t type;
2726  struct iovec iv[2];
2727 
2728  iv[0].iov_base = (char *)&type;
2729  iv[0].iov_len = sizeof(type);
2730  iv[1].iov_base = buf;
2731  iv[1].iov_len = len;
2732 
2733  return freebsd_modify_read_write_return(readv(tt->fd, iv, 2));
2734  }
2735  else
2736  {
2737  return read(tt->fd, buf, len);
2738  }
2739 }
2740 
2741 #elif defined(TARGET_DRAGONFLY)
2742 
2743 static inline int
2744 dragonfly_modify_read_write_return(int len)
2745 {
2746  if (len > 0)
2747  {
2748  return len > sizeof(u_int32_t) ? len - sizeof(u_int32_t) : 0;
2749  }
2750  else
2751  {
2752  return len;
2753  }
2754 }
2755 
2756 void
2757 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2758 {
2759  open_tun_generic(dev, dev_type, dev_node, true, tt);
2760 
2761  if (tt->fd >= 0)
2762  {
2763  int i = 0;
2764 
2765  /* Disable extended modes */
2766  ioctl(tt->fd, TUNSLMODE, &i);
2767  i = 1;
2768  ioctl(tt->fd, TUNSIFHEAD, &i);
2769  }
2770 }
2771 
2772 void
2773 close_tun(struct tuntap *tt)
2774 {
2775  ASSERT(tt);
2776 
2777  close_tun_generic(tt);
2778  free(tt);
2779 }
2780 
2781 int
2782 write_tun(struct tuntap *tt, uint8_t *buf, int len)
2783 {
2784  if (tt->type == DEV_TYPE_TUN)
2785  {
2786  u_int32_t type;
2787  struct iovec iv[2];
2788  struct ip *iph;
2789 
2790  iph = (struct ip *) buf;
2791 
2792  if (iph->ip_v == 6)
2793  {
2794  type = htonl(AF_INET6);
2795  }
2796  else
2797  {
2798  type = htonl(AF_INET);
2799  }
2800 
2801  iv[0].iov_base = (char *)&type;
2802  iv[0].iov_len = sizeof(type);
2803  iv[1].iov_base = buf;
2804  iv[1].iov_len = len;
2805 
2806  return dragonfly_modify_read_write_return(writev(tt->fd, iv, 2));
2807  }
2808  else
2809  {
2810  return write(tt->fd, buf, len);
2811  }
2812 }
2813 
2814 int
2815 read_tun(struct tuntap *tt, uint8_t *buf, int len)
2816 {
2817  if (tt->type == DEV_TYPE_TUN)
2818  {
2819  u_int32_t type;
2820  struct iovec iv[2];
2821 
2822  iv[0].iov_base = (char *)&type;
2823  iv[0].iov_len = sizeof(type);
2824  iv[1].iov_base = buf;
2825  iv[1].iov_len = len;
2826 
2827  return dragonfly_modify_read_write_return(readv(tt->fd, iv, 2));
2828  }
2829  else
2830  {
2831  return read(tt->fd, buf, len);
2832  }
2833 }
2834 
2835 #elif defined(TARGET_DARWIN)
2836 
2837 /* Darwin (MacOS X) is mostly "just use the generic stuff", but there
2838  * is always one caveat...:
2839  *
2840  * If IPv6 is configured, and the tun device is closed, the IPv6 address
2841  * configured to the tun interface changes to a lingering /128 route
2842  * pointing to lo0. Need to unconfigure... (observed on 10.5)
2843  */
2844 
2845 /*
2846  * utun is the native Darwin tun driver present since at least 10.7
2847  * Thanks goes to Jonathan Levin for providing an example how to utun
2848  * (http://newosxbook.com/src.jl?tree=listings&file=17-15-utun.c)
2849  */
2850 
2851 #ifdef HAVE_NET_IF_UTUN_H
2852 
2853 /* Helper functions that tries to open utun device
2854  * return -2 on early initialization failures (utun not supported
2855  * at all (old OS X) and -1 on initlization failure of utun
2856  * device (utun works but utunX is already used */
2857 static
2858 int
2859 utun_open_helper(struct ctl_info ctlInfo, int utunnum)
2860 {
2861  struct sockaddr_ctl sc;
2862  int fd;
2863 
2864  fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
2865 
2866  if (fd < 0)
2867  {
2868  msg(M_INFO | M_ERRNO, "Opening utun (socket(SYSPROTO_CONTROL))");
2869  return -2;
2870  }
2871 
2872  if (ioctl(fd, CTLIOCGINFO, &ctlInfo) == -1)
2873  {
2874  close(fd);
2875  msg(M_INFO | M_ERRNO, "Opening utun (ioctl(CTLIOCGINFO))");
2876  return -2;
2877  }
2878 
2879 
2880  sc.sc_id = ctlInfo.ctl_id;
2881  sc.sc_len = sizeof(sc);
2882  sc.sc_family = AF_SYSTEM;
2883  sc.ss_sysaddr = AF_SYS_CONTROL;
2884 
2885  sc.sc_unit = utunnum+1;
2886 
2887 
2888  /* If the connect is successful, a utun%d device will be created, where "%d"
2889  * is (sc.sc_unit - 1) */
2890 
2891  if (connect(fd, (struct sockaddr *)&sc, sizeof(sc)) < 0)
2892  {
2893  msg(M_INFO | M_ERRNO, "Opening utun (connect(AF_SYS_CONTROL))");
2894  close(fd);
2895  return -1;
2896  }
2897 
2898  set_nonblock(fd);
2899  set_cloexec(fd); /* don't pass fd to scripts */
2900 
2901  return fd;
2902 }
2903 
2904 void
2905 open_darwin_utun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2906 {
2907  struct ctl_info ctlInfo;
2908  int fd;
2909  char utunname[20];
2910  int utunnum = -1;
2911  socklen_t utunname_len = sizeof(utunname);
2912 
2913  /* dev_node is simply utun, do the normal dynamic utun
2914  * otherwise try to parse the utun number */
2915  if (dev_node && (strcmp("utun", dev_node) != 0 ))
2916  {
2917  if (sscanf(dev_node, "utun%d", &utunnum) != 1)
2918  {
2919  msg(M_FATAL, "Cannot parse 'dev-node %s' please use 'dev-node utunX'"
2920  "to use a utun device number X", dev_node);
2921  }
2922  }
2923 
2924 
2925 
2926  CLEAR(ctlInfo);
2927  if (strlcpy(ctlInfo.ctl_name, UTUN_CONTROL_NAME, sizeof(ctlInfo.ctl_name)) >=
2928  sizeof(ctlInfo.ctl_name))
2929  {
2930  msg(M_ERR, "Opening utun: UTUN_CONTROL_NAME too long");
2931  }
2932 
2933  /* try to open first available utun device if no specific utun is requested */
2934  if (utunnum == -1)
2935  {
2936  for (utunnum = 0; utunnum<255; utunnum++)
2937  {
2938  fd = utun_open_helper(ctlInfo, utunnum);
2939  /* Break if the fd is valid,
2940  * or if early initialization failed (-2) */
2941  if (fd !=-1)
2942  {
2943  break;
2944  }
2945  }
2946  }
2947  else
2948  {
2949  fd = utun_open_helper(ctlInfo, utunnum);
2950  }
2951 
2952  /* opening an utun device failed */
2953  tt->fd = fd;
2954 
2955  if (fd < 0)
2956  {
2957  return;
2958  }
2959 
2960  /* Retrieve the assigned interface name. */
2961  if (getsockopt(fd, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, utunname, &utunname_len))
2962  {
2963  msg(M_ERR | M_ERRNO, "Error retrieving utun interface name");
2964  }
2965 
2966  tt->actual_name = string_alloc(utunname, NULL);
2967 
2968  msg(M_INFO, "Opened utun device %s", utunname);
2969  tt->is_utun = true;
2970 }
2971 
2972 #endif /* ifdef HAVE_NET_IF_UTUN_H */
2973 
2974 void
2975 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
2976 {
2977 #ifdef HAVE_NET_IF_UTUN_H
2978  /* If dev_node does not start start with utun assume regular tun/tap */
2979  if ((!dev_node && tt->type==DEV_TYPE_TUN)
2980  || (dev_node && !strncmp(dev_node, "utun", 4)))
2981  {
2982 
2983  /* Check if user has specific dev_type tap and forced utun with
2984  * dev-node utun */
2985  if (tt->type!=DEV_TYPE_TUN)
2986  {
2987  msg(M_FATAL, "Cannot use utun devices with --dev-type %s",
2988  dev_type_string(dev, dev_type));
2989  }
2990 
2991  /* Try utun first and fall back to normal tun if utun fails
2992  * and dev_node is not specified */
2993  open_darwin_utun(dev, dev_type, dev_node, tt);
2994 
2995  if (!tt->is_utun)
2996  {
2997  if (!dev_node)
2998  {
2999  /* No explicit utun and utun failed, try the generic way) */
3000  msg(M_INFO, "Failed to open utun device. Falling back to /dev/tun device");
3001  open_tun_generic(dev, dev_type, NULL, true, tt);
3002  }
3003  else
3004  {
3005  /* Specific utun device or generic utun request with no tun
3006  * fall back failed, consider this a fatal failure */
3007  msg(M_FATAL, "Cannot open utun device");
3008  }
3009  }
3010  }
3011  else
3012 #endif /* ifdef HAVE_NET_IF_UTUN_H */
3013  {
3014 
3015  /* Use plain dev-node tun to select /dev/tun style
3016  * Unset dev_node variable prior to passing to open_tun_generic to
3017  * let open_tun_generic pick the first available tun device */
3018 
3019  if (dev_node && strcmp(dev_node, "tun")==0)
3020  {
3021  dev_node = NULL;
3022  }
3023 
3024  open_tun_generic(dev, dev_type, dev_node, true, tt);
3025  }
3026 }
3027 
3028 void
3029 close_tun(struct tuntap *tt)
3030 {
3031  ASSERT(tt);
3032 
3033  struct gc_arena gc = gc_new();
3034  struct argv argv = argv_new();
3035 
3036  if (tt->did_ifconfig_ipv6_setup)
3037  {
3038  const char *ifconfig_ipv6_local =
3039  print_in6_addr(tt->local_ipv6, 0, &gc);
3040 
3041  argv_printf(&argv, "%s delete -inet6 %s",
3042  ROUTE_PATH, ifconfig_ipv6_local );
3043  argv_msg(M_INFO, &argv);
3044  openvpn_execve_check(&argv, NULL, 0, "MacOS X 'remove inet6 route' failed (non-critical)");
3045  }
3046 
3047  close_tun_generic(tt);
3048  free(tt);
3049  argv_reset(&argv);
3050  gc_free(&gc);
3051 }
3052 
3053 int
3054 write_tun(struct tuntap *tt, uint8_t *buf, int len)
3055 {
3056 #ifdef HAVE_NET_IF_UTUN_H
3057  if (tt->is_utun)
3058  {
3059  return write_tun_header(tt, buf, len);
3060  }
3061  else
3062 #endif
3063  return write(tt->fd, buf, len);
3064 }
3065 
3066 int
3067 read_tun(struct tuntap *tt, uint8_t *buf, int len)
3068 {
3069 #ifdef HAVE_NET_IF_UTUN_H
3070  if (tt->is_utun)
3071  {
3072  return read_tun_header(tt, buf, len);
3073  }
3074  else
3075 #endif
3076  return read(tt->fd, buf, len);
3077 }
3078 
3079 #elif defined(TARGET_AIX)
3080 
3081 void
3082 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
3083 {
3084  char tunname[256];
3085  char dynamic_name[20];
3086  const char *p;
3087 
3088  if (tt->type == DEV_TYPE_NULL)
3089  {
3090  open_null(tt);
3091  return;
3092  }
3093 
3094  if (tt->type == DEV_TYPE_TUN)
3095  {
3096  msg(M_FATAL, "no support for 'tun' devices on AIX" );
3097  }
3098 
3099  if (strncmp( dev, "tap", 3 ) != 0 || dev_node)
3100  {
3101  msg(M_FATAL, "'--dev %s' and/or '--dev-node' not supported on AIX, use '--dev tap0', 'tap1', etc.", dev );
3102  }
3103 
3104  if (strcmp( dev, "tap" ) == 0) /* find first free tap dev */
3105  { /* (= no /dev/tapN node) */
3106  int i;
3107  for (i = 0; i<99; i++)
3108  {
3109  openvpn_snprintf(tunname, sizeof(tunname), "/dev/tap%d", i);
3110  if (access( tunname, F_OK ) < 0 && errno == ENOENT)
3111  {
3112  break;
3113  }
3114  }
3115  if (i >= 99)
3116  {
3117  msg( M_FATAL, "cannot find unused tap device" );
3118  }
3119 
3120  openvpn_snprintf( dynamic_name, sizeof(dynamic_name), "tap%d", i );
3121  dev = dynamic_name;
3122  }
3123  else /* name given, sanity check */
3124  {
3125  /* ensure that dev name is "tap+<digits>" *only* */
3126  p = &dev[3];
3127  while (isdigit(*p) )
3128  {
3129  p++;
3130  }
3131  if (*p != '\0')
3132  {
3133  msg( M_FATAL, "TAP device name must be '--dev tapNNNN'" );
3134  }
3135 
3136  openvpn_snprintf(tunname, sizeof(tunname), "/dev/%s", dev);
3137  }
3138 
3139  /* pre-existing device?
3140  */
3141  if (access( tunname, F_OK ) < 0 && errno == ENOENT)
3142  {
3143 
3144  /* tunnel device must be created with 'ifconfig tapN create'
3145  */
3146  struct argv argv = argv_new();
3147  struct env_set *es = env_set_create(NULL);
3148  argv_printf(&argv, "%s %s create", IFCONFIG_PATH, dev);
3149  argv_msg(M_INFO, &argv);
3150  env_set_add( es, "ODMDIR=/etc/objrepos" );
3151  openvpn_execve_check(&argv, es, S_FATAL, "AIX 'create tun interface' failed");
3152  env_set_destroy(es);
3153  argv_reset(&argv);
3154  }
3155  else
3156  {
3157  /* we didn't make it, we're not going to break it */
3158  tt->persistent_if = TRUE;
3159  }
3160 
3161  if ((tt->fd = open(tunname, O_RDWR)) < 0)
3162  {
3163  msg(M_ERR, "Cannot open TAP device '%s'", tunname);
3164  }
3165 
3166  set_nonblock(tt->fd);
3167  set_cloexec(tt->fd); /* don't pass fd to scripts */
3168  msg(M_INFO, "TUN/TAP device %s opened", tunname);
3169 
3170  /* tt->actual_name is passed to up and down scripts and used as the ifconfig dev name */
3171  tt->actual_name = string_alloc(dev, NULL);
3172 }
3173 
3174 /* tap devices need to be manually destroyed on AIX
3175  */
3176 void
3177 close_tun(struct tuntap *tt)
3178 {
3179  ASSERT(tt);
3180 
3181  struct argv argv = argv_new();
3182  struct env_set *es = env_set_create(NULL);
3183 
3184  /* persistent devices need IP address unconfig, others need destroyal
3185  */
3186  if (tt->persistent_if)
3187  {
3188  argv_printf(&argv, "%s %s 0.0.0.0 down",
3189  IFCONFIG_PATH, tt->actual_name);
3190  }
3191  else
3192  {
3193  argv_printf(&argv, "%s %s destroy",
3194  IFCONFIG_PATH, tt->actual_name);
3195  }
3196 
3197  close_tun_generic(tt);
3198  argv_msg(M_INFO, &argv);
3199  env_set_add( es, "ODMDIR=/etc/objrepos" );
3200  openvpn_execve_check(&argv, es, 0, "AIX 'destroy tap interface' failed (non-critical)");
3201 
3202  free(tt);
3203  env_set_destroy(es);
3204  argv_reset(&argv);
3205 }
3206 
3207 int
3208 write_tun(struct tuntap *tt, uint8_t *buf, int len)
3209 {
3210  return write(tt->fd, buf, len);
3211 }
3212 
3213 int
3214 read_tun(struct tuntap *tt, uint8_t *buf, int len)
3215 {
3216  return read(tt->fd, buf, len);
3217 }
3218 
3219 #elif defined(_WIN32)
3220 
3221 int
3222 tun_read_queue(struct tuntap *tt, int maxsize)
3223 {
3224  if (tt->reads.iostate == IOSTATE_INITIAL)
3225  {
3226  DWORD len;
3227  BOOL status;
3228  int err;
3229 
3230  /* reset buf to its initial state */
3231  tt->reads.buf = tt->reads.buf_init;
3232 
3233  len = maxsize ? maxsize : BLEN(&tt->reads.buf);
3234  ASSERT(len <= BLEN(&tt->reads.buf));
3235 
3236  /* the overlapped read will signal this event on I/O completion */
3237  ASSERT(ResetEvent(tt->reads.overlapped.hEvent));
3238 
3239  status = ReadFile(
3240  tt->hand,
3241  BPTR(&tt->reads.buf),
3242  len,
3243  &tt->reads.size,
3244  &tt->reads.overlapped
3245  );
3246 
3247  if (status) /* operation completed immediately? */
3248  {
3249  /* since we got an immediate return, we must signal the event object ourselves */
3250  ASSERT(SetEvent(tt->reads.overlapped.hEvent));
3251 
3253  tt->reads.status = 0;
3254 
3255  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read immediate return [%d,%d]",
3256  (int) len,
3257  (int) tt->reads.size);
3258  }
3259  else
3260  {
3261  err = GetLastError();
3262  if (err == ERROR_IO_PENDING) /* operation queued? */
3263  {
3265  tt->reads.status = err;
3266  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read queued [%d]",
3267  (int) len);
3268  }
3269  else /* error occurred */
3270  {
3271  struct gc_arena gc = gc_new();
3272  ASSERT(SetEvent(tt->reads.overlapped.hEvent));
3274  tt->reads.status = err;
3275  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Read error [%d] : %s",
3276  (int) len,
3277  strerror_win32(status, &gc));
3278  gc_free(&gc);
3279  }
3280  }
3281  }
3282  return tt->reads.iostate;
3283 }
3284 
3285 int
3286 tun_write_queue(struct tuntap *tt, struct buffer *buf)
3287 {
3288  if (tt->writes.iostate == IOSTATE_INITIAL)
3289  {
3290  BOOL status;
3291  int err;
3292 
3293  /* make a private copy of buf */
3294  tt->writes.buf = tt->writes.buf_init;
3295  tt->writes.buf.len = 0;
3296  ASSERT(buf_copy(&tt->writes.buf, buf));
3297 
3298  /* the overlapped write will signal this event on I/O completion */
3299  ASSERT(ResetEvent(tt->writes.overlapped.hEvent));
3300 
3301  status = WriteFile(
3302  tt->hand,
3303  BPTR(&tt->writes.buf),
3304  BLEN(&tt->writes.buf),
3305  &tt->writes.size,
3306  &tt->writes.overlapped
3307  );
3308 
3309  if (status) /* operation completed immediately? */
3310  {
3312 
3313  /* since we got an immediate return, we must signal the event object ourselves */
3314  ASSERT(SetEvent(tt->writes.overlapped.hEvent));
3315 
3316  tt->writes.status = 0;
3317 
3318  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write immediate return [%d,%d]",
3319  BLEN(&tt->writes.buf),
3320  (int) tt->writes.size);
3321  }
3322  else
3323  {
3324  err = GetLastError();
3325  if (err == ERROR_IO_PENDING) /* operation queued? */
3326  {
3328  tt->writes.status = err;
3329  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write queued [%d]",
3330  BLEN(&tt->writes.buf));
3331  }
3332  else /* error occurred */
3333  {
3334  struct gc_arena gc = gc_new();
3335  ASSERT(SetEvent(tt->writes.overlapped.hEvent));
3337  tt->writes.status = err;
3338  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Write error [%d] : %s",
3339  BLEN(&tt->writes.buf),
3340  strerror_win32(err, &gc));
3341  gc_free(&gc);
3342  }
3343  }
3344  }
3345  return tt->writes.iostate;
3346 }
3347 
3348 int
3350  HANDLE h,
3351  struct overlapped_io *io,
3352  struct buffer *buf)
3353 {
3354  int ret = -1;
3355  BOOL status;
3356 
3357  switch (io->iostate)
3358  {
3359  case IOSTATE_QUEUED:
3360  status = GetOverlappedResult(
3361  h,
3362  &io->overlapped,
3363  &io->size,
3364  FALSE
3365  );
3366  if (status)
3367  {
3368  /* successful return for a queued operation */
3369  if (buf)
3370  {
3371  *buf = io->buf;
3372  }
3373  ret = io->size;
3374  io->iostate = IOSTATE_INITIAL;
3375  ASSERT(ResetEvent(io->overlapped.hEvent));
3376  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Completion success [%d]", ret);
3377  }
3378  else
3379  {
3380  /* error during a queued operation */
3381  ret = -1;
3382  if (GetLastError() != ERROR_IO_INCOMPLETE)
3383  {
3384  /* if no error (i.e. just not finished yet),
3385  * then DON'T execute this code */
3386  io->iostate = IOSTATE_INITIAL;
3387  ASSERT(ResetEvent(io->overlapped.hEvent));
3388  msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: TAP Completion error");
3389  }
3390  }
3391  break;
3392 
3394  io->iostate = IOSTATE_INITIAL;
3395  ASSERT(ResetEvent(io->overlapped.hEvent));
3396  if (io->status)
3397  {
3398  /* error return for a non-queued operation */
3399  SetLastError(io->status);
3400  ret = -1;
3401  msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: TAP Completion non-queued error");
3402  }
3403  else
3404  {
3405  /* successful return for a non-queued operation */
3406  if (buf)
3407  {
3408  *buf = io->buf;
3409  }
3410  ret = io->size;
3411  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Completion non-queued success [%d]", ret);
3412  }
3413  break;
3414 
3415  case IOSTATE_INITIAL: /* were we called without proper queueing? */
3416  SetLastError(ERROR_INVALID_FUNCTION);
3417  ret = -1;
3418  dmsg(D_WIN32_IO, "WIN32 I/O: TAP Completion BAD STATE");
3419  break;
3420 
3421  default:
3422  ASSERT(0);
3423  }
3424 
3425  if (buf)
3426  {
3427  buf->len = ret;
3428  }
3429  return ret;
3430 }
3431 
3432 const struct tap_reg *
3434 {
3435  HKEY adapter_key;
3436  LONG status;
3437  DWORD len;
3438  struct tap_reg *first = NULL;
3439  struct tap_reg *last = NULL;
3440  int i = 0;
3441 
3442  status = RegOpenKeyEx(
3443  HKEY_LOCAL_MACHINE,
3444  ADAPTER_KEY,
3445  0,
3446  KEY_READ,
3447  &adapter_key);
3448 
3449  if (status != ERROR_SUCCESS)
3450  {
3451  msg(M_FATAL, "Error opening registry key: %s", ADAPTER_KEY);
3452  }
3453 
3454  while (true)
3455  {
3456  char enum_name[256];
3457  char unit_string[256];
3458  HKEY unit_key;
3459  char component_id_string[] = "ComponentId";
3460  char component_id[256];
3461  char net_cfg_instance_id_string[] = "NetCfgInstanceId";
3462  char net_cfg_instance_id[256];
3463  DWORD data_type;
3464 
3465  len = sizeof(enum_name);
3466  status = RegEnumKeyEx(
3467  adapter_key,
3468  i,
3469  enum_name,
3470  &len,
3471  NULL,
3472  NULL,
3473  NULL,
3474  NULL);
3475  if (status == ERROR_NO_MORE_ITEMS)
3476  {
3477  break;
3478  }
3479  else if (status != ERROR_SUCCESS)
3480  {
3481  msg(M_FATAL, "Error enumerating registry subkeys of key: %s",
3482  ADAPTER_KEY);
3483  }
3484 
3485  openvpn_snprintf(unit_string, sizeof(unit_string), "%s\\%s",
3486  ADAPTER_KEY, enum_name);
3487 
3488  status = RegOpenKeyEx(
3489  HKEY_LOCAL_MACHINE,
3490  unit_string,
3491  0,
3492  KEY_READ,
3493  &unit_key);
3494 
3495  if (status != ERROR_SUCCESS)
3496  {
3497  dmsg(D_REGISTRY, "Error opening registry key: %s", unit_string);
3498  }
3499  else
3500  {
3501  len = sizeof(component_id);
3502  status = RegQueryValueEx(
3503  unit_key,
3504  component_id_string,
3505  NULL,
3506  &data_type,
3507  component_id,
3508  &len);
3509 
3510  if (status != ERROR_SUCCESS || data_type != REG_SZ)
3511  {
3512  dmsg(D_REGISTRY, "Error opening registry key: %s\\%s",
3513  unit_string, component_id_string);
3514  }
3515  else
3516  {
3517  len = sizeof(net_cfg_instance_id);
3518  status = RegQueryValueEx(
3519  unit_key,
3520  net_cfg_instance_id_string,
3521  NULL,
3522  &data_type,
3523  net_cfg_instance_id,
3524  &len);
3525 
3526  if (status == ERROR_SUCCESS && data_type == REG_SZ)
3527  {
3528  if (!strcmp(component_id, TAP_WIN_COMPONENT_ID) ||
3529  !strcmp(component_id, "root\\" TAP_WIN_COMPONENT_ID))
3530  {
3531  struct tap_reg *reg;
3532  ALLOC_OBJ_CLEAR_GC(reg, struct tap_reg, gc);
3533  reg->guid = string_alloc(net_cfg_instance_id, gc);
3534 
3535  /* link into return list */
3536  if (!first)
3537  {
3538  first = reg;
3539  }
3540  if (last)
3541  {
3542  last->next = reg;
3543  }
3544  last = reg;
3545  }
3546  }
3547  }
3548  RegCloseKey(unit_key);
3549  }
3550  ++i;
3551  }
3552 
3553  RegCloseKey(adapter_key);
3554  return first;
3555 }
3556 
3557 const struct panel_reg *
3559 {
3560  LONG status;
3561  HKEY network_connections_key;
3562  DWORD len;
3563  struct panel_reg *first = NULL;
3564  struct panel_reg *last = NULL;
3565  int i = 0;
3566 
3567  status = RegOpenKeyEx(
3568  HKEY_LOCAL_MACHINE,
3569  NETWORK_CONNECTIONS_KEY,
3570  0,
3571  KEY_READ,
3572  &network_connections_key);
3573 
3574  if (status != ERROR_SUCCESS)
3575  {
3576  msg(M_FATAL, "Error opening registry key: %s", NETWORK_CONNECTIONS_KEY);
3577  }
3578 
3579  while (true)
3580  {
3581  char enum_name[256];
3582  char connection_string[256];
3583  HKEY connection_key;
3584  WCHAR name_data[256];
3585  DWORD name_type;
3586  const WCHAR name_string[] = L"Name";
3587 
3588  len = sizeof(enum_name);
3589  status = RegEnumKeyEx(
3590  network_connections_key,
3591  i,
3592  enum_name,
3593  &len,
3594  NULL,
3595  NULL,
3596  NULL,
3597  NULL);
3598  if (status == ERROR_NO_MORE_ITEMS)
3599  {
3600  break;
3601  }
3602  else if (status != ERROR_SUCCESS)
3603  {
3604  msg(M_FATAL, "Error enumerating registry subkeys of key: %s",
3605  NETWORK_CONNECTIONS_KEY);
3606  }
3607 
3608  openvpn_snprintf(connection_string, sizeof(connection_string),
3609  "%s\\%s\\Connection",
3610  NETWORK_CONNECTIONS_KEY, enum_name);
3611 
3612  status = RegOpenKeyEx(
3613  HKEY_LOCAL_MACHINE,
3614  connection_string,
3615  0,
3616  KEY_READ,
3617  &connection_key);
3618 
3619  if (status != ERROR_SUCCESS)
3620  {
3621  dmsg(D_REGISTRY, "Error opening registry key: %s", connection_string);
3622  }
3623  else
3624  {
3625  len = sizeof(name_data);
3626  status = RegQueryValueExW(
3627  connection_key,
3628  name_string,
3629  NULL,
3630  &name_type,
3631  (LPBYTE) name_data,
3632  &len);
3633 
3634  if (status != ERROR_SUCCESS || name_type != REG_SZ)
3635  {
3636  dmsg(D_REGISTRY, "Error opening registry key: %s\\%s\\%ls",
3637  NETWORK_CONNECTIONS_KEY, connection_string, name_string);
3638  }
3639  else
3640  {
3641  int n;
3642  LPSTR name;
3643  struct panel_reg *reg;
3644 
3645  ALLOC_OBJ_CLEAR_GC(reg, struct panel_reg, gc);
3646  n = WideCharToMultiByte(CP_UTF8, 0, name_data, -1, NULL, 0, NULL, NULL);
3647  name = gc_malloc(n, false, gc);
3648  WideCharToMultiByte(CP_UTF8, 0, name_data, -1, name, n, NULL, NULL);
3649  reg->name = name;
3650  reg->guid = string_alloc(enum_name, gc);
3651 
3652  /* link into return list */
3653  if (!first)
3654  {
3655  first = reg;
3656  }
3657  if (last)
3658  {
3659  last->next = reg;
3660  }
3661  last = reg;
3662  }
3663  RegCloseKey(connection_key);
3664  }
3665  ++i;
3666  }
3667 
3668  RegCloseKey(network_connections_key);
3669 
3670  return first;
3671 }
3672 
3673 /*
3674  * Check that two addresses are part of the same 255.255.255.252 subnet.
3675  */
3676 void
3678 {
3679  struct gc_arena gc = gc_new();
3680  const unsigned int mask = 3;
3681  const char *err = NULL;
3682 
3683  if (local == remote)
3684  {
3685  err = "must be different";
3686  goto error;
3687  }
3688  if ((local & (~mask)) != (remote & (~mask)))
3689  {
3690  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";
3691  goto error;
3692  }
3693  if ((local & mask) == 0
3694  || (local & mask) == 3
3695  || (remote & mask) == 0
3696  || (remote & mask) == 3)
3697  {
3698  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";
3699  goto error;
3700  }
3701 
3702  gc_free(&gc);
3703  return;
3704 
3705 error:
3706  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.",
3707  print_in_addr_t(local, 0, &gc),
3708  print_in_addr_t(remote, 0, &gc),
3709  err);
3710  gc_free(&gc);
3711 }
3712 
3713 void
3715 {
3716  int i;
3717  int col = 0;
3718 
3719  printf("On Windows, point-to-point IP support (i.e. --dev tun)\n");
3720  printf("is emulated by the TAP-Windows driver. The major limitation\n");
3721  printf("imposed by this approach is that the --ifconfig local and\n");
3722  printf("remote endpoints must be part of the same 255.255.255.252\n");
3723  printf("subnet. The following list shows examples of endpoint\n");
3724  printf("pairs which satisfy this requirement. Only the final\n");
3725  printf("component of the IP address pairs is at issue.\n\n");
3726  printf("As an example, the following option would be correct:\n");
3727  printf(" --ifconfig 10.7.0.5 10.7.0.6 (on host A)\n");
3728  printf(" --ifconfig 10.7.0.6 10.7.0.5 (on host B)\n");
3729  printf("because [5,6] is part of the below list.\n\n");
3730 
3731  for (i = 0; i < 256; i += 4)
3732  {
3733  printf("[%3d,%3d] ", i+1, i+2);
3734  if (++col > 4)
3735  {
3736  col = 0;
3737  printf("\n");
3738  }
3739  }
3740  if (col)
3741  {
3742  printf("\n");
3743  }
3744 }
3745 
3746 void
3747 show_tap_win_adapters(int msglev, int warnlev)
3748 {
3749  struct gc_arena gc = gc_new();
3750 
3751  bool warn_panel_null = false;
3752  bool warn_panel_dup = false;
3753  bool warn_tap_dup = false;
3754 
3755  int links;
3756 
3757  const struct tap_reg *tr;
3758  const struct tap_reg *tr1;
3759  const struct panel_reg *pr;
3760 
3761  const struct tap_reg *tap_reg = get_tap_reg(&gc);
3762  const struct panel_reg *panel_reg = get_panel_reg(&gc);
3763 
3764  msg(msglev, "Available TAP-WIN32 adapters [name, GUID]:");
3765 
3766  /* loop through each TAP-Windows adapter registry entry */
3767  for (tr = tap_reg; tr != NULL; tr = tr->next)
3768  {
3769  links = 0;
3770 
3771  /* loop through each network connections entry in the control panel */
3772  for (pr = panel_reg; pr != NULL; pr = pr->next)
3773  {
3774  if (!strcmp(tr->guid, pr->guid))
3775  {
3776  msg(msglev, "'%s' %s", pr->name, tr->guid);
3777  ++links;
3778  }
3779  }
3780 
3781  if (links > 1)
3782  {
3783  warn_panel_dup = true;
3784  }
3785  else if (links == 0)
3786  {
3787  /* a TAP adapter exists without a link from the network
3788  * connections control panel */
3789  warn_panel_null = true;
3790  msg(msglev, "[NULL] %s", tr->guid);
3791  }
3792  }
3793 
3794  /* check for TAP-Windows adapter duplicated GUIDs */
3795  for (tr = tap_reg; tr != NULL; tr = tr->next)
3796  {
3797  for (tr1 = tap_reg; tr1 != NULL; tr1 = tr1->next)
3798  {
3799  if (tr != tr1 && !strcmp(tr->guid, tr1->guid))
3800  {
3801  warn_tap_dup = true;
3802  }
3803  }
3804  }
3805 
3806  /* warn on registry inconsistencies */
3807  if (warn_tap_dup)
3808  {
3809  msg(warnlev, "WARNING: Some TAP-Windows adapters have duplicate GUIDs");
3810  }
3811 
3812  if (warn_panel_dup)
3813  {
3814  msg(warnlev, "WARNING: Some TAP-Windows adapters have duplicate links from the Network Connections control panel");
3815  }
3816 
3817  if (warn_panel_null)
3818  {
3819  msg(warnlev, "WARNING: Some TAP-Windows adapters have no link from the Network Connections control panel");
3820  }
3821 
3822  gc_free(&gc);
3823 }
3824 
3825 /*
3826  * Confirm that GUID is a TAP-Windows adapter.
3827  */
3828 static bool
3829 is_tap_win(const char *guid, const struct tap_reg *tap_reg)
3830 {
3831  const struct tap_reg *tr;
3832 
3833  for (tr = tap_reg; tr != NULL; tr = tr->next)
3834  {
3835  if (guid && !strcmp(tr->guid, guid))
3836  {
3837  return true;
3838  }
3839  }
3840 
3841  return false;
3842 }
3843 
3844 static const char *
3845 guid_to_name(const char *guid, const struct panel_reg *panel_reg)
3846 {
3847  const struct panel_reg *pr;
3848 
3849  for (pr = panel_reg; pr != NULL; pr = pr->next)
3850  {
3851  if (guid && !strcmp(pr->guid, guid))
3852  {
3853  return pr->name;
3854  }
3855  }
3856 
3857  return NULL;
3858 }
3859 
3860 static const char *
3861 name_to_guid(const char *name, const struct tap_reg *tap_reg, const struct panel_reg *panel_reg)
3862 {
3863  const struct panel_reg *pr;
3864 
3865  for (pr = panel_reg; pr != NULL; pr = pr->next)
3866  {
3867  if (name && !strcmp(pr->name, name) && is_tap_win(pr->guid, tap_reg))
3868  {
3869  return pr->guid;
3870  }
3871  }
3872 
3873  return NULL;
3874 }
3875 
3876 static void
3878 {
3879  if (!tap_reg)
3880  {
3881  msg(M_FATAL, "There are no TAP-Windows adapters on this system. You should be able to create a TAP-Windows adapter by going to Start -> All Programs -> TAP-Windows -> Utilities -> Add a new TAP-Windows virtual ethernet adapter.");
3882  }
3883 }
3884 
3885 /*
3886  * Get an adapter GUID and optional actual_name from the
3887  * registry for the TAP device # = device_number.
3888  */
3889 static const char *
3890 get_unspecified_device_guid(const int device_number,
3891  char *actual_name,
3892  int actual_name_size,
3893  const struct tap_reg *tap_reg_src,
3894  const struct panel_reg *panel_reg_src,
3895  struct gc_arena *gc)
3896 {
3897  const struct tap_reg *tap_reg = tap_reg_src;
3898  struct buffer ret = clear_buf();
3899  struct buffer actual = clear_buf();
3900  int i;
3901 
3902  ASSERT(device_number >= 0);
3903 
3904  /* Make sure we have at least one TAP adapter */
3905  if (!tap_reg)
3906  {
3907  return NULL;
3908  }
3909 
3910  /* The actual_name output buffer may be NULL */
3911  if (actual_name)
3912  {
3913  ASSERT(actual_name_size > 0);
3914  buf_set_write(&actual, actual_name, actual_name_size);
3915  }
3916 
3917  /* Move on to specified device number */
3918  for (i = 0; i < device_number; i++)
3919  {
3920  tap_reg = tap_reg->next;
3921  if (!tap_reg)
3922  {
3923  return NULL;
3924  }
3925  }
3926 
3927  /* Save Network Panel name (if exists) in actual_name */
3928  if (actual_name)
3929  {
3930  const char *act = guid_to_name(tap_reg->guid, panel_reg_src);
3931  if (act)
3932  {
3933  buf_printf(&actual, "%s", act);
3934  }
3935  else
3936  {
3937  buf_printf(&actual, "%s", tap_reg->guid);
3938  }
3939  }
3940 
3941  /* Save GUID for return value */
3942  ret = alloc_buf_gc(256, gc);
3943  buf_printf(&ret, "%s", tap_reg->guid);
3944  return BSTR(&ret);
3945 }
3946 
3947 /*
3948  * Lookup a --dev-node adapter name in the registry
3949  * returning the GUID and optional actual_name.
3950  */
3951 static const char *
3952 get_device_guid(const char *name,
3953  char *actual_name,
3954  int actual_name_size,
3955  const struct tap_reg *tap_reg,
3956  const struct panel_reg *panel_reg,
3957  struct gc_arena *gc)
3958 {
3959  struct buffer ret = alloc_buf_gc(256, gc);
3960  struct buffer actual = clear_buf();
3961 
3962  /* Make sure we have at least one TAP adapter */
3963  if (!tap_reg)
3964  {
3965  return NULL;
3966  }
3967 
3968  /* The actual_name output buffer may be NULL */
3969  if (actual_name)
3970  {
3971  ASSERT(actual_name_size > 0);
3972  buf_set_write(&actual, actual_name, actual_name_size);
3973  }
3974 
3975  /* Check if GUID was explicitly specified as --dev-node parameter */
3976  if (is_tap_win(name, tap_reg))
3977  {
3978  const char *act = guid_to_name(name, panel_reg);
3979  buf_printf(&ret, "%s", name);
3980  if (act)
3981  {
3982  buf_printf(&actual, "%s", act);
3983  }
3984  else
3985  {
3986  buf_printf(&actual, "%s", name);
3987  }
3988  return BSTR(&ret);
3989  }
3990 
3991  /* Lookup TAP adapter in network connections list */
3992  {
3993  const char *guid = name_to_guid(name, tap_reg, panel_reg);
3994  if (guid)
3995  {
3996  buf_printf(&actual, "%s", name);
3997  buf_printf(&ret, "%s", guid);
3998  return BSTR(&ret);
3999  }
4000  }
4001 
4002  return NULL;
4003 }
4004 
4005 /*
4006  * Get adapter info list
4007  */
4008 const IP_ADAPTER_INFO *
4010 {
4011  ULONG size = 0;
4012  IP_ADAPTER_INFO *pi = NULL;
4013  DWORD status;
4014 
4015  if ((status = GetAdaptersInfo(NULL, &size)) != ERROR_BUFFER_OVERFLOW)
4016  {
4017  msg(M_INFO, "GetAdaptersInfo #1 failed (status=%u) : %s",
4018  (unsigned int)status,
4019  strerror_win32(status, gc));
4020  }
4021  else
4022  {
4023  pi = (PIP_ADAPTER_INFO) gc_malloc(size, false, gc);
4024  if ((status = GetAdaptersInfo(pi, &size)) != NO_ERROR)
4025  {
4026  msg(M_INFO, "GetAdaptersInfo #2 failed (status=%u) : %s",
4027  (unsigned int)status,
4028  strerror_win32(status, gc));
4029  pi = NULL;
4030  }
4031  }
4032  return pi;
4033 }
4034 
4035 const IP_PER_ADAPTER_INFO *
4036 get_per_adapter_info(const DWORD index, struct gc_arena *gc)
4037 {
4038  ULONG size = 0;
4039  IP_PER_ADAPTER_INFO *pi = NULL;
4040  DWORD status;
4041 
4042  if (index != TUN_ADAPTER_INDEX_INVALID)
4043  {
4044  if ((status = GetPerAdapterInfo(index, NULL, &size)) != ERROR_BUFFER_OVERFLOW)
4045  {
4046  msg(M_INFO, "GetPerAdapterInfo #1 failed (status=%u) : %s",
4047  (unsigned int)status,
4048  strerror_win32(status, gc));
4049  }
4050  else
4051  {
4052  pi = (PIP_PER_ADAPTER_INFO) gc_malloc(size, false, gc);
4053  if ((status = GetPerAdapterInfo((ULONG)index, pi, &size)) == ERROR_SUCCESS)
4054  {
4055  return pi;
4056  }
4057  else
4058  {
4059  msg(M_INFO, "GetPerAdapterInfo #2 failed (status=%u) : %s",
4060  (unsigned int)status,
4061  strerror_win32(status, gc));
4062  }
4063  }
4064  }
4065  return pi;
4066 }
4067 
4068 static const IP_INTERFACE_INFO *
4070 {
4071  ULONG size = 0;
4072  IP_INTERFACE_INFO *ii = NULL;
4073  DWORD status;
4074 
4075  if ((status = GetInterfaceInfo(NULL, &size)) != ERROR_INSUFFICIENT_BUFFER)
4076  {
4077  msg(M_INFO, "GetInterfaceInfo #1 failed (status=%u) : %s",
4078  (unsigned int)status,
4079  strerror_win32(status, gc));
4080  }
4081  else
4082  {
4083  ii = (PIP_INTERFACE_INFO) gc_malloc(size, false, gc);
4084  if ((status = GetInterfaceInfo(ii, &size)) == NO_ERROR)
4085  {
4086  return ii;
4087  }
4088  else
4089  {
4090  msg(M_INFO, "GetInterfaceInfo #2 failed (status=%u) : %s",
4091  (unsigned int)status,
4092  strerror_win32(status, gc));
4093  }
4094  }
4095  return ii;
4096 }
4097 
4098 static const IP_ADAPTER_INDEX_MAP *
4099 get_interface_info(DWORD index, struct gc_arena *gc)
4100 {
4101  const IP_INTERFACE_INFO *list = get_interface_info_list(gc);
4102  if (list)
4103  {
4104  int i;
4105  for (i = 0; i < list->NumAdapters; ++i)
4106  {
4107  const IP_ADAPTER_INDEX_MAP *inter = &list->Adapter[i];
4108  if (index == inter->Index)
4109  {
4110  return inter;
4111  }
4112  }
4113  }
4114  return NULL;
4115 }
4116 
4117 /*
4118  * Given an adapter index, return a pointer to the
4119  * IP_ADAPTER_INFO structure for that adapter.
4120  */
4121 
4122 const IP_ADAPTER_INFO *
4123 get_adapter(const IP_ADAPTER_INFO *ai, DWORD index)
4124 {
4125  if (ai && index != TUN_ADAPTER_INDEX_INVALID)
4126  {
4127  const IP_ADAPTER_INFO *a;
4128 
4129  /* find index in the linked list */
4130  for (a = ai; a != NULL; a = a->Next)
4131  {
4132  if (a->Index == index)
4133  {
4134  return a;
4135  }
4136  }
4137  }
4138  return NULL;
4139 }
4140 
4141 const IP_ADAPTER_INFO *
4142 get_adapter_info(DWORD index, struct gc_arena *gc)
4143 {
4144  return get_adapter(get_adapter_info_list(gc), index);
4145 }
4146 
4147 static int
4148 get_adapter_n_ip_netmask(const IP_ADAPTER_INFO *ai)
4149 {
4150  if (ai)
4151  {
4152  int n = 0;
4153  const IP_ADDR_STRING *ip = &ai->IpAddressList;
4154 
4155  while (ip)
4156  {
4157  ++n;
4158  ip = ip->Next;
4159  }
4160  return n;
4161  }
4162  else
4163  {
4164  return 0;
4165  }
4166 }
4167 
4168 static bool
4169 get_adapter_ip_netmask(const IP_ADAPTER_INFO *ai, const int n, in_addr_t *ip, in_addr_t *netmask)
4170 {
4171  bool ret = false;
4172  *ip = 0;
4173  *netmask = 0;
4174 
4175  if (ai)
4176  {
4177  const IP_ADDR_STRING *iplist = &ai->IpAddressList;
4178  int i = 0;
4179 
4180  while (iplist)
4181  {
4182  if (i == n)
4183  {
4184  break;
4185  }
4186  ++i;
4187  iplist = iplist->Next;
4188  }
4189 
4190  if (iplist)
4191  {
4192  const unsigned int getaddr_flags = GETADDR_HOST_ORDER;
4193  const char *ip_str = iplist->IpAddress.String;
4194  const char *netmask_str = iplist->IpMask.String;
4195  bool succeed1 = false;
4196  bool succeed2 = false;
4197 
4198  if (ip_str && netmask_str && strlen(ip_str) && strlen(netmask_str))
4199  {
4200  *ip = getaddr(getaddr_flags, ip_str, 0, &succeed1, NULL);
4201  *netmask = getaddr(getaddr_flags, netmask_str, 0, &succeed2, NULL);
4202  ret = (succeed1 == true && succeed2 == true);
4203  }
4204  }
4205  }
4206 
4207  return ret;
4208 }
4209 
4210 static bool
4211 test_adapter_ip_netmask(const IP_ADAPTER_INFO *ai, const in_addr_t ip, const in_addr_t netmask)
4212 {
4213  if (ai)
4214  {
4215  in_addr_t ip_adapter = 0;
4216  in_addr_t netmask_adapter = 0;
4217  const bool status = get_adapter_ip_netmask(ai, 0, &ip_adapter, &netmask_adapter);
4218  return (status && ip_adapter == ip && netmask_adapter == netmask);
4219  }
4220  else
4221  {
4222  return false;
4223  }
4224 }
4225 
4226 const IP_ADAPTER_INFO *
4227 get_tun_adapter(const struct tuntap *tt, const IP_ADAPTER_INFO *list)
4228 {
4229  if (list && tt)
4230  {
4231  return get_adapter(list, tt->adapter_index);
4232  }
4233  else
4234  {
4235  return NULL;
4236  }
4237 }
4238 
4239 bool
4240 is_adapter_up(const struct tuntap *tt, const IP_ADAPTER_INFO *list)
4241 {
4242  int i;
4243  bool ret = false;
4244 
4245  const IP_ADAPTER_INFO *ai = get_tun_adapter(tt, list);
4246 
4247  if (ai)
4248  {
4249  const int n = get_adapter_n_ip_netmask(ai);
4250 
4251  /* loop once for every IP/netmask assigned to adapter */
4252  for (i = 0; i < n; ++i)
4253  {
4254  in_addr_t ip, netmask;
4255  if (get_adapter_ip_netmask(ai, i, &ip, &netmask))
4256  {
4257  if (tt->local && tt->adapter_netmask)
4258  {
4259  /* wait for our --ifconfig parms to match the actual adapter parms */
4260  if (tt->local == ip && tt->adapter_netmask == netmask)
4261  {
4262  ret = true;
4263  }
4264  }
4265  else
4266  {
4267  /* --ifconfig was not defined, maybe using a real DHCP server */
4268  if (ip && netmask)
4269  {
4270  ret = true;
4271  }
4272  }
4273  }
4274  }
4275  }
4276  else
4277  {
4278  ret = true; /* this can occur when TAP adapter is bridged */
4279 
4280  }
4281  return ret;
4282 }
4283 
4284 bool
4285 is_ip_in_adapter_subnet(const IP_ADAPTER_INFO *ai, const in_addr_t ip, in_addr_t *highest_netmask)
4286 {
4287  int i;
4288  bool ret = false;
4289 
4290  if (highest_netmask)
4291  {
4292  *highest_netmask = 0;
4293  }
4294 
4295  if (ai)
4296  {
4297  const int n = get_adapter_n_ip_netmask(ai);
4298  for (i = 0; i < n; ++i)
4299  {
4300  in_addr_t adapter_ip, adapter_netmask;
4301  if (get_adapter_ip_netmask(ai, i, &adapter_ip, &adapter_netmask))
4302  {
4303  if (adapter_ip && adapter_netmask && (ip & adapter_netmask) == (adapter_ip & adapter_netmask))
4304  {
4305  if (highest_netmask && adapter_netmask > *highest_netmask)
4306  {
4307  *highest_netmask = adapter_netmask;
4308  }
4309  ret = true;
4310  }
4311  }
4312  }
4313  }
4314  return ret;
4315 }
4316 
4317 DWORD
4318 adapter_index_of_ip(const IP_ADAPTER_INFO *list,
4319  const in_addr_t ip,
4320  int *count,
4321  in_addr_t *netmask)
4322 {
4323  struct gc_arena gc = gc_new();
4324  DWORD ret = TUN_ADAPTER_INDEX_INVALID;
4325  in_addr_t highest_netmask = 0;
4326  int lowest_metric = INT_MAX;
4327  bool first = true;
4328 
4329  if (count)
4330  {
4331  *count = 0;
4332  }
4333 
4334  while (list)
4335  {
4336  in_addr_t hn;
4337 
4338  if (is_ip_in_adapter_subnet(list, ip, &hn))
4339  {
4340  int metric = get_interface_metric(list->Index, AF_INET, NULL);
4341  if (first || hn > highest_netmask)
4342  {
4343  highest_netmask = hn;
4344  if (metric >= 0)
4345  {
4346  lowest_metric = metric;
4347  }
4348  if (count)
4349  {
4350  *count = 1;
4351  }
4352  ret = list->Index;
4353  first = false;
4354  }
4355  else if (hn == highest_netmask)
4356  {
4357  if (count)
4358  {
4359  ++*count;
4360  }
4361  if (metric >= 0 && metric < lowest_metric)
4362  {
4363  ret = list->Index;
4364  lowest_metric = metric;
4365  }
4366  }
4367  }
4368  list = list->Next;
4369  }
4370 
4371  dmsg(D_ROUTE_DEBUG, "DEBUG: IP Locate: ip=%s nm=%s index=%d count=%d metric=%d",
4372  print_in_addr_t(ip, 0, &gc),
4373  print_in_addr_t(highest_netmask, 0, &gc),
4374  (int)ret,
4375  count ? *count : -1,
4376  lowest_metric);
4377 
4378  if (ret == TUN_ADAPTER_INDEX_INVALID && count)
4379  {
4380  *count = 0;
4381  }
4382 
4383  if (netmask)
4384  {
4385  *netmask = highest_netmask;
4386  }
4387 
4388  gc_free(&gc);
4389  return ret;
4390 }
4391 
4392 /*
4393  * Given an adapter index, return true if the adapter
4394  * is DHCP disabled.
4395  */
4396 
4397 #define DHCP_STATUS_UNDEF 0
4398 #define DHCP_STATUS_ENABLED 1
4399 #define DHCP_STATUS_DISABLED 2
4400 
4401 static int
4402 dhcp_status(DWORD index)
4403 {
4404  struct gc_arena gc = gc_new();
4405  int ret = DHCP_STATUS_UNDEF;
4406  if (index != TUN_ADAPTER_INDEX_INVALID)
4407  {
4408  const IP_ADAPTER_INFO *ai = get_adapter_info(index, &gc);
4409 
4410  if (ai)
4411  {
4412  if (ai->DhcpEnabled)
4413  {
4414  ret = DHCP_STATUS_ENABLED;
4415  }
4416  else
4417  {
4418  ret = DHCP_STATUS_DISABLED;
4419  }
4420  }
4421  }
4422  gc_free(&gc);
4423  return ret;
4424 }
4425 
4426 /*
4427  * Delete all temporary address/netmask pairs which were added
4428  * to adapter (given by index) by previous calls to AddIPAddress.
4429  */
4430 static void
4432 {
4433  struct gc_arena gc = gc_new();
4434  const IP_ADAPTER_INFO *a = get_adapter_info(index, &gc);
4435 
4436  if (a)
4437  {
4438  const IP_ADDR_STRING *ip = &a->IpAddressList;
4439  while (ip)
4440  {
4441  DWORD status;
4442  const DWORD context = ip->Context;
4443 
4444  if ((status = DeleteIPAddress((ULONG) context)) == NO_ERROR)
4445  {
4446  msg(M_INFO, "Successfully deleted previously set dynamic IP/netmask: %s/%s",
4447  ip->IpAddress.String,
4448  ip->IpMask.String);
4449  }
4450  else
4451  {
4452  const char *empty = "0.0.0.0";
4453  if (strcmp(ip->IpAddress.String, empty)
4454  || strcmp(ip->IpMask.String, empty))
4455  {
4456  msg(M_INFO, "NOTE: could not delete previously set dynamic IP/netmask: %s/%s (status=%u)",
4457  ip->IpAddress.String,
4458  ip->IpMask.String,
4459  (unsigned int)status);
4460  }
4461  }
4462  ip = ip->Next;
4463  }
4464  }
4465  gc_free(&gc);
4466 }
4467 
4468 /*
4469  * Get interface index for use with IP Helper API functions.
4470  */
4471 static DWORD
4473 {
4474  DWORD index;
4475  ULONG aindex;
4476  wchar_t wbuf[256];
4477  openvpn_swprintf(wbuf, SIZE(wbuf), L"\\DEVICE\\TCPIP_%S", guid);
4478  if (GetAdapterIndex(wbuf, &aindex) != NO_ERROR)
4479  {
4480  index = TUN_ADAPTER_INDEX_INVALID;
4481  }
4482  else
4483  {
4484  index = (DWORD)aindex;
4485  }
4486  return index;
4487 }
4488 
4489 static DWORD
4491 {
4492  struct gc_arena gc = gc_new();
4493  DWORD index = TUN_ADAPTER_INDEX_INVALID;
4494 
4495  const IP_ADAPTER_INFO *list = get_adapter_info_list(&gc);
4496 
4497  while (list)
4498  {
4499  if (!strcmp(guid, list->AdapterName))
4500  {
4501  index = list->Index;
4502  break;
4503  }
4504  list = list->Next;
4505  }
4506 
4507  gc_free(&gc);
4508  return index;
4509 }
4510 
4511 static DWORD
4512 get_adapter_index(const char *guid)
4513 {
4514  DWORD index;
4515  index = get_adapter_index_method_1(guid);
4516  if (index == TUN_ADAPTER_INDEX_INVALID)
4517  {
4518  index = get_adapter_index_method_2(guid);
4519  }
4520  if (index == TUN_ADAPTER_INDEX_INVALID)
4521  {
4522  msg(M_INFO, "NOTE: could not get adapter index for %s", guid);
4523  }
4524  return index;
4525 }
4526 
4527 static DWORD
4528 get_adapter_index_flexible(const char *name) /* actual name or GUID */
4529 {
4530  struct gc_arena gc = gc_new();
4531  DWORD index;
4532  index = get_adapter_index_method_1(name);
4533  if (index == TUN_ADAPTER_INDEX_INVALID)
4534  {
4535  index = get_adapter_index_method_2(name);
4536  }
4537  if (index == TUN_ADAPTER_INDEX_INVALID)
4538  {
4539  const struct tap_reg *tap_reg = get_tap_reg(&gc);
4540  const struct panel_reg *panel_reg = get_panel_reg(&gc);
4541  const char *guid = name_to_guid(name, tap_reg, panel_reg);
4542  index = get_adapter_index_method_1(guid);
4543  if (index == TUN_ADAPTER_INDEX_INVALID)
4544  {
4545  index = get_adapter_index_method_2(guid);
4546  }
4547  }
4548  if (index == TUN_ADAPTER_INDEX_INVALID)
4549  {
4550  msg(M_INFO, "NOTE: could not get adapter index for name/GUID '%s'", name);
4551  }
4552  gc_free(&gc);
4553  return index;
4554 }
4555 
4556 /*
4557  * Return a string representing a PIP_ADDR_STRING
4558  */
4559 static const char *
4560 format_ip_addr_string(const IP_ADDR_STRING *ip, struct gc_arena *gc)
4561 {
4562  struct buffer out = alloc_buf_gc(256, gc);
4563  while (ip)
4564  {
4565  buf_printf(&out, "%s", ip->IpAddress.String);
4566  if (strlen(ip->IpMask.String))
4567  {
4568  buf_printf(&out, "/");
4569  buf_printf(&out, "%s", ip->IpMask.String);
4570  }
4571  buf_printf(&out, " ");
4572  ip = ip->Next;
4573  }
4574  return BSTR(&out);
4575 }
4576 
4577 /*
4578  * Show info for a single adapter
4579  */
4580 static void
4581 show_adapter(int msglev, const IP_ADAPTER_INFO *a, struct gc_arena *gc)
4582 {
4583  msg(msglev, "%s", a->Description);
4584  msg(msglev, " Index = %d", (int)a->Index);
4585  msg(msglev, " GUID = %s", a->AdapterName);
4586  msg(msglev, " IP = %s", format_ip_addr_string(&a->IpAddressList, gc));
4587  msg(msglev, " MAC = %s", format_hex_ex(a->Address, a->AddressLength, 0, 1, ":", gc));
4588  msg(msglev, " GATEWAY = %s", format_ip_addr_string(&a->GatewayList, gc));
4589  if (a->DhcpEnabled)
4590  {
4591  msg(msglev, " DHCP SERV = %s", format_ip_addr_string(&a->DhcpServer, gc));
4592  msg(msglev, " DHCP LEASE OBTAINED = %s", time_string(a->LeaseObtained, 0, false, gc));
4593  msg(msglev, " DHCP LEASE EXPIRES = %s", time_string(a->LeaseExpires, 0, false, gc));
4594  }
4595  if (a->HaveWins)
4596  {
4597  msg(msglev, " PRI WINS = %s", format_ip_addr_string(&a->PrimaryWinsServer, gc));
4598  msg(msglev, " SEC WINS = %s", format_ip_addr_string(&a->SecondaryWinsServer, gc));
4599  }
4600 
4601  {
4602  const IP_PER_ADAPTER_INFO *pai = get_per_adapter_info(a->Index, gc);
4603  if (pai)
4604  {
4605  msg(msglev, " DNS SERV = %s", format_ip_addr_string(&pai->DnsServerList, gc));
4606  }
4607  }
4608 }
4609 
4610 /*
4611  * Show current adapter list
4612  */
4613 void
4614 show_adapters(int msglev)
4615 {
4616  struct gc_arena gc = gc_new();
4617  const IP_ADAPTER_INFO *ai = get_adapter_info_list(&gc);
4618 
4619  msg(msglev, "SYSTEM ADAPTER LIST");
4620  if (ai)
4621  {
4622  const IP_ADAPTER_INFO *a;
4623 
4624  /* find index in the linked list */
4625  for (a = ai; a != NULL; a = a->Next)
4626  {
4627  show_adapter(msglev, a, &gc);
4628  }
4629  }
4630  gc_free(&gc);
4631 }
4632 
4633 /*
4634  * Set a particular TAP-Windows adapter (or all of them if
4635  * adapter_name == NULL) to allow it to be opened from
4636  * a non-admin account. This setting will only persist
4637  * for the lifetime of the device object.
4638  */
4639 
4640 static void
4641 tap_allow_nonadmin_access_handle(const char *device_path, HANDLE hand)
4642 {
4643  struct security_attributes sa;
4644  BOOL status;
4645 
4647  {
4648  msg(M_ERR, "Error: init SA failed");
4649  }
4650 
4651  status = SetKernelObjectSecurity(hand, DACL_SECURITY_INFORMATION, &sa.sd);
4652  if (!status)
4653  {
4654  msg(M_ERRNO, "Error: SetKernelObjectSecurity failed on %s", device_path);
4655  }
4656  else
4657  {
4658  msg(M_INFO|M_NOPREFIX, "TAP-Windows device: %s [Non-admin access allowed]", device_path);
4659  }
4660 }
4661 
4662 void
4663 tap_allow_nonadmin_access(const char *dev_node)
4664 {
4665  struct gc_arena gc = gc_new();
4666  const struct tap_reg *tap_reg = get_tap_reg(&gc);
4667  const struct panel_reg *panel_reg = get_panel_reg(&gc);
4668  const char *device_guid = NULL;
4669  HANDLE hand;
4670  char actual_buffer[256];
4671  char device_path[256];
4672 
4673  at_least_one_tap_win(tap_reg);
4674 
4675  if (dev_node)
4676  {
4677  /* Get the device GUID for the device specified with --dev-node. */
4678  device_guid = get_device_guid(dev_node, actual_buffer, sizeof(actual_buffer), tap_reg, panel_reg, &gc);
4679 
4680  if (!device_guid)
4681  {
4682  msg(M_FATAL, "TAP-Windows adapter '%s' not found", dev_node);
4683  }
4684 
4685  /* Open Windows TAP-Windows adapter */
4686  openvpn_snprintf(device_path, sizeof(device_path), "%s%s%s",
4687  USERMODEDEVICEDIR,
4688  device_guid,
4689  TAP_WIN_SUFFIX);
4690 
4691  hand = CreateFile(
4692  device_path,
4693  MAXIMUM_ALLOWED,
4694  0, /* was: FILE_SHARE_READ */
4695  0,
4696  OPEN_EXISTING,
4697  FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
4698  0
4699  );
4700 
4701  if (hand == INVALID_HANDLE_VALUE)
4702  {
4703  msg(M_ERR, "CreateFile failed on TAP device: %s", device_path);
4704  }
4705 
4706  tap_allow_nonadmin_access_handle(device_path, hand);
4707  CloseHandle(hand);
4708  }
4709  else
4710  {
4711  int device_number = 0;
4712 
4713  /* Try opening all TAP devices */
4714  while (true)
4715  {
4716  device_guid = get_unspecified_device_guid(device_number,
4717  actual_buffer,
4718  sizeof(actual_buffer),
4719  tap_reg,
4720  panel_reg,
4721  &gc);
4722 
4723  if (!device_guid)
4724  {
4725  break;
4726  }
4727 
4728  /* Open Windows TAP-Windows adapter */
4729  openvpn_snprintf(device_path, sizeof(device_path), "%s%s%s",
4730  USERMODEDEVICEDIR,
4731  device_guid,
4732  TAP_WIN_SUFFIX);
4733 
4734  hand = CreateFile(
4735  device_path,
4736  MAXIMUM_ALLOWED,
4737  0, /* was: FILE_SHARE_READ */
4738  0,
4739  OPEN_EXISTING,
4740  FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
4741  0
4742  );
4743 
4744  if (hand == INVALID_HANDLE_VALUE)
4745  {
4746  msg(M_WARN, "CreateFile failed on TAP device: %s", device_path);
4747  }
4748  else
4749  {
4750  tap_allow_nonadmin_access_handle(device_path, hand);
4751  CloseHandle(hand);
4752  }
4753 
4754  device_number++;
4755  }
4756  }
4757  gc_free(&gc);
4758 }
4759 
4760 /*
4761  * DHCP release/renewal
4762  */
4763 bool
4764 dhcp_release_by_adapter_index(const DWORD adapter_index)
4765 {
4766  struct gc_arena gc = gc_new();
4767  bool ret = false;
4768  const IP_ADAPTER_INDEX_MAP *inter = get_interface_info(adapter_index, &gc);
4769 
4770  if (inter)
4771  {
4772  DWORD status = IpReleaseAddress((IP_ADAPTER_INDEX_MAP *)inter);
4773  if (status == NO_ERROR)
4774  {
4775  msg(D_TUNTAP_INFO, "TAP: DHCP address released");
4776  ret = true;
4777  }
4778  else
4779  {
4780  msg(M_WARN, "NOTE: Release of DHCP-assigned IP address lease on TAP-Windows adapter failed: %s (code=%u)",
4781  strerror_win32(status, &gc),
4782  (unsigned int)status);
4783  }
4784  }
4785 
4786  gc_free(&gc);
4787  return ret;
4788 }
4789 
4790 static bool
4791 dhcp_release(const struct tuntap *tt)
4792 {
4794  {
4796  }
4797  else
4798  {
4799  return false;
4800  }
4801 }
4802 
4803 bool
4804 dhcp_renew_by_adapter_index(const DWORD adapter_index)
4805 {
4806  struct gc_arena gc = gc_new();
4807  bool ret = false;
4808  const IP_ADAPTER_INDEX_MAP *inter = get_interface_info(adapter_index, &gc);
4809 
4810  if (inter)
4811  {
4812  DWORD status = IpRenewAddress((IP_ADAPTER_INDEX_MAP *)inter);
4813  if (status == NO_ERROR)
4814  {
4815  msg(D_TUNTAP_INFO, "TAP: DHCP address renewal succeeded");
4816  ret = true;
4817  }
4818  else
4819  {
4820  msg(M_WARN, "WARNING: Failed to renew DHCP IP address lease on TAP-Windows adapter: %s (code=%u)",
4821  strerror_win32(status, &gc),
4822  (unsigned int)status);
4823  }
4824  }
4825  gc_free(&gc);
4826  return ret;
4827 }
4828 
4829 static bool
4830 dhcp_renew(const struct tuntap *tt)
4831 {
4833  {
4835  }
4836  else
4837  {
4838  return false;
4839  }
4840 }
4841 
4842 /*
4843  * netsh functions
4844  */
4845 
4846 static void
4847 netsh_command(const struct argv *a, int n, int msglevel)
4848 {
4849  int i;
4850  for (i = 0; i < n; ++i)
4851  {
4852  bool status;
4853  management_sleep(1);
4855  argv_msg_prefix(M_INFO, a, "NETSH");
4856  status = openvpn_execve_check(a, NULL, 0, "ERROR: netsh command failed");
4858  if (status)
4859  {
4860  return;
4861  }
4862  management_sleep(4);
4863  }
4864  msg(msglevel, "NETSH: command failed");
4865 }
4866 
4867 void
4869 {
4870  struct argv argv = argv_new();
4871  bool status;
4872  const char err[] = "ERROR: Windows ipconfig command failed";
4873 
4874  msg(D_TUNTAP_INFO, "Start ipconfig commands for register-dns...");
4876 
4877  argv_printf(&argv, "%s%sc /flushdns",
4878  get_win_sys_path(),
4880  argv_msg(D_TUNTAP_INFO, &argv);
4881  status = openvpn_execve_check(&argv, es, 0, err);
4882  argv_reset(&argv);
4883 
4884  argv_printf(&argv, "%s%sc /registerdns",
4885  get_win_sys_path(),
4887  argv_msg(D_TUNTAP_INFO, &argv);
4888  status = openvpn_execve_check(&argv, es, 0, err);
4889  argv_reset(&argv);
4890 
4892  msg(D_TUNTAP_INFO, "End ipconfig commands for register-dns...");
4893 }
4894 
4895 void
4896 ip_addr_string_to_array(in_addr_t *dest, int *dest_len, const IP_ADDR_STRING *src)
4897 {
4898  int i = 0;
4899  while (src)
4900  {
4901  const unsigned int getaddr_flags = GETADDR_HOST_ORDER;
4902  const char *ip_str = src->IpAddress.String;
4903  in_addr_t ip = 0;
4904  bool succeed = false;
4905 
4906  if (i >= *dest_len)
4907  {
4908  break;
4909  }
4910  if (!ip_str || !strlen(ip_str))
4911  {
4912  break;
4913  }
4914 
4915  ip = getaddr(getaddr_flags, ip_str, 0, &succeed, NULL);
4916  if (!succeed)
4917  {
4918  break;
4919  }
4920  dest[i++] = ip;
4921 
4922  src = src->Next;
4923  }
4924  *dest_len = i;
4925 
4926 #if 0
4927  {
4928  struct gc_arena gc = gc_new();
4929  msg(M_INFO, "ip_addr_string_to_array [%d]", *dest_len);
4930  for (i = 0; i < *dest_len; ++i)
4931  {
4932  msg(M_INFO, "%s", print_in_addr_t(dest[i], 0, &gc));
4933  }
4934  gc_free(&gc);
4935  }
4936 #endif
4937 }
4938 
4939 static bool
4940 ip_addr_one_to_one(const in_addr_t *a1, const int a1len, const IP_ADDR_STRING *ias)
4941 {
4942  in_addr_t a2[8];
4943  int a2len = SIZE(a2);
4944  int i;
4945 
4946  ip_addr_string_to_array(a2, &a2len, ias);
4947  /*msg (M_INFO, "a1len=%d a2len=%d", a1len, a2len);*/
4948  if (a1len != a2len)
4949  {
4950  return false;
4951  }
4952 
4953  for (i = 0; i < a1len; ++i)
4954  {
4955  if (a1[i] != a2[i])
4956  {
4957  return false;
4958  }
4959  }
4960  return true;
4961 }
4962 
4963 static bool
4964 ip_addr_member_of(const in_addr_t addr, const IP_ADDR_STRING *ias)
4965 {
4966  in_addr_t aa[8];
4967  int len = SIZE(aa);
4968  int i;
4969 
4970  ip_addr_string_to_array(aa, &len, ias);
4971  for (i = 0; i < len; ++i)
4972  {
4973  if (addr == aa[i])
4974  {
4975  return true;
4976  }
4977  }
4978  return false;
4979 }
4980 
4987 static void
4988 netsh_set_dns6_servers(const struct in6_addr *addr_list,
4989  const int addr_len,
4990  const char *flex_name)
4991 {
4992  struct gc_arena gc = gc_new();
4993  struct argv argv = argv_new();
4994 
4995  for (int i = 0; i < addr_len; ++i)
4996  {
4997  const char *fmt = (i == 0) ?
4998  "%s%sc interface ipv6 set dns %s static %s"
4999  : "%s%sc interface ipv6 add dns %s %s";
5000  argv_printf(&argv, fmt, get_win_sys_path(),
5001  NETSH_PATH_SUFFIX, flex_name,
5002  print_in6_addr(addr_list[i], 0, &gc));
5003 
5004  /* disable slow address validation on Windows 7 and higher */
5005  if (win32_version_info() >= WIN_7)
5006  {
5007  argv_printf_cat(&argv, "%s", "validate=no");
5008  }
5009 
5010  /* Treat errors while adding as non-fatal as we do not check for duplicates */
5011  netsh_command(&argv, 1, (i==0) ? M_FATAL : M_NONFATAL);
5012  }
5013 
5014  argv_reset(&argv);
5015  gc_free(&gc);
5016 }
5017 
5018 static void
5019 netsh_ifconfig_options(const char *type,
5020  const in_addr_t *addr_list,
5021  const int addr_len,
5022  const IP_ADDR_STRING *current,
5023  const char *flex_name,
5024  const bool test_first)
5025 {
5026  struct gc_arena gc = gc_new();
5027  struct argv argv = argv_new();
5028  bool delete_first = false;
5029 
5030  /* first check if we should delete existing DNS/WINS settings from TAP interface */
5031  if (test_first)
5032  {
5033  if (!ip_addr_one_to_one(addr_list, addr_len, current))
5034  {
5035  delete_first = true;
5036  }
5037  }
5038  else
5039  {
5040  delete_first = true;
5041  }
5042 
5043  /* delete existing DNS/WINS settings from TAP interface */
5044  if (delete_first)
5045  {
5046  argv_printf(&argv, "%s%sc interface ip delete %s %s all",
5047  get_win_sys_path(),
5049  type,
5050  flex_name);
5051  netsh_command(&argv, 2, M_FATAL);
5052  }
5053 
5054  /* add new DNS/WINS settings to TAP interface */
5055  {
5056  int count = 0;
5057  int i;
5058  for (i = 0; i < addr_len; ++i)
5059  {
5060  if (delete_first || !test_first || !ip_addr_member_of(addr_list[i], current))
5061  {
5062  const char *fmt = count ?
5063  "%s%sc interface ip add %s %s %s"
5064  : "%s%sc interface ip set %s %s static %s";
5065 
5066  argv_printf(&argv, fmt,
5067  get_win_sys_path(),
5069  type,
5070  flex_name,
5071  print_in_addr_t(addr_list[i], 0, &gc));
5072  netsh_command(&argv, 2, M_FATAL);
5073 
5074  ++count;
5075  }
5076  else
5077  {
5078  msg(M_INFO, "NETSH: \"%s\" %s %s [already set]",
5079  flex_name,
5080  type,
5081  print_in_addr_t(addr_list[i], 0, &gc));
5082  }
5083  }
5084  }
5085 
5086  argv_reset(&argv);
5087  gc_free(&gc);
5088 }
5089 
5090 static void
5091 init_ip_addr_string2(IP_ADDR_STRING *dest, const IP_ADDR_STRING *src1, const IP_ADDR_STRING *src2)
5092 {
5093  CLEAR(dest[0]);
5094  CLEAR(dest[1]);
5095  if (src1)
5096  {
5097  dest[0] = *src1;
5098  dest[0].Next = NULL;
5099  }
5100  if (src2)
5101  {
5102  dest[1] = *src2;
5103  dest[0].Next = &dest[1];
5104  dest[1].Next = NULL;
5105  }
5106 }
5107 
5108 static void
5110  const char *flex_name,
5111  const in_addr_t ip,
5112  const in_addr_t netmask,
5113  const unsigned int flags)
5114 {
5115  struct gc_arena gc = gc_new();
5116  struct argv argv = argv_new();
5117  const IP_ADAPTER_INFO *ai = NULL;
5118  const IP_PER_ADAPTER_INFO *pai = NULL;
5119 
5120  if (flags & NI_TEST_FIRST)
5121  {
5122  const IP_ADAPTER_INFO *list = get_adapter_info_list(&gc);
5123  const int index = get_adapter_index_flexible(flex_name);
5124  ai = get_adapter(list, index);
5125  pai = get_per_adapter_info(index, &gc);
5126  }
5127 
5128  if (flags & NI_IP_NETMASK)
5129  {
5130  if (test_adapter_ip_netmask(ai, ip, netmask))
5131  {
5132  msg(M_INFO, "NETSH: \"%s\" %s/%s [already set]",
5133  flex_name,
5134  print_in_addr_t(ip, 0, &gc),
5135  print_in_addr_t(netmask, 0, &gc));
5136  }
5137  else
5138  {
5139  /* example: netsh interface ip set address my-tap static 10.3.0.1 255.255.255.0 */
5140  argv_printf(&argv, "%s%sc interface ip set address %s static %s %s",
5141  get_win_sys_path(),
5143  flex_name,
5144  print_in_addr_t(ip, 0, &gc),
5145  print_in_addr_t(netmask, 0, &gc));
5146 
5147  netsh_command(&argv, 4, M_FATAL);
5148  }
5149  }
5150 
5151  /* set WINS/DNS options */
5152  if (flags & NI_OPTIONS)
5153  {
5154  IP_ADDR_STRING wins[2];
5155  CLEAR(wins[0]);
5156  CLEAR(wins[1]);
5157 
5158  netsh_ifconfig_options("dns",
5159  to->dns,
5160  to->dns_len,
5161  pai ? &pai->DnsServerList : NULL,
5162  flex_name,
5163  BOOL_CAST(flags & NI_TEST_FIRST));
5164  if (ai && ai->HaveWins)
5165  {
5166  init_ip_addr_string2(wins, &ai->PrimaryWinsServer, &ai->SecondaryWinsServer);
5167  }
5168 
5169  netsh_ifconfig_options("wins",
5170  to->wins,
5171  to->wins_len,
5172  ai ? wins : NULL,
5173  flex_name,
5174  BOOL_CAST(flags & NI_TEST_FIRST));
5175  }
5176 
5177  argv_reset(&argv);
5178  gc_free(&gc);
5179 }
5180 
5181 static void
5183  const char *actual_name)
5184 {
5185  struct argv argv = argv_new();
5186 
5187  /* example: netsh interface ip set address my-tap dhcp */
5188  argv_printf(&argv,
5189  "%s%sc interface ip set address %s dhcp",
5190  get_win_sys_path(),
5192  actual_name);
5193 
5194  netsh_command(&argv, 4, M_FATAL);
5195 
5196  argv_reset(&argv);
5197 }
5198 
5199 /* Enable dhcp on tap adapter using iservice */
5200 static bool
5201 service_enable_dhcp(const struct tuntap *tt)
5202 {
5203  DWORD len;
5204  bool ret = false;
5205  ack_message_t ack;
5206  struct gc_arena gc = gc_new();
5207  HANDLE pipe = tt->options.msg_channel;
5208 
5210  .header = {
5212  sizeof(enable_dhcp_message_t),
5213  0
5214  },
5215  .iface = { .index = tt->adapter_index, .name = "" }
5216  };
5217 
5218  if (!send_msg_iservice(pipe, &dhcp, sizeof(dhcp), &ack, "Enable_dhcp"))
5219  {
5220  goto out;
5221  }
5222 
5223  if (ack.error_number != NO_ERROR)
5224  {
5225  msg(M_NONFATAL, "TUN: enabling dhcp using service failed: %s [status=%u if_index=%d]",
5226  strerror_win32(ack.error_number, &gc), ack.error_number, dhcp.iface.index);
5227  }
5228  else
5229  {
5230  msg(M_INFO, "DHCP enabled on interface %d using service", dhcp.iface.index);
5231  ret = true;
5232  }
5233 
5234 out:
5235  gc_free(&gc);
5236  return ret;
5237 }
5238 
5239 /*
5240  * Return a TAP name for netsh commands.
5241  */
5242 static const char *
5243 netsh_get_id(const char *dev_node, struct gc_arena *gc)
5244 {
5245  const struct tap_reg *tap_reg = get_tap_reg(gc);
5246  const struct panel_reg *panel_reg = get_panel_reg(gc);
5247  struct buffer actual = alloc_buf_gc(256, gc);
5248  const char *guid;
5249 
5250  at_least_one_tap_win(tap_reg);
5251 
5252  if (dev_node)
5253  {
5254  guid = get_device_guid(dev_node, BPTR(&actual), BCAP(&actual), tap_reg, panel_reg, gc);
5255  }
5256  else
5257  {
5258  guid = get_unspecified_device_guid(0, BPTR(&actual), BCAP(&actual), tap_reg, panel_reg, gc);
5259 
5260  if (get_unspecified_device_guid(1, NULL, 0, tap_reg, panel_reg, gc)) /* ambiguous if more than one TAP-Windows adapter */
5261  {
5262  guid = NULL;
5263  }
5264  }
5265 
5266  if (!guid)
5267  {
5268  return "NULL"; /* not found */
5269  }
5270  else if (strcmp(BPTR(&actual), "NULL"))
5271  {
5272  return BPTR(&actual); /* control panel name */
5273  }
5274  else
5275  {
5276  return guid; /* no control panel name, return GUID instead */
5277  }
5278 }
5279 
5280 /*
5281  * Called iteratively on TAP-Windows wait-for-initialization polling loop
5282  */
5283 void
5284 tun_standby_init(struct tuntap *tt)
5285 {
5286  tt->standby_iter = 0;
5287 }
5288 
5289 bool
5290 tun_standby(struct tuntap *tt)
5291 {
5292  bool ret = true;
5293  ++tt->standby_iter;
5295  {
5297  {
5298  msg(M_INFO, "NOTE: now trying netsh (this may take some time)");
5299  netsh_ifconfig(&tt->options,
5300  tt->actual_name,
5301  tt->local,
5302  tt->adapter_netmask,
5304  }
5305  else if (tt->standby_iter >= IPW32_SET_ADAPTIVE_TRY_NETSH*2)
5306  {
5307  ret = false;
5308  }
5309  }
5310  return ret;
5311 }
5312 
5313 /*
5314  * Convert DHCP options from the command line / config file
5315  * into a raw DHCP-format options string.
5316  */
5317 
5318 static void
5319 write_dhcp_u8(struct buffer *buf, const int type, const int data, bool *error)
5320 {
5321  if (!buf_safe(buf, 3))
5322  {
5323  *error = true;
5324  msg(M_WARN, "write_dhcp_u8: buffer overflow building DHCP options");
5325  return;
5326  }
5327  buf_write_u8(buf, type);
5328  buf_write_u8(buf, 1);
5329  buf_write_u8(buf, data);
5330 }
5331 
5332 static void
5333 write_dhcp_u32_array(struct buffer *buf, const int type, const uint32_t *data, const unsigned int len, bool *error)
5334 {
5335  if (len > 0)
5336  {
5337  int i;
5338  const int size = len * sizeof(uint32_t);
5339 
5340  if (!buf_safe(buf, 2 + size))
5341  {
5342  *error = true;
5343  msg(M_WARN, "write_dhcp_u32_array: buffer overflow building DHCP options");
5344  return;
5345  }
5346  if (size < 1 || size > 255)
5347  {
5348  *error = true;
5349  msg(M_WARN, "write_dhcp_u32_array: size (%d) must be > 0 and <= 255", size);
5350  return;
5351  }
5352  buf_write_u8(buf, type);
5353  buf_write_u8(buf, size);
5354  for (i = 0; i < len; ++i)
5355  {
5356  buf_write_u32(buf, data[i]);
5357  }
5358  }
5359 }
5360 
5361 static void
5362 write_dhcp_str(struct buffer *buf, const int type, const char *str, bool *error)
5363 {
5364  const int len = strlen(str);
5365  if (!buf_safe(buf, 2 + len))
5366  {
5367  *error = true;
5368  msg(M_WARN, "write_dhcp_str: buffer overflow building DHCP options");
5369  return;
5370  }
5371  if (len < 1 || len > 255)
5372  {
5373  *error = true;
5374  msg(M_WARN, "write_dhcp_str: string '%s' must be > 0 bytes and <= 255 bytes", str);
5375  return;
5376  }
5377  buf_write_u8(buf, type);
5378  buf_write_u8(buf, len);
5379  buf_write(buf, str, len);
5380 }
5381 
5382 static bool
5383 build_dhcp_options_string(struct buffer *buf, const struct tuntap_options *o)
5384 {
5385  bool error = false;
5386  if (o->domain)
5387  {
5388  write_dhcp_str(buf, 15, o->domain, &error);
5389  }
5390 
5391  if (o->netbios_scope)
5392  {
5393  write_dhcp_str(buf, 47, o->netbios_scope, &error);
5394  }
5395 
5396  if (o->netbios_node_type)
5397  {
5398  write_dhcp_u8(buf, 46, o->netbios_node_type, &error);
5399  }
5400 
5401  write_dhcp_u32_array(buf, 6, (uint32_t *)o->dns, o->dns_len, &error);
5402  write_dhcp_u32_array(buf, 44, (uint32_t *)o->wins, o->wins_len, &error);
5403  write_dhcp_u32_array(buf, 42, (uint32_t *)o->ntp, o->ntp_len, &error);
5404  write_dhcp_u32_array(buf, 45, (uint32_t *)o->nbdd, o->nbdd_len, &error);
5405 
5406  /* the MS DHCP server option 'Disable Netbios-over-TCP/IP
5407  * is implemented as vendor option 001, value 002.
5408  * A value of 001 means 'leave NBT alone' which is the default */
5409  if (o->disable_nbt)
5410  {
5411  if (!buf_safe(buf, 8))
5412  {
5413  msg(M_WARN, "build_dhcp_options_string: buffer overflow building DHCP options");
5414  return false;
5415  }
5416  buf_write_u8(buf, 43);
5417  buf_write_u8(buf, 6);/* total length field */
5418  buf_write_u8(buf, 0x001);
5419  buf_write_u8(buf, 4);/* length of the vendor specified field */
5420  buf_write_u32(buf, 0x002);
5421  }
5422  return !error;
5423 }
5424 
5425 static void
5426 fork_dhcp_action(struct tuntap *tt)
5427 {
5428  if (tt->options.dhcp_pre_release || tt->options.dhcp_renew)
5429  {
5430  struct gc_arena gc = gc_new();
5431  struct buffer cmd = alloc_buf_gc(256, &gc);
5432  const int verb = 3;
5433  const int pre_sleep = 1;
5434 
5435  buf_printf(&cmd, "openvpn --verb %d --tap-sleep %d", verb, pre_sleep);
5436  if (tt->options.dhcp_pre_release)
5437  {
5438  buf_printf(&cmd, " --dhcp-pre-release");
5439  }
5440  if (tt->options.dhcp_renew)
5441  {
5442  buf_printf(&cmd, " --dhcp-renew");
5443  }
5444  buf_printf(&cmd, " --dhcp-internal %lu", tt->adapter_index);
5445 
5446  fork_to_self(BSTR(&cmd));
5447  gc_free(&gc);
5448  }
5449 }
5450 
5451 static void
5452 register_dns_service(const struct tuntap *tt)
5453 {
5454  HANDLE msg_channel = tt->options.msg_channel;
5455  ack_message_t ack;
5456  struct gc_arena gc = gc_new();
5457 
5458  message_header_t rdns = { msg_register_dns, sizeof(message_header_t), 0 };
5459 
5460  if (!send_msg_iservice(msg_channel, &rdns, sizeof(rdns), &ack, "Register_dns"))
5461  {
5462  gc_free(&gc);
5463  return;
5464  }
5465 
5466  else if (ack.error_number != NO_ERROR)
5467  {
5468  msg(M_WARN, "Register_dns failed using service: %s [status=0x%x]",
5469  strerror_win32(ack.error_number, &gc), ack.error_number);
5470  }
5471 
5472  else
5473  {
5474  msg(M_INFO, "Register_dns request sent to the service");
5475  }
5476 
5477  gc_free(&gc);
5478 }
5479 
5480 void
5481 fork_register_dns_action(struct tuntap *tt)
5482 {
5483  if (tt && tt->options.register_dns && tt->options.msg_channel)
5484  {
5486  }
5487  else if (tt && tt->options.register_dns)
5488  {
5489  struct gc_arena gc = gc_new();
5490  struct buffer cmd = alloc_buf_gc(256, &gc);
5491  const int verb = 3;
5492 
5493  buf_printf(&cmd, "openvpn --verb %d --register-dns --rdns-internal", verb);
5494  fork_to_self(BSTR(&cmd));
5495  gc_free(&gc);
5496  }
5497 }
5498 
5499 static uint32_t
5500 dhcp_masq_addr(const in_addr_t local, const in_addr_t netmask, const int offset)
5501 {
5502  struct gc_arena gc = gc_new();
5503  in_addr_t dsa; /* DHCP server addr */
5504 
5505  if (offset < 0)
5506  {
5507  dsa = (local | (~netmask)) + offset;
5508  }
5509  else
5510  {
5511  dsa = (local & netmask) + offset;
5512  }
5513 
5514  if (dsa == local)
5515  {
5516  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));
5517  }
5518 
5519  if ((local & netmask) != (dsa & netmask))
5520  {
5521  msg(M_FATAL, "ERROR: --ip-win32 dynamic [offset] : offset is outside of --ifconfig subnet");
5522  }
5523 
5524  gc_free(&gc);
5525  return htonl(dsa);
5526 }
5527 
5528 void
5529 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
5530 {
5531  struct gc_arena gc = gc_new();
5532  char device_path[256];
5533  const char *device_guid = NULL;
5534  DWORD len;
5535  bool dhcp_masq = false;
5536  bool dhcp_masq_post = false;
5537 
5538  /*netcmd_semaphore_lock ();*/
5539 
5540  msg( M_INFO, "open_tun");
5541 
5542  if (tt->type == DEV_TYPE_NULL)
5543  {
5544  open_null(tt);
5545  gc_free(&gc);
5546  return;
5547  }
5548  else if (tt->type == DEV_TYPE_TAP || tt->type == DEV_TYPE_TUN)
5549  {
5550  }
5551  else
5552  {
5553  msg(M_FATAL|M_NOPREFIX, "Unknown virtual device type: '%s'", dev);
5554  }
5555 
5556  /*
5557  * Lookup the device name in the registry, using the --dev-node high level name.
5558  */
5559  {
5560  const struct tap_reg *tap_reg = get_tap_reg(&gc);
5561  const struct panel_reg *panel_reg = get_panel_reg(&gc);
5562  char actual_buffer[256];
5563 
5564  at_least_one_tap_win(tap_reg);
5565 
5566  if (dev_node)
5567  {
5568  /* Get the device GUID for the device specified with --dev-node. */
5569  device_guid = get_device_guid(dev_node, actual_buffer, sizeof(actual_buffer), tap_reg, panel_reg, &gc);
5570 
5571  if (!device_guid)
5572  {
5573  msg(M_FATAL, "TAP-Windows adapter '%s' not found", dev_node);
5574  }
5575 
5576  /* Open Windows TAP-Windows adapter */
5577  openvpn_snprintf(device_path, sizeof(device_path), "%s%s%s",
5578  USERMODEDEVICEDIR,
5579  device_guid,
5580  TAP_WIN_SUFFIX);
5581 
5582  tt->hand = CreateFile(
5583  device_path,
5584  GENERIC_READ | GENERIC_WRITE,
5585  0, /* was: FILE_SHARE_READ */
5586  0,
5587  OPEN_EXISTING,
5588  FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
5589  0
5590  );
5591 
5592  if (tt->hand == INVALID_HANDLE_VALUE)
5593  {
5594  msg(M_ERR, "CreateFile failed on TAP device: %s", device_path);
5595  }
5596  }
5597  else
5598  {
5599  int device_number = 0;
5600 
5601  /* Try opening all TAP devices until we find one available */
5602  while (true)
5603  {
5604  device_guid = get_unspecified_device_guid(device_number,
5605  actual_buffer,
5606  sizeof(actual_buffer),
5607  tap_reg,
5608  panel_reg,
5609  &gc);
5610 
5611  if (!device_guid)
5612  {
5613  msg(M_FATAL, "All TAP-Windows adapters on this system are currently in use.");
5614  }
5615 
5616  /* Open Windows TAP-Windows adapter */
5617  openvpn_snprintf(device_path, sizeof(device_path), "%s%s%s",
5618  USERMODEDEVICEDIR,
5619  device_guid,
5620  TAP_WIN_SUFFIX);
5621 
5622  tt->hand = CreateFile(
5623  device_path,
5624  GENERIC_READ | GENERIC_WRITE,
5625  0, /* was: FILE_SHARE_READ */
5626  0,
5627  OPEN_EXISTING,
5628  FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
5629  0
5630  );
5631 
5632  if (tt->hand == INVALID_HANDLE_VALUE)
5633  {
5634  msg(D_TUNTAP_INFO, "CreateFile failed on TAP device: %s", device_path);
5635  }
5636  else
5637  {
5638  break;
5639  }
5640 
5641  device_number++;
5642  }
5643  }
5644 
5645  /* translate high-level device name into a device instance
5646  * GUID using the registry */
5647  tt->actual_name = string_alloc(actual_buffer, NULL);
5648  }
5649 
5650  msg(M_INFO, "TAP-WIN32 device [%s] opened: %s", tt->actual_name, device_path);
5651  tt->adapter_index = get_adapter_index(device_guid);
5652 
5653  /* get driver version info */
5654  {
5655  ULONG info[3];
5656  CLEAR(info);
5657  if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_VERSION,
5658  &info, sizeof(info),
5659  &info, sizeof(info), &len, NULL))
5660  {
5661  msg(D_TUNTAP_INFO, "TAP-Windows Driver Version %d.%d %s",
5662  (int) info[0],
5663  (int) info[1],
5664  (info[2] ? "(DEBUG)" : ""));
5665 
5666  }
5667  if (!(info[0] == TAP_WIN_MIN_MAJOR && info[1] >= TAP_WIN_MIN_MINOR))
5668  {
5669  msg(M_FATAL, "ERROR: This version of " PACKAGE_NAME " requires a TAP-Windows 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.",
5672  }
5673 
5674  /* usage of numeric constants is ugly, but this is really tied to
5675  * *this* version of the driver
5676  */
5677  if (tt->type == DEV_TYPE_TUN
5678  && info[0] == 9 && info[1] < 8)
5679  {
5680  msg( M_INFO, "WARNING: Tap-Win32 driver version %d.%d does not support IPv6 in TUN mode. IPv6 will not work. Upgrade your Tap-Win32 driver.", (int) info[0], (int) info[1] );
5681  }
5682 
5683  /* tap driver 9.8 (2.2.0 and 2.2.1 release) is buggy
5684  */
5685  if (tt->type == DEV_TYPE_TUN
5686  && info[0] == 9 && info[1] == 8)
5687  {
5688  msg( M_FATAL, "ERROR: Tap-Win32 driver version %d.%d is buggy regarding small IPv4 packets in TUN mode. Upgrade your Tap-Win32 driver.", (int) info[0], (int) info[1] );
5689  }
5690  }
5691 
5692  /* get driver MTU */
5693  {
5694  ULONG mtu;
5695  if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_MTU,
5696  &mtu, sizeof(mtu),
5697  &mtu, sizeof(mtu), &len, NULL))
5698  {
5699  tt->post_open_mtu = (int) mtu;
5700  msg(D_MTU_INFO, "TAP-Windows MTU=%d", (int) mtu);
5701  }
5702  }
5703 
5704  /*
5705  * Preliminaries for setting TAP-Windows adapter TCP/IP
5706  * properties via --ip-win32 dynamic or --ip-win32 adaptive.
5707  */
5708  if (tt->did_ifconfig_setup)
5709  {
5711  {
5712  /*
5713  * If adapter is set to non-DHCP, set to DHCP mode.
5714  */
5716  {
5717  /* try using the service if available, else directly execute netsh */
5718  if (tt->options.msg_channel)
5719  {
5720  service_enable_dhcp(tt);
5721  }
5722  else
5723  {
5725  }
5726  }
5727  dhcp_masq = true;
5728  dhcp_masq_post = true;
5729  }
5730  else if (tt->options.ip_win32_type == IPW32_SET_ADAPTIVE)
5731  {
5732  /*
5733  * If adapter is set to non-DHCP, use netsh right away.
5734  */
5736  {
5737  netsh_ifconfig(&tt->options,
5738  tt->actual_name,
5739  tt->local,
5740  tt->adapter_netmask,
5742  }
5743  else
5744  {
5745  dhcp_masq = true;
5746  }
5747  }
5748  }
5749 
5750  /* set point-to-point mode if TUN device */
5751 
5752  if (tt->type == DEV_TYPE_TUN)
5753  {
5755  {
5756  msg(M_FATAL, "ERROR: --dev tun also requires --ifconfig");
5757  }
5758 
5759  /* send 0/0/0 to the TAP driver even if we have no IPv4 configured to
5760  * ensure it is somehow initialized.
5761  */
5762  if (!tt->did_ifconfig_setup || tt->topology == TOP_SUBNET)
5763  {
5764  in_addr_t ep[3];
5765  BOOL status;
5766 
5767  ep[0] = htonl(tt->local);
5768  ep[1] = htonl(tt->local & tt->remote_netmask);
5769  ep[2] = htonl(tt->remote_netmask);
5770 
5771  status = DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_TUN,
5772  ep, sizeof(ep),
5773  ep, sizeof(ep), &len, NULL);
5774 
5775  if (tt->did_ifconfig_setup)
5776  {
5777  msg(status ? M_INFO : M_FATAL, "Set TAP-Windows TUN subnet mode network/local/netmask = %s/%s/%s [%s]",
5778  print_in_addr_t(ep[1], IA_NET_ORDER, &gc),
5779  print_in_addr_t(ep[0], IA_NET_ORDER, &gc),
5780  print_in_addr_t(ep[2], IA_NET_ORDER, &gc),
5781  status ? "SUCCEEDED" : "FAILED");
5782  }
5783  else
5784  {
5785  msg(status ? M_INFO : M_FATAL, "Set TAP-Windows TUN with fake IPv4 [%s]",
5786  status ? "SUCCEEDED" : "FAILED");
5787  }
5788  }
5789  else
5790  {
5791 
5792  in_addr_t ep[2];
5793  ep[0] = htonl(tt->local);
5794  ep[1] = htonl(tt->remote_netmask);
5795 
5796  if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_POINT_TO_POINT,
5797  ep, sizeof(ep),
5798  ep, sizeof(ep), &len, NULL))
5799  {
5800  msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a DeviceIoControl call to set Point-to-Point mode, which is required for --dev tun");
5801  }
5802  }
5803  }
5804 
5805  /* should we tell the TAP-Windows driver to masquerade as a DHCP server as a means
5806  * of setting the adapter address? */
5807  if (dhcp_masq)
5808  {
5809  uint32_t ep[4];
5810 
5811  /* We will answer DHCP requests with a reply to set IP/subnet to these values */
5812  ep[0] = htonl(tt->local);
5813  ep[1] = htonl(tt->adapter_netmask);
5814 
5815  /* At what IP address should the DHCP server masquerade at? */
5816  if (tt->type == DEV_TYPE_TUN)
5817  {
5818  if (tt->topology == TOP_SUBNET)
5819  {
5821  {
5823  }
5824  else
5825  {
5826  ep[2] = dhcp_masq_addr(tt->local, tt->remote_netmask, -1);
5827  }
5828  }
5829  else
5830  {
5831  ep[2] = htonl(tt->remote_netmask);
5832  }
5833  }
5834  else
5835  {
5836  ASSERT(tt->type == DEV_TYPE_TAP);
5838  }
5839 
5840  /* lease time in seconds */
5841  ep[3] = (uint32_t) tt->options.dhcp_lease_time;
5842 
5843  ASSERT(ep[3] > 0);
5844 
5845 #ifndef SIMULATE_DHCP_FAILED /* this code is disabled to simulate bad DHCP negotiation */
5846  if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_MASQ,
5847  ep, sizeof(ep),
5848  ep, sizeof(ep), &len, NULL))
5849  {
5850  msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a DeviceIoControl call to set TAP_WIN_IOCTL_CONFIG_DHCP_MASQ mode");
5851  }
5852 
5853  msg(M_INFO, "Notified TAP-Windows driver to set a DHCP IP/netmask of %s/%s on interface %s [DHCP-serv: %s, lease-time: %d]",
5854  print_in_addr_t(tt->local, 0, &gc),
5855  print_in_addr_t(tt->adapter_netmask, 0, &gc),
5856  device_guid,
5857  print_in_addr_t(ep[2], IA_NET_ORDER, &gc),
5858  ep[3]
5859  );
5860 
5861  /* user-supplied DHCP options capability */
5862  if (tt->options.dhcp_options)
5863  {
5864  struct buffer buf = alloc_buf(256);
5865  if (build_dhcp_options_string(&buf, &tt->options))
5866  {
5867  msg(D_DHCP_OPT, "DHCP option string: %s", format_hex(BPTR(&buf), BLEN(&buf), 0, &gc));
5868  if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_CONFIG_DHCP_SET_OPT,
5869  BPTR(&buf), BLEN(&buf),
5870  BPTR(&buf), BLEN(&buf), &len, NULL))
5871  {
5872  msg(M_FATAL, "ERROR: The TAP-Windows driver rejected a TAP_WIN_IOCTL_CONFIG_DHCP_SET_OPT DeviceIoControl call");
5873  }
5874  }
5875  else
5876  {
5877  msg(M_WARN, "DHCP option string not set due to error");
5878  }
5879  free_buf(&buf);
5880  }
5881 #endif /* ifndef SIMULATE_DHCP_FAILED */
5882  }
5883 
5884  /* set driver media status to 'connected' */
5885  {
5886  ULONG status = TRUE;
5887  if (!DeviceIoControl(tt->hand, TAP_WIN_IOCTL_SET_MEDIA_STATUS,
5888  &status, sizeof(status),
5889  &status, sizeof(status), &len, NULL))
5890  {
5891  msg(M_WARN, "WARNING: The TAP-Windows driver rejected a TAP_WIN_IOCTL_SET_MEDIA_STATUS DeviceIoControl call.");
5892  }
5893  }
5894 
5895  /* possible wait for adapter to come up */
5896  {
5897  int s = tt->options.tap_sleep;
5898  if (s > 0)
5899  {
5900  msg(M_INFO, "Sleeping for %d seconds...", s);
5901  management_sleep(s);
5902  }
5903  }
5904 
5905  /* possibly use IP Helper API to set IP address on adapter */
5906  {
5907  const DWORD index = tt->adapter_index;
5908 
5909  /* flush arp cache */
5910  if (index != TUN_ADAPTER_INDEX_INVALID)
5911  {
5912  DWORD status = -1;
5913 
5914  if (tt->options.msg_channel)
5915  {
5916  ack_message_t ack;
5918  .header = {
5920  sizeof(flush_neighbors_message_t),
5921  0
5922  },
5923  .family = AF_INET,
5924  .iface = { .index = index, .name = "" }
5925  };
5926 
5927  if (send_msg_iservice(tt->options.msg_channel, &msg, sizeof(msg),
5928  &ack, "TUN"))
5929  {
5930  status = ack.error_number;
5931  }
5932  }
5933  else
5934  {
5935  status = FlushIpNetTable(index);
5936  }
5937 
5938  if (status == NO_ERROR)
5939  {
5940  msg(M_INFO, "Successful ARP Flush on interface [%lu] %s",
5941  index,
5942  device_guid);
5943  }
5944  else if (status != -1)
5945  {
5946  msg(D_TUNTAP_INFO, "NOTE: FlushIpNetTable failed on interface [%lu] %s (status=%lu) : %s",
5947  index,
5948  device_guid,
5949  status,
5950  strerror_win32(status, &gc));
5951  }
5952  }
5953 
5954  /*
5955  * If the TAP-Windows driver is masquerading as a DHCP server
5956  * make sure the TCP/IP properties for the adapter are
5957  * set correctly.
5958  */
5959  if (dhcp_masq_post)
5960  {
5961  /* check dhcp enable status */
5962  if (dhcp_status(index) == DHCP_STATUS_DISABLED)
5963  {
5964  msg(M_WARN, "WARNING: You have selected '--ip-win32 dynamic', which will not work unless the TAP-Windows TCP/IP properties are set to 'Obtain an IP address automatically'");
5965  }
5966 
5967  /* force an explicit DHCP lease renewal on TAP adapter? */
5968  if (tt->options.dhcp_pre_release)
5969  {
5970  dhcp_release(tt);
5971  }
5972  if (tt->options.dhcp_renew)
5973  {
5974  dhcp_renew(tt);
5975  }
5976  }
5977  else
5978  {
5979  fork_dhcp_action(tt);
5980  }
5981 
5983  {
5984  DWORD status;
5985  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')";
5986 
5987  /* couldn't get adapter index */
5988  if (index == TUN_ADAPTER_INDEX_INVALID)
5989  {
5990  msg(M_FATAL, "ERROR: unable to get adapter index for interface %s -- %s",
5991  device_guid,
5992  error_suffix);
5993  }
5994 
5995  /* check dhcp enable status */
5996  if (dhcp_status(index) == DHCP_STATUS_DISABLED)
5997  {
5998  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-Windows TCP/IP properties are set to 'Obtain an IP address automatically'");
5999  }
6000 
6001  /* delete previously added IP addresses which were not
6002  * correctly deleted */
6003  delete_temp_addresses(index);
6004 
6005  /* add a new IP address */
6006  if ((status = AddIPAddress(htonl(tt->local),
6007  htonl(tt->adapter_netmask),
6008  index,
6009  &tt->ipapi_context,
6010  &tt->ipapi_instance)) == NO_ERROR)
6011  {
6012  msg(M_INFO, "Succeeded in adding a temporary IP/netmask of %s/%s to interface %s using the Win32 IP Helper API",
6013  print_in_addr_t(tt->local, 0, &gc),
6014  print_in_addr_t(tt->adapter_netmask, 0, &gc),
6015  device_guid
6016  );
6017  }
6018  else
6019  {
6020  msg(M_FATAL, "ERROR: AddIPAddress %s/%s failed on interface %s, index=%lu, status=%lu (windows error: '%s') -- %s",
6021  print_in_addr_t(tt->local, 0, &gc),
6022  print_in_addr_t(tt->adapter_netmask, 0, &gc),
6023  device_guid,
6024  index,
6025  status,
6026  strerror_win32(status, &gc),
6027  error_suffix);
6028  }
6029  tt->ipapi_context_defined = true;
6030  }
6031  }
6032  /*netcmd_semaphore_release ();*/
6033  gc_free(&gc);
6034 }
6035 
6036 const char *
6037 tap_win_getinfo(const struct tuntap *tt, struct gc_arena *gc)
6038 {
6039  if (tt && tt->hand != NULL)
6040  {
6041  struct buffer out = alloc_buf_gc(256, gc);
6042  DWORD len;
6043  if (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_INFO,
6044  BSTR(&out), BCAP(&out),
6045  BSTR(&out), BCAP(&out),
6046  &len, NULL))
6047  {
6048  return BSTR(&out);
6049  }
6050  }
6051  return NULL;
6052 }
6053 
6054 void
6055 tun_show_debug(struct tuntap *tt)
6056 {
6057  if (tt && tt->hand != NULL)
6058  {
6059  struct buffer out = alloc_buf(1024);
6060  DWORD len;
6061  while (DeviceIoControl(tt->hand, TAP_WIN_IOCTL_GET_LOG_LINE,
6062  BSTR(&out), BCAP(&out),
6063  BSTR(&out), BCAP(&out),
6064  &len, NULL))
6065  {
6066  msg(D_TAP_WIN_DEBUG, "TAP-Windows: %s", BSTR(&out));
6067  }
6068  free_buf(&out);
6069  }
6070 }
6071 
6072 void
6073 close_tun(struct tuntap *tt)
6074 {
6075  ASSERT(tt);
6076 
6077  struct gc_arena gc = gc_new();
6078 
6079  if (tt->did_ifconfig_ipv6_setup)
6080  {
6081  /* remove route pointing to interface */
6083 
6084  if (tt->options.msg_channel)
6085  {
6086  do_address_service(false, AF_INET6, tt);
6087  if (tt->options.dns6_len > 0)
6088  {
6089  do_dns6_service(false, tt);
6090  }
6091  }
6092  else
6093  {
6094  const char *ifconfig_ipv6_local;
6095  struct argv argv = argv_new();
6096 
6097  /* "store=active" is needed in Windows 8(.1) to delete the
6098  * address we added (pointed out by Cedric Tabary).
6099  */
6100 
6101  /* netsh interface ipv6 delete address \"%s\" %s */
6102  ifconfig_ipv6_local = print_in6_addr(tt->local_ipv6, 0, &gc);
6103  argv_printf(&argv,
6104  "%s%sc interface ipv6 delete address %s %s store=active",
6105  get_win_sys_path(),
6107  tt->actual_name,
6108  ifconfig_ipv6_local);
6109 
6110  netsh_command(&argv, 1, M_WARN);
6111 
6112  /* delete ipv6 dns servers if any were set */
6113  if (tt->options.dns6_len > 0)
6114  {
6115  argv_printf(&argv,
6116  "%s%sc interface ipv6 delete dns %s all",
6117  get_win_sys_path(),
6119  tt->actual_name);
6120  netsh_command(&argv, 1, M_WARN);
6121  }
6122  argv_reset(&argv);
6123  }
6124  }
6125 #if 1
6126  if (tt->ipapi_context_defined)
6127  {
6128  DWORD status;
6129  if ((status = DeleteIPAddress(tt->ipapi_context)) != NO_ERROR)
6130  {
6131  msg(M_WARN, "Warning: DeleteIPAddress[%u] failed on TAP-Windows adapter, status=%u : %s",
6132  (unsigned int)tt->ipapi_context,
6133  (unsigned int)status,
6134  strerror_win32(status, &gc));
6135  }
6136  }
6137 #endif
6138 
6139  dhcp_release(tt);
6140 
6141  if (tt->hand != NULL)
6142  {
6143  dmsg(D_WIN32_IO_LOW, "Attempting CancelIO on TAP-Windows adapter");
6144  if (!CancelIo(tt->hand))
6145  {
6146  msg(M_WARN | M_ERRNO, "Warning: CancelIO failed on TAP-Windows adapter");
6147  }
6148  }
6149 
6150  dmsg(D_WIN32_IO_LOW, "Attempting close of overlapped read event on TAP-Windows adapter");
6151  overlapped_io_close(&tt->reads);
6152 
6153  dmsg(D_WIN32_IO_LOW, "Attempting close of overlapped write event on TAP-Windows adapter");
6155 
6156  if (tt->hand != NULL)
6157  {
6158  dmsg(D_WIN32_IO_LOW, "Attempting CloseHandle on TAP-Windows adapter");
6159  if (!CloseHandle(tt->hand))
6160  {
6161  msg(M_WARN | M_ERRNO, "Warning: CloseHandle failed on TAP-Windows adapter");
6162  }
6163  }
6164 
6165  if (tt->actual_name)
6166  {
6167  free(tt->actual_name);
6168  }
6169 
6170  clear_tuntap(tt);
6171  free(tt);
6172  gc_free(&gc);
6173 }
6174 
6175 /*
6176  * Convert --ip-win32 constants between index and ascii form.
6177  */
6178 
6179 struct ipset_names {
6180  const char *short_form;
6181 };
6182 
6183 /* Indexed by IPW32_SET_x */
6184 static const struct ipset_names ipset_names[] = {
6185  {"manual"},
6186  {"netsh"},
6187  {"ipapi"},
6188  {"dynamic"},
6189  {"adaptive"}
6190 };
6191 
6192 int
6193 ascii2ipset(const char *name)
6194 {
6195  int i;
6196  ASSERT(IPW32_SET_N == SIZE(ipset_names));
6197  for (i = 0; i < IPW32_SET_N; ++i)
6198  {
6199  if (!strcmp(name, ipset_names[i].short_form))
6200  {
6201  return i;
6202  }
6203  }
6204  return -1;
6205 }
6206 
6207 const char *
6208 ipset2ascii(int index)
6209 {
6210  ASSERT(IPW32_SET_N == SIZE(ipset_names));
6211  if (index < 0 || index >= IPW32_SET_N)
6212  {
6213  return "[unknown --ip-win32 type]";
6214  }
6215  else
6216  {
6217  return ipset_names[index].short_form;
6218  }
6219 }
6220 
6221 const char *
6223 {
6224  struct buffer out = alloc_buf_gc(256, gc);
6225  int i;
6226 
6227  ASSERT(IPW32_SET_N == SIZE(ipset_names));
6228  for (i = 0; i < IPW32_SET_N; ++i)
6229  {
6230  if (i)
6231  {
6232  buf_printf(&out, " ");
6233  }
6234  buf_printf(&out, "[%s]", ipset2ascii(i));
6235  }
6236  return BSTR(&out);
6237 }
6238 
6239 #else /* generic */
6240 
6241 void
6242 open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt)
6243 {
6244  open_tun_generic(dev, dev_type, dev_node, true, tt);
6245 }
6246 
6247 void
6248 close_tun(struct tuntap *tt)
6249 {
6250  ASSERT(tt);
6251 
6252  close_tun_generic(tt);
6253  free(tt);
6254 }
6255 
6256 int
6257 write_tun(struct tuntap *tt, uint8_t *buf, int len)
6258 {
6259  return write(tt->fd, buf, len);
6260 }
6261 
6262 int
6263 read_tun(struct tuntap *tt, uint8_t *buf, int len)
6264 {
6265  return read(tt->fd, buf, len);
6266 }
6267 
6268 #endif /* if defined (TARGET_ANDROID) */
static in_addr_t generate_ifconfig_broadcast_addr(in_addr_t local, in_addr_t netmask)
Definition: tun.c:340
#define M_NONFATAL
Definition: error.h:95
int status
Definition: win32.h:204
static const char * netsh_get_id(const char *dev_node, struct gc_arena *gc)
Definition: tun.c:5243
in_addr_t gateway
Definition: route.h:120
static bool buf_write_u8(struct buffer *dest, int data)
Definition: buffer.h:713
in_addr_t addr
Definition: route.h:141
bool register_dns
Definition: tun.h:107
uint8_t version_len
Definition: proto.h:87
struct in6_addr remote_ipv6
Definition: tun.h:157
const struct panel_reg * get_panel_reg(struct gc_arena *gc)
Definition: tun.c:3558
int netbits_ipv6
Definition: tun.h:158
struct route_gateway_address gateway
Definition: route.h:165
static const char * guid_to_name(const char *guid, const struct panel_reg *panel_reg)
Definition: tun.c:3845
static void strncpynt(char *dest, const char *src, size_t maxlen)
Definition: buffer.h:348
static bool do_dns6_service(bool add, const struct tuntap *tt)
Definition: tun.c:138
struct env_set * env_set_create(struct gc_arena *gc)
Definition: env_set.c:158
struct buffer buf_init
Definition: win32.h:211
bool platform_group_get(const char *groupname, struct platform_state_group *state)
Definition: platform.c:108
int dev_type_enum(const char *dev, const char *dev_type)
Definition: tun.c:239
Definition: tun.h:131
const IP_PER_ADAPTER_INFO * get_per_adapter_info(const DWORD index, struct gc_arena *gc)
Definition: tun.c:4036
void do_ifconfig(struct tuntap *tt, const char *ifname, int tun_mtu, const struct env_set *es)
do_ifconfig - configure the tunnel interface
Definition: tun.c:1409
#define M_NOPREFIX
Definition: error.h:102
const IP_ADAPTER_INFO * get_adapter_info_list(struct gc_arena *gc)
Definition: tun.c:4009
in_addr_t ntp[N_DHCP_ADDR]
Definition: tun.h:94
struct in6_addr ipv6
Definition: openvpn-msg.h:52
#define D_OSBUF
Definition: errlevel.h:91
#define ALLOC_OBJ(dptr, type)
Definition: buffer.h:1045
struct overlapped_io writes
Definition: tun.h:163
in_addr_t network
Definition: route.h:118
void tun_standby_init(struct tuntap *tt)
Definition: tun.c:5284
#define IPW32_SET_IPAPI
Definition: tun.h:54
void free_buf(struct buffer *buf)
Definition: buffer.c:185
HANDLE read
Definition: win32.h:74
int netbios_node_type
Definition: tun.h:80
char * string_alloc(const char *str, struct gc_arena *gc)
Definition: buffer.c:688
static void write_dhcp_u32_array(struct buffer *buf, const int type, const uint32_t *data, const unsigned int len, bool *error)
Definition: tun.c:5333
#define IFCONFIG_PATH
Definition: config.h:700