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