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