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