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