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