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-2023 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  volatile int *signal_received = sig_info ? &sig_info->signal_received : NULL;
2009  switch (sock->mode)
2010  {
2011  case LS_MODE_DEFAULT:
2012  sock->sd = socket_listen_accept(sock->sd,
2013  &sock->info.lsa->actual,
2014  remote_dynamic,
2015  sock->info.lsa->bind_local,
2016  true,
2017  false,
2018  signal_received);
2019  break;
2020 
2021  case LS_MODE_TCP_LISTEN:
2022  socket_do_listen(sock->sd,
2023  sock->info.lsa->bind_local,
2024  true,
2025  false);
2026  break;
2027 
2029  sock->sd = socket_do_accept(sock->sd,
2030  &sock->info.lsa->actual,
2031  false);
2032  if (!socket_defined(sock->sd))
2033  {
2034  register_signal(sig_info, SIGTERM, "socket-undefiled");
2035  return;
2036  }
2038  break;
2039 
2040  default:
2041  ASSERT(0);
2042  }
2043 }
2044 
2045 
2046 static void
2047 phase2_tcp_client(struct link_socket *sock, struct signal_info *sig_info)
2048 {
2049  bool proxy_retry = false;
2050  do
2051  {
2052  socket_connect(&sock->sd,
2053  sock->info.lsa->current_remote->ai_addr,
2055  sig_info);
2056 
2057  if (sig_info->signal_received)
2058  {
2059  return;
2060  }
2061 
2062  if (sock->http_proxy)
2063  {
2064  proxy_retry = establish_http_proxy_passthru(sock->http_proxy,
2065  sock->sd,
2066  sock->proxy_dest_host,
2067  sock->proxy_dest_port,
2068  sock->server_poll_timeout,
2069  &sock->stream_buf.residual,
2070  sig_info);
2071  }
2072  else if (sock->socks_proxy)
2073  {
2075  sock->sd,
2076  sock->proxy_dest_host,
2077  sock->proxy_dest_port,
2078  sig_info);
2079  }
2080  if (proxy_retry)
2081  {
2082  openvpn_close_socket(sock->sd);
2083  sock->sd = create_socket_tcp(sock->info.lsa->current_remote);
2084  }
2085 
2086  } while (proxy_retry);
2087 
2088 }
2089 
2090 static void
2091 phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info)
2092 {
2093  socket_connect(&sock->ctrl_sd,
2094  sock->info.lsa->current_remote->ai_addr,
2096  sig_info);
2097 
2098  if (sig_info->signal_received)
2099  {
2100  return;
2101  }
2102 
2104  sock->ctrl_sd,
2105  sock->sd,
2106  &sock->socks_relay.dest,
2107  sig_info);
2108 
2109  if (sig_info->signal_received)
2110  {
2111  return;
2112  }
2113 
2114  sock->remote_host = sock->proxy_dest_host;
2115  sock->remote_port = sock->proxy_dest_port;
2116 
2117  addr_zero_host(&sock->info.lsa->actual.dest);
2118  if (sock->info.lsa->remote_list)
2119  {
2120  freeaddrinfo(sock->info.lsa->remote_list);
2121  sock->info.lsa->current_remote = NULL;
2122  sock->info.lsa->remote_list = NULL;
2123  }
2124 
2125  resolve_remote(sock, 1, NULL, sig_info);
2126 }
2127 
2128 #if defined(_WIN32)
2129 static void
2131  struct signal_info *sig_info)
2132 {
2133  if (!c->c1.tuntap)
2134  {
2135  struct tuntap *tt;
2136  ALLOC_OBJ(tt, struct tuntap);
2137 
2138  *tt = create_dco_handle(c->options.dev_node, &c->gc);
2139 
2140  /* Ensure we can "safely" cast the handle to a socket */
2141  static_assert(sizeof(sock->sd) == sizeof(tt->hand), "HANDLE and SOCKET size differs");
2142 
2143  c->c1.tuntap = tt;
2144  }
2145 
2147  sock->info.lsa->current_remote,
2148  sock->bind_local, sock->info.lsa->bind_local,
2150  sig_info);
2151 
2152  sock->sockflags |= SF_DCO_WIN;
2153 
2154  if (sig_info->signal_received)
2155  {
2156  return;
2157  }
2158 
2159  sock->sd = (SOCKET)c->c1.tuntap->hand;
2160  linksock_print_addr(sock);
2161 }
2162 #endif /* if defined(_WIN32) */
2163 
2164 /* finalize socket initialization */
2165 void
2167 {
2168  struct link_socket *sock = c->c2.link_socket;
2169  const struct frame *frame = &c->c2.frame;
2170  struct signal_info *sig_info = c->sig;
2171 
2172  const char *remote_dynamic = NULL;
2173  struct signal_info sig_save = {0};
2174 
2175  ASSERT(sock);
2176  ASSERT(sig_info);
2177 
2178  if (sig_info->signal_received)
2179  {
2180  sig_save = *sig_info;
2181  sig_save.signal_received = signal_reset(sig_info, 0);
2182  }
2183 
2184  /* initialize buffers */
2185  socket_frame_init(frame, sock);
2186 
2187  /*
2188  * Pass a remote name to connect/accept so that
2189  * they can test for dynamic IP address changes
2190  * and throw a SIGUSR1 if appropriate.
2191  */
2192  if (sock->resolve_retry_seconds)
2193  {
2194  remote_dynamic = sock->remote_host;
2195  }
2196 
2197  /* Second chance to resolv/create socket */
2198  resolve_remote(sock, 2, &remote_dynamic, sig_info);
2199 
2200  /* If a valid remote has been found, create the socket with its addrinfo */
2201  if (sock->info.lsa->current_remote)
2202  {
2203 #if defined(_WIN32)
2204  if (dco_enabled(&c->options))
2205  {
2206  create_socket_dco_win(c, sock, sig_info);
2207  goto done;
2208  }
2209  else
2210 #endif
2211  {
2212  create_socket(sock, sock->info.lsa->current_remote);
2213  }
2214 
2215  }
2216 
2217  /* If socket has not already been created create it now */
2218  if (sock->sd == SOCKET_UNDEFINED)
2219  {
2220  /* If we have no --remote and have still not figured out the
2221  * protocol family to use we will use the first of the bind */
2222 
2223  if (sock->bind_local && !sock->remote_host && sock->info.lsa->bind_local)
2224  {
2225  /* Warn if this is because neither v4 or v6 was specified
2226  * and we should not connect a remote */
2227  if (sock->info.af == AF_UNSPEC)
2228  {
2229  msg(M_WARN, "Could not determine IPv4/IPv6 protocol. Using %s",
2230  addr_family_name(sock->info.lsa->bind_local->ai_family));
2231  sock->info.af = sock->info.lsa->bind_local->ai_family;
2232  }
2233 
2234  create_socket(sock, sock->info.lsa->bind_local);
2235  }
2236  }
2237 
2238  /* Socket still undefined, give a warning and abort connection */
2239  if (sock->sd == SOCKET_UNDEFINED)
2240  {
2241  msg(M_WARN, "Could not determine IPv4/IPv6 protocol");
2242  register_signal(sig_info, SIGUSR1, "Could not determine IPv4/IPv6 protocol");
2243  goto done;
2244  }
2245 
2246  if (sig_info->signal_received)
2247  {
2248  goto done;
2249  }
2250 
2251  if (sock->info.proto == PROTO_TCP_SERVER)
2252  {
2253  phase2_tcp_server(sock, remote_dynamic, sig_info);
2254  }
2255  else if (sock->info.proto == PROTO_TCP_CLIENT)
2256  {
2257  phase2_tcp_client(sock, sig_info);
2258 
2259  }
2260  else if (sock->info.proto == PROTO_UDP && sock->socks_proxy)
2261  {
2262  phase2_socks_client(sock, sig_info);
2263  }
2264 #ifdef TARGET_ANDROID
2265  if (sock->sd != -1)
2266  {
2267  protect_fd_nonlocal(sock->sd, &sock->info.lsa->actual.dest.addr.sa);
2268  }
2269 #endif
2270  if (sig_info->signal_received)
2271  {
2272  goto done;
2273  }
2274 
2276  linksock_print_addr(sock);
2277 
2278 done:
2279  if (sig_save.signal_received)
2280  {
2281  /* Always restore the saved signal -- register/throw_signal will handle priority */
2282  if (sig_save.source == SIG_SOURCE_HARD && sig_info == &siginfo_static)
2283  {
2284  throw_signal(sig_save.signal_received);
2285  }
2286  else
2287  {
2288  register_signal(sig_info, sig_save.signal_received, sig_save.signal_text);
2289  }
2290  }
2291 }
2292 
2293 void
2295 {
2296  if (sock)
2297  {
2298 #ifdef ENABLE_DEBUG
2299  const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL(sock->gremlin);
2300 #else
2301  const int gremlin = 0;
2302 #endif
2303 
2304  if (socket_defined(sock->sd))
2305  {
2306 #ifdef _WIN32
2307  close_net_event_win32(&sock->listen_handle, sock->sd, 0);
2308 #endif
2309  if (!gremlin)
2310  {
2311  msg(D_LOW, "TCP/UDP: Closing socket");
2312  if (openvpn_close_socket(sock->sd))
2313  {
2314  msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
2315  }
2316  }
2317  sock->sd = SOCKET_UNDEFINED;
2318 #ifdef _WIN32
2319  if (!gremlin)
2320  {
2321  overlapped_io_close(&sock->reads);
2322  overlapped_io_close(&sock->writes);
2323  }
2324 #endif
2325  }
2326 
2327  if (socket_defined(sock->ctrl_sd))
2328  {
2329  if (openvpn_close_socket(sock->ctrl_sd))
2330  {
2331  msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
2332  }
2333  sock->ctrl_sd = SOCKET_UNDEFINED;
2334  }
2335 
2336  stream_buf_close(&sock->stream_buf);
2337  free_buf(&sock->stream_buf_data);
2338  if (!gremlin)
2339  {
2340  free(sock);
2341  }
2342  }
2343 }
2344 
2345 void
2346 setenv_trusted(struct env_set *es, const struct link_socket_info *info)
2347 {
2348  setenv_link_socket_actual(es, "trusted", &info->lsa->actual, SA_IP_PORT);
2349 }
2350 
2351 static void
2352 ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
2353 {
2354  const char *host = print_sockaddr_ex(&info->lsa->actual.dest.addr.sa, " ", PS_SHOW_PORT, gc);
2355  if (include_cmd)
2356  {
2358  argv_printf_cat(argv, "%s", host);
2359  }
2360  else
2361  {
2362  argv_printf(argv, "%s", host);
2363  }
2364 
2365 }
2366 
2367 void
2369  const struct link_socket_actual *act,
2370  const char *common_name,
2371  struct env_set *es)
2372 {
2373  struct gc_arena gc = gc_new();
2374 
2375  info->lsa->actual = *act; /* Note: skip this line for --force-dest */
2376  setenv_trusted(es, info);
2377  info->connection_established = true;
2378 
2379  /* Print connection initiated message, with common name if available */
2380  {
2381  struct buffer out = alloc_buf_gc(256, &gc);
2382  if (common_name)
2383  {
2384  buf_printf(&out, "[%s] ", common_name);
2385  }
2386  buf_printf(&out, "Peer Connection Initiated with %s", print_link_socket_actual(&info->lsa->actual, &gc));
2387  msg(M_INFO, "%s", BSTR(&out));
2388  }
2389 
2390  /* set environmental vars */
2391  setenv_str(es, "common_name", common_name);
2392 
2393  /* Process --ipchange plugin */
2395  {
2396  struct argv argv = argv_new();
2397  ipchange_fmt(false, &argv, info, &gc);
2399  {
2400  msg(M_WARN, "WARNING: ipchange plugin call failed");
2401  }
2402  argv_free(&argv);
2403  }
2404 
2405  /* Process --ipchange option */
2406  if (info->ipchange_command)
2407  {
2408  struct argv argv = argv_new();
2409  setenv_str(es, "script_type", "ipchange");
2410  ipchange_fmt(true, &argv, info, &gc);
2411  openvpn_run_script(&argv, es, 0, "--ipchange");
2412  argv_free(&argv);
2413  }
2414 
2415  gc_free(&gc);
2416 }
2417 
2418 void
2420  const struct link_socket_info *info,
2421  const struct link_socket_actual *from_addr)
2422 {
2423  struct gc_arena gc = gc_new();
2424  struct addrinfo *ai;
2425 
2426  switch (from_addr->dest.addr.sa.sa_family)
2427  {
2428  case AF_INET:
2429  case AF_INET6:
2431  "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
2432  print_link_socket_actual(from_addr, &gc),
2433  (int)from_addr->dest.addr.sa.sa_family,
2434  print_sockaddr_ex(info->lsa->remote_list->ai_addr, ":", PS_SHOW_PORT, &gc));
2435  /* print additional remote addresses */
2436  for (ai = info->lsa->remote_list->ai_next; ai; ai = ai->ai_next)
2437  {
2438  msg(D_LINK_ERRORS, "or from peer address: %s",
2439  print_sockaddr_ex(ai->ai_addr, ":", PS_SHOW_PORT, &gc));
2440  }
2441  break;
2442  }
2443  buf->len = 0;
2444  gc_free(&gc);
2445 }
2446 
2447 void
2449 {
2450  dmsg(D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
2451 }
2452 
2453 in_addr_t
2455 {
2456  const struct link_socket_addr *lsa = info->lsa;
2457 
2458 /*
2459  * This logic supports "redirect-gateway" semantic, which
2460  * makes sense only for PF_INET routes over PF_INET endpoints
2461  *
2462  * Maybe in the future consider PF_INET6 endpoints also ...
2463  * by now just ignore it
2464  *
2465  * For --remote entries with multiple addresses this
2466  * only return the actual endpoint we have successfully connected to
2467  */
2468  if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
2469  {
2470  return IPV4_INVALID_ADDR;
2471  }
2472 
2474  {
2475  return ntohl(lsa->actual.dest.addr.in4.sin_addr.s_addr);
2476  }
2477  else if (lsa->current_remote)
2478  {
2479  return ntohl(((struct sockaddr_in *)lsa->current_remote->ai_addr)
2480  ->sin_addr.s_addr);
2481  }
2482  else
2483  {
2484  return 0;
2485  }
2486 }
2487 
2488 const struct in6_addr *
2490 {
2491  const struct link_socket_addr *lsa = info->lsa;
2492 
2493 /* This logic supports "redirect-gateway" semantic,
2494  * for PF_INET6 routes over PF_INET6 endpoints
2495  *
2496  * For --remote entries with multiple addresses this
2497  * only return the actual endpoint we have successfully connected to
2498  */
2499  if (lsa->actual.dest.addr.sa.sa_family != AF_INET6)
2500  {
2501  return NULL;
2502  }
2503 
2505  {
2506  return &(lsa->actual.dest.addr.in6.sin6_addr);
2507  }
2508  else if (lsa->current_remote)
2509  {
2510  return &(((struct sockaddr_in6 *)lsa->current_remote->ai_addr)->sin6_addr);
2511  }
2512  else
2513  {
2514  return NULL;
2515  }
2516 }
2517 
2518 /*
2519  * Return a status string describing socket state.
2520  */
2521 const char *
2522 socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
2523 {
2524  struct buffer out = alloc_buf_gc(64, gc);
2525  if (s)
2526  {
2527  if (rwflags & EVENT_READ)
2528  {
2529  buf_printf(&out, "S%s",
2530  (s->rwflags_debug & EVENT_READ) ? "R" : "r");
2531 #ifdef _WIN32
2532  buf_printf(&out, "%s",
2534 #endif
2535  }
2536  if (rwflags & EVENT_WRITE)
2537  {
2538  buf_printf(&out, "S%s",
2539  (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
2540 #ifdef _WIN32
2541  buf_printf(&out, "%s",
2543 #endif
2544  }
2545  }
2546  else
2547  {
2548  buf_printf(&out, "S?");
2549  }
2550  return BSTR(&out);
2551 }
2552 
2553 /*
2554  * Stream buffer functions, used to packetize a TCP
2555  * stream connection.
2556  */
2557 
2558 static inline void
2560 {
2561  dmsg(D_STREAM_DEBUG, "STREAM: RESET");
2562  sb->residual_fully_formed = false;
2563  sb->buf = sb->buf_init;
2564  buf_reset(&sb->next);
2565  sb->len = -1;
2566 }
2567 
2568 static void
2570  struct buffer *buf,
2571  const unsigned int sockflags,
2572  const int proto)
2573 {
2574  sb->buf_init = *buf;
2575  sb->maxlen = sb->buf_init.len;
2576  sb->buf_init.len = 0;
2577  sb->residual = alloc_buf(sb->maxlen);
2578  sb->error = false;
2579 #if PORT_SHARE
2580  sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCP_SERVER))
2581  ? PS_ENABLED
2582  : PS_DISABLED;
2583 #endif
2584  stream_buf_reset(sb);
2585 
2586  dmsg(D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
2587 }
2588 
2589 static inline void
2591 {
2592  /* set up 'next' for next i/o read */
2593  sb->next = sb->buf;
2594  sb->next.offset = sb->buf.offset + sb->buf.len;
2595  sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
2596  dmsg(D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2597  sb->buf.offset, sb->buf.len,
2598  sb->next.offset, sb->next.len,
2599  sb->len, sb->maxlen);
2600  ASSERT(sb->next.len > 0);
2601  ASSERT(buf_safe(&sb->buf, sb->next.len));
2602 }
2603 
2604 static inline void
2605 stream_buf_get_final(struct stream_buf *sb, struct buffer *buf)
2606 {
2607  dmsg(D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
2608  buf_defined(&sb->buf) ? sb->buf.len : -1);
2609  ASSERT(buf_defined(&sb->buf));
2610  *buf = sb->buf;
2611 }
2612 
2613 static inline void
2614 stream_buf_get_next(struct stream_buf *sb, struct buffer *buf)
2615 {
2616  dmsg(D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
2617  buf_defined(&sb->next) ? sb->next.len : -1);
2618  ASSERT(buf_defined(&sb->next));
2619  *buf = sb->next;
2620 }
2621 
2622 bool
2624 {
2626  {
2627  ASSERT(buf_copy(&sock->stream_buf.buf, &sock->stream_buf.residual));
2628  ASSERT(buf_init(&sock->stream_buf.residual, 0));
2630  dmsg(D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2631  sock->stream_buf.residual_fully_formed ? "YES" : "NO",
2632  sock->stream_buf.residual.len);
2633  }
2634 
2635  if (!sock->stream_buf.residual_fully_formed)
2636  {
2638  }
2639  return !sock->stream_buf.residual_fully_formed;
2640 }
2641 
2642 static bool
2644  int length_added)
2645 {
2646  dmsg(D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
2647  if (length_added > 0)
2648  {
2649  sb->buf.len += length_added;
2650  }
2651 
2652  /* if length unknown, see if we can get the length prefix from
2653  * the head of the buffer */
2654  if (sb->len < 0 && sb->buf.len >= (int) sizeof(packet_size_type))
2655  {
2656  packet_size_type net_size;
2657 
2658 #if PORT_SHARE
2659  if (sb->port_share_state == PS_ENABLED)
2660  {
2661  if (!is_openvpn_protocol(&sb->buf))
2662  {
2663  msg(D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
2664  sb->port_share_state = PS_FOREIGN;
2665  sb->error = true;
2666  return false;
2667  }
2668  else
2669  {
2670  sb->port_share_state = PS_DISABLED;
2671  }
2672  }
2673 #endif
2674 
2675  ASSERT(buf_read(&sb->buf, &net_size, sizeof(net_size)));
2676  sb->len = ntohps(net_size);
2677 
2678  if (sb->len < 1 || sb->len > sb->maxlen)
2679  {
2680  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);
2681  stream_buf_reset(sb);
2682  sb->error = true;
2683  return false;
2684  }
2685  }
2686 
2687  /* is our incoming packet fully read? */
2688  if (sb->len > 0 && sb->buf.len >= sb->len)
2689  {
2690  /* save any residual data that's part of the next packet */
2691  ASSERT(buf_init(&sb->residual, 0));
2692  if (sb->buf.len > sb->len)
2693  {
2694  ASSERT(buf_copy_excess(&sb->residual, &sb->buf, sb->len));
2695  }
2696  dmsg(D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2697  BLEN(&sb->buf),
2698  BLEN(&sb->residual));
2699  return true;
2700  }
2701  else
2702  {
2703  dmsg(D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
2704  stream_buf_set_next(sb);
2705  return false;
2706  }
2707 }
2708 
2709 static void
2711 {
2712  free_buf(&sb->residual);
2713 }
2714 
2715 /*
2716  * The listen event is a special event whose sole purpose is
2717  * to tell us that there's a new incoming connection on a
2718  * TCP socket, for use in server mode.
2719  */
2720 event_t
2722 {
2723 #ifdef _WIN32
2725  {
2726  init_net_event_win32(&s->listen_handle, FD_ACCEPT, s->sd, 0);
2727  }
2728  return &s->listen_handle;
2729 #else /* ifdef _WIN32 */
2730  return s->sd;
2731 #endif
2732 }
2733 
2734 /*
2735  * Format IP addresses in ascii
2736  */
2737 
2738 const char *
2739 print_sockaddr_ex(const struct sockaddr *sa,
2740  const char *separator,
2741  const unsigned int flags,
2742  struct gc_arena *gc)
2743 {
2744  struct buffer out = alloc_buf_gc(128, gc);
2745  bool addr_is_defined = false;
2746  char hostaddr[NI_MAXHOST] = "";
2747  char servname[NI_MAXSERV] = "";
2748  int status;
2749 
2750  socklen_t salen = 0;
2751  switch (sa->sa_family)
2752  {
2753  case AF_INET:
2754  if (!(flags & PS_DONT_SHOW_FAMILY))
2755  {
2756  buf_puts(&out, "[AF_INET]");
2757  }
2758  salen = sizeof(struct sockaddr_in);
2759  addr_is_defined = ((struct sockaddr_in *) sa)->sin_addr.s_addr != 0;
2760  break;
2761 
2762  case AF_INET6:
2763  if (!(flags & PS_DONT_SHOW_FAMILY))
2764  {
2765  buf_puts(&out, "[AF_INET6]");
2766  }
2767  salen = sizeof(struct sockaddr_in6);
2768  addr_is_defined = !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *) sa)->sin6_addr);
2769  break;
2770 
2771  case AF_UNSPEC:
2772  if (!(flags & PS_DONT_SHOW_FAMILY))
2773  {
2774  return "[AF_UNSPEC]";
2775  }
2776  else
2777  {
2778  return "";
2779  }
2780 
2781  default:
2782  ASSERT(0);
2783  }
2784 
2785  status = getnameinfo(sa, salen, hostaddr, sizeof(hostaddr),
2786  servname, sizeof(servname), NI_NUMERICHOST | NI_NUMERICSERV);
2787 
2788  if (status!=0)
2789  {
2790  buf_printf(&out, "[nameinfo() err: %s]", gai_strerror(status));
2791  return BSTR(&out);
2792  }
2793 
2794  if (!(flags & PS_DONT_SHOW_ADDR))
2795  {
2796  if (addr_is_defined)
2797  {
2798  buf_puts(&out, hostaddr);
2799  }
2800  else
2801  {
2802  buf_puts(&out, "[undef]");
2803  }
2804  }
2805 
2806  if ((flags & PS_SHOW_PORT) || (flags & PS_SHOW_PORT_IF_DEFINED))
2807  {
2808  if (separator)
2809  {
2810  buf_puts(&out, separator);
2811  }
2812 
2813  buf_puts(&out, servname);
2814  }
2815 
2816  return BSTR(&out);
2817 }
2818 
2819 const char *
2821 {
2823 }
2824 
2825 #ifndef IF_NAMESIZE
2826 #define IF_NAMESIZE 16
2827 #endif
2828 
2829 const char *
2831  const char *separator,
2832  const unsigned int flags,
2833  struct gc_arena *gc)
2834 {
2835  if (act)
2836  {
2837  struct buffer out = alloc_buf_gc(128, gc);
2838  buf_printf(&out, "%s", print_sockaddr_ex(&act->dest.addr.sa, separator, flags, gc));
2839 #if ENABLE_IP_PKTINFO
2840  char ifname[IF_NAMESIZE] = "[undef]";
2841 
2842  if ((flags & PS_SHOW_PKTINFO) && addr_defined_ipi(act))
2843  {
2844  switch (act->dest.addr.sa.sa_family)
2845  {
2846  case AF_INET:
2847  {
2848  struct openvpn_sockaddr sa;
2849  CLEAR(sa);
2850  sa.addr.in4.sin_family = AF_INET;
2851 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2852  sa.addr.in4.sin_addr = act->pi.in4.ipi_spec_dst;
2853  if_indextoname(act->pi.in4.ipi_ifindex, ifname);
2854 #elif defined(IP_RECVDSTADDR)
2855  sa.addr.in4.sin_addr = act->pi.in4;
2856  ifname[0] = 0;
2857 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2858 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2859 #endif
2860  buf_printf(&out, " (via %s%%%s)",
2861  print_sockaddr_ex(&sa.addr.sa, separator, 0, gc),
2862  ifname);
2863  }
2864  break;
2865 
2866  case AF_INET6:
2867  {
2868  struct sockaddr_in6 sin6;
2869  char buf[INET6_ADDRSTRLEN] = "[undef]";
2870  CLEAR(sin6);
2871  sin6.sin6_family = AF_INET6;
2872  sin6.sin6_addr = act->pi.in6.ipi6_addr;
2873  if_indextoname(act->pi.in6.ipi6_ifindex, ifname);
2874  if (getnameinfo((struct sockaddr *)&sin6, sizeof(struct sockaddr_in6),
2875  buf, sizeof(buf), NULL, 0, NI_NUMERICHOST) == 0)
2876  {
2877  buf_printf(&out, " (via %s%%%s)", buf, ifname);
2878  }
2879  else
2880  {
2881  buf_printf(&out, " (via [getnameinfo() err]%%%s)", ifname);
2882  }
2883  }
2884  break;
2885  }
2886  }
2887 #endif /* if ENABLE_IP_PKTINFO */
2888  return BSTR(&out);
2889  }
2890  else
2891  {
2892  return "[NULL]";
2893  }
2894 }
2895 
2896 /*
2897  * Convert an in_addr_t in host byte order
2898  * to an ascii dotted quad.
2899  */
2900 const char *
2901 print_in_addr_t(in_addr_t addr, unsigned int flags, struct gc_arena *gc)
2902 {
2903  struct in_addr ia;
2904  char *out = gc_malloc(INET_ADDRSTRLEN, true, gc);
2905 
2906  if (addr || !(flags & IA_EMPTY_IF_UNDEF))
2907  {
2908  CLEAR(ia);
2909  ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl(addr);
2910 
2911  inet_ntop(AF_INET, &ia, out, INET_ADDRSTRLEN);
2912  }
2913  return out;
2914 }
2915 
2916 /*
2917  * Convert an in6_addr in host byte order
2918  * to an ascii representation of an IPv6 address
2919  */
2920 const char *
2921 print_in6_addr(struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
2922 {
2923  char *out = gc_malloc(INET6_ADDRSTRLEN, true, gc);
2924 
2925  if (memcmp(&a6, &in6addr_any, sizeof(a6)) != 0
2926  || !(flags & IA_EMPTY_IF_UNDEF))
2927  {
2928  inet_ntop(AF_INET6, &a6, out, INET6_ADDRSTRLEN);
2929  }
2930  return out;
2931 }
2932 
2933 /*
2934  * Convert an in_port_t in host byte order to a string
2935  */
2936 const char *
2937 print_in_port_t(in_port_t port, struct gc_arena *gc)
2938 {
2939  struct buffer buffer = alloc_buf_gc(8, gc);
2940  buf_printf(&buffer, "%hu", port);
2941  return BSTR(&buffer);
2942 }
2943 
2944 #ifndef UINT8_MAX
2945 #define UINT8_MAX 0xff
2946 #endif
2947 
2948 /* add some offset to an ipv6 address
2949  * (add in steps of 8 bits, taking overflow into next round)
2950  */
2951 struct in6_addr
2952 add_in6_addr( struct in6_addr base, uint32_t add )
2953 {
2954  int i;
2955 
2956  for (i = 15; i>=0 && add > 0; i--)
2957  {
2958  register int carry;
2959  register uint32_t h;
2960 
2961  h = (unsigned char) base.s6_addr[i];
2962  base.s6_addr[i] = (h+add) & UINT8_MAX;
2963 
2964  /* using explicit carry for the 8-bit additions will catch
2965  * 8-bit and(!) 32-bit overruns nicely
2966  */
2967  carry = ((h & 0xff) + (add & 0xff)) >> 8;
2968  add = (add>>8) + carry;
2969  }
2970  return base;
2971 }
2972 
2973 /* set environmental variables for ip/port in *addr */
2974 void
2975 setenv_sockaddr(struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const unsigned int flags)
2976 {
2977  char name_buf[256];
2978 
2979  char buf[INET6_ADDRSTRLEN];
2980  switch (addr->addr.sa.sa_family)
2981  {
2982  case AF_INET:
2983  if (flags & SA_IP_PORT)
2984  {
2985  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_ip", name_prefix);
2986  }
2987  else
2988  {
2989  openvpn_snprintf(name_buf, sizeof(name_buf), "%s", name_prefix);
2990  }
2991 
2992  inet_ntop(AF_INET, &addr->addr.in4.sin_addr, buf, sizeof(buf));
2993  setenv_str(es, name_buf, buf);
2994 
2995  if ((flags & SA_IP_PORT) && addr->addr.in4.sin_port)
2996  {
2997  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_port", name_prefix);
2998  setenv_int(es, name_buf, ntohs(addr->addr.in4.sin_port));
2999  }
3000  break;
3001 
3002  case AF_INET6:
3003  if (IN6_IS_ADDR_V4MAPPED( &addr->addr.in6.sin6_addr ))
3004  {
3005  struct in_addr ia;
3006  memcpy(&ia.s_addr, &addr->addr.in6.sin6_addr.s6_addr[12],
3007  sizeof(ia.s_addr));
3008  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_ip", name_prefix);
3009  inet_ntop(AF_INET, &ia, buf, sizeof(buf));
3010  }
3011  else
3012  {
3013  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_ip6", name_prefix);
3014  inet_ntop(AF_INET6, &addr->addr.in6.sin6_addr, buf, sizeof(buf));
3015  }
3016  setenv_str(es, name_buf, buf);
3017 
3018  if ((flags & SA_IP_PORT) && addr->addr.in6.sin6_port)
3019  {
3020  openvpn_snprintf(name_buf, sizeof(name_buf), "%s_port", name_prefix);
3021  setenv_int(es, name_buf, ntohs(addr->addr.in6.sin6_port));
3022  }
3023  break;
3024  }
3025 }
3026 
3027 void
3028 setenv_in_addr_t(struct env_set *es, const char *name_prefix, in_addr_t addr, const unsigned int flags)
3029 {
3030  if (addr || !(flags & SA_SET_IF_NONZERO))
3031  {
3032  struct openvpn_sockaddr si;
3033  CLEAR(si);
3034  si.addr.in4.sin_family = AF_INET;
3035  si.addr.in4.sin_addr.s_addr = htonl(addr);
3036  setenv_sockaddr(es, name_prefix, &si, flags);
3037  }
3038 }
3039 
3040 void
3042  const char *name_prefix,
3043  const struct in6_addr *addr,
3044  const unsigned int flags)
3045 {
3046  if (!IN6_IS_ADDR_UNSPECIFIED(addr) || !(flags & SA_SET_IF_NONZERO))
3047  {
3048  struct openvpn_sockaddr si;
3049  CLEAR(si);
3050  si.addr.in6.sin6_family = AF_INET6;
3051  si.addr.in6.sin6_addr = *addr;
3052  setenv_sockaddr(es, name_prefix, &si, flags);
3053  }
3054 }
3055 
3056 void
3058  const char *name_prefix,
3059  const struct link_socket_actual *act,
3060  const unsigned int flags)
3061 {
3062  setenv_sockaddr(es, name_prefix, &act->dest, flags);
3063 }
3064 
3065 /*
3066  * Convert protocol names between index and ascii form.
3067  */
3068 
3069 struct proto_names {
3070  const char *short_form;
3071  const char *display_form;
3073  int proto;
3074 };
3075 
3076 /* Indexed by PROTO_x */
3077 static const struct proto_names proto_names[] = {
3078  {"proto-uninitialized", "proto-NONE", AF_UNSPEC, PROTO_NONE},
3079  /* try IPv4 and IPv6 (client), bind dual-stack (server) */
3080  {"udp", "UDP", AF_UNSPEC, PROTO_UDP},
3081  {"tcp-server", "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER},
3082  {"tcp-client", "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT},
3083  {"tcp", "TCP", AF_UNSPEC, PROTO_TCP},
3084  /* force IPv4 */
3085  {"udp4", "UDPv4", AF_INET, PROTO_UDP},
3086  {"tcp4-server", "TCPv4_SERVER", AF_INET, PROTO_TCP_SERVER},
3087  {"tcp4-client", "TCPv4_CLIENT", AF_INET, PROTO_TCP_CLIENT},
3088  {"tcp4", "TCPv4", AF_INET, PROTO_TCP},
3089  /* force IPv6 */
3090  {"udp6", "UDPv6", AF_INET6, PROTO_UDP},
3091  {"tcp6-server", "TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
3092  {"tcp6-client", "TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
3093  {"tcp6", "TCPv6", AF_INET6, PROTO_TCP},
3094 };
3095 
3096 int
3097 ascii2proto(const char *proto_name)
3098 {
3099  int i;
3100  for (i = 0; i < SIZE(proto_names); ++i)
3101  {
3102  if (!strcmp(proto_name, proto_names[i].short_form))
3103  {
3104  return proto_names[i].proto;
3105  }
3106  }
3107  return -1;
3108 }
3109 
3111 ascii2af(const char *proto_name)
3112 {
3113  int i;
3114  for (i = 0; i < SIZE(proto_names); ++i)
3115  {
3116  if (!strcmp(proto_name, proto_names[i].short_form))
3117  {
3118  return proto_names[i].proto_af;
3119  }
3120  }
3121  return 0;
3122 }
3123 
3124 const char *
3126 {
3127  unsigned int i;
3128  for (i = 0; i < SIZE(proto_names); ++i)
3129  {
3130  if (proto_names[i].proto_af == af && proto_names[i].proto == proto)
3131  {
3132  if (display_form)
3133  {
3134  return proto_names[i].display_form;
3135  }
3136  else
3137  {
3138  return proto_names[i].short_form;
3139  }
3140  }
3141  }
3142 
3143  return "[unknown protocol]";
3144 }
3145 
3146 const char *
3148 {
3149  struct buffer out = alloc_buf_gc(256, gc);
3150  int i;
3151 
3152  for (i = 0; i < SIZE(proto_names); ++i)
3153  {
3154  if (i)
3155  {
3156  buf_printf(&out, " ");
3157  }
3158  buf_printf(&out, "[%s]", proto_names[i].short_form);
3159  }
3160  return BSTR(&out);
3161 }
3162 
3163 const char *
3165 {
3166  switch (af)
3167  {
3168  case AF_INET: return "AF_INET";
3169 
3170  case AF_INET6: return "AF_INET6";
3171  }
3172  return "AF_UNSPEC";
3173 }
3174 
3175 /*
3176  * Given a local proto, return local proto
3177  * if !remote, or compatible remote proto
3178  * if remote.
3179  *
3180  * This is used for options compatibility
3181  * checking.
3182  *
3183  * IPv6 and IPv4 protocols are comptabile but OpenVPN
3184  * has always sent UDPv4, TCPv4 over the wire. Keep these
3185  * strings for backward compatibility
3186  */
3187 const char *
3188 proto_remote(int proto, bool remote)
3189 {
3190  ASSERT(proto >= 0 && proto < PROTO_N);
3191  if (proto == PROTO_UDP)
3192  {
3193  return "UDPv4";
3194  }
3195 
3196  if ( (remote && proto == PROTO_TCP_CLIENT)
3197  || (!remote && proto == PROTO_TCP_SERVER))
3198  {
3199  return "TCPv4_SERVER";
3200  }
3201  if ( (remote && proto == PROTO_TCP_SERVER)
3202  || (!remote && proto == PROTO_TCP_CLIENT))
3203  {
3204  return "TCPv4_CLIENT";
3205  }
3206 
3207  ASSERT(0);
3208  return ""; /* Make the compiler happy */
3209 }
3210 
3211 /*
3212  * Bad incoming address lengths that differ from what
3213  * we expect are considered to be fatal errors.
3214  */
3215 void
3216 bad_address_length(int actual, int expected)
3217 {
3218  msg(M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
3219  actual,
3220  expected);
3221 }
3222 
3223 /*
3224  * Socket Read Routines
3225  */
3226 
3227 int
3229  struct buffer *buf)
3230 {
3231  int len = 0;
3232 
3233  if (!sock->stream_buf.residual_fully_formed)
3234  {
3235  /* with Linux-DCO, we sometimes try to access a socket that is
3236  * already installed in the kernel and has no valid file descriptor
3237  * anymore. This is a bug.
3238  * Handle by resetting client instance instead of crashing.
3239  */
3240  if (sock->sd == SOCKET_UNDEFINED)
3241  {
3242  msg(M_INFO, "BUG: link_socket_read_tcp(): sock->sd==-1, reset client instance" );
3243  sock->stream_reset = true; /* reset client instance */
3244  return buf->len = 0; /* nothing to read */
3245  }
3246 
3247 #ifdef _WIN32
3248  sockethandle_t sh = { .s = sock->sd };
3249  len = sockethandle_finalize(sh, &sock->reads, buf, NULL);
3250 #else
3251  struct buffer frag;
3252  stream_buf_get_next(&sock->stream_buf, &frag);
3253  len = recv(sock->sd, BPTR(&frag), BLEN(&frag), MSG_NOSIGNAL);
3254 #endif
3255 
3256  if (!len)
3257  {
3258  sock->stream_reset = true;
3259  }
3260  if (len <= 0)
3261  {
3262  return buf->len = len;
3263  }
3264  }
3265 
3267  || stream_buf_added(&sock->stream_buf, len)) /* packet complete? */
3268  {
3269  stream_buf_get_final(&sock->stream_buf, buf);
3270  stream_buf_reset(&sock->stream_buf);
3271  return buf->len;
3272  }
3273  else
3274  {
3275  return buf->len = 0; /* no error, but packet is still incomplete */
3276  }
3277 }
3278 
3279 #ifndef _WIN32
3280 
3281 #if ENABLE_IP_PKTINFO
3282 
3283 /* make the buffer large enough to handle ancillary socket data for
3284  * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
3285  */
3286 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3287 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3288  CMSG_SPACE(sizeof(struct in_pktinfo)) )
3289 #else
3290 #define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3291  CMSG_SPACE(sizeof(struct in_addr)) )
3292 #endif
3293 
3294 static socklen_t
3295 link_socket_read_udp_posix_recvmsg(struct link_socket *sock,
3296  struct buffer *buf,
3297  struct link_socket_actual *from)
3298 {
3299  struct iovec iov;
3300  uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];
3301  struct msghdr mesg = {0};
3302  socklen_t fromlen = sizeof(from->dest.addr);
3303 
3304  ASSERT(sock->sd >= 0); /* can't happen */
3305 
3306  iov.iov_base = BPTR(buf);
3307  iov.iov_len = buf_forward_capacity_total(buf);
3308  mesg.msg_iov = &iov;
3309  mesg.msg_iovlen = 1;
3310  mesg.msg_name = &from->dest.addr;
3311  mesg.msg_namelen = fromlen;
3312  mesg.msg_control = pktinfo_buf;
3313  mesg.msg_controllen = sizeof pktinfo_buf;
3314  buf->len = recvmsg(sock->sd, &mesg, 0);
3315  if (buf->len >= 0)
3316  {
3317  struct cmsghdr *cmsg;
3318  fromlen = mesg.msg_namelen;
3319  cmsg = CMSG_FIRSTHDR(&mesg);
3320  if (cmsg != NULL
3321  && CMSG_NXTHDR(&mesg, cmsg) == NULL
3322 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3323  && cmsg->cmsg_level == SOL_IP
3324  && cmsg->cmsg_type == IP_PKTINFO
3325  && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo)) )
3326 #elif defined(IP_RECVDSTADDR)
3327  && cmsg->cmsg_level == IPPROTO_IP
3328  && cmsg->cmsg_type == IP_RECVDSTADDR
3329  && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_addr)) )
3330 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3331 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3332 #endif
3333  {
3334 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3335  struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA(cmsg);
3336  from->pi.in4.ipi_ifindex = pkti->ipi_ifindex;
3337  from->pi.in4.ipi_spec_dst = pkti->ipi_spec_dst;
3338 #elif defined(IP_RECVDSTADDR)
3339  from->pi.in4 = *(struct in_addr *) CMSG_DATA(cmsg);
3340 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3341 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3342 #endif
3343  }
3344  else if (cmsg != NULL
3345  && CMSG_NXTHDR(&mesg, cmsg) == NULL
3346  && cmsg->cmsg_level == IPPROTO_IPV6
3347  && cmsg->cmsg_type == IPV6_PKTINFO
3348  && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in6_pktinfo)) )
3349  {
3350  struct in6_pktinfo *pkti6 = (struct in6_pktinfo *) CMSG_DATA(cmsg);
3351  from->pi.in6.ipi6_ifindex = pkti6->ipi6_ifindex;
3352  from->pi.in6.ipi6_addr = pkti6->ipi6_addr;
3353  }
3354  else if (cmsg != NULL)
3355  {
3356  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 );
3357  }
3358  }
3359 
3360  return fromlen;
3361 }
3362 #endif /* if ENABLE_IP_PKTINFO */
3363 
3364 int
3365 link_socket_read_udp_posix(struct link_socket *sock,
3366  struct buffer *buf,
3367  struct link_socket_actual *from)
3368 {
3369  socklen_t fromlen = sizeof(from->dest.addr);
3370  socklen_t expectedlen = af_addr_size(sock->info.af);
3371  addr_zero_host(&from->dest);
3372 
3373  ASSERT(sock->sd >= 0); /* can't happen */
3374 
3375 #if ENABLE_IP_PKTINFO
3376  /* Both PROTO_UDPv4 and PROTO_UDPv6 */
3377  if (sock->info.proto == PROTO_UDP && sock->sockflags & SF_USE_IP_PKTINFO)
3378  {
3379  fromlen = link_socket_read_udp_posix_recvmsg(sock, buf, from);
3380  }
3381  else
3382 #endif
3383  buf->len = recvfrom(sock->sd, BPTR(buf), buf_forward_capacity(buf), 0,
3384  &from->dest.addr.sa, &fromlen);
3385  /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3386  if (buf->len >= 0 && expectedlen && fromlen != expectedlen)
3387  {
3388  bad_address_length(fromlen, expectedlen);
3389  }
3390  return buf->len;
3391 }
3392 
3393 #endif /* ifndef _WIN32 */
3394 
3395 /*
3396  * Socket Write Routines
3397  */
3398 
3399 int
3401  struct buffer *buf,
3402  struct link_socket_actual *to)
3403 {
3404  packet_size_type len = BLEN(buf);
3405  dmsg(D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
3406  ASSERT(len <= sock->stream_buf.maxlen);
3407  len = htonps(len);
3408  ASSERT(buf_write_prepend(buf, &len, sizeof(len)));
3409 #ifdef _WIN32
3410  return link_socket_write_win32(sock, buf, to);
3411 #else
3412  return link_socket_write_tcp_posix(sock, buf, to);
3413 #endif
3414 }
3415 
3416 #if ENABLE_IP_PKTINFO
3417 
3418 size_t
3419 link_socket_write_udp_posix_sendmsg(struct link_socket *sock,
3420  struct buffer *buf,
3421  struct link_socket_actual *to)
3422 {
3423  struct iovec iov;
3424  struct msghdr mesg;
3425  struct cmsghdr *cmsg;
3426  uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];
3427 
3428  iov.iov_base = BPTR(buf);
3429  iov.iov_len = BLEN(buf);
3430  mesg.msg_iov = &iov;
3431  mesg.msg_iovlen = 1;
3432  switch (to->dest.addr.sa.sa_family)
3433  {
3434  case AF_INET:
3435  {
3436  mesg.msg_name = &to->dest.addr.sa;
3437  mesg.msg_namelen = sizeof(struct sockaddr_in);
3438  mesg.msg_control = pktinfo_buf;
3439  mesg.msg_flags = 0;
3440 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3441  mesg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
3442  cmsg = CMSG_FIRSTHDR(&mesg);
3443  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
3444  cmsg->cmsg_level = SOL_IP;
3445  cmsg->cmsg_type = IP_PKTINFO;
3446  {
3447  struct in_pktinfo *pkti;
3448  pkti = (struct in_pktinfo *) CMSG_DATA(cmsg);
3449  pkti->ipi_ifindex = to->pi.in4.ipi_ifindex;
3450  pkti->ipi_spec_dst = to->pi.in4.ipi_spec_dst;
3451  pkti->ipi_addr.s_addr = 0;
3452  }
3453 #elif defined(IP_RECVDSTADDR)
3454  ASSERT( CMSG_SPACE(sizeof(struct in_addr)) <= sizeof(pktinfo_buf) );
3455  mesg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
3456  cmsg = CMSG_FIRSTHDR(&mesg);
3457  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
3458  cmsg->cmsg_level = IPPROTO_IP;
3459  cmsg->cmsg_type = IP_RECVDSTADDR;
3460  *(struct in_addr *) CMSG_DATA(cmsg) = to->pi.in4;
3461 #else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3462 #error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3463 #endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3464  break;
3465  }
3466 
3467  case AF_INET6:
3468  {
3469  struct in6_pktinfo *pkti6;
3470  mesg.msg_name = &to->dest.addr.sa;
3471  mesg.msg_namelen = sizeof(struct sockaddr_in6);
3472 
3473  ASSERT( CMSG_SPACE(sizeof(struct in6_pktinfo)) <= sizeof(pktinfo_buf) );
3474  mesg.msg_control = pktinfo_buf;
3475  mesg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
3476  mesg.msg_flags = 0;
3477  cmsg = CMSG_FIRSTHDR(&mesg);
3478  cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
3479  cmsg->cmsg_level = IPPROTO_IPV6;
3480  cmsg->cmsg_type = IPV6_PKTINFO;
3481 
3482  pkti6 = (struct in6_pktinfo *) CMSG_DATA(cmsg);
3483  pkti6->ipi6_ifindex = to->pi.in6.ipi6_ifindex;
3484  pkti6->ipi6_addr = to->pi.in6.ipi6_addr;
3485  break;
3486  }
3487 
3488  default: ASSERT(0);
3489  }
3490  return sendmsg(sock->sd, &mesg, 0);
3491 }
3492 
3493 #endif /* if ENABLE_IP_PKTINFO */
3494 
3495 /*
3496  * Win32 overlapped socket I/O functions.
3497  */
3498 
3499 #ifdef _WIN32
3500 
3501 static int
3503 {
3504  if (socket_is_dco_win(sock))
3505  {
3506  return GetLastError();
3507  }
3508 
3509  return WSAGetLastError();
3510 }
3511 
3512 int
3513 socket_recv_queue(struct link_socket *sock, int maxsize)
3514 {
3515  if (sock->reads.iostate == IOSTATE_INITIAL)
3516  {
3517  WSABUF wsabuf[1];
3518  int status;
3519 
3520  /* reset buf to its initial state */
3521  if (proto_is_udp(sock->info.proto))
3522  {
3523  sock->reads.buf = sock->reads.buf_init;
3524  }
3525  else if (proto_is_tcp(sock->info.proto))
3526  {
3527  stream_buf_get_next(&sock->stream_buf, &sock->reads.buf);
3528  }
3529  else
3530  {
3531  ASSERT(0);
3532  }
3533 
3534  /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3535  wsabuf[0].buf = BSTR(&sock->reads.buf);
3536  wsabuf[0].len = maxsize ? maxsize : BLEN(&sock->reads.buf);
3537 
3538  /* check for buffer overflow */
3539  ASSERT(wsabuf[0].len <= BLEN(&sock->reads.buf));
3540 
3541  /* the overlapped read will signal this event on I/O completion */
3542  ASSERT(ResetEvent(sock->reads.overlapped.hEvent));
3543  sock->reads.flags = 0;
3544 
3545  if (socket_is_dco_win(sock))
3546  {
3547  status = ReadFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0].len,
3548  &sock->reads.size, &sock->reads.overlapped);
3549  /* Readfile status is inverted from WSARecv */
3550  status = !status;
3551  }
3552  else if (proto_is_udp(sock->info.proto))
3553  {
3554  sock->reads.addr_defined = true;
3555  sock->reads.addrlen = sizeof(sock->reads.addr6);
3556  status = WSARecvFrom(
3557  sock->sd,
3558  wsabuf,
3559  1,
3560  &sock->reads.size,
3561  &sock->reads.flags,
3562  (struct sockaddr *) &sock->reads.addr,
3563  &sock->reads.addrlen,
3564  &sock->reads.overlapped,
3565  NULL);
3566  }
3567  else if (proto_is_tcp(sock->info.proto))
3568  {
3569  sock->reads.addr_defined = false;
3570  status = WSARecv(
3571  sock->sd,
3572  wsabuf,
3573  1,
3574  &sock->reads.size,
3575  &sock->reads.flags,
3576  &sock->reads.overlapped,
3577  NULL);
3578  }
3579  else
3580  {
3581  status = 0;
3582  ASSERT(0);
3583  }
3584 
3585  if (!status) /* operation completed immediately? */
3586  {
3587  /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3588  int af_len = af_addr_size(sock->info.af);
3589  if (sock->reads.addr_defined && af_len && sock->reads.addrlen != af_len)
3590  {
3591  bad_address_length(sock->reads.addrlen, af_len);
3592  }
3594 
3595  /* since we got an immediate return, we must signal the event object ourselves */
3596  ASSERT(SetEvent(sock->reads.overlapped.hEvent));
3597  sock->reads.status = 0;
3598 
3599  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
3600  (int) wsabuf[0].len,
3601  (int) sock->reads.size);
3602  }
3603  else
3604  {
3605  status = socket_get_last_error(sock);
3606  if (status == WSA_IO_PENDING) /* operation queued? */
3607  {
3608  sock->reads.iostate = IOSTATE_QUEUED;
3609  sock->reads.status = status;
3610  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
3611  (int) wsabuf[0].len);
3612  }
3613  else /* error occurred */
3614  {
3615  struct gc_arena gc = gc_new();
3616  ASSERT(SetEvent(sock->reads.overlapped.hEvent));
3618  sock->reads.status = status;
3619  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
3620  (int) wsabuf[0].len,
3621  strerror_win32(status, &gc));
3622  gc_free(&gc);
3623  }
3624  }
3625  }
3626  return sock->reads.iostate;
3627 }
3628 
3629 int
3630 socket_send_queue(struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
3631 {
3632  if (sock->writes.iostate == IOSTATE_INITIAL)
3633  {
3634  WSABUF wsabuf[1];
3635  int status;
3636 
3637  /* make a private copy of buf */
3638  sock->writes.buf = sock->writes.buf_init;
3639  sock->writes.buf.len = 0;
3640  ASSERT(buf_copy(&sock->writes.buf, buf));
3641 
3642  /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3643  wsabuf[0].buf = BSTR(&sock->writes.buf);
3644  wsabuf[0].len = BLEN(&sock->writes.buf);
3645 
3646  /* the overlapped write will signal this event on I/O completion */
3647  ASSERT(ResetEvent(sock->writes.overlapped.hEvent));
3648  sock->writes.flags = 0;
3649 
3650  if (socket_is_dco_win(sock))
3651  {
3652  status = WriteFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0].len,
3653  &sock->writes.size, &sock->writes.overlapped);
3654 
3655  /* WriteFile status is inverted from WSASendTo */
3656  status = !status;
3657 
3658  }
3659  else if (proto_is_udp(sock->info.proto))
3660  {
3661  /* set destination address for UDP writes */
3662  sock->writes.addr_defined = true;
3663  if (to->dest.addr.sa.sa_family == AF_INET6)
3664  {
3665  sock->writes.addr6 = to->dest.addr.in6;
3666  sock->writes.addrlen = sizeof(sock->writes.addr6);
3667  }
3668  else
3669  {
3670  sock->writes.addr = to->dest.addr.in4;
3671  sock->writes.addrlen = sizeof(sock->writes.addr);
3672  }
3673 
3674  status = WSASendTo(
3675  sock->sd,
3676  wsabuf,
3677  1,
3678  &sock->writes.size,
3679  sock->writes.flags,
3680  (struct sockaddr *) &sock->writes.addr,
3681  sock->writes.addrlen,
3682  &sock->writes.overlapped,
3683  NULL);
3684  }
3685  else if (proto_is_tcp(sock->info.proto))
3686  {
3687  /* destination address for TCP writes was established on connection initiation */
3688  sock->writes.addr_defined = false;
3689 
3690  status = WSASend(
3691  sock->sd,
3692  wsabuf,
3693  1,
3694  &sock->writes.size,
3695  sock->writes.flags,
3696  &sock->writes.overlapped,
3697  NULL);
3698  }
3699  else
3700  {
3701  status = 0;
3702  ASSERT(0);
3703  }
3704 
3705  if (!status) /* operation completed immediately? */
3706  {
3708 
3709  /* since we got an immediate return, we must signal the event object ourselves */
3710  ASSERT(SetEvent(sock->writes.overlapped.hEvent));
3711 
3712  sock->writes.status = 0;
3713 
3714  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3715  (int) wsabuf[0].len,
3716  (int) sock->writes.size);
3717  }
3718  else
3719  {
3720  status = socket_get_last_error(sock);
3721  /* both status code have the identical value */
3722  if (status == WSA_IO_PENDING || status == ERROR_IO_PENDING) /* operation queued? */
3723  {
3724  sock->writes.iostate = IOSTATE_QUEUED;
3725  sock->writes.status = status;
3726  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
3727  (int) wsabuf[0].len);
3728  }
3729  else /* error occurred */
3730  {
3731  struct gc_arena gc = gc_new();
3732  ASSERT(SetEvent(sock->writes.overlapped.hEvent));
3734  sock->writes.status = status;
3735 
3736  dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
3737  (int) wsabuf[0].len,
3738  strerror_win32(status, &gc));
3739 
3740  gc_free(&gc);
3741  }
3742  }
3743  }
3744  return sock->writes.iostate;
3745 }
3746 
3747 /* Returns the number of bytes successfully read */
3748 int
3750  struct overlapped_io *io,
3751  struct buffer *buf,
3752  struct link_socket_actual *from)
3753 {
3754  int ret = -1;
3755  BOOL status;
3756 
3757  switch (io->iostate)
3758  {
3759  case IOSTATE_QUEUED:
3761  if (status)
3762  {
3763  /* successful return for a queued operation */
3764  if (buf)
3765  {
3766  *buf = io->buf;
3767  }
3768  ret = io->size;
3769  io->iostate = IOSTATE_INITIAL;
3770  ASSERT(ResetEvent(io->overlapped.hEvent));
3771 
3772  dmsg(D_WIN32_IO, "WIN32 I/O: Completion success [%d]", ret);
3773  }
3774  else
3775  {
3776  /* error during a queued operation */
3777  ret = -1;
3778  if (SocketHandleGetLastError(sh) != ERROR_IO_INCOMPLETE)
3779  {
3780  /* if no error (i.e. just not finished yet), then DON'T execute this code */
3781  io->iostate = IOSTATE_INITIAL;
3782  ASSERT(ResetEvent(io->overlapped.hEvent));
3783  msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion error");
3784  }
3785  }
3786  break;
3787 
3789  io->iostate = IOSTATE_INITIAL;
3790  ASSERT(ResetEvent(io->overlapped.hEvent));
3791  if (io->status)
3792  {
3793  /* error return for a non-queued operation */
3795  ret = -1;
3796  msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion non-queued error");
3797  }
3798  else
3799  {
3800  /* successful return for a non-queued operation */
3801  if (buf)
3802  {
3803  *buf = io->buf;
3804  }
3805  ret = io->size;
3806  dmsg(D_WIN32_IO, "WIN32 I/O: Completion non-queued success [%d]", ret);
3807  }
3808  break;
3809 
3810  case IOSTATE_INITIAL: /* were we called without proper queueing? */
3812  ret = -1;
3813  dmsg(D_WIN32_IO, "WIN32 I/O: Completion BAD STATE");
3814  break;
3815 
3816  default:
3817  ASSERT(0);
3818  }
3819 
3820  /* return from address if requested */
3821  if (!sh.is_handle && from)
3822  {
3823  if (ret >= 0 && io->addr_defined)
3824  {
3825  /* TODO(jjo): streamline this mess */
3826  /* in this func we don't have relevant info about the PF_ of this
3827  * endpoint, as link_socket_actual will be zero for the 1st received packet
3828  *
3829  * Test for inets PF_ possible sizes
3830  */
3831  switch (io->addrlen)
3832  {
3833  case sizeof(struct sockaddr_in):
3834  case sizeof(struct sockaddr_in6):
3835  /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3836  * under _WIN32*/
3837  case sizeof(struct sockaddr_in6)-4:
3838  break;
3839 
3840  default:
3841  bad_address_length(io->addrlen, af_addr_size(io->addr.sin_family));
3842  }
3843 
3844  switch (io->addr.sin_family)
3845  {
3846  case AF_INET:
3847  from->dest.addr.in4 = io->addr;
3848  break;
3849 
3850  case AF_INET6:
3851  from->dest.addr.in6 = io->addr6;
3852  break;
3853  }
3854  }
3855  else
3856  {
3857  CLEAR(from->dest.addr);
3858  }
3859  }
3860 
3861  if (buf)
3862  {
3863  buf->len = ret;
3864  }
3865  return ret;
3866 }
3867 
3868 #endif /* _WIN32 */
3869 
3870 /*
3871  * Socket event notification
3872  */
3873 
3874 unsigned int
3876  struct event_set *es,
3877  unsigned int rwflags,
3878  void *arg,
3879  unsigned int *persistent)
3880 {
3881  if (s)
3882  {
3883  if ((rwflags & EVENT_READ) && !stream_buf_read_setup(s))
3884  {
3885  ASSERT(!persistent);
3886  rwflags &= ~EVENT_READ;
3887  }
3888 
3889 #ifdef _WIN32
3890  if (rwflags & EVENT_READ)
3891  {
3892  socket_recv_queue(s, 0);
3893  }
3894 #endif
3895 
3896  /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
3897  if (!persistent || *persistent != rwflags)
3898  {
3899  event_ctl(es, socket_event_handle(s), rwflags, arg);
3900  if (persistent)
3901  {
3902  *persistent = rwflags;
3903  }
3904  }
3905 
3906  s->rwflags_debug = rwflags;
3907  }
3908  return rwflags;
3909 }
3910 
3911 void
3913 {
3914  if (sd && socket_defined(*sd))
3915  {
3916  openvpn_close_socket(*sd);
3917  *sd = SOCKET_UNDEFINED;
3918  }
3919 }
3920 
3921 #if UNIX_SOCK_SUPPORT
3922 
3923 /*
3924  * code for unix domain sockets
3925  */
3926 
3927 const char *
3928 sockaddr_unix_name(const struct sockaddr_un *local, const char *null)
3929 {
3930  if (local && local->sun_family == PF_UNIX)
3931  {
3932  return local->sun_path;
3933  }
3934  else
3935  {
3936  return null;
3937  }
3938 }
3939 
3941 create_socket_unix(void)
3942 {
3944 
3945  if ((sd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
3946  {
3947  msg(M_ERR, "Cannot create unix domain socket");
3948  }
3949 
3950  /* set socket file descriptor to not pass across execs, so that
3951  * scripts don't have access to it */
3952  set_cloexec(sd);
3953 
3954  return sd;
3955 }
3956 
3957 void
3958 socket_bind_unix(socket_descriptor_t sd,
3959  struct sockaddr_un *local,
3960  const char *prefix)
3961 {
3962  struct gc_arena gc = gc_new();
3963  const mode_t orig_umask = umask(0);
3964 
3965  if (bind(sd, (struct sockaddr *) local, sizeof(struct sockaddr_un)))
3966  {
3967  msg(M_FATAL | M_ERRNO,
3968  "%s: Socket bind[%d] failed on unix domain socket %s",
3969  prefix,
3970  (int)sd,
3971  sockaddr_unix_name(local, "NULL"));
3972  }
3973 
3974  umask(orig_umask);
3975  gc_free(&gc);
3976 }
3977 
3979 socket_accept_unix(socket_descriptor_t sd,
3980  struct sockaddr_un *remote)
3981 {
3982  socklen_t remote_len = sizeof(struct sockaddr_un);
3983  socket_descriptor_t ret;
3984 
3985  CLEAR(*remote);
3986  ret = accept(sd, (struct sockaddr *) remote, &remote_len);
3987  if (ret >= 0)
3988  {
3989  /* set socket file descriptor to not pass across execs, so that
3990  * scripts don't have access to it */
3991  set_cloexec(ret);
3992  }
3993  return ret;
3994 }
3995 
3996 int
3997 socket_connect_unix(socket_descriptor_t sd,
3998  struct sockaddr_un *remote)
3999 {
4000  int status = connect(sd, (struct sockaddr *) remote, sizeof(struct sockaddr_un));
4001  if (status)
4002  {
4003  status = openvpn_errno();
4004  }
4005  return status;
4006 }
4007 
4008 void
4009 sockaddr_unix_init(struct sockaddr_un *local, const char *path)
4010 {
4011  local->sun_family = PF_UNIX;
4012  strncpynt(local->sun_path, path, sizeof(local->sun_path));
4013 }
4014 
4015 void
4016 socket_delete_unix(const struct sockaddr_un *local)
4017 {
4018  const char *name = sockaddr_unix_name(local, NULL);
4019  if (name && strlen(name))
4020  {
4021  unlink(name);
4022  }
4023 }
4024 
4025 bool
4026 unix_socket_get_peer_uid_gid(const socket_descriptor_t sd, int *uid, int *gid)
4027 {
4028 #ifdef HAVE_GETPEEREID
4029  uid_t u;
4030  gid_t g;
4031  if (getpeereid(sd, &u, &g) == -1)
4032  {
4033  return false;
4034  }
4035  if (uid)
4036  {
4037  *uid = u;
4038  }
4039  if (gid)
4040  {
4041  *gid = g;
4042  }
4043  return true;
4044 #elif defined(SO_PEERCRED)
4045  struct ucred peercred;
4046  socklen_t so_len = sizeof(peercred);
4047  if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
4048  {
4049  return false;
4050  }
4051  if (uid)
4052  {
4053  *uid = peercred.uid;
4054  }
4055  if (gid)
4056  {
4057  *gid = peercred.gid;
4058  }
4059  return true;
4060 #else /* ifdef HAVE_GETPEEREID */
4061  return false;
4062 #endif /* ifdef HAVE_GETPEEREID */
4063 }
4064 
4065 #endif /* if UNIX_SOCK_SUPPORT */
overlapped_io_state_ascii
char * overlapped_io_state_ascii(const struct overlapped_io *o)
Definition: win32.c:199
proto_names::proto
int proto
Definition: socket.c:3073
setenv_trusted
void setenv_trusted(struct env_set *es, const struct link_socket_info *info)
Definition: socket.c:2346
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 signal_info *sig_info)
Definition: socks.c:511
buf_safe
static bool buf_safe(const struct buffer *buf, size_t len)
Definition: buffer.h:538
GETADDR_FATAL_ON_SIGNAL
#define GETADDR_FATAL_ON_SIGNAL
Definition: socket.h:508
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:2614
rw_handle::read
HANDLE read
Definition: win32.h:78
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:796
overlapped_io::buf
struct buffer buf
Definition: win32.h:216
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:1031
gc_addspecial
void gc_addspecial(void *addr, void(*free_function)(void *), struct gc_arena *a)
Definition: buffer.c:482
run_command.h
M_ERRNO
#define M_ERRNO
Definition: error.h:100
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:577
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:3147
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:95
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:3912
PS_DONT_SHOW_ADDR
#define PS_DONT_SHOW_ADDR
Definition: socket.h:343
overlapped_io::addr_defined
bool addr_defined
Definition: win32.h:209
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:708
proto2ascii
const char * proto2ascii(int proto, sa_family_t af, bool display_form)
Definition: socket.c:3125
M_NONFATAL
#define M_NONFATAL
Definition: error.h:96
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:771
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:3513
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:218
BSTR
#define BSTR(buf)
Definition: buffer.h:129
overlapped_io::addrlen
int addrlen
Definition: win32.h:214
proto_remote
const char * proto_remote(int proto, bool remote)
Definition: socket.c:3188
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:211
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:2975
proto_names::proto_af
sa_family_t proto_af
Definition: socket.c:3072
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:920
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:154
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:2047
http_proxy_info::options
struct http_proxy_options options
Definition: proxy.h:71
addr_family_name
const char * addr_family_name(int af)
Definition: socket.c:3164
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
buf_copy
static bool buf_copy(struct buffer *dest, const struct buffer *src)
Definition: buffer.h:730
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:2710
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:2605
overlapped_io::flags
DWORD flags
Definition: win32.h:207
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:203
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:904
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:2623
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:637
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:496
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:205
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:201
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:2921
proto_names
Definition: socket.c:3069
overlapped_io_close
void overlapped_io_close(struct overlapped_io *o)
Definition: win32.c:186
options::ip_remote_hint
const char * ip_remote_hint
Definition: options.h:355
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:90
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:2830
link_socket_bad_outgoing_addr
void link_socket_bad_outgoing_addr(void)
Definition: socket.c:2448
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:220
overlapped_io::addr6
struct sockaddr_in6 addr6
Definition: win32.h:212
ALLOC_OBJ
#define ALLOC_OBJ(dptr, type)
Definition: buffer.h:1061
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:698
OIA_HOSTNAME
#define OIA_HOSTNAME
Definition: socket.h:456
ascii2proto
int ascii2proto(const char *proto_name)
Definition: socket.c:3097
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:2643
M_WARN
#define M_WARN
Definition: error.h:97
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:2368
ALLOC_OBJ_CLEAR_GC
#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc)
Definition: buffer.h:1103
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:208
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:2352
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:111
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:2489
set_nonblock
void set_nonblock(socket_descriptor_t fd)
Definition: fdmisc.c:69
CC_DIGIT
#define CC_DIGIT
digit isdigit()
Definition: buffer.h:908
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:2739
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:2901
overlapped_io::iostate
int iostate
Definition: win32.h:204
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:400
socket_get_last_error
static int socket_get_last_error(const struct link_socket *sock)
Definition: socket.c:3502
sockethandle_finalize
int sockethandle_finalize(sockethandle_t sh, struct overlapped_io *io, struct buffer *buf, struct link_socket_actual *from)
Definition: socket.c:3749
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:2419
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:3070
CC_DOT
#define CC_DOT
dot
Definition: buffer.h:921
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:274
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:1066
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
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 signal_info *sig_info)
Definition: socks.c:450
options::resolve_retry_seconds
int resolve_retry_seconds
Definition: options.h:353
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:2590
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:2937
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:2721
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:3041
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:2569
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:908
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:3216
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:399
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:215
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:3111
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:380
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:3875
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:168
stream_buf_read_setup
static bool stream_buf_read_setup(struct link_socket *sock)
Definition: socket.h:1012
openvpn_snprintf
bool openvpn_snprintf(char *str, size_t size, const char *format,...)
Definition: buffer.c:294
status
static SERVICE_STATUS status
Definition: interactive.c:52
proto_names::display_form
const char * display_form
Definition: socket.c:3071
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:2820
management
Definition: manage.h:335
rw_handle::write
HANDLE write
Definition: win32.h:79
gc_free
static void gc_free(struct gc_arena *a)
Definition: buffer.h:1039
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:3630
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:2826
tuntap
Definition: tun.h:171
rw_handle
Definition: win32.h:77
socket.h
options::mark
int mark
Definition: options.h:403
link_socket_read_tcp
int link_socket_read_tcp(struct link_socket *sock, struct buffer *buf)
Definition: socket.c:3228
ALLOC_OBJ_CLEAR
#define ALLOC_OBJ_CLEAR(dptr, type)
Definition: buffer.h:1066
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:105
options::sockflags
unsigned int sockflags
Definition: options.h:407
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:2945
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:2454
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:78
plugin_defined
bool plugin_defined(const struct plugin_list *pl, const int type)
Definition: plugin.c:920
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:3057
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:559
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:2952
phase2_socks_client
static void phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info)
Definition: socket.c:2091
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:3400
options::bind_dev
char * bind_dev
Definition: options.h:404
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:201
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:150
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:2166
socket_stat
const char * socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
Definition: socket.c:2522
stream_buf_reset
static void stream_buf_reset(struct stream_buf *sb)
Definition: socket.c:2559
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:2294
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:206
overlapped_io
Definition: win32.h:200
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:3028
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:202
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:2130
D_INIT_MEDIUM
#define D_INIT_MEDIUM
Definition: errlevel.h:104
management::connection
struct man_connection connection
Definition: manage.h:339