OpenVPN
socket.c
Go to the documentation of this file.
1 /*
2  * OpenVPN -- An application to securely tunnel IP networks
3  * over a single TCP/UDP port, with support for SSL/TLS-based
4  * session authentication and key exchange,
5  * packet encryption, packet authentication, and
6  * packet compression.
7  *
8  * Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License version 2
12  * as published by the Free Software Foundation.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #elif defined(_MSC_VER)
27 #include "config-msvc.h"
28 #endif
29 
30 #include "syshead.h"
31 
32 #include "socket.h"
33 #include "fdmisc.h"
34 #include "misc.h"
35 #include "gremlin.h"
36 #include "plugin.h"
37 #include "ps.h"
38 #include "run_command.h"
39 #include "manage.h"
40 #include "misc.h"
41 #include "manage.h"
42 #include "openvpn.h"
43 #include "forward.h"
44 
45 #include "memdbg.h"
46 
47 const int proto_overhead[] = { /* indexed by PROTO_x */
48  0,
49  IPv4_UDP_HEADER_SIZE, /* IPv4 */
52  IPv6_UDP_HEADER_SIZE, /* IPv6 */
56 };
57 
58 /*
59  * Convert sockflags/getaddr_flags into getaddr_flags
60  */
61 static unsigned int
62 sf2gaf(const unsigned int getaddr_flags,
63  const unsigned int sockflags)
64 {
65  if (sockflags & SF_HOST_RANDOMIZE)
66  {
67  return getaddr_flags | GETADDR_RANDOMIZE;
68  }
69  else
70  {
71  return getaddr_flags;
72  }
73 }
74 
75 /*
76  * Functions related to the translation of DNS names to IP addresses.
77  */
78 static int
79 get_addr_generic(sa_family_t af, unsigned int flags, const char *hostname,
80  void *network, unsigned int *netbits,
81  int resolve_retry_seconds, volatile int *signal_received,
82  int msglevel)
83 {
84  char *endp, *sep, *var_host = NULL;
85  struct addrinfo *ai = NULL;
86  unsigned long bits;
87  uint8_t max_bits;
88  int ret = -1;
89 
90  if (!hostname)
91  {
92  msg(M_NONFATAL, "Can't resolve null hostname!");
93  goto out;
94  }
95 
96  /* assign family specific default values */
97  switch (af)
98  {
99  case AF_INET:
100  bits = 0;
101  max_bits = sizeof(in_addr_t) * 8;
102  break;
103 
104  case AF_INET6:
105  bits = 64;
106  max_bits = sizeof(struct in6_addr) * 8;
107  break;
108 
109  default:
110  msg(M_WARN,
111  "Unsupported AF family passed to getaddrinfo for %s (%d)",
112  hostname, af);
113  goto out;
114  }
115 
116  /* we need to modify the hostname received as input, but we don't want to
117  * touch it directly as it might be a constant string.
118  *
119  * Therefore, we clone the string here and free it at the end of the
120  * function */
121  var_host = strdup(hostname);
122  if (!var_host)
123  {
125  "Can't allocate hostname buffer for getaddrinfo");
126  goto out;
127  }
128 
129  /* check if this hostname has a /bits suffix */
130  sep = strchr(var_host, '/');
131  if (sep)
132  {
133  bits = strtoul(sep + 1, &endp, 10);
134  if ((*endp != '\0') || (bits > max_bits))
135  {
136  msg(msglevel, "IP prefix '%s': invalid '/bits' spec (%s)", hostname,
137  sep + 1);
138  goto out;
139  }
140  *sep = '\0';
141  }
142 
143  ret = openvpn_getaddrinfo(flags & ~GETADDR_HOST_ORDER, var_host, NULL,
144  resolve_retry_seconds, signal_received, af, &ai);
145  if ((ret == 0) && network)
146  {
147  struct in6_addr *ip6;
148  in_addr_t *ip4;
149 
150  switch (af)
151  {
152  case AF_INET:
153  ip4 = network;
154  *ip4 = ((struct sockaddr_in *)ai->ai_addr)->sin_addr.s_addr;
155 
156  if (flags & GETADDR_HOST_ORDER)
157  {
158  *ip4 = ntohl(*ip4);
159  }
160  break;
161 
162  case AF_INET6:
163  ip6 = network;
164  *ip6 = ((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
165  break;
166 
167  default:
168  /* can't get here because 'af' was previously checked */
169  msg(M_WARN,
170  "Unsupported AF family for %s (%d)", var_host, af);
171  goto out;
172  }
173  }
174 
175  if (netbits)
176  {
177  *netbits = bits;
178  }
179 
180  /* restore '/' separator, if any */
181  if (sep)
182  {
183  *sep = '/';
184  }
185 out:
186  freeaddrinfo(ai);
187  free(var_host);
188 
189  return ret;
190 }
191 
192 in_addr_t
193 getaddr(unsigned int flags,
194  const char *hostname,
195  int resolve_retry_seconds,
196  bool *succeeded,
197  volatile int *signal_received)
198 {
199  in_addr_t addr;
200  int status;
201 
202  status = get_addr_generic(AF_INET, flags, hostname, &addr, NULL,
203  resolve_retry_seconds, signal_received,
204  M_WARN);
205  if (status==0)
206  {
207  if (succeeded)
208  {
209  *succeeded = true;
210  }
211  return addr;
212  }
213  else
214  {
215  if (succeeded)
216  {
217  *succeeded = false;
218  }
219  return 0;
220  }
221 }
222 
223 bool
224 get_ipv6_addr(const char *hostname, struct in6_addr *network,
225  unsigned int *netbits, int msglevel)
226 {
227  if (get_addr_generic(AF_INET6, GETADDR_RESOLVE, hostname, network, netbits,
228  0, NULL, msglevel) < 0)
229  {
230  return false;
231  }
232 
233  return true; /* parsing OK, values set */
234 }
235 
236 static inline bool
237 streqnull(const char *a, const char *b)
238 {
239  if (a == NULL && b == NULL)
240  {
241  return true;
242  }
243  else if (a == NULL || b == NULL)
244  {
245  return false;
246  }
247  else
248  {
249  return streq(a, b);
250  }
251 }
252 
253 /*
254  * get_cached_dns_entry return 0 on success and -1
255  * otherwise. (like getaddrinfo)
256  */
257 static int
259  const char *hostname,
260  const char *servname,
261  int ai_family,
262  int resolve_flags,
263  struct addrinfo **ai)
264 {
265  struct cached_dns_entry *ph;
266  int flags;
267 
268  /* Only use flags that are relevant for the structure */
269  flags = resolve_flags & GETADDR_CACHE_MASK;
270 
271  for (ph = dns_cache; ph; ph = ph->next)
272  {
273  if (streqnull(ph->hostname, hostname)
274  && streqnull(ph->servname, servname)
275  && ph->ai_family == ai_family
276  && ph->flags == flags)
277  {
278  *ai = ph->ai;
279  return 0;
280  }
281  }
282  return -1;
283 }
284 
285 
286 static int
288  const char *hostname,
289  const char *servname,
290  const int af,
291  const int flags)
292 {
293  struct addrinfo *ai;
294  int status;
295 
297  hostname,
298  servname,
299  af,
300  flags,
301  &ai) == 0)
302  {
303  /* entry already cached, return success */
304  return 0;
305  }
306 
307  status = openvpn_getaddrinfo(flags, hostname, servname,
309  af, &ai);
310  if (status == 0)
311  {
312  struct cached_dns_entry *ph;
313 
314  ALLOC_OBJ_CLEAR_GC(ph, struct cached_dns_entry, &c->gc);
315  ph->ai = ai;
316  ph->hostname = hostname;
317  ph->servname = servname;
318  ph->flags = flags & GETADDR_CACHE_MASK;
319 
320  if (!c->c1.dns_cache)
321  {
322  c->c1.dns_cache = ph;
323  }
324  else
325  {
326  struct cached_dns_entry *prev = c->c1.dns_cache;
327  while (prev->next)
328  {
329  prev = prev->next;
330  }
331  prev->next = ph;
332  }
333 
335 
336  }
337  return status;
338 }
339 
340 void
342 {
343  int i;
344  struct connection_list *l = c->options.connection_list;
345  const unsigned int preresolve_flags = GETADDR_RESOLVE
348  |GETADDR_FATAL;
349 
350 
351  for (i = 0; i < l->len; ++i)
352  {
353  int status;
354  const char *remote;
355  int flags = preresolve_flags;
356 
357  struct connection_entry *ce = c->options.connection_list->array[i];
358 
359  if (proto_is_dgram(ce->proto))
360  {
361  flags |= GETADDR_DATAGRAM;
362  }
363 
365  {
366  flags |= GETADDR_RANDOMIZE;
367  }
368 
369  if (c->options.ip_remote_hint)
370  {
371  remote = c->options.ip_remote_hint;
372  }
373  else
374  {
375  remote = ce->remote;
376  }
377 
378  /* HTTP remote hostname does not need to be resolved */
379  if (!ce->http_proxy_options)
380  {
381  status = do_preresolve_host(c, remote, ce->remote_port, ce->af, flags);
382  if (status != 0)
383  {
384  goto err;
385  }
386  }
387 
388  /* Preresolve proxy */
389  if (ce->http_proxy_options)
390  {
391  status = do_preresolve_host(c,
394  ce->af,
395  preresolve_flags);
396 
397  if (status != 0)
398  {
399  goto err;
400  }
401  }
402 
403  if (ce->socks_proxy_server)
404  {
405  status = do_preresolve_host(c,
406  ce->socks_proxy_server,
407  ce->socks_proxy_port,
408  ce->af,
409  flags);
410  if (status != 0)
411  {
412  goto err;
413  }
414  }
415 
416  if (ce->bind_local)
417  {
418  flags |= GETADDR_PASSIVE;
419  flags &= ~GETADDR_RANDOMIZE;
420  status = do_preresolve_host(c, ce->local, ce->local_port, ce->af, flags);
421  if (status != 0)
422  {
423  goto err;
424  }
425 
426  }
427 
428  }
429  return;
430 
431 err:
432  throw_signal_soft(SIGHUP, "Preresolving failed");
433 }
434 
435 /*
436  * Translate IPv4/IPv6 addr or hostname into struct addrinfo
437  * If resolve error, try again for resolve_retry_seconds seconds.
438  */
439 int
441  const char *hostname,
442  const char *servname,
443  int resolve_retry_seconds,
444  volatile int *signal_received,
445  int ai_family,
446  struct addrinfo **res)
447 {
448  struct addrinfo hints;
449  int status;
450  int sigrec = 0;
451  int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
452  struct gc_arena gc = gc_new();
453  const char *print_hostname;
454  const char *print_servname;
455 
456  ASSERT(res);
457 
458  ASSERT(hostname || servname);
459  ASSERT(!(flags & GETADDR_HOST_ORDER));
460 
461  if (servname)
462  {
463  print_servname = servname;
464  }
465  else
466  {
467  print_servname = "";
468  }
469 
470  if (flags & GETADDR_MSG_VIRT_OUT)
471  {
472  msglevel |= M_MSG_VIRT_OUT;
473  }
474 
476  && !signal_received)
477  {
478  signal_received = &sigrec;
479  }
480 
481  /* try numeric ipv6 addr first */
482  CLEAR(hints);
483  hints.ai_family = ai_family;
484  hints.ai_flags = AI_NUMERICHOST;
485 
486  if (flags & GETADDR_PASSIVE)
487  {
488  hints.ai_flags |= AI_PASSIVE;
489  }
490 
491  if (flags & GETADDR_DATAGRAM)
492  {
493  hints.ai_socktype = SOCK_DGRAM;
494  }
495  else
496  {
497  hints.ai_socktype = SOCK_STREAM;
498  }
499 
500  status = getaddrinfo(hostname, servname, &hints, res);
501 
502  if (status != 0) /* parse as numeric address failed? */
503  {
504  const int fail_wait_interval = 5; /* seconds */
505  /* Add +4 to cause integer division rounding up (1 + 4) = 5, (0+4)/5=0 */
506  int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 :
507  ((resolve_retry_seconds + 4)/ fail_wait_interval);
508  const char *fmt;
509  int level = 0;
510 
511  if (hostname && (flags & GETADDR_RANDOMIZE))
512  {
513  hostname = hostname_randomize(hostname, &gc);
514  }
515 
516  if (hostname)
517  {
518  print_hostname = hostname;
519  }
520  else
521  {
522  print_hostname = "undefined";
523  }
524 
525  fmt = "RESOLVE: Cannot resolve host address: %s:%s (%s)";
526  if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
527  && !resolve_retry_seconds)
528  {
529  fmt = "RESOLVE: Cannot resolve host address: %s:%s (%s) (I would have retried this name query if you had specified the --resolv-retry option.)";
530  }
531 
532  if (!(flags & GETADDR_RESOLVE) || status == EAI_FAIL)
533  {
534  msg(msglevel, "RESOLVE: Cannot parse IP address: %s:%s (%s)",
535  print_hostname,print_servname, gai_strerror(status));
536  goto done;
537  }
538 
539 #ifdef ENABLE_MANAGEMENT
541  {
542  if (management)
543  {
546  NULL,
547  NULL,
548  NULL,
549  NULL,
550  NULL);
551  }
552  }
553 #endif
554 
555  /*
556  * Resolve hostname
557  */
558  while (true)
559  {
560 #ifndef _WIN32
561  res_init();
562 #endif
563  /* try hostname lookup */
564  hints.ai_flags &= ~AI_NUMERICHOST;
565  dmsg(D_SOCKET_DEBUG, "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
566  flags, hints.ai_family, hints.ai_socktype);
567  status = getaddrinfo(hostname, servname, &hints, res);
568 
569  if (signal_received)
570  {
571  get_signal(signal_received);
572  if (*signal_received) /* were we interrupted by a signal? */
573  {
574  if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
575  {
576  msg(level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
577  *signal_received = 0;
578  }
579  else
580  {
581  /* turn success into failure (interrupted syscall) */
582  if (0 == status)
583  {
584  ASSERT(res);
585  freeaddrinfo(*res);
586  *res = NULL;
587  status = EAI_AGAIN; /* = temporary failure */
588  errno = EINTR;
589  }
590  goto done;
591  }
592  }
593  }
594 
595  /* success? */
596  if (0 == status)
597  {
598  break;
599  }
600 
601  /* resolve lookup failed, should we
602  * continue or fail? */
603  level = msglevel;
604  if (resolve_retries > 0)
605  {
606  level = D_RESOLVE_ERRORS;
607  }
608 
609  msg(level,
610  fmt,
611  print_hostname,
612  print_servname,
613  gai_strerror(status));
614 
615  if (--resolve_retries <= 0)
616  {
617  goto done;
618  }
619 
620  management_sleep(fail_wait_interval);
621  }
622 
623  ASSERT(res);
624 
625  /* hostname resolve succeeded */
626 
627  /*
628  * Do not choose an IP Addresse by random or change the order *
629  * of IP addresses, doing so will break RFC 3484 address selection *
630  */
631  }
632  else
633  {
634  /* IP address parse succeeded */
635  if (flags & GETADDR_RANDOMIZE)
636  {
637  msg(M_WARN, "WARNING: ignoring --remote-random-hostname because the hostname is an IP address");
638  }
639  }
640 
641 done:
642  if (signal_received && *signal_received)
643  {
644  int level = 0;
645  if (flags & GETADDR_FATAL_ON_SIGNAL)
646  {
647  level = M_FATAL;
648  }
649  else if (flags & GETADDR_WARN_ON_SIGNAL)
650  {
651  level = M_WARN;
652  }
653  msg(level, "RESOLVE: signal received during DNS resolution attempt");
654  }
655 
656  gc_free(&gc);
657  return status;
658 }
659 
660 /*
661  * We do our own inet_aton because the glibc function
662  * isn't very good about error checking.
663  */
664 int
665 openvpn_inet_aton(const char *dotted_quad, struct in_addr *addr)
666 {
667  unsigned int a, b, c, d;
668 
669  CLEAR(*addr);
670  if (sscanf(dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
671  {
672  if (a < 256 && b < 256 && c < 256 && d < 256)
673  {
674  addr->s_addr = htonl(a<<24 | b<<16 | c<<8 | d);
675  return OIA_IP; /* good dotted quad */
676  }
677  }
678  if (string_class(dotted_quad, CC_DIGIT|CC_DOT, 0))
679  {
680  return OIA_ERROR; /* probably a badly formatted dotted quad */
681  }
682  else
683  {
684  return OIA_HOSTNAME; /* probably a hostname */
685  }
686 }
687 
688 bool
689 ip_addr_dotted_quad_safe(const char *dotted_quad)
690 {
691  /* verify non-NULL */
692  if (!dotted_quad)
693  {
694  return false;
695  }
696 
697  /* verify length is within limits */
698  if (strlen(dotted_quad) > 15)
699  {
700  return false;
701  }
702 
703  /* verify that all chars are either numeric or '.' and that no numeric
704  * substring is greater than 3 chars */
705  {
706  int nnum = 0;
707  const char *p = dotted_quad;
708  int c;
709 
710  while ((c = *p++))
711  {
712  if (c >= '0' && c <= '9')
713  {
714  ++nnum;
715  if (nnum > 3)
716  {
717  return false;
718  }
719  }
720  else if (c == '.')
721  {
722  nnum = 0;
723  }
724  else
725  {
726  return false;
727  }
728  }
729  }
730 
731  /* verify that string will convert to IP address */
732  {
733  struct in_addr a;
734  return openvpn_inet_aton(dotted_quad, &a) == OIA_IP;
735  }
736 }
737 
738 bool
739 ipv6_addr_safe(const char *ipv6_text_addr)
740 {
741  /* verify non-NULL */
742  if (!ipv6_text_addr)
743  {
744  return false;
745  }
746 
747  /* verify length is within limits */
748  if (strlen(ipv6_text_addr) > INET6_ADDRSTRLEN)
749  {
750  return false;
751  }
752 
753  /* verify that string will convert to IPv6 address */
754  {
755  struct in6_addr a6;
756  return inet_pton( AF_INET6, ipv6_text_addr, &a6 ) == 1;
757  }
758 }
759 
760 static bool
761 dns_addr_safe(const char *addr)
762 {
763  if (addr)
764  {
765  const size_t len = strlen(addr);
766  return len > 0 && len <= 255 && string_class(addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
767  }
768  else
769  {
770  return false;
771  }
772 }
773 
774 bool
775 ip_or_dns_addr_safe(const char *addr, const bool allow_fqdn)
776 {
777  if (ip_addr_dotted_quad_safe(addr))
778  {
779  return true;
780  }
781  else if (allow_fqdn)
782  {
783  return dns_addr_safe(addr);
784  }
785  else
786  {
787  return false;
788  }
789 }
790 
791 bool
792 mac_addr_safe(const char *mac_addr)
793 {
794  /* verify non-NULL */
795  if (!mac_addr)
796  {
797  return false;
798  }
799 
800  /* verify length is within limits */
801  if (strlen(mac_addr) > 17)
802  {
803  return false;
804  }
805 
806  /* verify that all chars are either alphanumeric or ':' and that no
807  * alphanumeric substring is greater than 2 chars */
808  {
809  int nnum = 0;
810  const char *p = mac_addr;
811  int c;
812 
813  while ((c = *p++))
814  {
815  if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
816  {
817  ++nnum;
818  if (nnum > 2)
819  {
820  return false;
821  }
822  }
823  else if (c == ':')
824  {
825  nnum = 0;
826  }
827  else
828  {
829  return false;
830  }
831  }
832  }
833 
834  /* error-checking is left to script invoked in lladdr.c */
835  return true;
836 }
837 
838 static int
840 {
841 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
842  int val;
843  socklen_t len;
844 
845  len = sizeof(val);
846  if (getsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
847  && len == sizeof(val))
848  {
849  return val;
850  }
851 #endif
852  return 0;
853 }
854 
855 static void
856 socket_set_sndbuf(int sd, int size)
857 {
858 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
859  if (setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof(size)) != 0)
860  {
861  msg(M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
862  }
863 #endif
864 }
865 
866 static int
868 {
869 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
870  int val;
871  socklen_t len;
872 
873  len = sizeof(val);
874  if (getsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
875  && len == sizeof(val))
876  {
877  return val;
878  }
879 #endif
880  return 0;
881 }
882 
883 static bool
884 socket_set_rcvbuf(int sd, int size)
885 {
886 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
887  if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof(size)) != 0)
888  {
889  msg(M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
890  return false;
891  }
892  return true;
893 #endif
894 }
895 
896 static void
897 socket_set_buffers(int fd, const struct socket_buffer_size *sbs)
898 {
899  if (sbs)
900  {
901  const int sndbuf_old = socket_get_sndbuf(fd);
902  const int rcvbuf_old = socket_get_rcvbuf(fd);
903 
904  if (sbs->sndbuf)
905  {
906  socket_set_sndbuf(fd, sbs->sndbuf);
907  }
908 
909  if (sbs->rcvbuf)
910  {
911  socket_set_rcvbuf(fd, sbs->rcvbuf);
912  }
913 
914  msg(D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
915  rcvbuf_old,
916  socket_get_rcvbuf(fd),
917  sndbuf_old,
918  socket_get_sndbuf(fd));
919  }
920 }
921 
922 /*
923  * Set other socket options
924  */
925 
926 static bool
927 socket_set_tcp_nodelay(int sd, int state)
928 {
929 #if defined(_WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
930  if (setsockopt(sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof(state)) != 0)
931  {
932  msg(M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
933  return false;
934  }
935  else
936  {
937  dmsg(D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
938  return true;
939  }
940 #else /* if defined(_WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY)) */
941  msg(M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
942  return false;
943 #endif
944 }
945 
946 static inline void
947 socket_set_mark(int sd, int mark)
948 {
949 #if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
950  if (mark && setsockopt(sd, SOL_SOCKET, SO_MARK, (void *) &mark, sizeof(mark)) != 0)
951  {
952  msg(M_WARN, "NOTE: setsockopt SO_MARK=%d failed", mark);
953  }
954 #endif
955 }
956 
957 static bool
958 socket_set_flags(int sd, unsigned int sockflags)
959 {
960  if (sockflags & SF_TCP_NODELAY)
961  {
962  return socket_set_tcp_nodelay(sd, 1);
963  }
964  else
965  {
966  return true;
967  }
968 }
969 
970 bool
971 link_socket_update_flags(struct link_socket *ls, unsigned int sockflags)
972 {
973  if (ls && socket_defined(ls->sd))
974  {
975  return socket_set_flags(ls->sd, ls->sockflags = sockflags);
976  }
977  else
978  {
979  return false;
980  }
981 }
982 
983 void
984 link_socket_update_buffer_sizes(struct link_socket *ls, int rcvbuf, int sndbuf)
985 {
986  if (ls && socket_defined(ls->sd))
987  {
988  ls->socket_buffer_sizes.sndbuf = sndbuf;
989  ls->socket_buffer_sizes.rcvbuf = rcvbuf;
991  }
992 }
993 
994 /*
995  * SOCKET INITIALIZATION CODE.
996  * Create a TCP/UDP socket
997  */
998 
1000 create_socket_tcp(struct addrinfo *addrinfo)
1001 {
1003 
1004  ASSERT(addrinfo);
1005  ASSERT(addrinfo->ai_socktype == SOCK_STREAM);
1006 
1007  if ((sd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol)) < 0)
1008  {
1009  msg(M_ERR, "Cannot create TCP socket");
1010  }
1011 
1012 #ifndef _WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
1013  /* set SO_REUSEADDR on socket */
1014  {
1015  int on = 1;
1016  if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR,
1017  (void *) &on, sizeof(on)) < 0)
1018  {
1019  msg(M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
1020  }
1021  }
1022 #endif
1023 
1024  /* set socket file descriptor to not pass across execs, so that
1025  * scripts don't have access to it */
1026  set_cloexec(sd);
1027 
1028  return sd;
1029 }
1030 
1031 static socket_descriptor_t
1032 create_socket_udp(struct addrinfo *addrinfo, const unsigned int flags)
1033 {
1035 
1036  ASSERT(addrinfo);
1037  ASSERT(addrinfo->ai_socktype == SOCK_DGRAM);
1038 
1039  if ((sd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol)) < 0)
1040  {
1041  msg(M_ERR, "UDP: Cannot create UDP/UDP6 socket");
1042  }
1043 #if ENABLE_IP_PKTINFO
1044  else if (flags & SF_USE_IP_PKTINFO)
1045  {
1046  int pad = 1;
1047  if (addrinfo->ai_family == AF_INET)
1048  {
1049 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
1050  if (setsockopt(sd, SOL_IP, IP_PKTINFO,
1051  (void *)&pad, sizeof(pad)) < 0)
1052  {
1053  msg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO");
1054  }
1055 #elif defined(IP_RECVDSTADDR)
1056  if (setsockopt(sd, IPPROTO_IP, IP_RECVDSTADDR,
1057  (void *)&pad, sizeof(pad)) < 0)
1058  {
1059  msg(M_ERR, "UDP: failed setsockopt for IP_RECVDSTADDR");
1060  }
1061 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
1062 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
1063 #endif
1064  }
1065  else if (addrinfo->ai_family == AF_INET6)
1066  {
1067 #ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
1068  if (setsockopt(sd, IPPROTO_IPV6, IPV6_PKTINFO,
1069  (void *)&pad, sizeof(pad)) < 0)
1070 #else
1071  if (setsockopt(sd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
1072  (void *)&pad, sizeof(pad)) < 0)
1073 #endif
1074  { msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");}
1075  }
1076  }
1077 #endif /* if ENABLE_IP_PKTINFO */
1078 
1079  /* set socket file descriptor to not pass across execs, so that
1080  * scripts don't have access to it */
1081  set_cloexec(sd);
1082 
1083  return sd;
1084 }
1085 
1086 static void
1087 bind_local(struct link_socket *sock, const sa_family_t ai_family)
1088 {
1089  /* bind to local address/port */
1090  if (sock->bind_local)
1091  {
1092  if (sock->socks_proxy && sock->info.proto == PROTO_UDP)
1093  {
1094  socket_bind(sock->ctrl_sd, sock->info.lsa->bind_local,
1095  ai_family, "SOCKS", false);
1096  }
1097  else
1098  {
1099  socket_bind(sock->sd, sock->info.lsa->bind_local,
1100  ai_family,
1101  "TCP/UDP", sock->info.bind_ipv6_only);
1102  }
1103  }
1104 }
1105 
1106 static void
1107 create_socket(struct link_socket *sock, struct addrinfo *addr)
1108 {
1109  if (addr->ai_protocol == IPPROTO_UDP || addr->ai_socktype == SOCK_DGRAM)
1110  {
1111  sock->sd = create_socket_udp(addr, sock->sockflags);
1113 
1114  /* Assume that control socket and data socket to the socks proxy
1115  * are using the same IP family */
1116  if (sock->socks_proxy)
1117  {
1118  /* Construct a temporary addrinfo to create the socket,
1119  * currently resolve two remote addresses is not supported,
1120  * TODO: Rewrite the whole resolve_remote */
1121  struct addrinfo addrinfo_tmp = *addr;
1122  addrinfo_tmp.ai_socktype = SOCK_STREAM;
1123  addrinfo_tmp.ai_protocol = IPPROTO_TCP;
1124  sock->ctrl_sd = create_socket_tcp(&addrinfo_tmp);
1125  }
1126  }
1127  else if (addr->ai_protocol == IPPROTO_TCP || addr->ai_socktype == SOCK_STREAM)
1128  {
1129  sock->sd = create_socket_tcp(addr);
1130  }
1131  else
1132  {
1133  ASSERT(0);
1134  }
1135  /* set socket buffers based on --sndbuf and --rcvbuf options */
1136  socket_set_buffers(sock->sd, &sock->socket_buffer_sizes);
1137 
1138  /* set socket to --mark packets with given value */
1139  socket_set_mark(sock->sd, sock->mark);
1140 
1141 #if defined(TARGET_LINUX)
1142  if (sock->bind_dev)
1143  {
1144  msg (M_INFO, "Using bind-dev %s", sock->bind_dev);
1145  if (setsockopt (sock->sd, SOL_SOCKET, SO_BINDTODEVICE, sock->bind_dev, strlen (sock->bind_dev) + 1) != 0)
1146  {
1147  msg(M_WARN|M_ERRNO, "WARN: setsockopt SO_BINDTODEVICE=%s failed", sock->bind_dev);
1148  }
1149 
1150  }
1151 #endif
1152 
1153  bind_local(sock, addr->ai_family);
1154 }
1155 
1156 #ifdef TARGET_ANDROID
1157 static void
1158 protect_fd_nonlocal(int fd, const struct sockaddr *addr)
1159 {
1160  /* pass socket FD to management interface to pass on to VPNService API
1161  * as "protected socket" (exempt from being routed into tunnel)
1162  */
1163  if (addr_local(addr))
1164  {
1165  msg(D_SOCKET_DEBUG, "Address is local, not protecting socket fd %d", fd);
1166  return;
1167  }
1168 
1169  msg(D_SOCKET_DEBUG, "Protecting socket fd %d", fd);
1170  management->connection.fdtosend = fd;
1171  management_android_control(management, "PROTECTFD", __func__);
1172 }
1173 #endif
1174 
1175 /*
1176  * Functions used for establishing a TCP stream connection.
1177  */
1178 static void
1180  const struct addrinfo *local,
1181  bool do_listen,
1182  bool do_set_nonblock)
1183 {
1184  struct gc_arena gc = gc_new();
1185  if (do_listen)
1186  {
1187  ASSERT(local);
1188  msg(M_INFO, "Listening for incoming TCP connection on %s",
1189  print_sockaddr(local->ai_addr, &gc));
1190  if (listen(sd, 32))
1191  {
1192  msg(M_ERR, "TCP: listen() failed");
1193  }
1194  }
1195 
1196  /* set socket to non-blocking mode */
1197  if (do_set_nonblock)
1198  {
1199  set_nonblock(sd);
1200  }
1201 
1202  gc_free(&gc);
1203 }
1204 
1207  struct link_socket_actual *act,
1208  const bool nowait)
1209 {
1210  /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
1211  * are compiled because act is empty here.
1212  * could use getsockname() to support later remote_len check
1213  */
1214  socklen_t remote_len_af = af_addr_size(act->dest.addr.sa.sa_family);
1215  socklen_t remote_len = sizeof(act->dest.addr);
1217 
1218  CLEAR(*act);
1219 
1220 #ifdef HAVE_GETPEERNAME
1221  if (nowait)
1222  {
1223  new_sd = getpeername(sd, &act->dest.addr.sa, &remote_len);
1224 
1225  if (!socket_defined(new_sd))
1226  {
1227  msg(D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
1228  }
1229  else
1230  {
1231  new_sd = sd;
1232  }
1233  }
1234 #else /* ifdef HAVE_GETPEERNAME */
1235  if (nowait)
1236  {
1237  msg(M_WARN, "TCP: this OS does not provide the getpeername() function");
1238  }
1239 #endif
1240  else
1241  {
1242  new_sd = accept(sd, &act->dest.addr.sa, &remote_len);
1243  }
1244 
1245 #if 0 /* For debugging only, test the effect of accept() failures */
1246  {
1247  static int foo = 0;
1248  ++foo;
1249  if (foo & 1)
1250  {
1251  new_sd = -1;
1252  }
1253  }
1254 #endif
1255 
1256  if (!socket_defined(new_sd))
1257  {
1258  msg(D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", (int)sd);
1259  }
1260  /* only valid if we have remote_len_af!=0 */
1261  else if (remote_len_af && remote_len != remote_len_af)
1262  {
1263  msg(D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
1264  openvpn_close_socket(new_sd);
1265  new_sd = SOCKET_UNDEFINED;
1266  }
1267  else
1268  {
1269  /* set socket file descriptor to not pass across execs, so that
1270  * scripts don't have access to it */
1271  set_cloexec(sd);
1272  }
1273  return new_sd;
1274 }
1275 
1276 static void
1278 {
1279  struct gc_arena gc = gc_new();
1280  msg(M_INFO, "TCP connection established with %s",
1281  print_link_socket_actual(act, &gc));
1282  gc_free(&gc);
1283 }
1284 
1285 static socket_descriptor_t
1287  struct link_socket_actual *act,
1288  const char *remote_dynamic,
1289  const struct addrinfo *local,
1290  bool do_listen,
1291  bool nowait,
1292  volatile int *signal_received)
1293 {
1294  struct gc_arena gc = gc_new();
1295  /* struct openvpn_sockaddr *remote = &act->dest; */
1296  struct openvpn_sockaddr remote_verify = act->dest;
1298 
1299  CLEAR(*act);
1300  socket_do_listen(sd, local, do_listen, true);
1301 
1302  while (true)
1303  {
1304  int status;
1305  fd_set reads;
1306  struct timeval tv;
1307 
1308  FD_ZERO(&reads);
1309  openvpn_fd_set(sd, &reads);
1310  tv.tv_sec = 0;
1311  tv.tv_usec = 0;
1312 
1313  status = select(sd + 1, &reads, NULL, NULL, &tv);
1314 
1315  get_signal(signal_received);
1316  if (*signal_received)
1317  {
1318  gc_free(&gc);
1319  return sd;
1320  }
1321 
1322  if (status < 0)
1323  {
1324  msg(D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
1325  }
1326 
1327  if (status <= 0)
1328  {
1329  management_sleep(1);
1330  continue;
1331  }
1332 
1333  new_sd = socket_do_accept(sd, act, nowait);
1334 
1335  if (socket_defined(new_sd))
1336  {
1337  struct addrinfo *ai = NULL;
1338  if (remote_dynamic)
1339  {
1340  openvpn_getaddrinfo(0, remote_dynamic, NULL, 1, NULL,
1341  remote_verify.addr.sa.sa_family, &ai);
1342  }
1343 
1344  if (ai && !addrlist_match(&remote_verify, ai))
1345  {
1346  msg(M_WARN,
1347  "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
1348  print_link_socket_actual(act, &gc));
1349  if (openvpn_close_socket(new_sd))
1350  {
1351  msg(M_ERR, "TCP: close socket failed (new_sd)");
1352  }
1353  freeaddrinfo(ai);
1354  }
1355  else
1356  {
1357  if (ai)
1358  {
1359  freeaddrinfo(ai);
1360  }
1361  break;
1362  }
1363  }
1364  management_sleep(1);
1365  }
1366 
1367  if (!nowait && openvpn_close_socket(sd))
1368  {
1369  msg(M_ERR, "TCP: close socket failed (sd)");
1370  }
1371 
1373 
1374  gc_free(&gc);
1375  return new_sd;
1376 }
1377 
1378 /* older mingw versions and WinXP do not have this define,
1379  * but Vista and up support the functionality - just define it here
1380  */
1381 #ifdef _WIN32
1382 #ifndef IPV6_V6ONLY
1383 #define IPV6_V6ONLY 27
1384 #endif
1385 #endif
1386 void
1388  struct addrinfo *local,
1389  int ai_family,
1390  const char *prefix,
1391  bool ipv6only)
1392 {
1393  struct gc_arena gc = gc_new();
1394 
1395  /* FIXME (schwabe)
1396  * getaddrinfo for the bind address might return multiple AF_INET/AF_INET6
1397  * entries for the requested protocol.
1398  * For example if an address has multiple A records
1399  * What is the correct way to deal with it?
1400  */
1401 
1402  struct addrinfo *cur;
1403 
1404  ASSERT(local);
1405 
1406 
1407  /* find the first addrinfo with correct ai_family */
1408  for (cur = local; cur; cur = cur->ai_next)
1409  {
1410  if (cur->ai_family == ai_family)
1411  {
1412  break;
1413  }
1414  }
1415  if (!cur)
1416  {
1417  msg(M_FATAL, "%s: Socket bind failed: Addr to bind has no %s record",
1418  prefix, addr_family_name(ai_family));
1419  }
1420 
1421  if (ai_family == AF_INET6)
1422  {
1423  int v6only = ipv6only ? 1 : 0; /* setsockopt must have an "int" */
1424 
1425  msg(M_INFO, "setsockopt(IPV6_V6ONLY=%d)", v6only);
1426  if (setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &v6only, sizeof(v6only)))
1427  {
1428  msg(M_NONFATAL|M_ERRNO, "Setting IPV6_V6ONLY=%d failed", v6only);
1429  }
1430  }
1431  if (bind(sd, cur->ai_addr, cur->ai_addrlen))
1432  {
1433  msg(M_FATAL | M_ERRNO, "%s: Socket bind failed on local address %s",
1434  prefix,
1435  print_sockaddr_ex(local->ai_addr, ":", PS_SHOW_PORT, &gc));
1436  }
1437  gc_free(&gc);
1438 }
1439 
1440 int
1442  const struct sockaddr *remote,
1443  int connect_timeout,
1444  volatile int *signal_received)
1445 {
1446  int status = 0;
1447 
1448 #ifdef TARGET_ANDROID
1449  protect_fd_nonlocal(sd, remote);
1450 #endif
1451 
1452 #ifdef CONNECT_NONBLOCK
1453  set_nonblock(sd);
1454  status = connect(sd, remote, af_addr_size(remote->sa_family));
1455  if (status)
1456  {
1457  status = openvpn_errno();
1458  }
1459  if (
1460 #ifdef _WIN32
1461  status == WSAEWOULDBLOCK
1462 #else
1463  status == EINPROGRESS
1464 #endif
1465  )
1466  {
1467  while (true)
1468  {
1469 #if POLL
1470  struct pollfd fds[1];
1471  fds[0].fd = sd;
1472  fds[0].events = POLLOUT;
1473  status = poll(fds, 1, 0);
1474 #else
1475  fd_set writes;
1476  struct timeval tv;
1477 
1478  FD_ZERO(&writes);
1479  openvpn_fd_set(sd, &writes);
1480  tv.tv_sec = 0;
1481  tv.tv_usec = 0;
1482 
1483  status = select(sd + 1, NULL, &writes, NULL, &tv);
1484 #endif
1485  if (signal_received)
1486  {
1487  get_signal(signal_received);
1488  if (*signal_received)
1489  {
1490  status = 0;
1491  break;
1492  }
1493  }
1494  if (status < 0)
1495  {
1496  status = openvpn_errno();
1497  break;
1498  }
1499  if (status <= 0)
1500  {
1501  if (--connect_timeout < 0)
1502  {
1503 #ifdef _WIN32
1504  status = WSAETIMEDOUT;
1505 #else
1506  status = ETIMEDOUT;
1507 #endif
1508  break;
1509  }
1510  management_sleep(1);
1511  continue;
1512  }
1513 
1514  /* got it */
1515  {
1516  int val = 0;
1517  socklen_t len;
1518 
1519  len = sizeof(val);
1520  if (getsockopt(sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
1521  && len == sizeof(val))
1522  {
1523  status = val;
1524  }
1525  else
1526  {
1527  status = openvpn_errno();
1528  }
1529  break;
1530  }
1531  }
1532  }
1533 #else /* ifdef CONNECT_NONBLOCK */
1534  status = connect(sd, remote, af_addr_size(remote->sa_family));
1535  if (status)
1536  {
1537  status = openvpn_errno();
1538  }
1539 #endif /* ifdef CONNECT_NONBLOCK */
1540 
1541  return status;
1542 }
1543 
1544 void
1545 set_actual_address(struct link_socket_actual *actual, struct addrinfo *ai)
1546 {
1547  CLEAR(*actual);
1548  ASSERT(ai);
1549 
1550  if (ai->ai_family == AF_INET)
1551  {
1552  actual->dest.addr.in4 =
1553  *((struct sockaddr_in *) ai->ai_addr);
1554  }
1555  else if (ai->ai_family == AF_INET6)
1556  {
1557  actual->dest.addr.in6 =
1558  *((struct sockaddr_in6 *) ai->ai_addr);
1559  }
1560  else
1561  {
1562  ASSERT(0);
1563  }
1564 
1565 }
1566 
1567 static void
1569  const struct sockaddr *dest,
1570  const int connect_timeout,
1571  struct signal_info *sig_info)
1572 {
1573  struct gc_arena gc = gc_new();
1574  int status;
1575 
1576 #ifdef CONNECT_NONBLOCK
1577  msg(M_INFO, "Attempting to establish TCP connection with %s [nonblock]",
1578  print_sockaddr(dest, &gc));
1579 #else
1580  msg(M_INFO, "Attempting to establish TCP connection with %s",
1581  print_sockaddr(dest, &gc));
1582 #endif
1583 
1584 #ifdef ENABLE_MANAGEMENT
1585  if (management)
1586  {
1589  NULL,
1590  NULL,
1591  NULL,
1592  NULL,
1593  NULL);
1594  }
1595 #endif
1596 
1597  /* Set the actual address */
1598  status = openvpn_connect(*sd, dest, connect_timeout, &sig_info->signal_received);
1599 
1600  get_signal(&sig_info->signal_received);
1601  if (sig_info->signal_received)
1602  {
1603  goto done;
1604  }
1605 
1606  if (status)
1607  {
1608 
1609  msg(D_LINK_ERRORS, "TCP: connect to %s failed: %s",
1610  print_sockaddr(dest, &gc), strerror(status));
1611 
1612  openvpn_close_socket(*sd);
1613  *sd = SOCKET_UNDEFINED;
1614  sig_info->signal_received = SIGUSR1;
1616  }
1617  else
1618  {
1619  msg(M_INFO, "TCP connection established with %s",
1620  print_sockaddr(dest, &gc));
1621  }
1622 
1623 done:
1624  gc_free(&gc);
1625 }
1626 
1627 /*
1628  * Stream buffer handling prototypes -- stream_buf is a helper class
1629  * to assist in the packetization of stream transport protocols
1630  * such as TCP.
1631  */
1632 
1633 static void
1634 stream_buf_init(struct stream_buf *sb, struct buffer *buf,
1635  const unsigned int sockflags, const int proto);
1636 
1637 static void
1638 stream_buf_close(struct stream_buf *sb);
1639 
1640 static bool
1641 stream_buf_added(struct stream_buf *sb, int length_added);
1642 
1643 /* For stream protocols, allocate a buffer to build up packet.
1644  * Called after frame has been finalized. */
1645 
1646 static void
1647 socket_frame_init(const struct frame *frame, struct link_socket *sock)
1648 {
1649 #ifdef _WIN32
1650  overlapped_io_init(&sock->reads, frame, FALSE, false);
1651  overlapped_io_init(&sock->writes, frame, TRUE, false);
1652  sock->rw_handle.read = sock->reads.overlapped.hEvent;
1653  sock->rw_handle.write = sock->writes.overlapped.hEvent;
1654 #endif
1655 
1657  {
1658 #ifdef _WIN32
1659  stream_buf_init(&sock->stream_buf,
1660  &sock->reads.buf_init,
1661  sock->sockflags,
1662  sock->info.proto);
1663 #else
1665  frame,
1666  false,
1668 
1669  stream_buf_init(&sock->stream_buf,
1670  &sock->stream_buf_data,
1671  sock->sockflags,
1672  sock->info.proto);
1673 #endif
1674  }
1675 }
1676 
1677 /*
1678  * Adjust frame structure based on a Path MTU value given
1679  * to us by the OS.
1680  */
1681 void
1682 frame_adjust_path_mtu(struct frame *frame, int pmtu, int proto)
1683 {
1685 }
1686 
1687 static void
1689 {
1690  struct gc_arena gc = gc_new();
1691 
1692  /* resolve local address if undefined */
1693  if (!sock->info.lsa->bind_local)
1694  {
1697  int status;
1698 
1699  if (proto_is_dgram(sock->info.proto))
1700  {
1701  flags |= GETADDR_DATAGRAM;
1702  }
1703 
1704  /* will return AF_{INET|INET6}from local_host */
1705  status = get_cached_dns_entry(sock->dns_cache,
1706  sock->local_host,
1707  sock->local_port,
1708  af,
1709  flags,
1710  &sock->info.lsa->bind_local);
1711 
1712  if (status)
1713  {
1714  status = openvpn_getaddrinfo(flags, sock->local_host, sock->local_port, 0,
1715  NULL, af, &sock->info.lsa->bind_local);
1716  }
1717 
1718  if (status !=0)
1719  {
1720  msg(M_FATAL, "getaddrinfo() failed for local \"%s:%s\": %s",
1721  sock->local_host, sock->local_port,
1722  gai_strerror(status));
1723  }
1724  }
1725 
1726  gc_free(&gc);
1727 }
1728 
1729 static void
1731  int phase,
1732  const char **remote_dynamic,
1733  volatile int *signal_received)
1734 {
1735  struct gc_arena gc = gc_new();
1736 
1737  /* resolve remote address if undefined */
1738  if (!sock->info.lsa->remote_list)
1739  {
1740  if (sock->remote_host)
1741  {
1743  int retry = 0;
1744  int status = -1;
1745  struct addrinfo *ai;
1746  if (proto_is_dgram(sock->info.proto))
1747  {
1748  flags |= GETADDR_DATAGRAM;
1749  }
1750 
1752  {
1753  if (phase == 2)
1754  {
1755  flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
1756  }
1757  retry = 0;
1758  }
1759  else if (phase == 1)
1760  {
1761  if (sock->resolve_retry_seconds)
1762  {
1763  retry = 0;
1764  }
1765  else
1766  {
1768  retry = 0;
1769  }
1770  }
1771  else if (phase == 2)
1772  {
1773  if (sock->resolve_retry_seconds)
1774  {
1775  flags |= GETADDR_FATAL;
1776  retry = sock->resolve_retry_seconds;
1777  }
1778  else
1779  {
1780  ASSERT(0);
1781  }
1782  }
1783  else
1784  {
1785  ASSERT(0);
1786  }
1787 
1788 
1789  status = get_cached_dns_entry(sock->dns_cache,
1790  sock->remote_host,
1791  sock->remote_port,
1792  sock->info.af,
1793  flags, &ai);
1794  if (status)
1795  {
1796  status = openvpn_getaddrinfo(flags, sock->remote_host, sock->remote_port,
1797  retry, signal_received, sock->info.af, &ai);
1798  }
1799 
1800  if (status == 0)
1801  {
1802  sock->info.lsa->remote_list = ai;
1803  sock->info.lsa->current_remote = ai;
1804 
1805  dmsg(D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1806  flags,
1807  phase,
1808  retry,
1809  signal_received ? *signal_received : -1,
1810  status);
1811  }
1812  if (signal_received)
1813  {
1814  if (*signal_received)
1815  {
1816  goto done;
1817  }
1818  }
1819  if (status!=0)
1820  {
1821  if (signal_received)
1822  {
1823  *signal_received = SIGUSR1;
1824  }
1825  goto done;
1826  }
1827  }
1828  }
1829 
1830  /* should we re-use previous active remote address? */
1832  {
1833  msg(M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
1834  print_link_socket_actual(&sock->info.lsa->actual, &gc));
1835  if (remote_dynamic)
1836  {
1837  *remote_dynamic = NULL;
1838  }
1839  }
1840  else
1841  {
1842  CLEAR(sock->info.lsa->actual);
1843  if (sock->info.lsa->current_remote)
1844  {
1846  sock->info.lsa->current_remote);
1847  }
1848  }
1849 
1850 done:
1851  gc_free(&gc);
1852 }
1853 
1854 
1855 
1856 struct link_socket *
1858 {
1859  struct link_socket *sock;
1860 
1861  ALLOC_OBJ_CLEAR(sock, struct link_socket);
1862  sock->sd = SOCKET_UNDEFINED;
1863  sock->ctrl_sd = SOCKET_UNDEFINED;
1864  return sock;
1865 }
1866 
1867 void
1869  const char *local_host,
1870  const char *local_port,
1871  const char *remote_host,
1872  const char *remote_port,
1873  struct cached_dns_entry *dns_cache,
1874  int proto,
1875  sa_family_t af,
1876  bool bind_ipv6_only,
1877  int mode,
1878  const struct link_socket *accept_from,
1879  struct http_proxy_info *http_proxy,
1880  struct socks_proxy_info *socks_proxy,
1881 #ifdef ENABLE_DEBUG
1882  int gremlin,
1883 #endif
1884  bool bind_local,
1885  bool remote_float,
1886  int inetd,
1887  struct link_socket_addr *lsa,
1888  const char *ipchange_command,
1889  const struct plugin_list *plugins,
1891  int mtu_discover_type,
1892  int rcvbuf,
1893  int sndbuf,
1894  int mark,
1895  const char *bind_dev,
1897  unsigned int sockflags)
1898 {
1899  ASSERT(sock);
1900 
1901  sock->local_host = local_host;
1902  sock->local_port = local_port;
1903  sock->remote_host = remote_host;
1904  sock->remote_port = remote_port;
1905  sock->dns_cache = dns_cache;
1906  sock->http_proxy = http_proxy;
1907  sock->socks_proxy = socks_proxy;
1908  sock->bind_local = bind_local;
1909  sock->inetd = inetd;
1912 
1913 #ifdef ENABLE_DEBUG
1914  sock->gremlin = gremlin;
1915 #endif
1916 
1917  sock->socket_buffer_sizes.rcvbuf = rcvbuf;
1918  sock->socket_buffer_sizes.sndbuf = sndbuf;
1919 
1920  sock->sockflags = sockflags;
1921  sock->mark = mark;
1922  sock->bind_dev = bind_dev;
1923 
1924  sock->info.proto = proto;
1925  sock->info.af = af;
1926  sock->info.remote_float = remote_float;
1927  sock->info.lsa = lsa;
1928  sock->info.bind_ipv6_only = bind_ipv6_only;
1929  sock->info.ipchange_command = ipchange_command;
1930  sock->info.plugins = plugins;
1932 
1933  sock->mode = mode;
1934  if (mode == LS_MODE_TCP_ACCEPT_FROM)
1935  {
1936  ASSERT(accept_from);
1937  ASSERT(sock->info.proto == PROTO_TCP_SERVER);
1938  ASSERT(!sock->inetd);
1939  sock->sd = accept_from->sd;
1940  /* inherit (possibly guessed) info AF from parent context */
1941  sock->info.af = accept_from->info.af;
1942  }
1943 
1944  /* are we running in HTTP proxy mode? */
1945  if (sock->http_proxy)
1946  {
1947  ASSERT(sock->info.proto == PROTO_TCP_CLIENT);
1948  ASSERT(!sock->inetd);
1949 
1950  /* the proxy server */
1951  sock->remote_host = http_proxy->options.server;
1952  sock->remote_port = http_proxy->options.port;
1953 
1954  /* the OpenVPN server we will use the proxy to connect to */
1955  sock->proxy_dest_host = remote_host;
1956  sock->proxy_dest_port = remote_port;
1957  }
1958  /* or in Socks proxy mode? */
1959  else if (sock->socks_proxy)
1960  {
1961  ASSERT(!sock->inetd);
1962 
1963  /* the proxy server */
1964  sock->remote_host = socks_proxy->server;
1965  sock->remote_port = socks_proxy->port;
1966 
1967  /* the OpenVPN server we will use the proxy to connect to */
1968  sock->proxy_dest_host = remote_host;
1969  sock->proxy_dest_port = remote_port;
1970  }
1971  else
1972  {
1973  sock->remote_host = remote_host;
1974  sock->remote_port = remote_port;
1975  }
1976 
1977  /* bind behavior for TCP server vs. client */
1978  if (sock->info.proto == PROTO_TCP_SERVER)
1979  {
1980  if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
1981  {
1982  sock->bind_local = false;
1983  }
1984  else
1985  {
1986  sock->bind_local = true;
1987  }
1988  }
1989 
1990  /* were we started by inetd or xinetd? */
1991  if (sock->inetd)
1992  {
1993  ASSERT(sock->info.proto != PROTO_TCP_CLIENT);
1995  sock->sd = inetd_socket_descriptor;
1996  set_cloexec(sock->sd); /* not created by create_socket*() */
1997  }
1998  else if (mode != LS_MODE_TCP_ACCEPT_FROM)
1999  {
2000  if (sock->bind_local)
2001  {
2002  resolve_bind_local(sock, sock->info.af);
2003  }
2004  resolve_remote(sock, 1, NULL, NULL);
2005  }
2006 }
2007 
2008 static
2009 void
2010 phase2_inetd(struct link_socket *sock, const struct frame *frame,
2011  const char *remote_dynamic, volatile int *signal_received)
2012 {
2013  bool remote_changed = false;
2014 
2015  if (sock->info.proto == PROTO_TCP_SERVER)
2016  {
2017  /* AF_INET as default (and fallback) for inetd */
2018  sock->info.lsa->actual.dest.addr.sa.sa_family = AF_INET;
2019 #ifdef HAVE_GETSOCKNAME
2020  {
2021  /* inetd: hint family type for dest = local's */
2022  struct openvpn_sockaddr local_addr;
2023  socklen_t addrlen = sizeof(local_addr);
2024  if (getsockname(sock->sd, &local_addr.addr.sa, &addrlen) == 0)
2025  {
2026  sock->info.lsa->actual.dest.addr.sa.sa_family = local_addr.addr.sa.sa_family;
2027  dmsg(D_SOCKET_DEBUG, "inetd(%s): using sa_family=%d from getsockname(%d)",
2028  proto2ascii(sock->info.proto, sock->info.af, false),
2029  local_addr.addr.sa.sa_family, (int)sock->sd);
2030  }
2031  else
2032  {
2033  msg(M_WARN, "inetd(%s): getsockname(%d) failed, using AF_INET",
2034  proto2ascii(sock->info.proto, sock->info.af, false), (int)sock->sd);
2035  }
2036  }
2037 #else /* ifdef HAVE_GETSOCKNAME */
2038  msg(M_WARN, "inetd(%s): this OS does not provide the getsockname() "
2039  "function, using AF_INET",
2040  proto2ascii(sock->info.proto, false));
2041 #endif /* ifdef HAVE_GETSOCKNAME */
2042  sock->sd =
2043  socket_listen_accept(sock->sd,
2044  &sock->info.lsa->actual,
2045  remote_dynamic,
2046  sock->info.lsa->bind_local,
2047  false,
2048  sock->inetd == INETD_NOWAIT,
2049  signal_received);
2050 
2051  }
2052  ASSERT(!remote_changed);
2053 }
2054 
2055 static void
2057 {
2058  /* set misc socket parameters */
2059  socket_set_flags(sock->sd, sock->sockflags);
2060 
2061  /* set socket to non-blocking mode */
2062  set_nonblock(sock->sd);
2063 
2064  /* set Path MTU discovery options on the socket */
2065  set_mtu_discover_type(sock->sd, sock->mtu_discover_type, sock->info.af);
2066 
2067 #if EXTENDED_SOCKET_ERROR_CAPABILITY
2068  /* if the OS supports it, enable extended error passing on the socket */
2069  set_sock_extended_error_passing(sock->sd);
2070 #endif
2071 }
2072 
2073 
2074 static void
2076 {
2077  struct gc_arena gc = gc_new();
2078  const int msglevel = (sock->mode == LS_MODE_TCP_ACCEPT_FROM) ? D_INIT_MEDIUM : M_INFO;
2079 
2080  /* print local address */
2081  if (sock->inetd)
2082  {
2083  msg(msglevel, "%s link local: [inetd]", proto2ascii(sock->info.proto, sock->info.af, true));
2084  }
2085  else if (sock->bind_local)
2086  {
2087  sa_family_t ai_family = sock->info.lsa->actual.dest.addr.sa.sa_family;
2088  /* Socket is always bound on the first matching address,
2089  * For bound sockets with no remote addr this is the element of
2090  * the list */
2091  struct addrinfo *cur;
2092  for (cur = sock->info.lsa->bind_local; cur; cur = cur->ai_next)
2093  {
2094  if (!ai_family || ai_family == cur->ai_family)
2095  {
2096  break;
2097  }
2098  }
2099  ASSERT(cur);
2100  msg(msglevel, "%s link local (bound): %s",
2101  proto2ascii(sock->info.proto, sock->info.af, true),
2102  print_sockaddr(cur->ai_addr,&gc));
2103  }
2104  else
2105  {
2106  msg(msglevel, "%s link local: (not bound)",
2107  proto2ascii(sock->info.proto, sock->info.af, true));
2108  }
2109 
2110  /* print active remote address */
2111  msg(msglevel, "%s link remote: %s",
2112  proto2ascii(sock->info.proto, sock->info.af, true),
2114  ":",
2116  &gc));
2117  gc_free(&gc);
2118 }
2119 
2120 static void
2121 phase2_tcp_server(struct link_socket *sock, const char *remote_dynamic,
2122  volatile int *signal_received)
2123 {
2124  switch (sock->mode)
2125  {
2126  case LS_MODE_DEFAULT:
2127  sock->sd = socket_listen_accept(sock->sd,
2128  &sock->info.lsa->actual,
2129  remote_dynamic,
2130  sock->info.lsa->bind_local,
2131  true,
2132  false,
2133  signal_received);
2134  break;
2135 
2136  case LS_MODE_TCP_LISTEN:
2137  socket_do_listen(sock->sd,
2138  sock->info.lsa->bind_local,
2139  true,
2140  false);
2141  break;
2142 
2144  sock->sd = socket_do_accept(sock->sd,
2145  &sock->info.lsa->actual,
2146  false);
2147  if (!socket_defined(sock->sd))
2148  {
2149  *signal_received = SIGTERM;
2150  return;
2151  }
2153  break;
2154 
2155  default:
2156  ASSERT(0);
2157  }
2158 }
2159 
2160 
2161 static void
2162 phase2_tcp_client(struct link_socket *sock, struct signal_info *sig_info)
2163 {
2164  bool proxy_retry = false;
2165  do
2166  {
2167  socket_connect(&sock->sd,
2168  sock->info.lsa->current_remote->ai_addr,
2170  sig_info);
2171 
2172  if (sig_info->signal_received)
2173  {
2174  return;
2175  }
2176 
2177  if (sock->http_proxy)
2178  {
2179  proxy_retry = establish_http_proxy_passthru(sock->http_proxy,
2180  sock->sd,
2181  sock->proxy_dest_host,
2182  sock->proxy_dest_port,
2183  sock->server_poll_timeout,
2184  &sock->stream_buf.residual,
2185  &sig_info->signal_received);
2186  }
2187  else if (sock->socks_proxy)
2188  {
2190  sock->sd,
2191  sock->proxy_dest_host,
2192  sock->proxy_dest_port,
2193  &sig_info->signal_received);
2194  }
2195  if (proxy_retry)
2196  {
2197  openvpn_close_socket(sock->sd);
2198  sock->sd = create_socket_tcp(sock->info.lsa->current_remote);
2199  }
2200 
2201  } while (proxy_retry);
2202 
2203 }
2204 
2205 static void
2206 phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info)
2207 {
2208  socket_connect(&sock->ctrl_sd,
2209  sock->info.lsa->current_remote->ai_addr,
2211  sig_info);
2212 
2213  if (sig_info->signal_received)
2214  {
2215  return;
2216  }
2217 
2219  sock->ctrl_sd,
2220  sock->sd,
2221  &sock->socks_relay.dest,
2222  &sig_info->signal_received);
2223 
2224  if (sig_info->signal_received)
2225  {
2226  return;
2227  }
2228 
2229  sock->remote_host = sock->proxy_dest_host;
2230  sock->remote_port = sock->proxy_dest_port;
2231 
2232  addr_zero_host(&sock->info.lsa->actual.dest);
2233  if (sock->info.lsa->remote_list)
2234  {
2235  freeaddrinfo(sock->info.lsa->remote_list);
2236  sock->info.lsa->current_remote = NULL;
2237  sock->info.lsa->remote_list = NULL;
2238  }
2239 
2240  resolve_remote(sock, 1, NULL, &sig_info->signal_received);
2241 }
2242 
2243 /* finalize socket initialization */
2244 void
2246  const struct frame *frame,
2247  struct signal_info *sig_info)
2248 {
2249  const char *remote_dynamic = NULL;
2250  int sig_save = 0;
2251 
2252  ASSERT(sock);
2253  ASSERT(sig_info);
2254 
2255  if (sig_info->signal_received)
2256  {
2257  sig_save = sig_info->signal_received;
2258  sig_info->signal_received = 0;
2259  }
2260 
2261  /* initialize buffers */
2262  socket_frame_init(frame, sock);
2263 
2264  /*
2265  * Pass a remote name to connect/accept so that
2266  * they can test for dynamic IP address changes
2267  * and throw a SIGUSR1 if appropriate.
2268  */
2269  if (sock->resolve_retry_seconds)
2270  {
2271  remote_dynamic = sock->remote_host;
2272  }
2273 
2274  /* were we started by inetd or xinetd? */
2275  if (sock->inetd)
2276  {
2277  phase2_inetd(sock, frame, remote_dynamic, &sig_info->signal_received);
2278  if (sig_info->signal_received)
2279  {
2280  goto done;
2281  }
2282 
2283  }
2284  else
2285  {
2286  /* Second chance to resolv/create socket */
2287  resolve_remote(sock, 2, &remote_dynamic, &sig_info->signal_received);
2288 
2289  /* If a valid remote has been found, create the socket with its addrinfo */
2290  if (sock->info.lsa->current_remote)
2291  {
2292  create_socket(sock, sock->info.lsa->current_remote);
2293  }
2294 
2295  /* If socket has not already been created create it now */
2296  if (sock->sd == SOCKET_UNDEFINED)
2297  {
2298  /* If we have no --remote and have still not figured out the
2299  * protocol family to use we will use the first of the bind */
2300 
2301  if (sock->bind_local && !sock->remote_host && sock->info.lsa->bind_local)
2302  {
2303  /* Warn if this is because neither v4 or v6 was specified
2304  * and we should not connect a remote */
2305  if (sock->info.af == AF_UNSPEC)
2306  {
2307  msg(M_WARN, "Could not determine IPv4/IPv6 protocol. Using %s",
2308  addr_family_name(sock->info.lsa->bind_local->ai_family));
2309  sock->info.af = sock->info.lsa->bind_local->ai_family;
2310  }
2311 
2312  create_socket(sock, sock->info.lsa->bind_local);
2313  }
2314  }
2315 
2316  /* Socket still undefined, give a warning and abort connection */
2317  if (sock->sd == SOCKET_UNDEFINED)
2318  {
2319  msg(M_WARN, "Could not determine IPv4/IPv6 protocol");
2320  sig_info->signal_received = SIGUSR1;
2321  goto done;
2322  }
2323 
2324  if (sig_info->signal_received)
2325  {
2326  goto done;
2327  }
2328 
2329  if (sock->info.proto == PROTO_TCP_SERVER)
2330  {
2331  phase2_tcp_server(sock, remote_dynamic,
2332  &sig_info->signal_received);
2333  }
2334  else if (sock->info.proto == PROTO_TCP_CLIENT)
2335  {
2336  phase2_tcp_client(sock, sig_info);
2337 
2338  }
2339  else if (sock->info.proto == PROTO_UDP && sock->socks_proxy)
2340  {
2341  phase2_socks_client(sock, sig_info);
2342  }
2343 #ifdef TARGET_ANDROID
2344  if (sock->sd != -1)
2345  {
2346  protect_fd_nonlocal(sock->sd, &sock->info.lsa->actual.dest.addr.sa);
2347  }
2348 #endif
2349  if (sig_info->signal_received)
2350  {
2351  goto done;
2352  }
2353  }
2354 
2356  linksock_print_addr(sock);
2357 
2358 done:
2359  if (sig_save)
2360  {
2361  if (!sig_info->signal_received)
2362  {
2363  sig_info->signal_received = sig_save;
2364  }
2365  }
2366 }
2367 
2368 void
2370 {
2371  if (sock)
2372  {
2373 #ifdef ENABLE_DEBUG
2374  const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL(sock->gremlin);
2375 #else
2376  const int gremlin = 0;
2377 #endif
2378 
2379  if (socket_defined(sock->sd))
2380  {
2381 #ifdef _WIN32
2382  close_net_event_win32(&sock->listen_handle, sock->sd, 0);
2383 #endif
2384  if (!gremlin)
2385  {
2386  msg(D_LOW, "TCP/UDP: Closing socket");
2387  if (openvpn_close_socket(sock->sd))
2388  {
2389  msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
2390  }
2391  }
2392  sock->sd = SOCKET_UNDEFINED;
2393 #ifdef _WIN32
2394  if (!gremlin)
2395  {
2396  overlapped_io_close(&sock->reads);
2397  overlapped_io_close(&sock->writes);
2398  }
2399 #endif
2400  }
2401 
2402  if (socket_defined(sock->ctrl_sd))
2403  {
2404  if (openvpn_close_socket(sock->ctrl_sd))
2405  {
2406  msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
2407  }
2408  sock->ctrl_sd = SOCKET_UNDEFINED;
2409  }
2410 
2411  stream_buf_close(&sock->stream_buf);
2412  free_buf(&sock->stream_buf_data);
2413  if (!gremlin)
2414  {
2415  free(sock);
2416  }
2417  }
2418 }
2419 
2420 /* for stream protocols, allow for packet length prefix */
2421 void
2423 {
2425  {
2427  }
2428 }
2429 
2430 void
2431 setenv_trusted(struct env_set *es, const struct link_socket_info *info)
2432 {
2433  setenv_link_socket_actual(es, "trusted", &info->lsa->actual, SA_IP_PORT);
2434 }
2435 
2436 static void
2437 ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
2438 {
2439  const char *host = print_sockaddr_ex(&info->lsa->actual.dest.addr.sa, " ", PS_SHOW_PORT, gc);
2440  if (include_cmd)
2441  {
2442  argv_parse_cmd(argv, info->ipchange_command);
2443  argv_printf_cat(argv, "%s", host);
2444  }
2445  else
2446  {
2447  argv_printf(argv, "%s", host);
2448  }
2449 
2450 }
2451 
2452 void
2454  const struct link_socket_actual *act,
2455  const char *common_name,
2456  struct env_set *es)
2457 {
2458  struct gc_arena gc = gc_new();
2459 
2460  info->lsa->actual = *act; /* Note: skip this line for --force-dest */
2461  setenv_trusted(es, info);
2462  info->connection_established = true;
2463 
2464  /* Print connection initiated message, with common name if available */
2465  {
2466  struct buffer out = alloc_buf_gc(256, &gc);
2467  if (common_name)
2468  {
2469  buf_printf(&out, "[%s] ", common_name);
2470  }
2471  buf_printf(&out, "Peer Connection Initiated with %s", print_link_socket_actual(&info->lsa->actual, &gc));
2472  msg(M_INFO, "%s", BSTR(&out));
2473  }
2474 
2475  /* set environmental vars */
2476  setenv_str(es, "common_name", common_name);
2477 
2478  /* Process --ipchange plugin */
2480  {
2481  struct argv argv = argv_new();
2482  ipchange_fmt(false, &argv, info, &gc);
2484  {
2485  msg(M_WARN, "WARNING: ipchange plugin call failed");
2486  }
2487  argv_free(&argv);
2488  }
2489 
2490  /* Process --ipchange option */
2491  if (info->ipchange_command)
2492  {
2493  struct argv argv = argv_new();
2494  setenv_str(es, "script_type", "ipchange");
2495  ipchange_fmt(true, &argv, info, &gc);
2496  openvpn_run_script(&argv, es, 0, "--ipchange");
2497  argv_free(&argv);
2498  }
2499 
2500  gc_free(&gc);
2501 }
2502 
2503 void
2505  const struct link_socket_info *info,
2506  const struct link_socket_actual *from_addr)
2507 {
2508  struct gc_arena gc = gc_new();
2509  struct addrinfo *ai;
2510 
2511  switch (from_addr->dest.addr.sa.sa_family)
2512  {
2513  case AF_INET:
2514  case AF_INET6:
2516  "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
2517  print_link_socket_actual(from_addr, &gc),
2518  (int)from_addr->dest.addr.sa.sa_family,
2519  print_sockaddr_ex(info->lsa->remote_list->ai_addr,":",PS_SHOW_PORT, &gc));
2520  /* print additional remote addresses */
2521  for (ai = info->lsa->remote_list->ai_next; ai; ai = ai->ai_next)
2522  {
2523  msg(D_LINK_ERRORS,"or from peer address: %s",
2524  print_sockaddr_ex(ai->ai_addr,":",PS_SHOW_PORT, &gc));
2525  }
2526  break;
2527  }
2528  buf->len = 0;
2529  gc_free(&gc);
2530 }
2531 
2532 void
2534 {
2535  dmsg(D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
2536 }
2537 
2538 in_addr_t
2540 {
2541  const struct link_socket_addr *lsa = info->lsa;
2542 
2543 /*
2544  * This logic supports "redirect-gateway" semantic, which
2545  * makes sense only for PF_INET routes over PF_INET endpoints
2546  *
2547  * Maybe in the future consider PF_INET6 endpoints also ...
2548  * by now just ignore it
2549  *
2550  * For --remote entries with multiple addresses this
2551  * only return the actual endpoint we have successfully connected to
2552  */
2553  if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
2554  {
2555  return IPV4_INVALID_ADDR;
2556  }
2557 
2559  {
2560  return ntohl(lsa->actual.dest.addr.in4.sin_addr.s_addr);
2561  }
2562  else if (lsa->current_remote)
2563  {
2564  return ntohl(((struct sockaddr_in *)lsa->current_remote->ai_addr)
2565  ->sin_addr.s_addr);
2566  }
2567  else
2568  {
2569  return 0;
2570  }
2571 }
2572 
2573 const struct in6_addr *
2575 {
2576  const struct link_socket_addr *lsa = info->lsa;
2577 
2578 /* This logic supports "redirect-gateway" semantic,
2579  * for PF_INET6 routes over PF_INET6 endpoints
2580  *
2581  * For --remote entries with multiple addresses this
2582  * only return the actual endpoint we have successfully connected to
2583  */
2584  if (lsa->actual.dest.addr.sa.sa_family != AF_INET6)
2585  {
2586  return NULL;
2587  }
2588 
2590  {
2591  return &(lsa->actual.dest.addr.in6.sin6_addr);
2592  }
2593  else if (lsa->current_remote)
2594  {
2595  return &(((struct sockaddr_in6 *)lsa->current_remote->ai_addr)->sin6_addr);
2596  }
2597  else
2598  {
2599  return NULL;
2600  }
2601 }
2602 
2603 /*
2604  * Return a status string describing socket state.
2605  */
2606 const char *
2607 socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
2608 {
2609  struct buffer out = alloc_buf_gc(64, gc);
2610  if (s)
2611  {
2612  if (rwflags & EVENT_READ)
2613  {
2614  buf_printf(&out, "S%s",
2615  (s->rwflags_debug & EVENT_READ) ? "R" : "r");
2616 #ifdef _WIN32
2617  buf_printf(&out, "%s",
2619 #endif
2620  }
2621  if (rwflags & EVENT_WRITE)
2622  {
2623  buf_printf(&out, "S%s",
2624  (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
2625 #ifdef _WIN32
2626  buf_printf(&out, "%s",
2628 #endif
2629  }
2630  }
2631  else
2632  {
2633  buf_printf(&out, "S?");
2634  }
2635  return BSTR(&out);
2636 }
2637 
2638 /*
2639  * Stream buffer functions, used to packetize a TCP
2640  * stream connection.
2641  */
2642 
2643 static inline void
2645 {
2646  dmsg(D_STREAM_DEBUG, "STREAM: RESET");
2647  sb->residual_fully_formed = false;
2648  sb->buf = sb->buf_init;
2649  buf_reset(&sb->next);
2650  sb->len = -1;
2651 }
2652 
2653 static void
2655  struct buffer *buf,
2656  const unsigned int sockflags,
2657  const int proto)
2658 {
2659  sb->buf_init = *buf;
2660  sb->maxlen = sb->buf_init.len;
2661  sb->buf_init.len = 0;
2662  sb->residual = alloc_buf(sb->maxlen);
2663  sb->error = false;
2664 #if PORT_SHARE
2665  sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCP_SERVER))
2666  ? PS_ENABLED
2667  : PS_DISABLED;
2668 #endif
2669  stream_buf_reset(sb);
2670 
2671  dmsg(D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
2672 }
2673 
2674 static inline void
2676 {
2677  /* set up 'next' for next i/o read */
2678  sb->next = sb->buf;
2679  sb->next.offset = sb->buf.offset + sb->buf.len;
2680  sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
2681  dmsg(D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2682  sb->buf.offset, sb->buf.len,
2683  sb->next.offset, sb->next.len,
2684  sb->len, sb->maxlen);
2685  ASSERT(sb->next.len > 0);
2686  ASSERT(buf_safe(&sb->buf, sb->next.len));
2687 }
2688 
2689 static inline void
2690 stream_buf_get_final(struct stream_buf *sb, struct buffer *buf)
2691 {
2692  dmsg(D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
2693  buf_defined(&sb->buf) ? sb->buf.len : -1);
2694  ASSERT(buf_defined(&sb->buf));
2695  *buf = sb->buf;
2696 }
2697 
2698 static inline void
2699 stream_buf_get_next(struct stream_buf *sb, struct buffer *buf)
2700 {
2701  dmsg(D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
2702  buf_defined(&sb->next) ? sb->next.len : -1);
2703  ASSERT(buf_defined(&sb->next));
2704  *buf = sb->next;
2705 }
2706 
2707 bool
2709 {
2711  {
2712  ASSERT(buf_copy(&sock->stream_buf.buf, &sock->stream_buf.residual));
2713  ASSERT(buf_init(&sock->stream_buf.residual, 0));
2715  dmsg(D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2716  sock->stream_buf.residual_fully_formed ? "YES" : "NO",
2717  sock->stream_buf.residual.len);
2718  }
2719 
2720  if (!sock->stream_buf.residual_fully_formed)
2721  {
2723  }
2724  return !sock->stream_buf.residual_fully_formed;
2725 }
2726 
2727 static bool
2729  int length_added)
2730 {
2731  dmsg(D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
2732  if (length_added > 0)
2733  {
2734  sb->buf.len += length_added;
2735  }
2736 
2737  /* if length unknown, see if we can get the length prefix from
2738  * the head of the buffer */
2739  if (sb->len < 0 && sb->buf.len >= (int) sizeof(packet_size_type))
2740  {
2741  packet_size_type net_size;
2742 
2743 #if PORT_SHARE
2744  if (sb->port_share_state == PS_ENABLED)
2745  {
2746  if (!is_openvpn_protocol(&sb->buf))
2747  {
2748  msg(D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
2749  sb->port_share_state = PS_FOREIGN;
2750  sb->error = true;
2751  return false;
2752  }
2753  else
2754  {
2755  sb->port_share_state = PS_DISABLED;
2756  }
2757  }
2758 #endif
2759 
2760  ASSERT(buf_read(&sb->buf, &net_size, sizeof(net_size)));
2761  sb->len = ntohps(net_size);
2762 
2763  if (sb->len < 1 || sb->len > sb->maxlen)
2764  {
2765  msg(M_WARN, "WARNING: Bad encapsulated packet length from peer (%d), which must be > 0 and <= %d -- please ensure that --tun-mtu or --link-mtu is equal on both peers -- this condition could also indicate a possible active attack on the TCP link -- [Attempting restart...]", sb->len, sb->maxlen);
2766  stream_buf_reset(sb);
2767  sb->error = true;
2768  return false;
2769  }
2770  }
2771 
2772  /* is our incoming packet fully read? */
2773  if (sb->len > 0 && sb->buf.len >= sb->len)
2774  {
2775  /* save any residual data that's part of the next packet */
2776  ASSERT(buf_init(&sb->residual, 0));
2777  if (sb->buf.len > sb->len)
2778  {
2779  ASSERT(buf_copy_excess(&sb->residual, &sb->buf, sb->len));
2780  }
2781  dmsg(D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2782  BLEN(&sb->buf),
2783  BLEN(&sb->residual));
2784  return true;
2785  }
2786  else
2787  {
2788  dmsg(D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
2789  stream_buf_set_next(sb);
2790  return false;
2791  }
2792 }
2793 
2794 static void
2796 {
2797  free_buf(&sb->residual);
2798 }
2799 
2800 /*
2801  * The listen event is a special event whose sole purpose is
2802  * to tell us that there's a new incoming connection on a
2803  * TCP socket, for use in server mode.
2804  */
2805 event_t
2807 {
2808 #ifdef _WIN32
2810  {
2811  init_net_event_win32(&s->listen_handle, FD_ACCEPT, s->sd, 0);
2812  }
2813  return &s->listen_handle;
2814 #else /* ifdef _WIN32 */
2815  return s->sd;
2816 #endif
2817 }
2818 
2819 /*
2820  * Format IP addresses in ascii
2821  */
2822 
2823 const char *
2824 print_sockaddr_ex(const struct sockaddr *sa,
2825  const char *separator,
2826  const unsigned int flags,
2827  struct gc_arena *gc)
2828 {
2829  struct buffer out = alloc_buf_gc(128, gc);
2830  bool addr_is_defined = false;
2831  char hostaddr[NI_MAXHOST] = "";
2832  char servname[NI_MAXSERV] = "";
2833  int status;
2834 
2835  socklen_t salen = 0;
2836  switch (sa->sa_family)
2837  {
2838  case AF_INET:
2839  if (!(flags & PS_DONT_SHOW_FAMILY))
2840  {
2841  buf_puts(&out, "[AF_INET]");
2842  }
2843  salen = sizeof(struct sockaddr_in);
2844  addr_is_defined = ((struct sockaddr_in *) sa)->sin_addr.s_addr != 0;
2845  break;
2846 
2847  case AF_INET6:
2848  if (!(flags & PS_DONT_SHOW_FAMILY))
2849  {
2850  buf_puts(&out, "[AF_INET6]");
2851  }
2852  salen = sizeof(struct sockaddr_in6);
2853  addr_is_defined = !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *) sa)->sin6_addr);
2854  break;
2855 
2856  case AF_UNSPEC:
2857  if (!(flags & PS_DONT_SHOW_FAMILY))
2858  {
2859  return "[AF_UNSPEC]";
2860  }
2861  else
2862  {
2863  return "";
2864  }
2865 
2866  default:
2867  ASSERT(0);
2868  }
2869 
2870  status = getnameinfo(sa, salen, hostaddr, sizeof(hostaddr),
2871  servname, sizeof(servname), NI_NUMERICHOST | NI_NUMERICSERV);
2872 
2873  if (status!=0)
2874  {
2875  buf_printf(&out,"[nameinfo() err: %s]",gai_strerror(status));
2876  return BSTR(&out);
2877  }
2878 
2879  if (!(flags & PS_DONT_SHOW_ADDR))
2880  {
2881  if (addr_is_defined)
2882  {
2883  buf_puts(&out, hostaddr);
2884  }
2885  else
2886  {
2887  buf_puts(&out, "[undef]");
2888  }
2889  }
2890 
2891  if ((flags & PS_SHOW_PORT) || (flags & PS_SHOW_PORT_IF_DEFINED))
2892  {
2893  if (separator)
2894  {
2895  buf_puts(&out, separator);
2896  }
2897 
2898  buf_puts(&out, servname);
2899  }
2900 
2901  return BSTR(&out);
2902 }
2903 
2904 const char *
2906 {
2908 }
2909 
2910 #ifndef IF_NAMESIZE
2911 #define IF_NAMESIZE 16
2912 #endif
2913 
2914 const char *
2916  const char *separator,
2917  const unsigned int flags,
2918  struct gc_arena *gc)
2919 {
2920  if (act)
2921  {
2922  char ifname[IF_NAMESIZE] = "[undef]";
2923  struct buffer out = alloc_buf_gc(128, gc);
2924  buf_printf(&out, "%s", print_sockaddr_ex(&act->dest.addr.sa, separator, flags, gc));
2925 #if ENABLE_IP_PKTINFO
2926  if ((flags & PS_SHOW_PKTINFO) && addr_defined_ipi(act))
2927  {
2928  switch (act->dest.addr.sa.sa_family)
2929  {
2930  case AF_INET:
2931  {
2932  struct openvpn_sockaddr sa;
2933  CLEAR(sa);
2934  sa.addr.in4.sin_family = AF_INET;
2935 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2936  sa.addr.in4.sin_addr = act->pi.in4.ipi_spec_dst;
2937  if_indextoname(act->pi.in4.ipi_ifindex, ifname);
2938 #elif defined(IP_RECVDSTADDR)
2939  sa.addr.in4.sin_addr = act->pi.in4;
2940  ifname[0] = 0;
2941 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2942 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2943 #endif
2944  buf_printf(&out, " (via %s%%%s)",
2945  print_sockaddr_ex(&sa.addr.sa, separator, 0, gc),
2946  ifname);
2947  }
2948  break;
2949 
2950  case AF_INET6:
2951  {
2952  struct sockaddr_in6 sin6;
2953  char buf[INET6_ADDRSTRLEN] = "[undef]";
2954  CLEAR(sin6);
2955  sin6.sin6_family = AF_INET6;
2956  sin6.sin6_addr = act->pi.in6.ipi6_addr;
2957  if_indextoname(act->pi.in6.ipi6_ifindex, ifname);
2958  if (getnameinfo((struct sockaddr *)&sin6, sizeof(struct sockaddr_in6),
2959  buf, sizeof(buf), NULL, 0, NI_NUMERICHOST) == 0)
2960  {
2961  buf_printf(&out, " (via %s%%%s)", buf, ifname);
2962  }
2963  else
2964  {
2965  buf_printf(&out, " (via [getnameinfo() err]%%%s)", ifname);
2966  }
2967  }
2968  break;
2969  }
2970  }
2971 #endif /* if ENABLE_IP_PKTINFO */
2972  return BSTR(&out);
2973  }
2974  else
2975  {
2976  return "[NULL]";
2977  }
2978 }
2979 
2980 /*
2981  * Convert an in_addr_t in host byte order
2982  * to an ascii dotted quad.
2983  */
2984 const char *
2985 print_in_addr_t(in_addr_t addr, unsigned int flags, struct gc_arena *gc)
2986 {
2987  struct in_addr ia;
2988  struct buffer out = alloc_buf_gc(64, gc);
2989 
2990  if (addr || !(flags & IA_EMPTY_IF_UNDEF))
2991  {
2992  CLEAR(ia);
2993  ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl(addr);
2994 
2995  buf_printf(&out, "%s", inet_ntoa(ia));
2996  }
2997  return BSTR(&out);
2998 }
2999 
3000 /*
3001  * Convert an in6_addr in host byte order
3002  * to an ascii representation of an IPv6 address
3003  */
3004 const char *
3005 print_in6_addr(struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
3006 {
3007  struct buffer out = alloc_buf_gc(64, gc);
3008  char tmp_out_buf[64]; /* inet_ntop wants pointer to buffer */
3009 
3010  if (memcmp(&a6, &in6addr_any, sizeof(a6)) != 0
3011  || !(flags & IA_EMPTY_IF_UNDEF))
3012  {
3013  inet_ntop(AF_INET6, &a6, tmp_out_buf, sizeof(tmp_out_buf)-1);
3014  buf_printf(&out, "%s", tmp_out_buf );
3015  }
3016  return BSTR(&out);
3017 }
3018 
3019 #ifndef UINT8_MAX
3020 #define UINT8_MAX 0xff
3021 #endif
3022 
3023 /* add some offset to an ipv6 address
3024  * (add in steps of 8 bits, taking overflow into next round)
3025  */
3026 struct in6_addr
3027 add_in6_addr( struct in6_addr base, uint32_t add )
3028 {
3029  int i;
3030 
3031  for (i = 15; i>=0 && add > 0; i--)
3032  {
3033  register int carry;
3034  register uint32_t h;
3035 
3036  h = (unsigned char) base.s6_addr[i];
3037  base.s6_addr[i] = (h+add) & UINT8_MAX;
3038 
3039  /* using explicit carry for the 8-bit additions will catch
3040  * 8-bit and(!) 32-bit overruns nicely
3041  */
3042  carry = ((h & 0xff) + (add & 0xff)) >> 8;
3043  add = (add>>8) + carry;
3044  }
3045  return base;
3046 }
3047 
3048 /* set environmental variables for ip/port in *addr */
3049 void
3050 setenv_sockaddr(struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const unsigned int flags)
3051 {
3052  char name_buf[256];
3053 
3054  char buf[128];
3055  switch (addr->addr.sa.sa_family)
3056  {
3057  case AF_INET:
3058  if (flags & SA_IP_PORT)
3059  {
3060  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_ip", name_prefix);
3061  }
3062  else
3063  {
3064  openvpn_snprintf(name_buf, sizeof(name_buf), "%s", name_prefix);
3065  }
3066 
3067  setenv_str(es, name_buf, inet_ntoa(addr->addr.in4.sin_addr));
3068 
3069  if ((flags & SA_IP_PORT) && addr->addr.in4.sin_port)
3070  {
3071  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_port", name_prefix);
3072  setenv_int(es, name_buf, ntohs(addr->addr.in4.sin_port));
3073  }
3074  break;
3075 
3076  case AF_INET6:
3077  if (IN6_IS_ADDR_V4MAPPED( &addr->addr.in6.sin6_addr ))
3078  {
3079  struct in_addr ia;
3080  memcpy(&ia.s_addr, &addr->addr.in6.sin6_addr.s6_addr[12],
3081  sizeof(ia.s_addr));
3082  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_ip", name_prefix);
3083  openvpn_snprintf(buf, sizeof(buf), "%s", inet_ntoa(ia) );
3084  }
3085  else
3086  {
3087  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_ip6", name_prefix);
3088  getnameinfo(&addr->addr.sa, sizeof(struct sockaddr_in6),
3089  buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
3090  }
3091  setenv_str(es, name_buf, buf);
3092 
3093  if ((flags & SA_IP_PORT) && addr->addr.in6.sin6_port)
3094  {
3095  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_port", name_prefix);
3096  setenv_int(es, name_buf, ntohs(addr->addr.in6.sin6_port));
3097  }
3098  break;
3099  }
3100 }
3101 
3102 void
3103 setenv_in_addr_t(struct env_set *es, const char *name_prefix, in_addr_t addr, const unsigned int flags)
3104 {
3105  if (addr || !(flags & SA_SET_IF_NONZERO))
3106  {
3107  struct openvpn_sockaddr si;
3108  CLEAR(si);
3109  si.addr.in4.sin_family = AF_INET;
3110  si.addr.in4.sin_addr.s_addr = htonl(addr);
3111  setenv_sockaddr(es, name_prefix, &si, flags);
3112  }
3113 }
3114 
3115 void
3117  const char *name_prefix,
3118  const struct in6_addr *addr,
3119  const unsigned int flags)
3120 {
3121  if (!IN6_IS_ADDR_UNSPECIFIED(addr) || !(flags & SA_SET_IF_NONZERO))
3122  {
3123  struct openvpn_sockaddr si;
3124  CLEAR(si);
3125  si.addr.in6.sin6_family = AF_INET6;
3126  si.addr.in6.sin6_addr = *addr;
3127  setenv_sockaddr(es, name_prefix, &si, flags);
3128  }
3129 }
3130 
3131 void
3133  const char *name_prefix,
3134  const struct link_socket_actual *act,
3135  const unsigned int flags)
3136 {
3137  setenv_sockaddr(es, name_prefix, &act->dest, flags);
3138 }
3139 
3140 /*
3141  * Convert protocol names between index and ascii form.
3142  */
3143 
3144 struct proto_names {
3145  const char *short_form;
3146  const char *display_form;
3148  int proto;
3149 };
3150 
3151 /* Indexed by PROTO_x */
3152 static const struct proto_names proto_names[] = {
3153  {"proto-uninitialized", "proto-NONE", AF_UNSPEC, PROTO_NONE},
3154  /* try IPv4 and IPv6 (client), bind dual-stack (server) */
3155  {"udp", "UDP", AF_UNSPEC, PROTO_UDP},
3156  {"tcp-server", "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER},
3157  {"tcp-client", "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT},
3158  {"tcp", "TCP", AF_UNSPEC, PROTO_TCP},
3159  /* force IPv4 */
3160  {"udp4", "UDPv4", AF_INET, PROTO_UDP},
3161  {"tcp4-server","TCPv4_SERVER", AF_INET, PROTO_TCP_SERVER},
3162  {"tcp4-client","TCPv4_CLIENT", AF_INET, PROTO_TCP_CLIENT},
3163  {"tcp4", "TCPv4", AF_INET, PROTO_TCP},
3164  /* force IPv6 */
3165  {"udp6","UDPv6", AF_INET6, PROTO_UDP},
3166  {"tcp6-server","TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
3167  {"tcp6-client","TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
3168  {"tcp6","TCPv6", AF_INET6, PROTO_TCP},
3169 };
3170 
3171 bool
3173 {
3174  if (proto < 0 || proto >= PROTO_N)
3175  {
3176  ASSERT(0);
3177  }
3178  return proto != PROTO_NONE;
3179 }
3180 bool
3182 {
3183  return proto_is_udp(proto);
3184 }
3185 
3186 bool
3188 {
3189  if (proto < 0 || proto >= PROTO_N)
3190  {
3191  ASSERT(0);
3192  }
3193  return proto == PROTO_UDP;
3194 }
3195 
3196 bool
3198 {
3199  if (proto < 0 || proto >= PROTO_N)
3200  {
3201  ASSERT(0);
3202  }
3203  return proto == PROTO_TCP_CLIENT || proto == PROTO_TCP_SERVER;
3204 }
3205 
3206 int
3207 ascii2proto(const char *proto_name)
3208 {
3209  int i;
3210  for (i = 0; i < SIZE(proto_names); ++i)
3211  {
3212  if (!strcmp(proto_name, proto_names[i].short_form))
3213  {
3214  return proto_names[i].proto;
3215  }
3216  }
3217  return -1;
3218 }
3219 
3221 ascii2af(const char *proto_name)
3222 {
3223  int i;
3224  for (i = 0; i < SIZE(proto_names); ++i)
3225  {
3226  if (!strcmp(proto_name, proto_names[i].short_form))
3227  {
3228  return proto_names[i].proto_af;
3229  }
3230  }
3231  return 0;
3232 }
3233 
3234 const char *
3236 {
3237  unsigned int i;
3238  for (i = 0; i < SIZE(proto_names); ++i)
3239  {
3240  if (proto_names[i].proto_af == af && proto_names[i].proto == proto)
3241  {
3242  if (display_form)
3243  {
3244  return proto_names[i].display_form;
3245  }
3246  else
3247  {
3248  return proto_names[i].short_form;
3249  }
3250  }
3251  }
3252 
3253  return "[unknown protocol]";
3254 }
3255 
3256 const char *
3258 {
3259  struct buffer out = alloc_buf_gc(256, gc);
3260  int i;
3261 
3262  for (i = 0; i < SIZE(proto_names); ++i)
3263  {
3264  if (i)
3265  {
3266  buf_printf(&out, " ");
3267  }
3268  buf_printf(&out, "[%s]", proto_names[i].short_form);
3269  }
3270  return BSTR(&out);
3271 }
3272 
3273 const char *
3275 {
3276  switch (af)
3277  {
3278  case AF_INET: return "AF_INET";
3279 
3280  case AF_INET6: return "AF_INET6";
3281  }
3282  return "AF_UNSPEC";
3283 }
3284 
3285 /*
3286  * Given a local proto, return local proto
3287  * if !remote, or compatible remote proto
3288  * if remote.
3289  *
3290  * This is used for options compatibility
3291  * checking.
3292  *
3293  * IPv6 and IPv4 protocols are comptabile but OpenVPN
3294  * has always sent UDPv4, TCPv4 over the wire. Keep these
3295  * strings for backward compatibility
3296  */
3297 const char *
3298 proto_remote(int proto, bool remote)
3299 {
3300  ASSERT(proto >= 0 && proto < PROTO_N);
3301  if (proto == PROTO_UDP)
3302  {
3303  return "UDPv4";
3304  }
3305 
3306  if ( (remote && proto == PROTO_TCP_CLIENT)
3307  || (!remote && proto == PROTO_TCP_SERVER))
3308  {
3309  return "TCPv4_SERVER";
3310  }
3311  if ( (remote && proto == PROTO_TCP_SERVER)
3312  || (!remote && proto == PROTO_TCP_CLIENT))
3313  {
3314  return "TCPv4_CLIENT";
3315  }
3316 
3317  ASSERT(0);
3318  return ""; /* Make the compiler happy */
3319 }
3320 
3321 /*
3322  * Bad incoming address lengths that differ from what
3323  * we expect are considered to be fatal errors.
3324  */
3325 void
3326 bad_address_length(int actual, int expected)
3327 {
3328  msg(M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
3329  actual,
3330  expected);
3331 }
3332 
3333 /*
3334  * Socket Read Routines
3335  */
3336 
3337 int
3339  struct buffer *buf)
3340 {
3341  int len = 0;
3342 
3343  if (!sock->stream_buf.residual_fully_formed)
3344  {
3345 #ifdef _WIN32
3346  len = socket_finalize(sock->sd, &sock->reads, buf, NULL);
3347 #else
3348  struct buffer frag;
3349  stream_buf_get_next(&sock->stream_buf, &frag);
3350  len = recv(sock->sd, BPTR(&frag), BLEN(&frag), MSG_NOSIGNAL);
3351 #endif
3352 
3353  if (!len)
3354  {
3355  sock->stream_reset = true;
3356  }
3357  if (len <= 0)
3358  {
3359  return buf->len = len;
3360  }
3361  }
3362 
3364  || stream_buf_added(&sock->stream_buf, len)) /* packet complete? */
3365  {
3366  stream_buf_get_final(&sock->stream_buf, buf);
3367  stream_buf_reset(&sock->stream_buf);
3368  return buf->len;
3369  }
3370  else
3371  {
3372  return buf->len = 0; /* no error, but packet is still incomplete */
3373  }
3374 }
3375 
3376 #ifndef _WIN32
3377 
3378 #if ENABLE_IP_PKTINFO
3379 
3380 /* make the buffer large enough to handle ancillary socket data for
3381  * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
3382  */
3383 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3384 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3385  CMSG_SPACE(sizeof(struct in_pktinfo)) )
3386 #else
3387 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3388  CMSG_SPACE(sizeof(struct in_addr)) )
3389 #endif
3390 
3391 static socklen_t
3392 link_socket_read_udp_posix_recvmsg(struct link_socket *sock,
3393  struct buffer *buf,
3394  struct link_socket_actual *from)
3395 {
3396  struct iovec iov;
3397  uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];
3398  struct msghdr mesg;
3399  socklen_t fromlen = sizeof(from->dest.addr);
3400 
3401  iov.iov_base = BPTR(buf);
3402  iov.iov_len = buf_forward_capacity_total(buf);
3403  mesg.msg_iov = &iov;
3404  mesg.msg_iovlen = 1;
3405  mesg.msg_name = &from->dest.addr;
3406  mesg.msg_namelen = fromlen;
3407  mesg.msg_control = pktinfo_buf;
3408  mesg.msg_controllen = sizeof pktinfo_buf;
3409  buf->len = recvmsg(sock->sd, &mesg, 0);
3410  if (buf->len >= 0)
3411  {
3412  struct cmsghdr *cmsg;
3413  fromlen = mesg.msg_namelen;
3414  cmsg = CMSG_FIRSTHDR(&mesg);
3415  if (cmsg != NULL
3416  && CMSG_NXTHDR(&mesg, cmsg) == NULL
3417 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3418  && cmsg->cmsg_level == SOL_IP
3419  && cmsg->cmsg_type == IP_PKTINFO
3420  && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo)) )
3421 #elif defined(IP_RECVDSTADDR)
3422  && cmsg->cmsg_level == IPPROTO_IP
3423  && cmsg->cmsg_type == IP_RECVDSTADDR
3424  && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_addr)) )
3425 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3426 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3427 #endif
3428  {
3429 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3430  struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA(cmsg);
3431  from->pi.in4.ipi_ifindex = pkti->ipi_ifindex;
3432  from->pi.in4.ipi_spec_dst = pkti->ipi_spec_dst;
3433 #elif defined(IP_RECVDSTADDR)
3434  from->pi.in4 = *(struct in_addr *) CMSG_DATA(cmsg);
3435 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3436 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3437 #endif
3438  }
3439  else if (cmsg != NULL
3440  && CMSG_NXTHDR(&mesg, cmsg) == NULL
3441  && cmsg->cmsg_level == IPPROTO_IPV6
3442  && cmsg->cmsg_type == IPV6_PKTINFO
3443  && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in6_pktinfo)) )
3444  {
3445  struct in6_pktinfo *pkti6 = (struct in6_pktinfo *) CMSG_DATA(cmsg);
3446  from->pi.in6.ipi6_ifindex = pkti6->ipi6_ifindex;
3447  from->pi.in6.ipi6_addr = pkti6->ipi6_addr;
3448  }
3449  else if (cmsg != NULL)
3450  {
3451  msg(M_WARN, "CMSG received that cannot be parsed (cmsg_level=%d, cmsg_type=%d, cmsg=len=%d)", (int)cmsg->cmsg_level, (int)cmsg->cmsg_type, (int)cmsg->cmsg_len );
3452  }
3453  }
3454 
3455  return fromlen;
3456 }
3457 #endif /* if ENABLE_IP_PKTINFO */
3458 
3459 int
3460 link_socket_read_udp_posix(struct link_socket *sock,
3461  struct buffer *buf,
3462  struct link_socket_actual *from)
3463 {
3464  socklen_t fromlen = sizeof(from->dest.addr);
3465  socklen_t expectedlen = af_addr_size(sock->info.af);
3466  addr_zero_host(&from->dest);
3467 #if ENABLE_IP_PKTINFO
3468  /* Both PROTO_UDPv4 and PROTO_UDPv6 */
3469  if (sock->info.proto == PROTO_UDP && sock->sockflags & SF_USE_IP_PKTINFO)
3470  {
3471  fromlen = link_socket_read_udp_posix_recvmsg(sock, buf, from);
3472  }
3473  else
3474 #endif
3475  buf->len = recvfrom(sock->sd, BPTR(buf), buf_forward_capacity(buf), 0,
3476  &from->dest.addr.sa, &fromlen);
3477  /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3478  if (buf->len >= 0 && expectedlen && fromlen != expectedlen)
3479  {
3480  bad_address_length(fromlen, expectedlen);
3481  }
3482  return buf->len;
3483 }
3484 
3485 #endif /* ifndef _WIN32 */
3486 
3487 /*
3488  * Socket Write Routines
3489  */
3490 
3491 int
3493  struct buffer *buf,
3494  struct link_socket_actual *to)
3495 {
3496  packet_size_type len = BLEN(buf);
3497  dmsg(D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
3498  ASSERT(len <= sock->stream_buf.maxlen);
3499  len = htonps(len);
3500  ASSERT(buf_write_prepend(buf, &len, sizeof(len)));
3501 #ifdef _WIN32
3502  return link_socket_write_win32(sock, buf, to);
3503 #else
3504  return link_socket_write_tcp_posix(sock, buf, to);
3505 #endif
3506 }
3507 
3508 #if ENABLE_IP_PKTINFO
3509 
3510 size_t
3511 link_socket_write_udp_posix_sendmsg(struct link_socket *sock,
3512  struct buffer *buf,
3513  struct link_socket_actual *to)
3514 {
3515  struct iovec iov;
3516  struct msghdr mesg;
3517  struct cmsghdr *cmsg;
3518  uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];
3519 
3520  iov.iov_base = BPTR(buf);
3521  iov.iov_len = BLEN(buf);
3522  mesg.msg_iov = &iov;
3523  mesg.msg_iovlen = 1;
3524  switch (to->dest.addr.sa.sa_family)
3525  {
3526  case AF_INET:
3527  {
3528  mesg.msg_name = &to->dest.addr.sa;
3529  mesg.msg_namelen = sizeof(struct sockaddr_in);
3530  mesg.msg_control = pktinfo_buf;
3531  mesg.msg_flags = 0;
3532 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3533  mesg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
3534  cmsg = CMSG_FIRSTHDR(&mesg);
3535  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
3536  cmsg->cmsg_level = SOL_IP;
3537  cmsg->cmsg_type = IP_PKTINFO;
3538  {
3539  struct in_pktinfo *pkti;
3540  pkti = (struct in_pktinfo *) CMSG_DATA(cmsg);
3541  pkti->ipi_ifindex = to->pi.in4.ipi_ifindex;
3542  pkti->ipi_spec_dst = to->pi.in4.ipi_spec_dst;
3543  pkti->ipi_addr.s_addr = 0;
3544  }
3545 #elif defined(IP_RECVDSTADDR)
3546  ASSERT( CMSG_SPACE(sizeof(struct in_addr)) <= sizeof(pktinfo_buf) );
3547  mesg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
3548  cmsg = CMSG_FIRSTHDR(&mesg);
3549  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
3550  cmsg->cmsg_level = IPPROTO_IP;
3551  cmsg->cmsg_type = IP_RECVDSTADDR;
3552  *(struct in_addr *) CMSG_DATA(cmsg) = to->pi.in4;
3553 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3554 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3555 #endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3556  break;
3557  }
3558 
3559  case AF_INET6:
3560  {
3561  struct in6_pktinfo *pkti6;
3562  mesg.msg_name = &to->dest.addr.sa;
3563  mesg.msg_namelen = sizeof(struct sockaddr_in6);
3564 
3565  ASSERT( CMSG_SPACE(sizeof(struct in6_pktinfo)) <= sizeof(pktinfo_buf) );
3566  mesg.msg_control = pktinfo_buf;
3567  mesg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
3568  mesg.msg_flags = 0;
3569  cmsg = CMSG_FIRSTHDR(&mesg);
3570  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
3571  cmsg->cmsg_level = IPPROTO_IPV6;
3572  cmsg->cmsg_type = IPV6_PKTINFO;
3573 
3574  pkti6 = (struct in6_pktinfo *) CMSG_DATA(cmsg);
3575  pkti6->ipi6_ifindex = to->pi.in6.ipi6_ifindex;
3576  pkti6->ipi6_addr = to->pi.in6.ipi6_addr;
3577  break;
3578  }
3579 
3580  default: ASSERT(0);
3581  }
3582  return sendmsg(sock->sd, &mesg, 0);
3583 }
3584 
3585 #endif /* if ENABLE_IP_PKTINFO */
3586 
3587 /*
3588  * Win32 overlapped socket I/O functions.
3589  */
3590 
3591 #ifdef _WIN32
3592 
3593 int
3594 socket_recv_queue(struct link_socket *sock, int maxsize)
3595 {
3596  if (sock->reads.iostate == IOSTATE_INITIAL)
3597  {
3598  WSABUF wsabuf[1];
3599  int status;
3600 
3601  /* reset buf to its initial state */
3602  if (proto_is_udp(sock->info.proto))
3603  {
3604  sock->reads.buf = sock->reads.buf_init;
3605  }
3606  else if (proto_is_tcp(sock->info.proto))
3607  {
3608  stream_buf_get_next(&sock->stream_buf, &sock->reads.buf);
3609  }
3610  else
3611  {
3612  ASSERT(0);
3613  }
3614 
3615  /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3616  wsabuf[0].buf = BPTR(&sock->reads.buf);
3617  wsabuf[0].len = maxsize ? maxsize : BLEN(&sock->reads.buf);
3618 
3619  /* check for buffer overflow */
3620  ASSERT(wsabuf[0].len <= BLEN(&sock->reads.buf));
3621 
3622  /* the overlapped read will signal this event on I/O completion */
3623  ASSERT(ResetEvent(sock->reads.overlapped.hEvent));
3624  sock->reads.flags = 0;
3625 
3626  if (proto_is_udp(sock->info.proto))
3627  {
3628  sock->reads.addr_defined = true;
3629  sock->reads.addrlen = sizeof(sock->reads.addr6);
3630  status = WSARecvFrom(
3631  sock->sd,
3632  wsabuf,
3633  1,
3634  &sock->reads.size,
3635  &sock->reads.flags,
3636  (struct sockaddr *) &sock->reads.addr,
3637  &sock->reads.addrlen,
3638  &sock->reads.overlapped,
3639  NULL);
3640  }
3641  else if (proto_is_tcp(sock->info.proto))
3642  {
3643  sock->reads.addr_defined = false;
3644  status = WSARecv(
3645  sock->sd,
3646  wsabuf,
3647  1,
3648  &sock->reads.size,
3649  &sock->reads.flags,
3650  &sock->reads.overlapped,
3651  NULL);
3652  }
3653  else
3654  {
3655  status = 0;
3656  ASSERT(0);
3657  }
3658 
3659  if (!status) /* operation completed immediately? */
3660  {
3661  /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3662  int af_len = af_addr_size(sock->info.af);
3663  if (sock->reads.addr_defined && af_len && sock->reads.addrlen != af_len)
3664  {
3665  bad_address_length(sock->reads.addrlen, af_len);
3666  }
3668 
3669  /* since we got an immediate return, we must signal the event object ourselves */
3670  ASSERT(SetEvent(sock->reads.overlapped.hEvent));
3671  sock->reads.status = 0;
3672 
3673  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
3674  (int) wsabuf[0].len,
3675  (int) sock->reads.size);
3676  }
3677  else
3678  {
3679  status = WSAGetLastError();
3680  if (status == WSA_IO_PENDING) /* operation queued? */
3681  {
3682  sock->reads.iostate = IOSTATE_QUEUED;
3683  sock->reads.status = status;
3684  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
3685  (int) wsabuf[0].len);
3686  }
3687  else /* error occurred */
3688  {
3689  struct gc_arena gc = gc_new();
3690  ASSERT(SetEvent(sock->reads.overlapped.hEvent));
3692  sock->reads.status = status;
3693  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
3694  (int) wsabuf[0].len,
3695  strerror_win32(status, &gc));
3696  gc_free(&gc);
3697  }
3698  }
3699  }
3700  return sock->reads.iostate;
3701 }
3702 
3703 int
3704 socket_send_queue(struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
3705 {
3706  if (sock->writes.iostate == IOSTATE_INITIAL)
3707  {
3708  WSABUF wsabuf[1];
3709  int status;
3710 
3711  /* make a private copy of buf */
3712  sock->writes.buf = sock->writes.buf_init;
3713  sock->writes.buf.len = 0;
3714  ASSERT(buf_copy(&sock->writes.buf, buf));
3715 
3716  /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3717  wsabuf[0].buf = BPTR(&sock->writes.buf);
3718  wsabuf[0].len = BLEN(&sock->writes.buf);
3719 
3720  /* the overlapped write will signal this event on I/O completion */
3721  ASSERT(ResetEvent(sock->writes.overlapped.hEvent));
3722  sock->writes.flags = 0;
3723 
3724  if (proto_is_udp(sock->info.proto))
3725  {
3726  /* set destination address for UDP writes */
3727  sock->writes.addr_defined = true;
3728  if (to->dest.addr.sa.sa_family == AF_INET6)
3729  {
3730  sock->writes.addr6 = to->dest.addr.in6;
3731  sock->writes.addrlen = sizeof(sock->writes.addr6);
3732  }
3733  else
3734  {
3735  sock->writes.addr = to->dest.addr.in4;
3736  sock->writes.addrlen = sizeof(sock->writes.addr);
3737  }
3738 
3739  status = WSASendTo(
3740  sock->sd,
3741  wsabuf,
3742  1,
3743  &sock->writes.size,
3744  sock->writes.flags,
3745  (struct sockaddr *) &sock->writes.addr,
3746  sock->writes.addrlen,
3747  &sock->writes.overlapped,
3748  NULL);
3749  }
3750  else if (proto_is_tcp(sock->info.proto))
3751  {
3752  /* destination address for TCP writes was established on connection initiation */
3753  sock->writes.addr_defined = false;
3754 
3755  status = WSASend(
3756  sock->sd,
3757  wsabuf,
3758  1,
3759  &sock->writes.size,
3760  sock->writes.flags,
3761  &sock->writes.overlapped,
3762  NULL);
3763  }
3764  else
3765  {
3766  status = 0;
3767  ASSERT(0);
3768  }
3769 
3770  if (!status) /* operation completed immediately? */
3771  {
3773 
3774  /* since we got an immediate return, we must signal the event object ourselves */
3775  ASSERT(SetEvent(sock->writes.overlapped.hEvent));
3776 
3777  sock->writes.status = 0;
3778 
3779  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3780  (int) wsabuf[0].len,
3781  (int) sock->writes.size);
3782  }
3783  else
3784  {
3785  status = WSAGetLastError();
3786  if (status == WSA_IO_PENDING) /* operation queued? */
3787  {
3788  sock->writes.iostate = IOSTATE_QUEUED;
3789  sock->writes.status = status;
3790  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
3791  (int) wsabuf[0].len);
3792  }
3793  else /* error occurred */
3794  {
3795  struct gc_arena gc = gc_new();
3796  ASSERT(SetEvent(sock->writes.overlapped.hEvent));
3798  sock->writes.status = status;
3799 
3800  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
3801  (int) wsabuf[0].len,
3802  strerror_win32(status, &gc));
3803 
3804  gc_free(&gc);
3805  }
3806  }
3807  }
3808  return sock->writes.iostate;
3809 }
3810 
3811 int
3813  struct overlapped_io *io,
3814  struct buffer *buf,
3815  struct link_socket_actual *from)
3816 {
3817  int ret = -1;
3818  BOOL status;
3819 
3820  switch (io->iostate)
3821  {
3822  case IOSTATE_QUEUED:
3823  status = WSAGetOverlappedResult(
3824  s,
3825  &io->overlapped,
3826  &io->size,
3827  FALSE,
3828  &io->flags
3829  );
3830  if (status)
3831  {
3832  /* successful return for a queued operation */
3833  if (buf)
3834  {
3835  *buf = io->buf;
3836  }
3837  ret = io->size;
3838  io->iostate = IOSTATE_INITIAL;
3839  ASSERT(ResetEvent(io->overlapped.hEvent));
3840 
3841  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
3842  }
3843  else
3844  {
3845  /* error during a queued operation */
3846  ret = -1;
3847  if (WSAGetLastError() != WSA_IO_INCOMPLETE)
3848  {
3849  /* if no error (i.e. just not finished yet), then DON'T execute this code */
3850  io->iostate = IOSTATE_INITIAL;
3851  ASSERT(ResetEvent(io->overlapped.hEvent));
3852  msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion error");
3853  }
3854  }
3855  break;
3856 
3858  io->iostate = IOSTATE_INITIAL;
3859  ASSERT(ResetEvent(io->overlapped.hEvent));
3860  if (io->status)
3861  {
3862  /* error return for a non-queued operation */
3863  WSASetLastError(io->status);
3864  ret = -1;
3865  msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion non-queued error");
3866  }
3867  else
3868  {
3869  /* successful return for a non-queued operation */
3870  if (buf)
3871  {
3872  *buf = io->buf;
3873  }
3874  ret = io->size;
3875  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
3876  }
3877  break;
3878 
3879  case IOSTATE_INITIAL: /* were we called without proper queueing? */
3880  WSASetLastError(WSAEINVAL);
3881  ret = -1;
3882  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
3883  break;
3884 
3885  default:
3886  ASSERT(0);
3887  }
3888 
3889  /* return from address if requested */
3890  if (from)
3891  {
3892  if (ret >= 0 && io->addr_defined)
3893  {
3894  /* TODO(jjo): streamline this mess */
3895  /* in this func we don't have relevant info about the PF_ of this
3896  * endpoint, as link_socket_actual will be zero for the 1st received packet
3897  *
3898  * Test for inets PF_ possible sizes
3899  */
3900  switch (io->addrlen)
3901  {
3902  case sizeof(struct sockaddr_in):
3903  case sizeof(struct sockaddr_in6):
3904  /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3905  * under _WIN32*/
3906  case sizeof(struct sockaddr_in6)-4:
3907  break;
3908 
3909  default:
3910  bad_address_length(io->addrlen, af_addr_size(io->addr.sin_family));
3911  }
3912 
3913  switch (io->addr.sin_family)
3914  {
3915  case AF_INET:
3916  from->dest.addr.in4 = io->addr;
3917  break;
3918 
3919  case AF_INET6:
3920  from->dest.addr.in6 = io->addr6;
3921  break;
3922  }
3923  }
3924  else
3925  {
3926  CLEAR(from->dest.addr);
3927  }
3928  }
3929 
3930  if (buf)
3931  {
3932  buf->len = ret;
3933  }
3934  return ret;
3935 }
3936 
3937 #endif /* _WIN32 */
3938 
3939 /*
3940  * Socket event notification
3941  */
3942 
3943 unsigned int
3945  struct event_set *es,
3946  unsigned int rwflags,
3947  void *arg,
3948  unsigned int *persistent)
3949 {
3950  if (s)
3951  {
3952  if ((rwflags & EVENT_READ) && !stream_buf_read_setup(s))
3953  {
3954  ASSERT(!persistent);
3955  rwflags &= ~EVENT_READ;
3956  }
3957 
3958 #ifdef _WIN32
3959  if (rwflags & EVENT_READ)
3960  {
3961  socket_recv_queue(s, 0);
3962  }
3963 #endif
3964 
3965  /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
3966  if (!persistent || *persistent != rwflags)
3967  {
3968  event_ctl(es, socket_event_handle(s), rwflags, arg);
3969  if (persistent)
3970  {
3971  *persistent = rwflags;
3972  }
3973  }
3974 
3975  s->rwflags_debug = rwflags;
3976  }
3977  return rwflags;
3978 }
3979 
3980 void
3982 {
3983  if (sd && socket_defined(*sd))
3984  {
3985  openvpn_close_socket(*sd);
3986  *sd = SOCKET_UNDEFINED;
3987  }
3988 }
3989 
3990 #if UNIX_SOCK_SUPPORT
3991 
3992 /*
3993  * code for unix domain sockets
3994  */
3995 
3996 const char *
3997 sockaddr_unix_name(const struct sockaddr_un *local, const char *null)
3998 {
3999  if (local && local->sun_family == PF_UNIX)
4000  {
4001  return local->sun_path;
4002  }
4003  else
4004  {
4005  return null;
4006  }
4007 }
4008 
4010 create_socket_unix(void)
4011 {
4013 
4014  if ((sd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
4015  {
4016  msg(M_ERR, "Cannot create unix domain socket");
4017  }
4018 
4019  /* set socket file descriptor to not pass across execs, so that
4020  * scripts don't have access to it */
4021  set_cloexec(sd);
4022 
4023  return sd;
4024 }
4025 
4026 void
4027 socket_bind_unix(socket_descriptor_t sd,
4028  struct sockaddr_un *local,
4029  const char *prefix)
4030 {
4031  struct gc_arena gc = gc_new();
4032 
4033 #ifdef HAVE_UMASK
4034  const mode_t orig_umask = umask(0);
4035 #endif
4036 
4037  if (bind(sd, (struct sockaddr *) local, sizeof(struct sockaddr_un)))
4038  {
4039  msg(M_FATAL | M_ERRNO,
4040  "%s: Socket bind[%d] failed on unix domain socket %s",
4041  prefix,
4042  (int)sd,
4043  sockaddr_unix_name(local, "NULL"));
4044  }
4045 
4046 #ifdef HAVE_UMASK
4047  umask(orig_umask);
4048 #endif
4049 
4050  gc_free(&gc);
4051 }
4052 
4054 socket_accept_unix(socket_descriptor_t sd,
4055  struct sockaddr_un *remote)
4056 {
4057  socklen_t remote_len = sizeof(struct sockaddr_un);
4058  socket_descriptor_t ret;
4059 
4060  CLEAR(*remote);
4061  ret = accept(sd, (struct sockaddr *) remote, &remote_len);
4062  if (ret >= 0)
4063  {
4064  /* set socket file descriptor to not pass across execs, so that
4065  * scripts don't have access to it */
4066  set_cloexec(ret);
4067  }
4068  return ret;
4069 }
4070 
4071 int
4072 socket_connect_unix(socket_descriptor_t sd,
4073  struct sockaddr_un *remote)
4074 {
4075  int status = connect(sd, (struct sockaddr *) remote, sizeof(struct sockaddr_un));
4076  if (status)
4077  {
4078  status = openvpn_errno();
4079  }
4080  return status;
4081 }
4082 
4083 void
4084 sockaddr_unix_init(struct sockaddr_un *local, const char *path)
4085 {
4086  local->sun_family = PF_UNIX;
4087  strncpynt(local->sun_path, path, sizeof(local->sun_path));
4088 }
4089 
4090 void
4091 socket_delete_unix(const struct sockaddr_un *local)
4092 {
4093  const char *name = sockaddr_unix_name(local, NULL);
4094 #ifdef HAVE_UNLINK
4095  if (name && strlen(name))
4096  {
4097  unlink(name);
4098  }
4099 #endif
4100 }
4101 
4102 bool
4103 unix_socket_get_peer_uid_gid(const socket_descriptor_t sd, int *uid, int *gid)
4104 {
4105 #ifdef HAVE_GETPEEREID
4106  uid_t u;
4107  gid_t g;
4108  if (getpeereid(sd, &u, &g) == -1)
4109  {
4110  return false;
4111  }
4112  if (uid)
4113  {
4114  *uid = u;
4115  }
4116  if (gid)
4117  {
4118  *gid = g;
4119  }
4120  return true;
4121 #elif defined(SO_PEERCRED)
4122  struct ucred peercred;
4123  socklen_t so_len = sizeof(peercred);
4124  if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
4125  {
4126  return false;
4127  }
4128  if (uid)
4129  {
4130  *uid = peercred.uid;
4131  }
4132  if (gid)
4133  {
4134  *gid = peercred.gid;
4135  }
4136  return true;
4137 #else /* ifdef HAVE_GETPEEREID */
4138  return false;
4139 #endif /* ifdef HAVE_GETPEEREID */
4140 }
4141 
4142 #endif /* if UNIX_SOCK_SUPPORT */
#define M_NONFATAL
Definition: error.h:95
int status
Definition: win32.h:206
bool string_class(const char *str, const unsigned int inclusive, const unsigned int exclusive)
Definition: buffer.c:1062
bool argv_printf_cat(struct argv *argres, const char *format,...)
printf() inspired argv concatenation.
Definition: argv.c:466
#define OPENVPN_STATE_RESOLVE
Definition: manage.h:506
#define PS_SHOW_PORT_IF_DEFINED
Definition: socket.h:349
#define CC_ALNUM
Definition: buffer.h:910
static void strncpynt(char *dest, const char *src, size_t maxlen)
Definition: buffer.h:348
const char * socks_proxy_port
Definition: options.h:104
struct buffer buf_init
Definition: win32.h:213
#define MSG_NOSIGNAL
Definition: socket.h:257
static int socket_get_rcvbuf(int sd)
Definition: socket.c:867
bool error
Definition: socket.h:140
#define D_INIT_MEDIUM
Definition: errlevel.h:105
int openvpn_getaddrinfo(unsigned int flags, const char *hostname, const char *servname, int resolve_retry_seconds, volatile int *signal_received, int ai_family, struct addrinfo **res)
Definition: socket.c:440
#define GETADDR_WARN_ON_SIGNAL
Definition: socket.h:528
struct options options
Options loaded from command line or configuration file.
Definition: openvpn.h:505
#define D_OSBUF
Definition: errlevel.h:91
void free_buf(struct buffer *buf)
Definition: buffer.c:185
HANDLE read
Definition: win32.h:76
struct link_socket * link_socket_new(void)
Definition: socket.c:1857
void init_net_event_win32(struct rw_handle *event, long network_events, socket_descriptor_t sd, unsigned int flags)
Definition: win32.c:218
struct sockaddr_in6 addr6
Definition: win32.h:210
void setenv_trusted(struct env_set *es, const struct link_socket_info *info)
Definition: socket.c:2431
struct argv argv_new(void)
Allocates a new struct argv and ensures it is initialised.
Definition: argv.c:90
#define openvpn_errno()
Definition: error.h:74
struct cached_dns_entry * dns_cache
Definition: openvpn.h:163
int len
Definition: socket.h:138
#define streq(x, y)
Definition: options.h:653
void establish_socks_proxy_passthru(struct socks_proxy_info *p, socket_descriptor_t sd, const char *host, const char *servname, volatile int *signal_received)
Definition: socks.c:448
in_addr_t getaddr(unsigned int flags, const char *hostname, int resolve_retry_seconds, bool *succeeded, volatile int *signal_received)
Translate an IPv4 addr or hostname from string form to in_addr_t.
Definition: socket.c:193
#define GETADDR_TRY_ONCE
Definition: socket.h:530
sa_family_t ascii2af(const char *proto_name)
Definition: socket.c:3221
const char * print_in6_addr(struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
Definition: socket.c:3005
#define M_INFO
Definition: errlevel.h:55
Contains all state information for one tunnel.
Definition: openvpn.h:503
Packet geometry parameters.
Definition: mtu.h:93
bool proto_is_tcp(int proto)
Definition: socket.c:3197
static bool streqnull(const char *a, const char *b)
Definition: socket.c:237
void overlapped_io_init(struct overlapped_io *o, const struct frame *frame, BOOL event_state, bool tuntap_buffer)
Definition: win32.c:165
#define IPv6_UDP_HEADER_SIZE
Definition: socket.h:598
bool proto_is_udp(int proto)
Definition: socket.c:3187
static int af_addr_size(sa_family_t af)
Definition: socket.h:867
#define SA_IP_PORT
Definition: socket.h:405
void throw_signal_soft(const int signum, const char *signal_text)
Definition: sig.c:111
static socket_descriptor_t socket_listen_accept(socket_descriptor_t sd, struct link_socket_actual *act, const char *remote_dynamic, const struct addrinfo *local, bool do_listen, bool nowait, volatile int *signal_received)
Definition: socket.c:1286
DWORD size
Definition: win32.h:204
const char * print_link_socket_actual(const struct link_socket_actual *act, struct gc_arena *gc)
Definition: socket.c:2905
static void gc_free(struct gc_arena *a)
Definition: buffer.h:1023
OVERLAPPED overlapped
Definition: win32.h:203
bool proto_is_net(int proto)
Definition: socket.c:3172
static void frame_add_to_extra_frame(struct frame *frame, const unsigned int increment)
Definition: mtu.h:274
static int plugin_call(const struct plugin_list *pl, const int type, const struct argv *av, struct plugin_return *pr, struct env_set *es)
Definition: plugin.h:202
#define M_MSG_VIRT_OUT
Definition: error.h:104
#define dmsg
Definition: error.h:174
#define IPv6_TCP_HEADER_SIZE
Definition: socket.h:599
static int link_socket_write_win32(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *to)
Definition: socket.h:1089
#define OIA_HOSTNAME
Definition: socket.h:463
static bool buf_safe(const struct buffer *buf, int len)
Definition: buffer.h:541
struct man_connection connection
Definition: manage.h:326
unsigned short sa_family_t
Definition: syshead.h:448
Definition: options.h:86
#define SIGUSR1
Definition: config-msvc.h:152
#define SET_MTU_UPPER_BOUND
Definition: mtu.h:221
#define CC_DIGIT
Definition: buffer.h:914
struct buffer alloc_buf(size_t size)
Definition: buffer.c:64
static void stream_buf_get_final(struct stream_buf *sb, struct buffer *buf)
Definition: socket.c:2690
struct buffer buf_init
Definition: socket.h:131
struct connection_list * connection_list
Definition: options.h:231
int openvpn_inet_aton(const char *dotted_quad, struct in_addr *addr)
Definition: socket.c:665
#define LS_MODE_DEFAULT
Definition: socket.h:196
unsigned int sockflags
Definition: options.h:356
bool buf_printf(struct buffer *buf, const char *format,...)
Definition: buffer.c:245
void set_mtu_discover_type(int sd, int mtu_type, sa_family_t proto_af)
Definition: mtu.c:169
const char * proto2ascii_all(struct gc_arena *gc)
Definition: socket.c:3257
int resolve_retry_seconds
Definition: options.h:297
#define SF_TCP_NODELAY
Definition: socket.h:209
const int proto_overhead[]
Definition: socket.c:47
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition: env_set.c:285
#define SF_GETADDRINFO_DGRAM
Definition: socket.h:212
#define OPENVPN_STATE_TCP_CONNECT
Definition: manage.h:507
#define SIZE(x)
Definition: basic.h:30
#define D_READ_WRITE
Definition: errlevel.h:164
#define in_addr_t
Definition: config-msvc.h:140
const char * hostname_randomize(const char *hostname, struct gc_arena *gc)
Definition: misc.c:104
static void tcp_connection_established(const struct link_socket_actual *act)
Definition: socket.c:1277
const char * port
Definition: proxy.h:46
const char * local_port
Definition: options.h:90
struct cached_dns_entry * next
Definition: socket.h:81
struct sockaddr_in addr
Definition: win32.h:209
bool link_socket_update_flags(struct link_socket *ls, unsigned int sockflags)
Definition: socket.c:971
#define SIGTERM
Definition: config-msvc.h:154
#define D_RESOLVE_ERRORS
Definition: errlevel.h:60
static void get_signal(volatile int *sig)
Definition: sig.h:89
#define SIGHUP
Definition: config-msvc.h:150
#define ASSERT(x)
Definition: error.h:221
struct buffer residual
Definition: socket.h:132
const char * display_form
Definition: socket.c:3146
#define IA_NET_ORDER
Definition: socket.h:398
#define GETADDR_MENTION_RESOLVE_RETRY
Definition: socket.h:526
#define OPENVPN_PLUGIN_FUNC_SUCCESS
Definition: socket.h:75
#define CC_DOT
Definition: buffer.h:927
static bool link_socket_connection_oriented(const struct link_socket *sock)
Definition: socket.h:621
#define D_LOW
Definition: errlevel.h:97
int ascii2proto(const char *proto_name)
Definition: socket.c:3207
#define GETADDR_RANDOMIZE
Definition: socket.h:532
void close_net_event_win32(struct rw_handle *event, socket_descriptor_t sd, unsigned int flags)
Definition: win32.c:272
int proto
Definition: socket.c:3148
const char * proto_remote(int proto, bool remote)
Definition: socket.c:3298
static bool buf_read(struct buffer *src, void *dest, int size)
Definition: buffer.h:800
#define INETD_NOWAIT
Definition: socket.h:193
static event_t socket_event_handle(const struct link_socket *s)
Definition: socket.h:1225
int offset
Offset in bytes of the actual content within the allocated memory.
Definition: buffer.h:64
#define PS_SHOW_PORT
Definition: socket.h:350
static socket_descriptor_t create_socket_udp(struct addrinfo *addrinfo, const unsigned int flags)
Definition: socket.c:1032
static int get_cached_dns_entry(struct cached_dns_entry *dns_cache, const char *hostname, const char *servname, int ai_family, int resolve_flags, struct addrinfo **ai)
Definition: socket.c:258
int add(int a, int b)
struct sockaddr_in6 in6
Definition: socket.h:70
list flags
int len
Length in bytes of the actual content within the allocated memory.
Definition: buffer.h:66
#define GETADDR_DATAGRAM
Definition: socket.h:534
int inet_pton(int af, const char *src, void *dst)
static void phase2_tcp_client(struct link_socket *sock, struct signal_info *sig_info)
Definition: socket.c:2162
void link_socket_bad_incoming_addr(struct buffer *buf, const struct link_socket_info *info, const struct link_socket_actual *from_addr)
Definition: socket.c:2504
#define OIA_IP
Definition: socket.h:464
#define openvpn_close_socket(s)
Definition: socket.h:262
int iostate
Definition: win32.h:202
#define LS_MODE_TCP_ACCEPT_FROM
Definition: socket.h:198
struct context_1 c1
Level 1 context.
Definition: openvpn.h:543
#define htonps(x)
Definition: socket.h:58
static void bind_local(struct link_socket *sock, const sa_family_t ai_family)
Definition: socket.c:1087
#define OPENVPN_PLUGIN_IPCHANGE
const char * inet_ntop(int af, const void *src, char *dst, socklen_t size)
#define CLEAR(x)
Definition: basic.h:33
#define BPTR(buf)
Definition: buffer.h:124
#define IPV4_INVALID_ADDR
Definition: socket.h:432
#define IPv4_UDP_HEADER_SIZE
Definition: socket.h:596
#define OIA_ERROR
Definition: socket.h:465
#define PS_DONT_SHOW_FAMILY
Definition: socket.h:353
#define ntohps(x)
Definition: socket.h:61
static void stream_buf_close(struct stream_buf *sb)
Definition: socket.c:2795
bool openvpn_snprintf(char *str, size_t size, const char *format,...)
Definition: buffer.c:299
int socket_recv_queue(struct link_socket *sock, int maxsize)
Definition: socket.c:3594
int socket_finalize(SOCKET s, struct overlapped_io *io, struct buffer *buf, struct link_socket_actual *from)
Definition: socket.c:3812
int ai_family
Definition: socket.h:78
static void socket_connect(socket_descriptor_t *sd, const struct sockaddr *dest, const int connect_timeout, struct signal_info *sig_info)
Definition: socket.c:1568
const char * socks_proxy_server
Definition: options.h:103
#define IA_EMPTY_IF_UNDEF
Definition: socket.h:397
#define LS_MODE_TCP_LISTEN
Definition: socket.h:197
#define GETADDR_UPDATE_MANAGEMENT_STATE
Definition: socket.h:531
#define IPv4_TCP_HEADER_SIZE
Definition: socket.h:597
struct buffer next
Definition: socket.h:137
int proto
Definition: options.h:88
void setenv_link_socket_actual(struct env_set *es, const char *name_prefix, const struct link_socket_actual *act, const unsigned int flags)
Definition: socket.c:3132
void gc_addspecial(void *addr, void(*free_function)(void *), struct gc_arena *a)
Definition: buffer.c:477
bool buf_puts(struct buffer *buf, const char *str)
Definition: buffer.c:272
const char * print_link_socket_actual_ex(const struct link_socket_actual *act, const char *separator, const unsigned int flags, struct gc_arena *gc)
Definition: socket.c:2915
bool ip_or_dns_addr_safe(const char *addr, const bool allow_fqdn)
Definition: socket.c:775
static struct gc_arena gc_new(void)
Definition: buffer.h:1015
#define IOSTATE_IMMEDIATE_RETURN
Definition: win32.h:201
static void openvpn_fd_set(int fd, fd_set *setp)
Definition: fdmisc.h:40
const char * hostname
Definition: socket.h:76
static const char * print_sockaddr(const struct sockaddr *addr, struct gc_arena *gc)
Definition: socket.h:380
int inetd_socket_descriptor
Definition: misc.c:82
static bool addrlist_match(const struct openvpn_sockaddr *a1, const struct addrinfo *addrlist)
Definition: socket.h:720
void link_socket_bad_outgoing_addr(void)
Definition: socket.c:2533
static bool addr_defined_ipi(const struct link_socket_actual *lsa)
Definition: socket.h:672
#define ALLOC_OBJ_CLEAR(dptr, type)
Definition: buffer.h:1050
static void ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
Definition: socket.c:2437
const char * print_in_addr_t(in_addr_t addr, unsigned int flags, struct gc_arena *gc)
Definition: socket.c:2985
int get_server_poll_remaining_time(struct event_timeout *server_poll_timeout)
Definition: forward.c:409
static bool buf_copy_excess(struct buffer *dest, struct buffer *src, int len)
Definition: buffer.h:775
struct sockaddr_in in4
Definition: socket.h:69
sa_family_t proto_af
Definition: socket.c:3147
static void stream_buf_get_next(struct stream_buf *sb, struct buffer *buf)
Definition: socket.c:2699
unsigned __int32 uint32_t
Definition: config-msvc.h:157
#define IOSTATE_QUEUED
Definition: win32.h:200
static void gc_freeaddrinfo_callback(void *addr)
Definition: buffer.h:202
static int socket_defined(const socket_descriptor_t sd)
Definition: syshead.h:496
struct http_proxy_options * http_proxy_options
Definition: options.h:102
static bool link_socket_actual_defined(const struct link_socket_actual *act)
Definition: socket.h:699
int addrlen
Definition: win32.h:212
#define HAVE_IN_PKTINFO
Definition: config-msvc.h:55
void setenv_sockaddr(struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const unsigned int flags)
Definition: socket.c:3050
void overlapped_io_close(struct overlapped_io *o)
Definition: win32.c:184
bool stream_buf_read_setup_dowork(struct link_socket *sock)
Definition: socket.c:2708
static bool defined_net_event_win32(const struct rw_handle *event)
Definition: win32.h:88
static void linksock_print_addr(struct link_socket *sock)
Definition: socket.c:2075
static SERVICE_STATUS status
Definition: automatic.c:43
static int buf_forward_capacity(const struct buffer *buf)
Definition: buffer.h:562
#define D_SOCKET_DEBUG
Definition: errlevel.h:137
void link_socket_init_phase1(struct link_socket *sock, const char *local_host, const char *local_port, const char *remote_host, const char *remote_port, struct cached_dns_entry *dns_cache, int proto, sa_family_t af, bool bind_ipv6_only, int mode, const struct link_socket *accept_from, struct http_proxy_info *http_proxy, struct socks_proxy_info *socks_proxy, bool bind_local, bool remote_float, int inetd, struct link_socket_addr *lsa, const char *ipchange_command, const struct plugin_list *plugins, int resolve_retry_seconds, int mtu_discover_type, int rcvbuf, int sndbuf, int mark, const char *bind_dev, struct event_timeout *server_poll_timeout, unsigned int sockflags)
Definition: socket.c:1868
#define ENABLE_DEBUG
Definition: config-msvc.h:8
static bool socket_set_rcvbuf(int sd, int size)
Definition: socket.c:884
int link_socket_write_tcp(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *to)
Definition: socket.c:3492
void link_socket_init_phase2(struct link_socket *sock, const struct frame *frame, struct signal_info *sig_info)
Definition: socket.c:2245
static void event_ctl(struct event_set *es, event_t event, unsigned int rwflags, void *arg)
Definition: event.h:119
void socket_bind(socket_descriptor_t sd, struct addrinfo *local, int ai_family, const char *prefix, bool ipv6only)
Definition: socket.c:1387
const struct in6_addr * link_socket_current_remote_ipv6(const struct link_socket_info *info)
Definition: socket.c:2574
struct buffer buf
Definition: socket.h:136
union openvpn_sockaddr::@10 addr
void sd_close(socket_descriptor_t *sd)
Definition: socket.c:3981
static bool buf_copy(struct buffer *dest, const struct buffer *src)
Definition: buffer.h:734
#define M_ERRNO
Definition: error.h:99
#define msg
Definition: error.h:173
struct buffer buf
Definition: win32.h:214
const char * socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
Definition: socket.c:2607
static bool stream_buf_added(struct stream_buf *sb, int length_added)
Definition: socket.c:2728
static void resolve_remote(struct link_socket *sock, int phase, const char **remote_dynamic, volatile int *signal_received)
Definition: socket.c:1730
#define HAVE_IPI_SPEC_DST
Definition: config.h:336
Interface functions to the internal and external multiplexers.
static void phase2_set_socket_flags(struct link_socket *sock)
Definition: socket.c:2056
const char * remote
Definition: options.h:94
#define GETADDR_HOST_ORDER
Definition: socket.h:525
static void stream_buf_reset(struct stream_buf *sb)
Definition: socket.c:2644
static void phase2_inetd(struct link_socket *sock, const struct frame *frame, const char *remote_dynamic, volatile int *signal_received)
Definition: socket.c:2010
const char * server
Definition: proxy.h:45
#define SOCKET_UNDEFINED
Definition: syshead.h:488
const char * strerror_win32(DWORD errnum, struct gc_arena *gc)
Definition: error.c:823
char * overlapped_io_state_ascii(const struct overlapped_io *o)
Definition: win32.c:197
#define EVENT_READ
Definition: event.h:36
static void socket_set_mark(int sd, int mark)
Definition: socket.c:947
static bool stream_buf_read_setup(struct link_socket *sock)
Definition: socket.h:1011
volatile int source
Definition: sig.h:46
#define BLEN(buf)
Definition: buffer.h:127
static bool socket_set_flags(int sd, unsigned int sockflags)
Definition: socket.c:958
#define FRAME_HEADROOM_MARKER_READ_STREAM
Definition: mtu.h:132
static void socket_frame_init(const struct frame *frame, struct link_socket *sock)
Definition: socket.c:1647
const char * remote_port
Definition: options.h:92
void alloc_buf_sock_tun(struct buffer *buf, const struct frame *frame, const bool tuntap_buffer, const unsigned int align_mask)
Definition: mtu.c:43
#define SA_SET_IF_NONZERO
Definition: socket.h:406
struct connection_entry * array[CONNECTION_LIST_SIZE]
Definition: options.h:163
int openvpn_connect(socket_descriptor_t sd, const struct sockaddr *remote, int connect_timeout, volatile int *signal_received)
Definition: socket.c:1441
static bool buf_defined(const struct buffer *buf)
Definition: buffer.h:215
const char * ip_remote_hint
Definition: options.h:299
unsigned __int8 uint8_t
Definition: config-msvc.h:159
#define SIG_SOURCE_CONNECTION_FAILED
Definition: sig.h:37
const char * print_sockaddr_ex(const struct sockaddr *sa, const char *separator, const unsigned int flags, struct gc_arena *gc)
Definition: socket.c:2824
HANDLE write
Definition: win32.h:77
const char * local
Definition: options.h:93
unsigned int socket_set(struct link_socket *s, struct event_set *es, unsigned int rwflags, void *arg, unsigned int *persistent)
Definition: socket.c:3944
void setenv_in6_addr(struct env_set *es, const char *name_prefix, const struct in6_addr *addr, const unsigned int flags)
Definition: socket.c:3116
void frame_set_mtu_dynamic(struct frame *frame, int mtu, unsigned int flags)
Definition: mtu.c:87
volatile int signal_received
Definition: sig.h:45
#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc)
Definition: buffer.h:1087
uint16_t packet_size_type
Definition: socket.h:55
#define M_ERR
Definition: error.h:110
bool plugin_defined(const struct plugin_list *pl, const int type)
Definition: plugin.c:901
socket_descriptor_t create_socket_tcp(struct addrinfo *addrinfo)
Definition: socket.c:1000
bool ip_addr_dotted_quad_safe(const char *dotted_quad)
Definition: socket.c:689
struct addrinfo * ai
Definition: socket.h:80
void bad_address_length(int actual, int expected)
Definition: socket.c:3326
#define GETADDR_FATAL
Definition: socket.h:524
void socket_adjust_frame_parameters(struct frame *frame, int proto)
Definition: socket.c:2422
SOCKET socket_descriptor_t
Definition: syshead.h:489
static void socket_set_buffers(int fd, const struct socket_buffer_size *sbs)
Definition: socket.c:897
#define D_STREAM_DEBUG
Definition: errlevel.h:169
#define IF_NAMESIZE
Definition: socket.c:2911
static void phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info)
Definition: socket.c:2206
char server[128]
Definition: socks.h:40
void setenv_int(struct env_set *es, const char *name, int value)
Definition: env_set.c:269
bool addr_defined
Definition: win32.h:207
Wrapper structure for dynamically allocated memory.
Definition: buffer.h:60
#define M_FATAL
Definition: error.h:94
static void socket_do_listen(socket_descriptor_t sd, const struct addrinfo *local, bool do_listen, bool do_set_nonblock)
Definition: socket.c:1179
void set_actual_address(struct link_socket_actual *actual, struct addrinfo *ai)
Definition: socket.c:1545
DWORD flags
Definition: win32.h:205
void set_nonblock(int fd)
Definition: fdmisc.c:71
bool proto_is_dgram(int proto)
Definition: socket.c:3181
int link_socket_read_tcp(struct link_socket *sock, struct buffer *buf)
Definition: socket.c:3338
void frame_adjust_path_mtu(struct frame *frame, int pmtu, int proto)
Definition: socket.c:1682
#define GETADDR_CACHE_MASK
Definition: socket.h:536
#define buf_init(buf, offset)
Definition: buffer.h:196
bool residual_fully_formed
Definition: socket.h:134
static bool buf_write_prepend(struct buffer *dest, const void *src, int size)
Definition: buffer.h:701
static bool socket_set_tcp_nodelay(int sd, int state)
Definition: socket.c:927
void set_cloexec(int fd)
Definition: fdmisc.c:81
static unsigned int sf2gaf(const unsigned int getaddr_flags, const unsigned int sockflags)
Definition: socket.c:62
const char * port
Definition: socks.h:41
void do_preresolve(struct context *c)
Definition: socket.c:341
void management_set_state(struct management *man, const int state, const char *detail, const in_addr_t *tun_local_ip, const struct in6_addr *tun_local_ip6, const struct openvpn_sockaddr *local, const struct openvpn_sockaddr *remote)
Definition: manage.c:2746
#define IOSTATE_INITIAL
Definition: win32.h:199
int flags
Definition: socket.h:79
static void phase2_tcp_server(struct link_socket *sock, const char *remote_dynamic, volatile int *signal_received)
Definition: socket.c:2121
static void resolve_bind_local(struct link_socket *sock, const sa_family_t af)
Definition: socket.c:1688
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition: buffer.c:90
#define ENABLE_IP_PKTINFO
Definition: syshead.h:433
bool establish_http_proxy_passthru(struct http_proxy_info *p, socket_descriptor_t sd, const char *host, const char *port, struct event_timeout *server_poll_timeout, struct buffer *lookahead, volatile int *signal_received)
Definition: proxy.c:634
#define GETADDR_MSG_VIRT_OUT
Definition: socket.h:529
static bool dns_addr_safe(const char *addr)
Definition: socket.c:761
#define M_WARN
Definition: error.h:96
static int get_addr_generic(sa_family_t af, unsigned int flags, const char *hostname, void *network, unsigned int *netbits, int resolve_retry_seconds, volatile int *signal_received, int msglevel)
Definition: socket.c:79
socket_descriptor_t socket_do_accept(socket_descriptor_t sd, struct link_socket_actual *act, const bool nowait)
Definition: socket.c:1206
static void addr_zero_host(struct openvpn_sockaddr *addr)
Definition: socket.h:838
static void create_socket(struct link_socket *sock, struct addrinfo *addr)
Definition: socket.c:1107
static int buf_forward_capacity_total(const struct buffer *buf)
Definition: buffer.h:580
static int do_preresolve_host(struct context *c, const char *hostname, const char *servname, const int af, const int flags)
Definition: socket.c:287
#define SOL_IP
Definition: syshead.h:441
#define free
Definition: cmocka.c:1850
static void buf_reset(struct buffer *buf)
Definition: buffer.h:290
#define EVENT_WRITE
Definition: event.h:37
void argv_parse_cmd(struct argv *argres, const char *cmdstr)
Parses a command string, tokenizes it and puts each element into a separate struct argv argument slot...
Definition: argv.c:485
bool get_ipv6_addr(const char *hostname, struct in6_addr *network, unsigned int *netbits, int msglevel)
Translate an IPv6 addr or hostname from string form to in6_addr.
Definition: socket.c:224
Garbage collection arena used to keep track of dynamically allocated memory.
Definition: buffer.h:116
sa_family_t af
Definition: options.h:89
void establish_socks_proxy_udpassoc(struct socks_proxy_info *p, socket_descriptor_t ctrl_sd, socket_descriptor_t udp_sd, struct openvpn_sockaddr *relay_addr, volatile int *signal_received)
Definition: socks.c:511
void management_sleep(const int n)
A sleep function that services the management layer for n seconds rather than doing nothing...
Definition: manage.c:4118
bool bind_local
Definition: options.h:98
#define GETADDR_PASSIVE
Definition: socket.h:533
#define SF_PORT_SHARE
Definition: socket.h:210
#define GETADDR_FATAL_ON_SIGNAL
Definition: socket.h:527
#define D_STREAM_ERRORS
Definition: errlevel.h:63
#define BSTR(buf)
Definition: buffer.h:129
void link_socket_update_buffer_sizes(struct link_socket *ls, int rcvbuf, int sndbuf)
Definition: socket.c:984
void argv_free(struct argv *a)
Frees all memory allocations allocated by the struct argv related functions.
Definition: argv.c:104
#define PS_DONT_SHOW_ADDR
Definition: socket.h:352
struct gc_arena gc
Garbage collection arena for allocations done in the scope of this context structure.
Definition: openvpn.h:522
static bool addr_local(const struct sockaddr *addr)
Definition: socket.h:651
#define UINT8_MAX
Definition: socket.c:3020
void link_socket_close(struct link_socket *sock)
Definition: socket.c:2369
#define PS_SHOW_PKTINFO
Definition: socket.h:351
Definition: argv.h:35
event_t socket_listen_event_handle(struct link_socket *s)
Definition: socket.c:2806
int socket_send_queue(struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
Definition: socket.c:3704
static int datagram_overhead(int proto)
Definition: socket.h:604
const char * proto2ascii(int proto, sa_family_t af, bool display_form)
Definition: socket.c:3235
void setenv_in_addr_t(struct env_set *es, const char *name_prefix, in_addr_t addr, const unsigned int flags)
Definition: socket.c:3103
#define D_WIN32_IO
Definition: errlevel.h:170
bool mac_addr_safe(const char *mac_addr)
Definition: socket.c:792
static void stream_buf_set_next(struct stream_buf *sb)
Definition: socket.c:2675
char * dest
Definition: compat-lz4.h:431
#define CC_DASH
Definition: buffer.h:926
void link_socket_connection_initiated(struct link_socket_info *info, const struct link_socket_actual *act, const char *common_name, struct env_set *es)
Definition: socket.c:2453
#define SF_USE_IP_PKTINFO
Definition: socket.h:208
struct sockaddr sa
Definition: socket.h:68
static void socket_set_sndbuf(int sd, int size)
Definition: socket.c:856
static void stream_buf_init(struct stream_buf *sb, struct buffer *buf, const unsigned int sockflags, const int proto)
Definition: socket.c:2654
#define GETADDR_RESOLVE
Definition: socket.h:523
static bool openvpn_run_script(const struct argv *a, const struct env_set *es, const unsigned int flags, const char *hook)
Definition: run_command.h:57
const char * short_form
Definition: socket.c:3145
#define SF_HOST_RANDOMIZE
Definition: socket.h:211
#define RESOLV_RETRY_INFINITE
Definition: socket.h:47
#define IPV6_V6ONLY
Definition: socket.c:1383
struct http_proxy_options options
Definition: proxy.h:70
static bool link_socket_proto_connection_oriented(int proto)
Definition: socket.h:615
bool ipv6_addr_safe(const char *ipv6_text_addr)
Definition: socket.c:739
#define D_LINK_ERRORS
Definition: errlevel.h:57
struct in6_addr add_in6_addr(struct in6_addr base, uint32_t add)
Definition: socket.c:3027
int maxlen
Definition: socket.h:133
const char * servname
Definition: socket.h:77
in_addr_t link_socket_current_remote(const struct link_socket_info *info)
Definition: socket.c:2539
static int socket_get_sndbuf(int sd)
Definition: socket.c:839
bool argv_printf(struct argv *argres, const char *format,...)
printf() variant which populates a struct argv.
Definition: argv.c:442
const char * addr_family_name(int af)
Definition: socket.c:3274