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 resolved 'local entry' might have a different family than what
1745 * was globally configured */
1746 sock->info.af = sock->info.lsa->bind_local->ai_family;
1747 }
1748
1749 gc_free(&gc);
1750}
1751
1752static void
1754 int phase,
1755 const char **remote_dynamic,
1756 struct signal_info *sig_info)
1757{
1758 volatile int *signal_received = sig_info ? &sig_info->signal_received : NULL;
1759 struct gc_arena gc = gc_new();
1760
1761 /* resolve remote address if undefined */
1762 if (!sock->info.lsa->remote_list)
1763 {
1764 if (sock->remote_host)
1765 {
1767 int retry = 0;
1768 int status = -1;
1769 struct addrinfo *ai;
1770 if (proto_is_dgram(sock->info.proto))
1771 {
1772 flags |= GETADDR_DATAGRAM;
1773 }
1774
1776 {
1777 if (phase == 2)
1778 {
1779 flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
1780 }
1781 retry = 0;
1782 }
1783 else if (phase == 1)
1784 {
1785 if (sock->resolve_retry_seconds)
1786 {
1787 retry = 0;
1788 }
1789 else
1790 {
1792 retry = 0;
1793 }
1794 }
1795 else if (phase == 2)
1796 {
1797 if (sock->resolve_retry_seconds)
1798 {
1799 flags |= GETADDR_FATAL;
1800 retry = sock->resolve_retry_seconds;
1801 }
1802 else
1803 {
1804 ASSERT(0);
1805 }
1806 }
1807 else
1808 {
1809 ASSERT(0);
1810 }
1811
1812
1814 sock->remote_host,
1815 sock->remote_port,
1816 sock->info.af,
1817 flags, &ai);
1818 if (status)
1819 {
1820 status = openvpn_getaddrinfo(flags, sock->remote_host, sock->remote_port,
1821 retry, sig_info, sock->info.af, &ai);
1822 }
1823
1824 if (status == 0)
1825 {
1826 sock->info.lsa->remote_list = ai;
1827 sock->info.lsa->current_remote = ai;
1828
1830 "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1831 flags,
1832 phase,
1833 retry,
1834 signal_received ? *signal_received : -1,
1835 status);
1836 }
1837 if (signal_received && *signal_received)
1838 {
1839 goto done;
1840 }
1841 if (status!=0)
1842 {
1843 if (signal_received)
1844 {
1845 /* potential overwrite of signal */
1846 register_signal(sig_info, SIGUSR1, "socks-resolve-failure");
1847 }
1848 goto done;
1849 }
1850 }
1851 }
1852
1853 /* should we re-use previous active remote address? */
1855 {
1856 msg(M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
1858 if (remote_dynamic)
1859 {
1860 *remote_dynamic = NULL;
1861 }
1862 }
1863 else
1864 {
1865 CLEAR(sock->info.lsa->actual);
1866 if (sock->info.lsa->current_remote)
1867 {
1869 sock->info.lsa->current_remote);
1870 }
1871 }
1872
1873done:
1874 gc_free(&gc);
1875}
1876
1877
1878
1879struct link_socket *
1881{
1882 struct link_socket *sock;
1883
1884 ALLOC_OBJ_CLEAR(sock, struct link_socket);
1885 sock->sd = SOCKET_UNDEFINED;
1886 sock->ctrl_sd = SOCKET_UNDEFINED;
1888 sock->ev_arg.u.sock = sock;
1889
1890 return sock;
1891}
1892
1893void
1894link_socket_init_phase1(struct context *c, int sock_index, int mode)
1895{
1896 struct link_socket *sock = c->c2.link_sockets[sock_index];
1897 struct options *o = &c->options;
1898 ASSERT(sock);
1899
1900 const char *host = o->ce.local_list->array[sock_index]->local;
1901 const char *port = o->ce.local_list->array[sock_index]->port;
1902 int proto = o->ce.local_list->array[sock_index]->proto;
1903 const char *remote_host = o->ce.remote;
1904 const char *remote_port = o->ce.remote_port;
1905
1906 if (remote_host)
1907 {
1908 proto = o->ce.proto;
1909 }
1910
1911 if (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP)
1912 {
1913 struct link_socket *tmp_sock = NULL;
1914 if (c->mode == CM_CHILD_TCP)
1915 {
1916 tmp_sock = (struct link_socket *)c->c2.accept_from;
1917 }
1918 else if (c->mode == CM_CHILD_UDP)
1919 {
1920 tmp_sock = c->c2.link_sockets[0];
1921 }
1922
1923 host = tmp_sock->local_host;
1924 port = tmp_sock->local_port;
1925 proto = tmp_sock->info.proto;
1926 }
1927
1928 sock->local_host = host;
1929 sock->local_port = port;
1930 sock->remote_host = remote_host;
1931 sock->remote_port = remote_port;
1932 sock->dns_cache = c->c1.dns_cache;
1933 sock->http_proxy = c->c1.http_proxy;
1934 sock->socks_proxy = c->c1.socks_proxy;
1935 sock->bind_local = o->ce.bind_local;
1938
1939#ifdef ENABLE_DEBUG
1940 sock->gremlin = o->gremlin;
1941#endif
1942
1945
1946 sock->sockflags = o->sockflags;
1947
1948#if PORT_SHARE
1949 if (o->port_share_host && o->port_share_port)
1950 {
1951 sock->sockflags |= SF_PORT_SHARE;
1952 }
1953#endif
1954
1955 sock->mark = o->mark;
1956 sock->bind_dev = o->bind_dev;
1957 sock->info.proto = proto;
1958 sock->info.af = o->ce.af;
1959 sock->info.remote_float = o->ce.remote_float;
1960 sock->info.lsa = &c->c1.link_socket_addrs[sock_index];
1962 sock->info.ipchange_command = o->ipchange;
1963 sock->info.plugins = c->plugins;
1965
1966 sock->mode = mode;
1968 {
1969 ASSERT(c->c2.accept_from);
1971 sock->sd = c->c2.accept_from->sd;
1972 /* inherit (possibly guessed) info AF from parent context */
1973 sock->info.af = c->c2.accept_from->info.af;
1974 }
1975
1976 /* are we running in HTTP proxy mode? */
1977 if (sock->http_proxy)
1978 {
1980
1981 /* the proxy server */
1983 sock->remote_port = c->c1.http_proxy->options.port;
1984
1985 /* the OpenVPN server we will use the proxy to connect to */
1988 }
1989 /* or in Socks proxy mode? */
1990 else if (sock->socks_proxy)
1991 {
1992 /* the proxy server */
1993 sock->remote_host = c->c1.socks_proxy->server;
1994 sock->remote_port = c->c1.socks_proxy->port;
1995
1996 /* the OpenVPN server we will use the proxy to connect to */
1999 }
2000 else
2001 {
2002 sock->remote_host = remote_host;
2003 sock->remote_port = remote_port;
2004 }
2005
2006 /* bind behavior for TCP server vs. client */
2007 if (sock->info.proto == PROTO_TCP_SERVER)
2008 {
2009 if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
2010 {
2011 sock->bind_local = false;
2012 }
2013 else
2014 {
2015 sock->bind_local = true;
2016 }
2017 }
2018
2020 {
2021 if (sock->bind_local)
2022 {
2023 resolve_bind_local(sock, sock->info.af);
2024 }
2025 resolve_remote(sock, 1, NULL, NULL);
2026 }
2027}
2028
2029static void
2031{
2032 /* set misc socket parameters */
2033 socket_set_flags(sock->sd, sock->sockflags);
2034
2035 /* set socket to non-blocking mode */
2036 set_nonblock(sock->sd);
2037
2038 /* set Path MTU discovery options on the socket */
2039 set_mtu_discover_type(sock->sd, sock->mtu_discover_type, sock->info.af);
2040
2041#if EXTENDED_SOCKET_ERROR_CAPABILITY
2042 /* if the OS supports it, enable extended error passing on the socket */
2043 set_sock_extended_error_passing(sock->sd, sock->info.af);
2044#endif
2045}
2046
2047
2048static void
2050{
2051 struct gc_arena gc = gc_new();
2052 const int msglevel = (sock->mode == LS_MODE_TCP_ACCEPT_FROM) ? D_INIT_MEDIUM : M_INFO;
2053
2054 /* print local address */
2055 if (sock->bind_local)
2056 {
2057 sa_family_t ai_family = sock->info.lsa->actual.dest.addr.sa.sa_family;
2058 /* Socket is always bound on the first matching address,
2059 * For bound sockets with no remote addr this is the element of
2060 * the list */
2061 struct addrinfo *cur;
2062 for (cur = sock->info.lsa->bind_local; cur; cur = cur->ai_next)
2063 {
2064 if (!ai_family || ai_family == cur->ai_family)
2065 {
2066 break;
2067 }
2068 }
2069 ASSERT(cur);
2070 msg(msglevel, "%s link local (bound): %s",
2071 proto2ascii(sock->info.proto, sock->info.af, true),
2072 print_sockaddr(cur->ai_addr, &gc));
2073 }
2074 else
2075 {
2076 msg(msglevel, "%s link local: (not bound)",
2077 proto2ascii(sock->info.proto, sock->info.af, true));
2078 }
2079
2080 /* print active remote address */
2081 msg(msglevel, "%s link remote: %s",
2082 proto2ascii(sock->info.proto, sock->info.af, true),
2084 ":",
2086 &gc));
2087 gc_free(&gc);
2088}
2089
2090static void
2091phase2_tcp_server(struct link_socket *sock, const char *remote_dynamic,
2092 struct signal_info *sig_info)
2093{
2094 ASSERT(sig_info);
2095 volatile int *signal_received = &sig_info->signal_received;
2096 switch (sock->mode)
2097 {
2098 case LS_MODE_DEFAULT:
2099 sock->sd = socket_listen_accept(sock->sd,
2100 &sock->info.lsa->actual,
2101 remote_dynamic,
2102 sock->info.lsa->bind_local,
2103 true,
2104 false,
2105 signal_received);
2106 break;
2107
2108 case LS_MODE_TCP_LISTEN:
2109 socket_do_listen(sock->sd,
2110 sock->info.lsa->bind_local,
2111 true,
2112 false);
2113 break;
2114
2116 sock->sd = socket_do_accept(sock->sd,
2117 &sock->info.lsa->actual,
2118 false);
2119 if (!socket_defined(sock->sd))
2120 {
2121 register_signal(sig_info, SIGTERM, "socket-undefined");
2122 return;
2123 }
2125 break;
2126
2127 default:
2128 ASSERT(0);
2129 }
2130}
2131
2132
2133static void
2134phase2_tcp_client(struct link_socket *sock, struct signal_info *sig_info)
2135{
2136 bool proxy_retry = false;
2137 do
2138 {
2139 socket_connect(&sock->sd,
2140 sock->info.lsa->current_remote->ai_addr,
2142 sig_info);
2143
2144 if (sig_info->signal_received)
2145 {
2146 return;
2147 }
2148
2149 if (sock->http_proxy)
2150 {
2151 proxy_retry = establish_http_proxy_passthru(sock->http_proxy,
2152 sock->sd,
2153 sock->proxy_dest_host,
2154 sock->proxy_dest_port,
2155 sock->server_poll_timeout,
2156 &sock->stream_buf.residual,
2157 sig_info);
2158 }
2159 else if (sock->socks_proxy)
2160 {
2162 sock->sd,
2163 sock->proxy_dest_host,
2164 sock->proxy_dest_port,
2165 sock->server_poll_timeout,
2166 sig_info);
2167 }
2168 if (proxy_retry)
2169 {
2170 openvpn_close_socket(sock->sd);
2171 sock->sd = create_socket_tcp(sock->info.lsa->current_remote);
2172 }
2173
2174 } while (proxy_retry);
2175
2176}
2177
2178static void
2179phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info)
2180{
2181 socket_connect(&sock->ctrl_sd,
2182 sock->info.lsa->current_remote->ai_addr,
2184 sig_info);
2185
2186 if (sig_info->signal_received)
2187 {
2188 return;
2189 }
2190
2192 sock->ctrl_sd,
2193 &sock->socks_relay.dest,
2194 sock->server_poll_timeout,
2195 sig_info);
2196
2197 if (sig_info->signal_received)
2198 {
2199 return;
2200 }
2201
2202 sock->remote_host = sock->proxy_dest_host;
2203 sock->remote_port = sock->proxy_dest_port;
2204
2206 if (sock->info.lsa->remote_list)
2207 {
2208 freeaddrinfo(sock->info.lsa->remote_list);
2209 sock->info.lsa->current_remote = NULL;
2210 sock->info.lsa->remote_list = NULL;
2211 }
2212
2213 resolve_remote(sock, 1, NULL, sig_info);
2214}
2215
2216#if defined(_WIN32)
2217static void
2219 struct signal_info *sig_info)
2220{
2221 /* in P2P mode we must have remote resolved at this point */
2222 struct addrinfo *remoteaddr = sock->info.lsa->current_remote;
2223 if ((c->options.mode == MODE_POINT_TO_POINT) && (!remoteaddr))
2224 {
2225 return;
2226 }
2227
2228 if (!c->c1.tuntap)
2229 {
2230 struct tuntap *tt;
2231 ALLOC_OBJ_CLEAR(tt, struct tuntap);
2232
2235
2236 const char *device_guid = NULL; /* not used */
2237 tun_open_device(tt, c->options.dev_node, &device_guid, &c->gc);
2238
2239 /* Ensure we can "safely" cast the handle to a socket */
2240 static_assert(sizeof(sock->sd) == sizeof(tt->hand), "HANDLE and SOCKET size differs");
2241
2242 c->c1.tuntap = tt;
2243 }
2244
2245 if (c->options.mode == MODE_SERVER)
2246 {
2247 dco_mp_start_vpn(c->c1.tuntap->hand, sock);
2248 }
2249 else
2250 {
2251 dco_p2p_new_peer(c->c1.tuntap->hand, &c->c1.tuntap->dco_new_peer_ov, sock, sig_info);
2252 }
2253 sock->sockflags |= SF_DCO_WIN;
2254
2255 if (sig_info->signal_received)
2256 {
2257 return;
2258 }
2259
2260 sock->sd = (SOCKET)c->c1.tuntap->hand;
2261 linksock_print_addr(sock);
2262}
2263#endif /* if defined(_WIN32) */
2264
2265/* finalize socket initialization */
2266void
2268 struct link_socket *sock)
2269{
2270 const struct frame *frame = &c->c2.frame;
2271 struct signal_info *sig_info = c->sig;
2272
2273 const char *remote_dynamic = NULL;
2274 struct signal_info sig_save = {0};
2275
2276 ASSERT(sock);
2277 ASSERT(sig_info);
2278
2279 if (sig_info->signal_received)
2280 {
2281 sig_save = *sig_info;
2282 sig_save.signal_received = signal_reset(sig_info, 0);
2283 }
2284
2285 /* initialize buffers */
2286 socket_frame_init(frame, sock);
2287
2288 /*
2289 * Pass a remote name to connect/accept so that
2290 * they can test for dynamic IP address changes
2291 * and throw a SIGUSR1 if appropriate.
2292 */
2293 if (sock->resolve_retry_seconds)
2294 {
2295 remote_dynamic = sock->remote_host;
2296 }
2297
2298 /* Second chance to resolv/create socket */
2299 resolve_remote(sock, 2, &remote_dynamic, sig_info);
2300
2301 /* If a valid remote has been found, create the socket with its addrinfo */
2302#if defined(_WIN32)
2303 if (dco_enabled(&c->options))
2304 {
2305 create_socket_dco_win(c, sock, sig_info);
2306 goto done;
2307 }
2308#endif
2309 if (sock->info.lsa->current_remote)
2310 {
2311 create_socket(sock, sock->info.lsa->current_remote);
2312 }
2313
2314 /* If socket has not already been created create it now */
2315 if (sock->sd == SOCKET_UNDEFINED)
2316 {
2317 /* If we have no --remote and have still not figured out the
2318 * protocol family to use we will use the first of the bind */
2319
2320 if (sock->bind_local && !sock->remote_host && sock->info.lsa->bind_local)
2321 {
2322 /* Warn if this is because neither v4 or v6 was specified
2323 * and we should not connect a remote */
2324 if (sock->info.af == AF_UNSPEC)
2325 {
2326 msg(M_WARN, "Could not determine IPv4/IPv6 protocol. Using %s",
2327 addr_family_name(sock->info.lsa->bind_local->ai_family));
2328 sock->info.af = sock->info.lsa->bind_local->ai_family;
2329 }
2330 create_socket(sock, sock->info.lsa->bind_local);
2331 }
2332 }
2333
2334 /* Socket still undefined, give a warning and abort connection */
2335 if (sock->sd == SOCKET_UNDEFINED)
2336 {
2337 msg(M_WARN, "Could not determine IPv4/IPv6 protocol");
2338 register_signal(sig_info, SIGUSR1, "Could not determine IPv4/IPv6 protocol");
2339 goto done;
2340 }
2341
2342 if (sig_info->signal_received)
2343 {
2344 goto done;
2345 }
2346
2347 if (sock->info.proto == PROTO_TCP_SERVER)
2348 {
2349 phase2_tcp_server(sock, remote_dynamic, sig_info);
2350 }
2351 else if (sock->info.proto == PROTO_TCP_CLIENT)
2352 {
2353 phase2_tcp_client(sock, sig_info);
2354
2355 }
2356 else if (sock->info.proto == PROTO_UDP && sock->socks_proxy)
2357 {
2358 phase2_socks_client(sock, sig_info);
2359 }
2360#ifdef TARGET_ANDROID
2361 if (sock->sd != -1)
2362 {
2363 protect_fd_nonlocal(sock->sd, &sock->info.lsa->actual.dest.addr.sa);
2364 }
2365#endif
2366 if (sig_info->signal_received)
2367 {
2368 goto done;
2369 }
2370
2372 linksock_print_addr(sock);
2373
2374done:
2375 if (sig_save.signal_received)
2376 {
2377 /* Always restore the saved signal -- register/throw_signal will handle priority */
2378 if (sig_save.source == SIG_SOURCE_HARD && sig_info == &siginfo_static)
2379 {
2380 throw_signal(sig_save.signal_received);
2381 }
2382 else
2383 {
2384 register_signal(sig_info, sig_save.signal_received, sig_save.signal_text);
2385 }
2386 }
2387}
2388
2389void
2391{
2392 if (sock)
2393 {
2394#ifdef ENABLE_DEBUG
2395 const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL(sock->gremlin);
2396#else
2397 const int gremlin = 0;
2398#endif
2399
2400 if (socket_defined(sock->sd))
2401 {
2402#ifdef _WIN32
2403 close_net_event_win32(&sock->listen_handle, sock->sd, 0);
2404#endif
2405 if (!gremlin)
2406 {
2407 msg(D_LOW, "TCP/UDP: Closing socket");
2408 if (openvpn_close_socket(sock->sd))
2409 {
2410 msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
2411 }
2412 }
2413 sock->sd = SOCKET_UNDEFINED;
2414#ifdef _WIN32
2415 if (!gremlin)
2416 {
2417 overlapped_io_close(&sock->reads);
2419 }
2420#endif
2421 }
2422
2423 if (socket_defined(sock->ctrl_sd))
2424 {
2425 if (openvpn_close_socket(sock->ctrl_sd))
2426 {
2427 msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
2428 }
2429 sock->ctrl_sd = SOCKET_UNDEFINED;
2430 }
2431
2433 free_buf(&sock->stream_buf_data);
2434 if (!gremlin)
2435 {
2436 free(sock);
2437 }
2438 }
2439}
2440
2441void
2442setenv_trusted(struct env_set *es, const struct link_socket_info *info)
2443{
2444 setenv_link_socket_actual(es, "trusted", &info->lsa->actual, SA_IP_PORT);
2445}
2446
2447static void
2448ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
2449{
2450 const char *host = print_sockaddr_ex(&info->lsa->actual.dest.addr.sa, " ", PS_SHOW_PORT, gc);
2451 if (include_cmd)
2452 {
2454 argv_printf_cat(argv, "%s", host);
2455 }
2456 else
2457 {
2458 argv_printf(argv, "%s", host);
2459 }
2460
2461}
2462
2463void
2465 const struct link_socket_actual *act,
2466 const char *common_name,
2467 struct env_set *es)
2468{
2469 struct gc_arena gc = gc_new();
2470
2471 info->lsa->actual = *act; /* Note: skip this line for --force-dest */
2472 setenv_trusted(es, info);
2473 info->connection_established = true;
2474
2475 /* Print connection initiated message, with common name if available */
2476 {
2477 struct buffer out = alloc_buf_gc(256, &gc);
2478 if (common_name)
2479 {
2480 buf_printf(&out, "[%s] ", common_name);
2481 }
2482 buf_printf(&out, "Peer Connection Initiated with %s", print_link_socket_actual(&info->lsa->actual, &gc));
2483 msg(M_INFO, "%s", BSTR(&out));
2484 }
2485
2486 /* set environmental vars */
2487 setenv_str(es, "common_name", common_name);
2488
2489 /* Process --ipchange plugin */
2491 {
2492 struct argv argv = argv_new();
2493 ipchange_fmt(false, &argv, info, &gc);
2495 {
2496 msg(M_WARN, "WARNING: ipchange plugin call failed");
2497 }
2498 argv_free(&argv);
2499 }
2500
2501 /* Process --ipchange option */
2502 if (info->ipchange_command)
2503 {
2504 struct argv argv = argv_new();
2505 setenv_str(es, "script_type", "ipchange");
2506 ipchange_fmt(true, &argv, info, &gc);
2507 openvpn_run_script(&argv, es, 0, "--ipchange");
2508 argv_free(&argv);
2509 }
2510
2511 gc_free(&gc);
2512}
2513
2514void
2516 const struct link_socket_info *info,
2517 const struct link_socket_actual *from_addr)
2518{
2519 struct gc_arena gc = gc_new();
2520 struct addrinfo *ai;
2521
2522 switch (from_addr->dest.addr.sa.sa_family)
2523 {
2524 case AF_INET:
2525 case AF_INET6:
2527 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
2528 print_link_socket_actual(from_addr, &gc),
2529 (int)from_addr->dest.addr.sa.sa_family,
2530 print_sockaddr_ex(info->lsa->remote_list->ai_addr, ":", PS_SHOW_PORT, &gc));
2531 /* print additional remote addresses */
2532 for (ai = info->lsa->remote_list->ai_next; ai; ai = ai->ai_next)
2533 {
2534 msg(D_LINK_ERRORS, "or from peer address: %s",
2535 print_sockaddr_ex(ai->ai_addr, ":", PS_SHOW_PORT, &gc));
2536 }
2537 break;
2538 }
2539 buf->len = 0;
2540 gc_free(&gc);
2541}
2542
2543void
2545{
2546 dmsg(D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
2547}
2548
2549in_addr_t
2551{
2552 const struct link_socket_addr *lsa = info->lsa;
2553
2554/*
2555 * This logic supports "redirect-gateway" semantic, which
2556 * makes sense only for PF_INET routes over PF_INET endpoints
2557 *
2558 * Maybe in the future consider PF_INET6 endpoints also ...
2559 * by now just ignore it
2560 *
2561 * For --remote entries with multiple addresses this
2562 * only return the actual endpoint we have successfully connected to
2563 */
2564 if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
2565 {
2566 return IPV4_INVALID_ADDR;
2567 }
2568
2570 {
2571 return ntohl(lsa->actual.dest.addr.in4.sin_addr.s_addr);
2572 }
2573 else if (lsa->current_remote)
2574 {
2575 return ntohl(((struct sockaddr_in *)lsa->current_remote->ai_addr)
2576 ->sin_addr.s_addr);
2577 }
2578 else
2579 {
2580 return 0;
2581 }
2582}
2583
2584const struct in6_addr *
2586{
2587 const struct link_socket_addr *lsa = info->lsa;
2588
2589/* This logic supports "redirect-gateway" semantic,
2590 * for PF_INET6 routes over PF_INET6 endpoints
2591 *
2592 * For --remote entries with multiple addresses this
2593 * only return the actual endpoint we have successfully connected to
2594 */
2595 if (lsa->actual.dest.addr.sa.sa_family != AF_INET6)
2596 {
2597 return NULL;
2598 }
2599
2601 {
2602 return &(lsa->actual.dest.addr.in6.sin6_addr);
2603 }
2604 else if (lsa->current_remote)
2605 {
2606 return &(((struct sockaddr_in6 *)lsa->current_remote->ai_addr)->sin6_addr);
2607 }
2608 else
2609 {
2610 return NULL;
2611 }
2612}
2613
2614/*
2615 * Return a status string describing socket state.
2616 */
2617const char *
2618socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
2619{
2620 struct buffer out = alloc_buf_gc(64, gc);
2621 if (s)
2622 {
2623 if (rwflags & EVENT_READ)
2624 {
2625 buf_printf(&out, "S%s",
2626 (s->rwflags_debug & EVENT_READ) ? "R" : "r");
2627#ifdef _WIN32
2628 buf_printf(&out, "%s",
2630#endif
2631 }
2632 if (rwflags & EVENT_WRITE)
2633 {
2634 buf_printf(&out, "S%s",
2635 (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
2636#ifdef _WIN32
2637 buf_printf(&out, "%s",
2639#endif
2640 }
2641 }
2642 else
2643 {
2644 buf_printf(&out, "S?");
2645 }
2646 return BSTR(&out);
2647}
2648
2649/*
2650 * Stream buffer functions, used to packetize a TCP
2651 * stream connection.
2652 */
2653
2654static inline void
2656{
2657 dmsg(D_STREAM_DEBUG, "STREAM: RESET");
2658 sb->residual_fully_formed = false;
2659 sb->buf = sb->buf_init;
2660 buf_reset(&sb->next);
2661 sb->len = -1;
2662}
2663
2664static void
2666 struct buffer *buf,
2667 const unsigned int sockflags,
2668 const int proto)
2669{
2670 sb->buf_init = *buf;
2671 sb->maxlen = sb->buf_init.len;
2672 sb->buf_init.len = 0;
2673 sb->residual = alloc_buf(sb->maxlen);
2674 sb->error = false;
2675#if PORT_SHARE
2676 sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCP_SERVER))
2677 ? PS_ENABLED
2678 : PS_DISABLED;
2679#endif
2681
2682 dmsg(D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
2683}
2684
2685static inline void
2687{
2688 /* set up 'next' for next i/o read */
2689 sb->next = sb->buf;
2690 sb->next.offset = sb->buf.offset + sb->buf.len;
2691 sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
2692 dmsg(D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2693 sb->buf.offset, sb->buf.len,
2694 sb->next.offset, sb->next.len,
2695 sb->len, sb->maxlen);
2696 ASSERT(sb->next.len > 0);
2697 ASSERT(buf_safe(&sb->buf, sb->next.len));
2698}
2699
2700static inline void
2702{
2703 dmsg(D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
2704 buf_defined(&sb->buf) ? sb->buf.len : -1);
2705 ASSERT(buf_defined(&sb->buf));
2706 *buf = sb->buf;
2707}
2708
2709static inline void
2711{
2712 dmsg(D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
2713 buf_defined(&sb->next) ? sb->next.len : -1);
2714 ASSERT(buf_defined(&sb->next));
2715 *buf = sb->next;
2716}
2717
2718bool
2720{
2722 {
2724 ASSERT(buf_init(&sock->stream_buf.residual, 0));
2726 dmsg(D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2727 sock->stream_buf.residual_fully_formed ? "YES" : "NO",
2728 sock->stream_buf.residual.len);
2729 }
2730
2732 {
2734 }
2735 return !sock->stream_buf.residual_fully_formed;
2736}
2737
2738static bool
2740 int length_added)
2741{
2742 dmsg(D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
2743 if (length_added > 0)
2744 {
2745 sb->buf.len += length_added;
2746 }
2747
2748 /* if length unknown, see if we can get the length prefix from
2749 * the head of the buffer */
2750 if (sb->len < 0 && sb->buf.len >= (int) sizeof(packet_size_type))
2751 {
2753
2754#if PORT_SHARE
2755 if (sb->port_share_state == PS_ENABLED)
2756 {
2757 if (!is_openvpn_protocol(&sb->buf))
2758 {
2759 msg(D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
2760 sb->port_share_state = PS_FOREIGN;
2761 sb->error = true;
2762 return false;
2763 }
2764 else
2765 {
2766 sb->port_share_state = PS_DISABLED;
2767 }
2768 }
2769#endif
2770
2771 ASSERT(buf_read(&sb->buf, &net_size, sizeof(net_size)));
2772 sb->len = ntohps(net_size);
2773
2774 if (sb->len < 1 || sb->len > sb->maxlen)
2775 {
2776 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);
2778 sb->error = true;
2779 return false;
2780 }
2781 }
2782
2783 /* is our incoming packet fully read? */
2784 if (sb->len > 0 && sb->buf.len >= sb->len)
2785 {
2786 /* save any residual data that's part of the next packet */
2787 ASSERT(buf_init(&sb->residual, 0));
2788 if (sb->buf.len > sb->len)
2789 {
2790 ASSERT(buf_copy_excess(&sb->residual, &sb->buf, sb->len));
2791 }
2792 dmsg(D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2793 BLEN(&sb->buf),
2794 BLEN(&sb->residual));
2795 return true;
2796 }
2797 else
2798 {
2799 dmsg(D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
2801 return false;
2802 }
2803}
2804
2805static void
2807{
2808 free_buf(&sb->residual);
2809}
2810
2811/*
2812 * The listen event is a special event whose sole purpose is
2813 * to tell us that there's a new incoming connection on a
2814 * TCP socket, for use in server mode.
2815 */
2816event_t
2818{
2819#ifdef _WIN32
2821 {
2823 }
2824 return &s->listen_handle;
2825#else /* ifdef _WIN32 */
2826 return s->sd;
2827#endif
2828}
2829
2830/*
2831 * Format IP addresses in ascii
2832 */
2833
2834const char *
2836 const char *separator,
2837 const unsigned int flags,
2838 struct gc_arena *gc)
2839{
2840 struct buffer out = alloc_buf_gc(128, gc);
2841 bool addr_is_defined = false;
2842 char hostaddr[NI_MAXHOST] = "";
2843 char servname[NI_MAXSERV] = "";
2844 int status;
2845
2846 socklen_t salen = 0;
2847 switch (sa->sa_family)
2848 {
2849 case AF_INET:
2850 if (!(flags & PS_DONT_SHOW_FAMILY))
2851 {
2852 buf_puts(&out, "[AF_INET]");
2853 }
2854 salen = sizeof(struct sockaddr_in);
2855 addr_is_defined = ((struct sockaddr_in *) sa)->sin_addr.s_addr != 0;
2856 break;
2857
2858 case AF_INET6:
2859 if (!(flags & PS_DONT_SHOW_FAMILY))
2860 {
2861 buf_puts(&out, "[AF_INET6]");
2862 }
2863 salen = sizeof(struct sockaddr_in6);
2864 addr_is_defined = !IN6_IS_ADDR_UNSPECIFIED(&((struct sockaddr_in6 *) sa)->sin6_addr);
2865 break;
2866
2867 case AF_UNSPEC:
2868 if (!(flags & PS_DONT_SHOW_FAMILY))
2869 {
2870 return "[AF_UNSPEC]";
2871 }
2872 else
2873 {
2874 return "";
2875 }
2876
2877 default:
2878 ASSERT(0);
2879 }
2880
2881 status = getnameinfo(sa, salen, hostaddr, sizeof(hostaddr),
2882 servname, sizeof(servname), NI_NUMERICHOST | NI_NUMERICSERV);
2883
2884 if (status!=0)
2885 {
2886 buf_printf(&out, "[nameinfo() err: %s]", gai_strerror(status));
2887 return BSTR(&out);
2888 }
2889
2890 if (!(flags & PS_DONT_SHOW_ADDR))
2891 {
2892 if (addr_is_defined)
2893 {
2894 buf_puts(&out, hostaddr);
2895 }
2896 else
2897 {
2898 buf_puts(&out, "[undef]");
2899 }
2900 }
2901
2902 if ((flags & PS_SHOW_PORT) || (flags & PS_SHOW_PORT_IF_DEFINED))
2903 {
2904 if (separator)
2905 {
2906 buf_puts(&out, separator);
2907 }
2908
2909 buf_puts(&out, servname);
2910 }
2911
2912 return BSTR(&out);
2913}
2914
2915const char *
2920
2921#ifndef IF_NAMESIZE
2922#define IF_NAMESIZE 16
2923#endif
2924
2925const char *
2927 const char *separator,
2928 const unsigned int flags,
2929 struct gc_arena *gc)
2930{
2931 if (act)
2932 {
2933 struct buffer out = alloc_buf_gc(128, gc);
2934 buf_printf(&out, "%s", print_sockaddr_ex(&act->dest.addr.sa, separator, flags, gc));
2935#if ENABLE_IP_PKTINFO
2936 char ifname[IF_NAMESIZE] = "[undef]";
2937
2938 if ((flags & PS_SHOW_PKTINFO) && addr_defined_ipi(act))
2939 {
2940 switch (act->dest.addr.sa.sa_family)
2941 {
2942 case AF_INET:
2943 {
2944 struct openvpn_sockaddr sa;
2945 CLEAR(sa);
2946 sa.addr.in4.sin_family = AF_INET;
2947#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2948 sa.addr.in4.sin_addr = act->pi.in4.ipi_spec_dst;
2949 if_indextoname(act->pi.in4.ipi_ifindex, ifname);
2950#elif defined(IP_RECVDSTADDR)
2951 sa.addr.in4.sin_addr = act->pi.in4;
2952 ifname[0] = 0;
2953#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2954#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2955#endif
2956 buf_printf(&out, " (via %s%%%s)",
2957 print_sockaddr_ex(&sa.addr.sa, separator, 0, gc),
2958 ifname);
2959 }
2960 break;
2961
2962 case AF_INET6:
2963 {
2964 struct sockaddr_in6 sin6;
2965 char buf[INET6_ADDRSTRLEN] = "[undef]";
2966 CLEAR(sin6);
2967 sin6.sin6_family = AF_INET6;
2968 sin6.sin6_addr = act->pi.in6.ipi6_addr;
2969 if_indextoname(act->pi.in6.ipi6_ifindex, ifname);
2970 if (getnameinfo((struct sockaddr *)&sin6, sizeof(struct sockaddr_in6),
2971 buf, sizeof(buf), NULL, 0, NI_NUMERICHOST) == 0)
2972 {
2973 buf_printf(&out, " (via %s%%%s)", buf, ifname);
2974 }
2975 else
2976 {
2977 buf_printf(&out, " (via [getnameinfo() err]%%%s)", ifname);
2978 }
2979 }
2980 break;
2981 }
2982 }
2983#endif /* if ENABLE_IP_PKTINFO */
2984 return BSTR(&out);
2985 }
2986 else
2987 {
2988 return "[NULL]";
2989 }
2990}
2991
2992/*
2993 * Convert an in_addr_t in host byte order
2994 * to an ascii dotted quad.
2995 */
2996const char *
2997print_in_addr_t(in_addr_t addr, unsigned int flags, struct gc_arena *gc)
2998{
2999 struct in_addr ia;
3000 char *out = gc_malloc(INET_ADDRSTRLEN, true, gc);
3001
3002 if (addr || !(flags & IA_EMPTY_IF_UNDEF))
3003 {
3004 CLEAR(ia);
3005 ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl(addr);
3006
3007 inet_ntop(AF_INET, &ia, out, INET_ADDRSTRLEN);
3008 }
3009 return out;
3010}
3011
3012/*
3013 * Convert an in6_addr in host byte order
3014 * to an ascii representation of an IPv6 address
3015 */
3016const char *
3017print_in6_addr(struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
3018{
3019 char *out = gc_malloc(INET6_ADDRSTRLEN, true, gc);
3020
3021 if (memcmp(&a6, &in6addr_any, sizeof(a6)) != 0
3022 || !(flags & IA_EMPTY_IF_UNDEF))
3023 {
3024 inet_ntop(AF_INET6, &a6, out, INET6_ADDRSTRLEN);
3025 }
3026 return out;
3027}
3028
3029/*
3030 * Convert an in_port_t in host byte order to a string
3031 */
3032const char *
3033print_in_port_t(in_port_t port, struct gc_arena *gc)
3034{
3035 struct buffer buffer = alloc_buf_gc(8, gc);
3036 buf_printf(&buffer, "%hu", port);
3037 return BSTR(&buffer);
3038}
3039
3040/* add some offset to an ipv6 address
3041 * (add in steps of 8 bits, taking overflow into next round)
3042 */
3043struct in6_addr
3044add_in6_addr( struct in6_addr base, uint32_t add )
3045{
3046 int i;
3047
3048 for (i = 15; i>=0 && add > 0; i--)
3049 {
3050 register int carry;
3051 register uint32_t h;
3052
3053 h = (unsigned char) base.s6_addr[i];
3054 base.s6_addr[i] = (h+add) & UINT8_MAX;
3055
3056 /* using explicit carry for the 8-bit additions will catch
3057 * 8-bit and(!) 32-bit overruns nicely
3058 */
3059 carry = ((h & 0xff) + (add & 0xff)) >> 8;
3060 add = (add>>8) + carry;
3061 }
3062 return base;
3063}
3064
3065/* set environmental variables for ip/port in *addr */
3066void
3067setenv_sockaddr(struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const unsigned int flags)
3068{
3069 char name_buf[256];
3070
3071 char buf[INET6_ADDRSTRLEN];
3072 switch (addr->addr.sa.sa_family)
3073 {
3074 case AF_INET:
3075 if (flags & SA_IP_PORT)
3076 {
3077 snprintf(name_buf, sizeof(name_buf), "%s_ip", name_prefix);
3078 }
3079 else
3080 {
3081 snprintf(name_buf, sizeof(name_buf), "%s", name_prefix);
3082 }
3083
3084 inet_ntop(AF_INET, &addr->addr.in4.sin_addr, buf, sizeof(buf));
3085 setenv_str(es, name_buf, buf);
3086
3087 if ((flags & SA_IP_PORT) && addr->addr.in4.sin_port)
3088 {
3089 snprintf(name_buf, sizeof(name_buf), "%s_port", name_prefix);
3090 setenv_int(es, name_buf, ntohs(addr->addr.in4.sin_port));
3091 }
3092 break;
3093
3094 case AF_INET6:
3095 if (IN6_IS_ADDR_V4MAPPED( &addr->addr.in6.sin6_addr ))
3096 {
3097 struct in_addr ia;
3098 memcpy(&ia.s_addr, &addr->addr.in6.sin6_addr.s6_addr[12],
3099 sizeof(ia.s_addr));
3100 snprintf(name_buf, sizeof(name_buf), "%s_ip", name_prefix);
3101 inet_ntop(AF_INET, &ia, buf, sizeof(buf));
3102 }
3103 else
3104 {
3105 snprintf(name_buf, sizeof(name_buf), "%s_ip6", name_prefix);
3106 inet_ntop(AF_INET6, &addr->addr.in6.sin6_addr, buf, sizeof(buf));
3107 }
3108 setenv_str(es, name_buf, buf);
3109
3110 if ((flags & SA_IP_PORT) && addr->addr.in6.sin6_port)
3111 {
3112 snprintf(name_buf, sizeof(name_buf), "%s_port", name_prefix);
3113 setenv_int(es, name_buf, ntohs(addr->addr.in6.sin6_port));
3114 }
3115 break;
3116 }
3117}
3118
3119void
3120setenv_in_addr_t(struct env_set *es, const char *name_prefix, in_addr_t addr, const unsigned int flags)
3121{
3122 if (addr || !(flags & SA_SET_IF_NONZERO))
3123 {
3124 struct openvpn_sockaddr si;
3125 CLEAR(si);
3126 si.addr.in4.sin_family = AF_INET;
3127 si.addr.in4.sin_addr.s_addr = htonl(addr);
3128 setenv_sockaddr(es, name_prefix, &si, flags);
3129 }
3130}
3131
3132void
3134 const char *name_prefix,
3135 const struct in6_addr *addr,
3136 const unsigned int flags)
3137{
3138 if (!IN6_IS_ADDR_UNSPECIFIED(addr) || !(flags & SA_SET_IF_NONZERO))
3139 {
3140 struct openvpn_sockaddr si;
3141 CLEAR(si);
3142 si.addr.in6.sin6_family = AF_INET6;
3143 si.addr.in6.sin6_addr = *addr;
3144 setenv_sockaddr(es, name_prefix, &si, flags);
3145 }
3146}
3147
3148void
3150 const char *name_prefix,
3151 const struct link_socket_actual *act,
3152 const unsigned int flags)
3153{
3154 setenv_sockaddr(es, name_prefix, &act->dest, flags);
3155}
3156
3157/*
3158 * Convert protocol names between index and ascii form.
3159 */
3160
3167
3168/* Indexed by PROTO_x */
3169static const struct proto_names proto_names[] = {
3170 {"proto-uninitialized", "proto-NONE", AF_UNSPEC, PROTO_NONE},
3171 /* try IPv4 and IPv6 (client), bind dual-stack (server) */
3172 {"udp", "UDP", AF_UNSPEC, PROTO_UDP},
3173 {"tcp-server", "TCP_SERVER", AF_UNSPEC, PROTO_TCP_SERVER},
3174 {"tcp-client", "TCP_CLIENT", AF_UNSPEC, PROTO_TCP_CLIENT},
3175 {"tcp", "TCP", AF_UNSPEC, PROTO_TCP},
3176 /* force IPv4 */
3177 {"udp4", "UDPv4", AF_INET, PROTO_UDP},
3178 {"tcp4-server", "TCPv4_SERVER", AF_INET, PROTO_TCP_SERVER},
3179 {"tcp4-client", "TCPv4_CLIENT", AF_INET, PROTO_TCP_CLIENT},
3180 {"tcp4", "TCPv4", AF_INET, PROTO_TCP},
3181 /* force IPv6 */
3182 {"udp6", "UDPv6", AF_INET6, PROTO_UDP},
3183 {"tcp6-server", "TCPv6_SERVER", AF_INET6, PROTO_TCP_SERVER},
3184 {"tcp6-client", "TCPv6_CLIENT", AF_INET6, PROTO_TCP_CLIENT},
3185 {"tcp6", "TCPv6", AF_INET6, PROTO_TCP},
3186};
3187
3188int
3189ascii2proto(const char *proto_name)
3190{
3191 for (size_t i = 0; i < SIZE(proto_names); ++i)
3192 {
3193 if (!strcmp(proto_name, proto_names[i].short_form))
3194 {
3195 return proto_names[i].proto;
3196 }
3197 }
3198 return -1;
3199}
3200
3202ascii2af(const char *proto_name)
3203{
3204 for (size_t i = 0; i < SIZE(proto_names); ++i)
3205 {
3206 if (!strcmp(proto_name, proto_names[i].short_form))
3207 {
3208 return proto_names[i].proto_af;
3209 }
3210 }
3211 return 0;
3212}
3213
3214const char *
3216{
3217 for (size_t i = 0; i < SIZE(proto_names); ++i)
3218 {
3219 if (proto_names[i].proto_af == af && proto_names[i].proto == proto)
3220 {
3221 if (display_form)
3222 {
3223 return proto_names[i].display_form;
3224 }
3225 else
3226 {
3227 return proto_names[i].short_form;
3228 }
3229 }
3230 }
3231
3232 return "[unknown protocol]";
3233}
3234
3235const char *
3237{
3238 struct buffer out = alloc_buf_gc(256, gc);
3239
3240 for (size_t i = 0; i < SIZE(proto_names); ++i)
3241 {
3242 if (i)
3243 {
3244 buf_printf(&out, " ");
3245 }
3246 buf_printf(&out, "[%s]", proto_names[i].short_form);
3247 }
3248 return BSTR(&out);
3249}
3250
3251const char *
3253{
3254 switch (af)
3255 {
3256 case AF_INET: return "AF_INET";
3257
3258 case AF_INET6: return "AF_INET6";
3259 }
3260 return "AF_UNSPEC";
3261}
3262
3263/*
3264 * Given a local proto, return local proto
3265 * if !remote, or compatible remote proto
3266 * if remote.
3267 *
3268 * This is used for options compatibility
3269 * checking.
3270 *
3271 * IPv6 and IPv4 protocols are comptabile but OpenVPN
3272 * has always sent UDPv4, TCPv4 over the wire. Keep these
3273 * strings for backward compatibility
3274 */
3275const char *
3276proto_remote(int proto, bool remote)
3277{
3278 ASSERT(proto >= 0 && proto < PROTO_N);
3279 if (proto == PROTO_UDP)
3280 {
3281 return "UDPv4";
3282 }
3283
3284 if ( (remote && proto == PROTO_TCP_CLIENT)
3285 || (!remote && proto == PROTO_TCP_SERVER))
3286 {
3287 return "TCPv4_SERVER";
3288 }
3289 if ( (remote && proto == PROTO_TCP_SERVER)
3290 || (!remote && proto == PROTO_TCP_CLIENT))
3291 {
3292 return "TCPv4_CLIENT";
3293 }
3294
3295 ASSERT(0);
3296 return ""; /* Make the compiler happy */
3297}
3298
3299/*
3300 * Bad incoming address lengths that differ from what
3301 * we expect are considered to be fatal errors.
3302 */
3303void
3305{
3306 msg(M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
3307 actual,
3308 expected);
3309}
3310
3311/*
3312 * Socket Read Routines
3313 */
3314
3315int
3317 struct buffer *buf)
3318{
3319 int len = 0;
3320
3322 {
3323 /* with Linux-DCO, we sometimes try to access a socket that is
3324 * already installed in the kernel and has no valid file descriptor
3325 * anymore. This is a bug.
3326 * Handle by resetting client instance instead of crashing.
3327 */
3328 if (sock->sd == SOCKET_UNDEFINED)
3329 {
3330 msg(M_INFO, "BUG: link_socket_read_tcp(): sock->sd==-1, reset client instance" );
3331 sock->stream_reset = true; /* reset client instance */
3332 return buf->len = 0; /* nothing to read */
3333 }
3334
3335#ifdef _WIN32
3336 sockethandle_t sh = { .s = sock->sd };
3337 len = sockethandle_finalize(sh, &sock->reads, buf, NULL);
3338#else
3339 struct buffer frag;
3341 len = recv(sock->sd, BPTR(&frag), BLEN(&frag), MSG_NOSIGNAL);
3342#endif
3343
3344 if (!len)
3345 {
3346 sock->stream_reset = true;
3347 }
3348 if (len <= 0)
3349 {
3350 return buf->len = len;
3351 }
3352 }
3353
3355 || stream_buf_added(&sock->stream_buf, len)) /* packet complete? */
3356 {
3357 stream_buf_get_final(&sock->stream_buf, buf);
3359 return buf->len;
3360 }
3361 else
3362 {
3363 return buf->len = 0; /* no error, but packet is still incomplete */
3364 }
3365}
3366
3367#ifndef _WIN32
3368
3369#if ENABLE_IP_PKTINFO
3370
3371/* make the buffer large enough to handle ancillary socket data for
3372 * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
3373 */
3374#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3375#define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3376 CMSG_SPACE(sizeof(struct in_pktinfo)) )
3377#else
3378#define PKTINFO_BUF_SIZE max_int( CMSG_SPACE(sizeof(struct in6_pktinfo)), \
3379 CMSG_SPACE(sizeof(struct in_addr)) )
3380#endif
3381
3382static socklen_t
3384 struct buffer *buf,
3385 struct link_socket_actual *from)
3386{
3387 struct iovec iov;
3388 uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];
3389 struct msghdr mesg = {0};
3390 socklen_t fromlen = sizeof(from->dest.addr);
3391
3392 ASSERT(sock->sd >= 0); /* can't happen */
3393
3394 iov.iov_base = BPTR(buf);
3395 iov.iov_len = buf_forward_capacity_total(buf);
3396 mesg.msg_iov = &iov;
3397 mesg.msg_iovlen = 1;
3398 mesg.msg_name = &from->dest.addr;
3399 mesg.msg_namelen = fromlen;
3400 mesg.msg_control = pktinfo_buf;
3401 mesg.msg_controllen = sizeof pktinfo_buf;
3402 buf->len = recvmsg(sock->sd, &mesg, 0);
3403 if (buf->len >= 0)
3404 {
3405 struct cmsghdr *cmsg;
3406 fromlen = mesg.msg_namelen;
3407 cmsg = CMSG_FIRSTHDR(&mesg);
3408 if (cmsg != NULL
3409 && CMSG_NXTHDR(&mesg, cmsg) == NULL
3410#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3411 && cmsg->cmsg_level == SOL_IP
3412 && cmsg->cmsg_type == IP_PKTINFO
3413 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo)) )
3414#elif defined(IP_RECVDSTADDR)
3415 && cmsg->cmsg_level == IPPROTO_IP
3416 && cmsg->cmsg_type == IP_RECVDSTADDR
3417 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_addr)) )
3418#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3419#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3420#endif
3421 {
3422#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3423 struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA(cmsg);
3424 from->pi.in4.ipi_ifindex = pkti->ipi_ifindex;
3425 from->pi.in4.ipi_spec_dst = pkti->ipi_spec_dst;
3426#elif defined(IP_RECVDSTADDR)
3427 from->pi.in4 = *(struct in_addr *) CMSG_DATA(cmsg);
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 else if (cmsg != NULL
3433 && CMSG_NXTHDR(&mesg, cmsg) == NULL
3434 && cmsg->cmsg_level == IPPROTO_IPV6
3435 && cmsg->cmsg_type == IPV6_PKTINFO
3436 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in6_pktinfo)) )
3437 {
3438 struct in6_pktinfo *pkti6 = (struct in6_pktinfo *) CMSG_DATA(cmsg);
3439 from->pi.in6.ipi6_ifindex = pkti6->ipi6_ifindex;
3440 from->pi.in6.ipi6_addr = pkti6->ipi6_addr;
3441 }
3442 else if (cmsg != NULL)
3443 {
3444 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 );
3445 }
3446 }
3447
3448 return fromlen;
3449}
3450#endif /* if ENABLE_IP_PKTINFO */
3451
3452int
3453link_socket_read_udp_posix(struct link_socket *sock,
3454 struct buffer *buf,
3455 struct link_socket_actual *from)
3456{
3457 socklen_t fromlen = sizeof(from->dest.addr);
3458 socklen_t expectedlen = af_addr_size(sock->info.af);
3459 addr_zero_host(&from->dest);
3460
3461 ASSERT(sock->sd >= 0); /* can't happen */
3462
3463#if ENABLE_IP_PKTINFO
3464 /* Both PROTO_UDPv4 and PROTO_UDPv6 */
3465 if (sock->info.proto == PROTO_UDP && sock->sockflags & SF_USE_IP_PKTINFO)
3466 {
3467 fromlen = link_socket_read_udp_posix_recvmsg(sock, buf, from);
3468 }
3469 else
3470#endif
3471 {
3472 buf->len = recvfrom(sock->sd, BPTR(buf), buf_forward_capacity(buf), 0,
3473 &from->dest.addr.sa, &fromlen);
3474 }
3475 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3476 if (buf->len >= 0 && expectedlen && fromlen != expectedlen)
3477 {
3478 bad_address_length(fromlen, expectedlen);
3479 }
3480 return buf->len;
3481}
3482
3483#endif /* ifndef _WIN32 */
3484
3485/*
3486 * Socket Write Routines
3487 */
3488
3489ssize_t
3491 struct buffer *buf,
3492 struct link_socket_actual *to)
3493{
3494 packet_size_type len = BLEN(buf);
3495 dmsg(D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
3496 ASSERT(len <= sock->stream_buf.maxlen);
3497 len = htonps(len);
3498 ASSERT(buf_write_prepend(buf, &len, sizeof(len)));
3499#ifdef _WIN32
3500 return link_socket_write_win32(sock, buf, to);
3501#else
3502 return link_socket_write_tcp_posix(sock, buf);
3503#endif
3504}
3505
3506#if ENABLE_IP_PKTINFO
3507
3508ssize_t
3509link_socket_write_udp_posix_sendmsg(struct link_socket *sock,
3510 struct buffer *buf,
3511 struct link_socket_actual *to)
3512{
3513 struct iovec iov;
3514 struct msghdr mesg;
3515 struct cmsghdr *cmsg;
3516 uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];
3517
3518 iov.iov_base = BPTR(buf);
3519 iov.iov_len = BLEN(buf);
3520 mesg.msg_iov = &iov;
3521 mesg.msg_iovlen = 1;
3522 switch (to->dest.addr.sa.sa_family)
3523 {
3524 case AF_INET:
3525 {
3526 mesg.msg_name = &to->dest.addr.sa;
3527 mesg.msg_namelen = sizeof(struct sockaddr_in);
3528 mesg.msg_control = pktinfo_buf;
3529 mesg.msg_flags = 0;
3530#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
3531 mesg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
3532 cmsg = CMSG_FIRSTHDR(&mesg);
3533 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
3534 cmsg->cmsg_level = SOL_IP;
3535 cmsg->cmsg_type = IP_PKTINFO;
3536 {
3537 struct in_pktinfo *pkti;
3538 pkti = (struct in_pktinfo *) CMSG_DATA(cmsg);
3539 pkti->ipi_ifindex = to->pi.in4.ipi_ifindex;
3540 pkti->ipi_spec_dst = to->pi.in4.ipi_spec_dst;
3541 pkti->ipi_addr.s_addr = 0;
3542 }
3543#elif defined(IP_RECVDSTADDR)
3544 ASSERT( CMSG_SPACE(sizeof(struct in_addr)) <= sizeof(pktinfo_buf) );
3545 mesg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
3546 cmsg = CMSG_FIRSTHDR(&mesg);
3547 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
3548 cmsg->cmsg_level = IPPROTO_IP;
3549 cmsg->cmsg_type = IP_RECVDSTADDR;
3550 *(struct in_addr *) CMSG_DATA(cmsg) = to->pi.in4;
3551#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3552#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
3553#endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
3554 break;
3555 }
3556
3557 case AF_INET6:
3558 {
3559 struct in6_pktinfo *pkti6;
3560 mesg.msg_name = &to->dest.addr.sa;
3561 mesg.msg_namelen = sizeof(struct sockaddr_in6);
3562
3563 ASSERT( CMSG_SPACE(sizeof(struct in6_pktinfo)) <= sizeof(pktinfo_buf) );
3564 mesg.msg_control = pktinfo_buf;
3565 mesg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
3566 mesg.msg_flags = 0;
3567 cmsg = CMSG_FIRSTHDR(&mesg);
3568 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
3569 cmsg->cmsg_level = IPPROTO_IPV6;
3570 cmsg->cmsg_type = IPV6_PKTINFO;
3571
3572 pkti6 = (struct in6_pktinfo *) CMSG_DATA(cmsg);
3573 pkti6->ipi6_ifindex = to->pi.in6.ipi6_ifindex;
3574 pkti6->ipi6_addr = to->pi.in6.ipi6_addr;
3575 break;
3576 }
3577
3578 default: ASSERT(0);
3579 }
3580 return sendmsg(sock->sd, &mesg, 0);
3581}
3582
3583#endif /* if ENABLE_IP_PKTINFO */
3584
3585/*
3586 * Win32 overlapped socket I/O functions.
3587 */
3588
3589#ifdef _WIN32
3590
3591static int
3593{
3594 if (socket_is_dco_win(sock))
3595 {
3596 return GetLastError();
3597 }
3598
3599 return WSAGetLastError();
3600}
3601
3602int
3603socket_recv_queue(struct link_socket *sock, int maxsize)
3604{
3605 if (sock->reads.iostate == IOSTATE_INITIAL)
3606 {
3607 WSABUF wsabuf[1];
3608 int status;
3609
3610 /* reset buf to its initial state */
3611 if (proto_is_udp(sock->info.proto))
3612 {
3613 sock->reads.buf = sock->reads.buf_init;
3614 }
3615 else if (proto_is_tcp(sock->info.proto))
3616 {
3617 stream_buf_get_next(&sock->stream_buf, &sock->reads.buf);
3618 }
3619 else
3620 {
3621 ASSERT(0);
3622 }
3623
3624 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3625 wsabuf[0].buf = BSTR(&sock->reads.buf);
3626 wsabuf[0].len = maxsize ? maxsize : BLEN(&sock->reads.buf);
3627
3628 /* check for buffer overflow */
3629 ASSERT(wsabuf[0].len <= BLEN(&sock->reads.buf));
3630
3631 /* the overlapped read will signal this event on I/O completion */
3632 ASSERT(ResetEvent(sock->reads.overlapped.hEvent));
3633 sock->reads.flags = 0;
3634
3635 if (socket_is_dco_win(sock))
3636 {
3637 status = ReadFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0].len,
3638 &sock->reads.size, &sock->reads.overlapped);
3639 /* Readfile status is inverted from WSARecv */
3640 status = !status;
3641 }
3642 else if (proto_is_udp(sock->info.proto))
3643 {
3644 sock->reads.addr_defined = true;
3645 sock->reads.addrlen = sizeof(sock->reads.addr6);
3646 status = WSARecvFrom(
3647 sock->sd,
3648 wsabuf,
3649 1,
3650 &sock->reads.size,
3651 &sock->reads.flags,
3652 (struct sockaddr *) &sock->reads.addr,
3653 &sock->reads.addrlen,
3654 &sock->reads.overlapped,
3655 NULL);
3656 }
3657 else if (proto_is_tcp(sock->info.proto))
3658 {
3659 sock->reads.addr_defined = false;
3660 status = WSARecv(
3661 sock->sd,
3662 wsabuf,
3663 1,
3664 &sock->reads.size,
3665 &sock->reads.flags,
3666 &sock->reads.overlapped,
3667 NULL);
3668 }
3669 else
3670 {
3671 status = 0;
3672 ASSERT(0);
3673 }
3674
3675 if (!status) /* operation completed immediately? */
3676 {
3677 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
3678 int af_len = af_addr_size(sock->info.af);
3679 if (sock->reads.addr_defined && af_len && sock->reads.addrlen != af_len)
3680 {
3681 bad_address_length(sock->reads.addrlen, af_len);
3682 }
3684
3685 /* since we got an immediate return, we must signal the event object ourselves */
3686 ASSERT(SetEvent(sock->reads.overlapped.hEvent));
3687 sock->reads.status = 0;
3688
3689 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
3690 (int) wsabuf[0].len,
3691 (int) sock->reads.size);
3692 }
3693 else
3694 {
3696 if (status == WSA_IO_PENDING) /* operation queued? */
3697 {
3699 sock->reads.status = status;
3700 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
3701 (int) wsabuf[0].len);
3702 }
3703 else /* error occurred */
3704 {
3705 struct gc_arena gc = gc_new();
3706 ASSERT(SetEvent(sock->reads.overlapped.hEvent));
3708 sock->reads.status = status;
3709 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
3710 (int) wsabuf[0].len,
3712 gc_free(&gc);
3713 }
3714 }
3715 }
3716 return sock->reads.iostate;
3717}
3718
3719int
3720socket_send_queue(struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
3721{
3722 if (sock->writes.iostate == IOSTATE_INITIAL)
3723 {
3724 WSABUF wsabuf[1];
3725 int status;
3726
3727 /* make a private copy of buf */
3728 sock->writes.buf = sock->writes.buf_init;
3729 sock->writes.buf.len = 0;
3730 ASSERT(buf_copy(&sock->writes.buf, buf));
3731
3732 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
3733 wsabuf[0].buf = BSTR(&sock->writes.buf);
3734 wsabuf[0].len = BLEN(&sock->writes.buf);
3735
3736 /* the overlapped write will signal this event on I/O completion */
3737 ASSERT(ResetEvent(sock->writes.overlapped.hEvent));
3738 sock->writes.flags = 0;
3739
3740 if (socket_is_dco_win(sock))
3741 {
3742 status = WriteFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0].len,
3743 &sock->writes.size, &sock->writes.overlapped);
3744
3745 /* WriteFile status is inverted from WSASendTo */
3746 status = !status;
3747
3748 }
3749 else if (proto_is_udp(sock->info.proto))
3750 {
3751 /* set destination address for UDP writes */
3752 sock->writes.addr_defined = true;
3753 if (to->dest.addr.sa.sa_family == AF_INET6)
3754 {
3755 sock->writes.addr6 = to->dest.addr.in6;
3756 sock->writes.addrlen = sizeof(sock->writes.addr6);
3757 }
3758 else
3759 {
3760 sock->writes.addr = to->dest.addr.in4;
3761 sock->writes.addrlen = sizeof(sock->writes.addr);
3762 }
3763
3764 status = WSASendTo(
3765 sock->sd,
3766 wsabuf,
3767 1,
3768 &sock->writes.size,
3769 sock->writes.flags,
3770 (struct sockaddr *) &sock->writes.addr,
3771 sock->writes.addrlen,
3772 &sock->writes.overlapped,
3773 NULL);
3774 }
3775 else if (proto_is_tcp(sock->info.proto))
3776 {
3777 /* destination address for TCP writes was established on connection initiation */
3778 sock->writes.addr_defined = false;
3779
3780 status = WSASend(
3781 sock->sd,
3782 wsabuf,
3783 1,
3784 &sock->writes.size,
3785 sock->writes.flags,
3786 &sock->writes.overlapped,
3787 NULL);
3788 }
3789 else
3790 {
3791 status = 0;
3792 ASSERT(0);
3793 }
3794
3795 if (!status) /* operation completed immediately? */
3796 {
3798
3799 /* since we got an immediate return, we must signal the event object ourselves */
3800 ASSERT(SetEvent(sock->writes.overlapped.hEvent));
3801
3802 sock->writes.status = 0;
3803
3804 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3805 (int) wsabuf[0].len,
3806 (int) sock->writes.size);
3807 }
3808 else
3809 {
3811 /* both status code have the identical value */
3812 if (status == WSA_IO_PENDING || status == ERROR_IO_PENDING) /* operation queued? */
3813 {
3815 sock->writes.status = status;
3816 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
3817 (int) wsabuf[0].len);
3818 }
3819 else /* error occurred */
3820 {
3821 struct gc_arena gc = gc_new();
3822 ASSERT(SetEvent(sock->writes.overlapped.hEvent));
3824 sock->writes.status = status;
3825
3826 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
3827 (int) wsabuf[0].len,
3829
3830 gc_free(&gc);
3831 }
3832 }
3833 }
3834 return sock->writes.iostate;
3835}
3836
3837void
3838read_sockaddr_from_overlapped(struct overlapped_io *io, struct sockaddr *dst, int overlapped_ret)
3839{
3840 if (overlapped_ret >= 0 && io->addr_defined)
3841 {
3842 /* TODO(jjo): streamline this mess */
3843 /* in this func we don't have relevant info about the PF_ of this
3844 * endpoint, as link_socket_actual will be zero for the 1st received packet
3845 *
3846 * Test for inets PF_ possible sizes
3847 */
3848 switch (io->addrlen)
3849 {
3850 case sizeof(struct sockaddr_in):
3851 case sizeof(struct sockaddr_in6):
3852 /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3853 * under _WIN32*/
3854 case sizeof(struct sockaddr_in6) - 4:
3855 break;
3856
3857 default:
3858 bad_address_length(io->addrlen, af_addr_size(io->addr.sin_family));
3859 }
3860
3861 switch (io->addr.sin_family)
3862 {
3863 case AF_INET:
3864 memcpy(dst, &io->addr, sizeof(struct sockaddr_in));
3865 break;
3866
3867 case AF_INET6:
3868 memcpy(dst, &io->addr6, sizeof(struct sockaddr_in6));
3869 break;
3870 }
3871 }
3872 else
3873 {
3874 CLEAR(*dst);
3875 }
3876}
3877
3887static int
3888read_sockaddr_from_packet(struct buffer *buf, struct sockaddr *dst)
3889{
3890 int sa_len = 0;
3891
3892 const struct sockaddr *sa = (const struct sockaddr *)BPTR(buf);
3893 switch (sa->sa_family)
3894 {
3895 case AF_INET:
3896 sa_len = sizeof(struct sockaddr_in);
3897 if (buf_len(buf) < sa_len)
3898 {
3899 msg(M_FATAL, "ERROR: received incoming packet with too short length of %d -- must be at least %d.", buf_len(buf), sa_len);
3900 }
3901 memcpy(dst, sa, sa_len);
3902 buf_advance(buf, sa_len);
3903 break;
3904
3905 case AF_INET6:
3906 sa_len = sizeof(struct sockaddr_in6);
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 default:
3916 msg(M_FATAL, "ERROR: received incoming packet with invalid address family %d.", sa->sa_family);
3917 }
3918
3919 return sa_len;
3920}
3921
3922/* Returns the number of bytes successfully read */
3923int
3925 struct overlapped_io *io,
3926 struct buffer *buf,
3927 struct link_socket_actual *from)
3928{
3929 int ret = -1;
3930 BOOL status;
3931
3932 switch (io->iostate)
3933 {
3934 case IOSTATE_QUEUED:
3936 if (status)
3937 {
3938 /* successful return for a queued operation */
3939 if (buf)
3940 {
3941 *buf = io->buf;
3942 }
3943 ret = io->size;
3945 ASSERT(ResetEvent(io->overlapped.hEvent));
3946
3947 dmsg(D_WIN32_IO, "WIN32 I/O: Completion success [%d]", ret);
3948 }
3949 else
3950 {
3951 /* error during a queued operation */
3952 ret = -1;
3953 if (SocketHandleGetLastError(sh) != ERROR_IO_INCOMPLETE)
3954 {
3955 /* if no error (i.e. just not finished yet), then DON'T execute this code */
3957 ASSERT(ResetEvent(io->overlapped.hEvent));
3958 msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion error");
3959 }
3960 }
3961 break;
3962
3965 ASSERT(ResetEvent(io->overlapped.hEvent));
3966 if (io->status)
3967 {
3968 /* error return for a non-queued operation */
3970 ret = -1;
3971 msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion non-queued error");
3972 }
3973 else
3974 {
3975 /* successful return for a non-queued operation */
3976 if (buf)
3977 {
3978 *buf = io->buf;
3979 }
3980 ret = io->size;
3981 dmsg(D_WIN32_IO, "WIN32 I/O: Completion non-queued success [%d]", ret);
3982 }
3983 break;
3984
3985 case IOSTATE_INITIAL: /* were we called without proper queueing? */
3987 ret = -1;
3988 dmsg(D_WIN32_IO, "WIN32 I/O: Completion BAD STATE");
3989 break;
3990
3991 default:
3992 ASSERT(0);
3993 }
3994
3995 if (from && ret > 0 && sh.is_handle && sh.prepend_sa)
3996 {
3997 ret -= read_sockaddr_from_packet(buf, &from->dest.addr.sa);
3998 }
3999
4000 if (!sh.is_handle && from)
4001 {
4002 read_sockaddr_from_overlapped(io, &from->dest.addr.sa, ret);
4003 }
4004
4005 if (buf)
4006 {
4007 buf->len = ret;
4008 }
4009 return ret;
4010}
4011
4012#endif /* _WIN32 */
4013
4014/*
4015 * Socket event notification
4016 */
4017
4018unsigned int
4020 struct event_set *es,
4021 unsigned int rwflags,
4022 void *arg,
4023 unsigned int *persistent)
4024{
4025 if (s)
4026 {
4027 if ((rwflags & EVENT_READ) && !stream_buf_read_setup(s))
4028 {
4029 ASSERT(!persistent);
4030 rwflags &= ~EVENT_READ;
4031 }
4032
4033#ifdef _WIN32
4034 if (rwflags & EVENT_READ)
4035 {
4036 socket_recv_queue(s, 0);
4037 }
4038#endif
4039
4040 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
4041 if (!persistent || *persistent != rwflags)
4042 {
4043 event_ctl(es, socket_event_handle(s), rwflags, arg);
4044 if (persistent)
4045 {
4046 *persistent = rwflags;
4047 }
4048 }
4049
4050 s->rwflags_debug = rwflags;
4051 }
4052 return rwflags;
4053}
4054
4055void
4057{
4058 if (sd && socket_defined(*sd))
4059 {
4061 *sd = SOCKET_UNDEFINED;
4062 }
4063}
4064
4065#if UNIX_SOCK_SUPPORT
4066
4067/*
4068 * code for unix domain sockets
4069 */
4070
4071const char *
4072sockaddr_unix_name(const struct sockaddr_un *local, const char *null)
4073{
4074 if (local && local->sun_family == PF_UNIX)
4075 {
4076 return local->sun_path;
4077 }
4078 else
4079 {
4080 return null;
4081 }
4082}
4083
4085create_socket_unix(void)
4086{
4088
4089 if ((sd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
4090 {
4091 msg(M_ERR, "Cannot create unix domain socket");
4092 }
4093
4094 /* set socket file descriptor to not pass across execs, so that
4095 * scripts don't have access to it */
4096 set_cloexec(sd);
4097
4098 return sd;
4099}
4100
4101void
4102socket_bind_unix(socket_descriptor_t sd,
4103 struct sockaddr_un *local,
4104 const char *prefix)
4105{
4106 struct gc_arena gc = gc_new();
4107 const mode_t orig_umask = umask(0);
4108
4109 if (bind(sd, (struct sockaddr *) local, sizeof(struct sockaddr_un)))
4110 {
4112 "%s: Socket bind[%d] failed on unix domain socket %s",
4113 prefix,
4114 (int)sd,
4115 sockaddr_unix_name(local, "NULL"));
4116 }
4117
4118 umask(orig_umask);
4119 gc_free(&gc);
4120}
4121
4123socket_accept_unix(socket_descriptor_t sd,
4124 struct sockaddr_un *remote)
4125{
4126 socklen_t remote_len = sizeof(struct sockaddr_un);
4128
4129 CLEAR(*remote);
4130 ret = accept(sd, (struct sockaddr *) remote, &remote_len);
4131 if (ret >= 0)
4132 {
4133 /* set socket file descriptor to not pass across execs, so that
4134 * scripts don't have access to it */
4135 set_cloexec(ret);
4136 }
4137 return ret;
4138}
4139
4140int
4141socket_connect_unix(socket_descriptor_t sd,
4142 struct sockaddr_un *remote)
4143{
4144 int status = connect(sd, (struct sockaddr *) remote, sizeof(struct sockaddr_un));
4145 if (status)
4146 {
4148 }
4149 return status;
4150}
4151
4152void
4153sockaddr_unix_init(struct sockaddr_un *local, const char *path)
4154{
4155 local->sun_family = PF_UNIX;
4156 strncpynt(local->sun_path, path, sizeof(local->sun_path));
4157}
4158
4159void
4160socket_delete_unix(const struct sockaddr_un *local)
4161{
4162 const char *name = sockaddr_unix_name(local, NULL);
4163 if (name && strlen(name))
4164 {
4165 unlink(name);
4166 }
4167}
4168
4169bool
4170unix_socket_get_peer_uid_gid(const socket_descriptor_t sd, int *uid, int *gid)
4171{
4172#ifdef HAVE_GETPEEREID
4173 uid_t u;
4174 gid_t g;
4175 if (getpeereid(sd, &u, &g) == -1)
4176 {
4177 return false;
4178 }
4179 if (uid)
4180 {
4181 *uid = u;
4182 }
4183 if (gid)
4184 {
4185 *gid = g;
4186 }
4187 return true;
4188#elif defined(SO_PEERCRED)
4189 struct ucred peercred;
4190 socklen_t so_len = sizeof(peercred);
4191 if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
4192 {
4193 return false;
4194 }
4195 if (uid)
4196 {
4197 *uid = peercred.uid;
4198 }
4199 if (gid)
4200 {
4201 *gid = peercred.gid;
4202 }
4203 return true;
4204#else /* ifdef HAVE_GETPEEREID */
4205 return false;
4206#endif /* ifdef HAVE_GETPEEREID */
4207}
4208
4209#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:267
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition env_set.c:283
#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:53
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:2749
void management_sleep(const int n)
A sleep function that services the management layer for n seconds rather than doing nothing.
Definition manage.c:4120
#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:486
#define CM_CHILD_UDP
Definition openvpn.h:485
#define MODE_POINT_TO_POINT
Definition options.h:258
#define MODE_SERVER
Definition options.h:259
#define streq(x, y)
Definition options.h:726
static bool dco_enabled(const struct options *o)
Returns whether the current configuration has dco enabled.
Definition options.h:928
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:1894
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:2267
int socket_send_queue(struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
Definition socket.c:3720
static void ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
Definition socket.c:2448
const char * proto2ascii(int proto, sa_family_t af, bool display_form)
Definition socket.c:3215
static int socket_get_last_error(const struct link_socket *sock)
Definition socket.c:3592
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:3490
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:2091
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:2585
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:2686
const char * socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
Definition socket.c:2618
void bad_address_length(int actual, int expected)
Definition socket.c:3304
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:3120
const char * print_sockaddr_ex(const struct sockaddr *sa, const char *separator, const unsigned int flags, struct gc_arena *gc)
Definition socket.c:2835
static bool stream_buf_added(struct stream_buf *sb, int length_added)
Definition socket.c:2739
event_t socket_listen_event_handle(struct link_socket *s)
Definition socket.c:2817
void sd_close(socket_descriptor_t *sd)
Definition socket.c:4056
const char * print_in_port_t(in_port_t port, struct gc_arena *gc)
Definition socket.c:3033
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:2049
const char * proto2ascii_all(struct gc_arena *gc)
Definition socket.c:3236
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:3149
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:3133
static void stream_buf_close(struct stream_buf *sb)
Definition socket.c:2806
const char * print_link_socket_actual(const struct link_socket_actual *act, struct gc_arena *gc)
Definition socket.c:2916
static void stream_buf_get_final(struct stream_buf *sb, struct buffer *buf)
Definition socket.c:2701
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:2719
static void phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info)
Definition socket.c:2179
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:3067
int socket_recv_queue(struct link_socket *sock, int maxsize)
Definition socket.c:3603
void link_socket_close(struct link_socket *sock)
Definition socket.c:2390
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:2464
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:2926
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:3044
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:2030
static void resolve_remote(struct link_socket *sock, int phase, const char **remote_dynamic, struct signal_info *sig_info)
Definition socket.c:1753
sa_family_t ascii2af(const char *proto_name)
Definition socket.c:3202
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:2544
int sockethandle_finalize(sockethandle_t sh, struct overlapped_io *io, struct buffer *buf, struct link_socket_actual *from)
Definition socket.c:3924
in_addr_t link_socket_current_remote(const struct link_socket_info *info)
Definition socket.c:2550
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:3316
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:4019
const char * proto_remote(int proto, bool remote)
Definition socket.c:3276
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:3017
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:2515
static void phase2_tcp_client(struct link_socket *sock, struct signal_info *sig_info)
Definition socket.c:2134
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:3189
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:2997
static void stream_buf_reset(struct stream_buf *sb)
Definition socket.c:2655
static void stream_buf_get_next(struct stream_buf *sb, struct buffer *buf)
Definition socket.c:2710
static void create_socket_dco_win(struct context *c, struct link_socket *sock, struct signal_info *sig_info)
Definition socket.c:2218
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:1880
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:3888
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:2442
#define IF_NAMESIZE
Definition socket.c:2922
const char * addr_family_name(int af)
Definition socket.c:3252
void read_sockaddr_from_overlapped(struct overlapped_io *io, struct sockaddr *dst, int overlapped_ret)
Definition socket.c:3838
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:2665
#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:158
int link_sockets_num
Definition openvpn.h:157
struct http_proxy_info * http_proxy
Definition openvpn.h:188
struct socks_proxy_info * socks_proxy
Definition openvpn.h:192
struct cached_dns_entry * dns_cache
Definition openvpn.h:166
struct tuntap * tuntap
Tun/tap virtual network interface.
Definition openvpn.h:171
struct event_timeout server_poll_interval
Definition openvpn.h:408
const struct link_socket * accept_from
Definition openvpn.h:242
struct frame frame
Definition openvpn.h:248
struct link_socket ** link_sockets
Definition openvpn.h:237
Contains all state information for one tunnel.
Definition openvpn.h:474
int mode
Role of this context within the OpenVPN process.
Definition openvpn.h:487
struct signal_info * sig
Internal error signaling object.
Definition openvpn.h:500
struct plugin_list * plugins
List of plug-ins.
Definition openvpn.h:502
struct context_2 c2
Level 2 context.
Definition openvpn.h:514
struct options options
Options loaded from command line or configuration file.
Definition openvpn.h:475
struct gc_arena gc
Garbage collection arena for allocations done in the scope of this context structure.
Definition openvpn.h:492
struct context_1 c1
Level 1 context.
Definition openvpn.h:513
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
union openvpn_sockaddr::@25 addr
struct sockaddr sa
Definition socket.h:69
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:3162
const char * display_form
Definition socket.c:3163
sa_family_t proto_af
Definition socket.c:3164
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:90
Definition tun.h:181
enum tun_driver_type backend_driver
The backend driver that used for this tun/tap device.
Definition tun.h:191
OVERLAPPED dco_new_peer_ov
Definition tun.h:217
struct tuntap_options options
Definition tun.h:203
HANDLE hand
Definition tun.h:216
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:6648
@ DRIVER_DCO
Definition tun.h:55
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