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