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-2026 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, see <https://www.gnu.org/licenses/>.
21 */
22
23#ifdef HAVE_CONFIG_H
24#include "config.h"
25#endif
26
27#include "syshead.h"
28
29#include "socket.h"
30#include "fdmisc.h"
31#include "misc.h"
32#include "gremlin.h"
33#include "plugin.h"
34#include "ps.h"
35#include "run_command.h"
36#include "manage.h"
37#include "misc.h"
38#include "manage.h"
39#include "openvpn.h"
40#include "forward.h"
41#include "resolve.h"
42
43#include "memdbg.h"
44
45bool
47{
48 for (int i = 0; i < c->c1.link_sockets_num; i++)
49 {
51 {
52 return true;
53 }
54 }
55 return false;
56}
57
58static int
60{
61 int val;
62 socklen_t len = sizeof(val);
63
64 if (getsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *)&val, &len) == 0 && len == sizeof(val))
65 {
66 return val;
67 }
68 return 0;
69}
70
71static void
73{
74 if (setsockopt(sd, SOL_SOCKET, SO_SNDBUF, (void *)&size, sizeof(size)) != 0)
75 {
76 msg(M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
77 }
78}
79
80static int
82{
83 int val;
84 socklen_t len = sizeof(val);
85
86 if (getsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *)&val, &len) == 0 && len == sizeof(val))
87 {
88 return val;
89 }
90 return 0;
91}
92
93static void
95{
96 if (setsockopt(sd, SOL_SOCKET, SO_RCVBUF, (void *)&size, sizeof(size)) != 0)
97 {
98 msg(M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
99 }
100}
101
102void
103socket_set_buffers(socket_descriptor_t fd, const struct socket_buffer_size *sbs, bool reduce_size)
104{
105 if (sbs)
106 {
107 const int sndbuf_old = socket_get_sndbuf(fd);
108 const int rcvbuf_old = socket_get_rcvbuf(fd);
109
110 if (sbs->sndbuf && (reduce_size || sndbuf_old < sbs->sndbuf))
111 {
112 socket_set_sndbuf(fd, sbs->sndbuf);
113 }
114
115 if (sbs->rcvbuf && (reduce_size || rcvbuf_old < sbs->rcvbuf))
116 {
117 socket_set_rcvbuf(fd, sbs->rcvbuf);
118 }
119
120 msg(D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]", rcvbuf_old, socket_get_rcvbuf(fd),
121 sndbuf_old, socket_get_sndbuf(fd));
122 }
123}
124
125/*
126 * Set other socket options
127 */
128
129static bool
131{
132#if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY))
133 if (setsockopt(sd, IPPROTO_TCP, TCP_NODELAY, (void *)&state, sizeof(state)) != 0)
134 {
135 msg(M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
136 return false;
137 }
138 else
139 {
140 dmsg(D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
141 return true;
142 }
143#else /* if defined(_WIN32) || (defined(IPPROTO_TCP) && defined(TCP_NODELAY)) */
144 msg(M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
145 return false;
146#endif
147}
148
149static inline void
151{
152#if defined(TARGET_LINUX)
153 if (mark && setsockopt(sd, SOL_SOCKET, SO_MARK, (void *)&mark, sizeof(mark)) != 0)
154 {
155 msg(M_WARN, "NOTE: setsockopt SO_MARK=%d failed", mark);
156 }
157#endif
158}
159
160void
161link_socket_update_buffer_sizes(struct link_socket *sock, int rcvbuf, int sndbuf)
162{
163 if (sock && socket_defined(sock->sd))
164 {
165 sock->socket_buffer_sizes.sndbuf = sndbuf;
166 sock->socket_buffer_sizes.rcvbuf = rcvbuf;
167 socket_set_buffers(sock->sd, &sock->socket_buffer_sizes, true);
168 }
169}
170
171/*
172 * SOCKET INITIALIZATION CODE.
173 * Create a TCP/UDP socket
174 */
175
177create_socket_tcp(struct addrinfo *addrinfo)
178{
180
181 ASSERT(addrinfo);
182 ASSERT(addrinfo->ai_socktype == SOCK_STREAM);
183
184 if ((sd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol))
186 {
187 msg(M_ERR, "Cannot create TCP socket");
188 }
189
190#ifndef _WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
191 /* set SO_REUSEADDR on socket */
192 {
193 int on = 1;
194 if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)) < 0)
195 {
196 msg(M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
197 }
198 }
199#endif
200
201 /* set socket file descriptor to not pass across execs, so that
202 * scripts don't have access to it */
203 set_cloexec(sd);
204
205 return sd;
206}
207
209create_socket_udp(struct addrinfo *addrinfo, const unsigned int flags, bool optional)
210{
212
213 ASSERT(addrinfo);
214 ASSERT(addrinfo->ai_socktype == SOCK_DGRAM);
215
216 if ((sd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol))
218 {
219 msg(optional ? D_LOW | M_ERRNO : M_ERR, "UDP: Cannot create UDP/UDP6 socket");
220 return SOCKET_UNDEFINED;
221 }
222#if ENABLE_IP_PKTINFO
223 else if (flags & SF_USE_IP_PKTINFO)
224 {
225 int pad = 1;
226 if (addrinfo->ai_family == AF_INET)
227 {
228#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
229 if (setsockopt(sd, SOL_IP, IP_PKTINFO, (void *)&pad, sizeof(pad)) < 0)
230 {
231 msg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO");
232 }
233#elif defined(IP_RECVDSTADDR)
234 if (setsockopt(sd, IPPROTO_IP, IP_RECVDSTADDR, (void *)&pad, sizeof(pad)) < 0)
235 {
236 msg(M_ERR, "UDP: failed setsockopt for IP_RECVDSTADDR");
237 }
238#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
239#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
240#endif
241 }
242 else if (addrinfo->ai_family == AF_INET6)
243 {
244#ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
245 if (setsockopt(sd, IPPROTO_IPV6, IPV6_PKTINFO, (void *)&pad, sizeof(pad)) < 0)
246#else
247 if (setsockopt(sd, IPPROTO_IPV6, IPV6_RECVPKTINFO, (void *)&pad, sizeof(pad)) < 0)
248#endif
249 {
250 msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");
251 }
252 }
253 }
254#endif /* if ENABLE_IP_PKTINFO */
255
256 /* set socket file descriptor to not pass across execs, so that
257 * scripts don't have access to it */
258 set_cloexec(sd);
259
260 return sd;
261}
262
263static void
264bind_local(const struct link_socket *sock)
265{
266 /* bind to local address/port */
267 if (sock->bind_local)
268 {
269 if (sock->socks_proxy && sock->info.proto == PROTO_UDP)
270 {
271 socket_bind(sock->ctrl_sd, sock->info.lsa->bind_local, sock->info.af, "SOCKS", false);
272 }
273 else
274 {
275 socket_bind(sock->sd, sock->info.lsa->bind_local, sock->info.af, "TCP/UDP",
276 sock->info.bind_ipv6_only);
277 }
278 }
279}
280
281/* The per-socket options every link socket gets right after creation. */
282static void
284 const char *bind_dev)
285{
286 /* set socket buffers based on --sndbuf and --rcvbuf options */
287 socket_set_buffers(sd, sbs, true);
288
289 /* set socket to --mark packets with given value */
290 socket_set_mark(sd, mark);
291
292#if defined(TARGET_LINUX)
293 if (bind_dev)
294 {
295 msg(M_INFO, "Using bind-dev %s", bind_dev);
296 /* Note: We verify strlen of bind_dev in options parsing */
297 if (setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, bind_dev, (socklen_t)(strlen(bind_dev) + 1))
298 != 0)
299 {
300 msg(M_WARN | M_ERRNO, "WARN: setsockopt SO_BINDTODEVICE=%s failed", bind_dev);
301 }
302 }
303#else
304 (void)bind_dev;
305#endif
306}
307
309create_socket_udp_configured(sa_family_t af, unsigned int sockflags, const struct socket_buffer_size *sbs,
310 int mark, const char *bind_dev, struct addrinfo *bind_addr,
311 bool bind_ipv6_only, bool optional)
312{
313 struct addrinfo ai = { .ai_family = af, .ai_socktype = SOCK_DGRAM, .ai_protocol = IPPROTO_UDP };
314 socket_descriptor_t sd = create_socket_udp(&ai, sockflags, optional);
315
316 if (sd == SOCKET_UNDEFINED)
317 {
318 return SOCKET_UNDEFINED;
319 }
320
321 socket_apply_options(sd, sbs, mark, bind_dev);
322 if (bind_addr)
323 {
324 socket_bind(sd, bind_addr, af, "TCP/UDP", bind_ipv6_only);
325 }
326 return sd;
327}
328
329static void
330create_socket(struct link_socket *sock, struct addrinfo *addr)
331{
332 /* Set af field of sock->info, so it always reflects the address family
333 * of the created socket */
334 sock->info.af = (sa_family_t)addr->ai_family;
335
336 if (addr->ai_protocol == IPPROTO_UDP || addr->ai_socktype == SOCK_DGRAM)
337 {
338 /* With a SOCKS proxy the local bind goes on the control socket instead
339 * (see bind_local()), so the UDP socket is created unbound then. */
340 struct addrinfo *bind_addr =
341 (sock->bind_local && !sock->socks_proxy) ? sock->info.lsa->bind_local : NULL;
343 sock->mark, sock->bind_dev, bind_addr,
344 sock->info.bind_ipv6_only, false);
346
347 /* Assume that control socket and data socket to the socks proxy
348 * are using the same IP family */
349 if (sock->socks_proxy)
350 {
351 /* Construct a temporary addrinfo to create the socket,
352 * currently resolve two remote addresses is not supported,
353 * TODO: Rewrite the whole resolve_remote */
354 struct addrinfo addrinfo_tmp = *addr;
355 addrinfo_tmp.ai_socktype = SOCK_STREAM;
356 addrinfo_tmp.ai_protocol = IPPROTO_TCP;
357 sock->ctrl_sd = create_socket_tcp(&addrinfo_tmp);
358 bind_local(sock);
359 }
360 }
361 else if (addr->ai_protocol == IPPROTO_TCP || addr->ai_socktype == SOCK_STREAM)
362 {
363 sock->sd = create_socket_tcp(addr);
364 socket_apply_options(sock->sd, &sock->socket_buffer_sizes, sock->mark, sock->bind_dev);
365 bind_local(sock);
366 }
367 else
368 {
369 ASSERT(0);
370 }
371}
372
373#ifdef TARGET_ANDROID
374static void
375protect_fd_nonlocal(int fd, const struct sockaddr *addr)
376{
377 if (!management)
378 {
379 msg(M_FATAL, "Required management interface not available.");
380 }
381
382 /* pass socket FD to management interface to pass on to VPNService API
383 * as "protected socket" (exempt from being routed into tunnel)
384 */
385 if (addr_local(addr))
386 {
387 msg(D_SOCKET_DEBUG, "Address is local, not protecting socket fd %d", fd);
388 return;
389 }
390
391 msg(D_SOCKET_DEBUG, "Protecting socket fd %d", fd);
392 management->connection.fdtosend = fd;
393 management_android_control(management, "PROTECTFD", __func__);
394}
395#endif
396
397/*
398 * Functions used for establishing a TCP stream connection.
399 */
400static void
401socket_do_listen(socket_descriptor_t sd, const struct addrinfo *local, bool do_listen,
402 bool do_set_nonblock)
403{
404 struct gc_arena gc = gc_new();
405 if (do_listen)
406 {
407 ASSERT(local);
408 msg(M_INFO, "Listening for incoming TCP connection on %s",
409 print_sockaddr(local->ai_addr, &gc));
410 if (listen(sd, 32))
411 {
412 msg(M_ERR, "TCP: listen() failed");
413 }
414 }
415
416 /* set socket to non-blocking mode */
417 if (do_set_nonblock)
418 {
419 set_nonblock(sd);
420 }
421
422 gc_free(&gc);
423}
424
425#if defined(__GNUC__) || defined(__clang__)
426#pragma GCC diagnostic push
427#pragma GCC diagnostic ignored "-Wsign-conversion"
428#endif
429
431socket_do_accept(socket_descriptor_t sd, struct link_socket_actual *act, const bool nowait)
432{
433 /* af_addr_size WILL return 0 in this case if AFs other than AF_INET
434 * are compiled because act is empty here.
435 * could use getsockname() to support later remote_len check
436 */
437 socklen_t remote_len_af = af_addr_size(act->dest.addr.sa.sa_family);
438 socklen_t remote_len = sizeof(act->dest.addr);
439 socket_descriptor_t new_sd;
440
441 CLEAR(*act);
442
443 if (nowait)
444 {
445 new_sd = getpeername(sd, &act->dest.addr.sa, &remote_len);
446
447 if (!socket_defined(new_sd))
448 {
449 msg(D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
450 }
451 else
452 {
453 new_sd = sd;
454 }
455 }
456 else
457 {
458 new_sd = accept(sd, &act->dest.addr.sa, &remote_len);
459 }
460
461#if 0 /* For debugging only, test the effect of accept() failures */
462 {
463 static int foo = 0;
464 ++foo;
465 if (foo & 1)
466 {
467 new_sd = -1;
468 }
469 }
470#endif
471
472 if (!socket_defined(new_sd))
473 {
474 msg(D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", (int)sd);
475 }
476 /* only valid if we have remote_len_af!=0 */
477 else if (remote_len_af && remote_len != remote_len_af)
478 {
480 "TCP: Received strange incoming connection with unknown address length=%u",
481 (unsigned int)remote_len);
482 openvpn_close_socket(new_sd);
483 new_sd = SOCKET_UNDEFINED;
484 }
485 else
486 {
487 /* set socket file descriptor to not pass across execs, so that
488 * scripts don't have access to it */
489 set_cloexec(new_sd);
490 }
491 return new_sd;
492}
493
494static void
496{
497 struct gc_arena gc = gc_new();
498 msg(M_INFO, "TCP connection established with %s", print_link_socket_actual(act, &gc));
499 gc_free(&gc);
500}
501
504 const struct addrinfo *local, bool do_listen,
505 bool nowait, volatile int *signal_received)
506{
508
509 CLEAR(*act);
510 socket_do_listen(sd, local, do_listen, true);
511
512 while (true)
513 {
514 int status;
515 fd_set reads;
516 struct timeval tv;
517
518 FD_ZERO(&reads);
519 openvpn_fd_set(sd, &reads);
520 tv.tv_sec = 0;
521 tv.tv_usec = 0;
522
523 status = openvpn_select(sd + 1, &reads, NULL, NULL, &tv);
524
525 get_signal(signal_received);
526 if (*signal_received)
527 {
528 return sd;
529 }
530
531 if (status < 0)
532 {
533 msg(D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
534 }
535
536 if (status <= 0)
537 {
539 continue;
540 }
541
542 new_sd = socket_do_accept(sd, act, nowait);
543
544 if (socket_defined(new_sd))
545 {
546 break;
547 }
549 }
550
551 if (!nowait && openvpn_close_socket(sd))
552 {
553 msg(M_ERR, "TCP: close socket failed (sd)");
554 }
555
557
558 return new_sd;
559}
560
561void
562socket_bind(socket_descriptor_t sd, const struct addrinfo *local, int ai_family,
563 const char *prefix, bool ipv6only)
564{
565 struct gc_arena gc = gc_new();
566
567 /* FIXME (schwabe)
568 * getaddrinfo for the bind address might return multiple AF_INET/AF_INET6
569 * entries for the requested protocol.
570 * For example if an address has multiple A records
571 * What is the correct way to deal with it?
572 */
573
574 ASSERT(local);
575
576 /* find the first addrinfo with correct ai_family */
577 const struct addrinfo *cur;
578 for (cur = local; cur; cur = cur->ai_next)
579 {
580 if (cur->ai_family == ai_family)
581 {
582 break;
583 }
584 }
585 if (!cur)
586 {
587 msg(M_FATAL, "%s: Socket bind failed: Addr to bind has no %s record", prefix,
588 addr_family_name(ai_family));
589 }
590
591 if (ai_family == AF_INET6)
592 {
593 int v6only = ipv6only ? 1 : 0; /* setsockopt must have an "int" */
594
595 msg(M_INFO, "setsockopt(IPV6_V6ONLY=%d)", v6only);
596 if (setsockopt(sd, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&v6only, sizeof(v6only)))
597 {
598 msg(M_NONFATAL | M_ERRNO, "Setting IPV6_V6ONLY=%d failed", v6only);
599 }
600 }
601 if (openvpn_bind(sd, cur->ai_addr, cur->ai_addrlen))
602 {
603 msg(M_FATAL | M_ERRNO, "%s: Socket bind failed on local address %s", prefix,
604 print_sockaddr_ex(local->ai_addr, ":", PS_SHOW_PORT, &gc));
605 }
606 gc_free(&gc);
607}
608
609int
610openvpn_connect(socket_descriptor_t sd, const struct sockaddr *remote, int connect_timeout,
611 volatile int *signal_received)
612{
613 int status = 0;
614
615#ifdef TARGET_ANDROID
616 protect_fd_nonlocal(sd, remote);
617#endif
618 set_nonblock(sd);
619 status = connect(sd, remote, af_addr_size(remote->sa_family));
620 if (status)
621 {
623 }
624 if (
625#ifdef _WIN32
626 status == WSAEWOULDBLOCK
627#else
628 status == EINPROGRESS
629#endif
630 )
631 {
632 while (true)
633 {
634#if POLL
635 struct pollfd fds[1];
636 fds[0].fd = sd;
637 fds[0].events = POLLOUT;
638 status = poll(fds, 1, (connect_timeout > 0) ? 1000 : 0);
639#else
640 fd_set writes;
641 struct timeval tv;
642
643 FD_ZERO(&writes);
644 openvpn_fd_set(sd, &writes);
645 tv.tv_sec = (connect_timeout > 0) ? 1 : 0;
646 tv.tv_usec = 0;
647
648 status = openvpn_select(sd + 1, NULL, &writes, NULL, &tv);
649#endif
650 if (signal_received)
651 {
652 get_signal(signal_received);
653 if (*signal_received)
654 {
655 status = 0;
656 break;
657 }
658 }
659 if (status < 0)
660 {
662 break;
663 }
664 if (status <= 0)
665 {
666 if (--connect_timeout < 0)
667 {
668#ifdef _WIN32
669 status = WSAETIMEDOUT;
670#else
671 status = ETIMEDOUT;
672#endif
673 break;
674 }
676 continue;
677 }
678
679 /* got it */
680 {
681 int val = 0;
682 socklen_t len;
683
684 len = sizeof(val);
685 if (getsockopt(sd, SOL_SOCKET, SO_ERROR, (void *)&val, &len) == 0
686 && len == sizeof(val))
687 {
688 status = val;
689 }
690 else
691 {
693 }
694 break;
695 }
696 }
697 }
698
699 return status;
700}
701
702void
703set_actual_address(struct link_socket_actual *actual, struct addrinfo *ai)
704{
705 CLEAR(*actual);
706 ASSERT(ai);
707
708 if (ai->ai_family == AF_INET)
709 {
710 actual->dest.addr.in4 = *((struct sockaddr_in *)ai->ai_addr);
711 }
712 else if (ai->ai_family == AF_INET6)
713 {
714 actual->dest.addr.in6 = *((struct sockaddr_in6 *)ai->ai_addr);
715 }
716 else
717 {
718 ASSERT(0);
719 }
720}
721
722static void
723socket_connect(socket_descriptor_t *sd, const struct sockaddr *dest, const int connect_timeout,
724 struct signal_info *sig_info)
725{
726 struct gc_arena gc = gc_new();
727 int status;
728
729 msg(M_INFO, "Attempting to establish TCP connection with %s", print_sockaddr(dest, &gc));
730
731#ifdef ENABLE_MANAGEMENT
732 if (management)
733 {
734 management_set_state(management, OPENVPN_STATE_TCP_CONNECT, NULL, NULL, NULL, NULL, NULL);
735 }
736#endif
737
738 /* Set the actual address */
739 status = openvpn_connect(*sd, dest, connect_timeout, &sig_info->signal_received);
740
741 get_signal(&sig_info->signal_received);
742 if (sig_info->signal_received)
743 {
744 goto done;
745 }
746
747 if (status)
748 {
749 msg(D_LINK_ERRORS, "TCP: connect to %s failed: %s", print_sockaddr(dest, &gc),
750 strerror(status));
751
753 *sd = SOCKET_UNDEFINED;
754 register_signal(sig_info, SIGUSR1, "connection-failed");
755 }
756 else
757 {
758 msg(M_INFO, "TCP connection established with %s", print_sockaddr(dest, &gc));
759 }
760
761done:
762 gc_free(&gc);
763}
764
765/*
766 * Stream buffer handling prototypes -- stream_buf is a helper class
767 * to assist in the packetization of stream transport protocols
768 * such as TCP.
769 */
770
771static void stream_buf_init(struct stream_buf *sb, const struct buffer *buf,
772 const unsigned int sockflags, const int proto);
773
774static void stream_buf_close(struct stream_buf *sb);
775
776static bool stream_buf_added(struct stream_buf *sb, ssize_t length_added);
777
778/* For stream protocols, allocate a buffer to build up packet.
779 * Called after frame has been finalized. */
780
781static void
782socket_frame_init(const struct frame *frame, struct link_socket *sock)
783{
784#ifdef _WIN32
785 overlapped_io_init(&sock->reads, frame, FALSE);
786 overlapped_io_init(&sock->writes, frame, TRUE);
787 sock->rw_handle.read = sock->reads.overlapped.hEvent;
788 sock->rw_handle.write = sock->writes.overlapped.hEvent;
789#endif
790
792 {
793#ifdef _WIN32
794 stream_buf_init(&sock->stream_buf, &sock->reads.buf_init, sock->sockflags,
795 sock->info.proto);
796#else
798
800 sock->info.proto);
801#endif
802 }
803}
804
805static void
807{
808 /* resolve local address if undefined */
809 if (!sock->info.lsa->bind_local)
810 {
812 int status;
813
814 if (proto_is_dgram(sock->info.proto))
815 {
816 flags |= GETADDR_DATAGRAM;
817 }
818
819 /* will return AF_{INET|INET6}from local_host */
820 status = get_cached_dns_entry(sock->dns_cache, sock->local_host, sock->local_port, sock->info.af,
821 flags, &sock->info.lsa->bind_local);
822
823 if (status)
824 {
825 status = openvpn_getaddrinfo(flags, sock->local_host, sock->local_port, 0, NULL, sock->info.af,
826 &sock->info.lsa->bind_local);
827 }
828
829 if (status != 0)
830 {
831 msg(M_FATAL, "getaddrinfo() failed for local \"%s:%s\": %s", sock->local_host,
832 sock->local_port, gai_strerror(status));
833 }
834
835 /* the address family returned by openvpn_getaddrinfo() should be
836 * taken into consideration only if we really passed an hostname
837 * to resolve. Otherwise its value is not useful to us and may
838 * actually break our socket, i.e. when it returns AF_INET
839 * but our remote is v6 only.
840 */
841 if (sock->local_host)
842 {
843 /* the resolved 'local entry' might have a different family than
844 * what was globally configured
845 */
846 sock->info.af = (sa_family_t)sock->info.lsa->bind_local->ai_family;
847 }
848 }
849}
850
851static void
852resolve_remote(struct link_socket *sock, int phase, struct signal_info *sig_info)
853{
854 volatile int *signal_received = sig_info ? &sig_info->signal_received : NULL;
855 struct gc_arena gc = gc_new();
856
857 /* resolve remote address if undefined */
858 if (!sock->info.lsa->remote_list)
859 {
860 if (sock->remote_host)
861 {
862 unsigned int flags =
864 int retry = 0;
865 int status = -1;
866 struct addrinfo *ai;
867 if (proto_is_dgram(sock->info.proto))
868 {
869 flags |= GETADDR_DATAGRAM;
870 }
871
873 {
874 if (phase == 2)
875 {
876 flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
877 }
878 retry = 0;
879 }
880 else if (phase == 1)
881 {
882 if (sock->resolve_retry_seconds)
883 {
884 retry = 0;
885 }
886 else
887 {
889 retry = 0;
890 }
891 }
892 else if (phase == 2)
893 {
894 if (sock->resolve_retry_seconds)
895 {
896 flags |= GETADDR_FATAL;
897 retry = sock->resolve_retry_seconds;
898 }
899 else
900 {
901 ASSERT(0);
902 }
903 }
904 else
905 {
906 ASSERT(0);
907 }
908
909
911 sock->info.af, flags, &ai);
912 if (status)
913 {
914 status = openvpn_getaddrinfo(flags, sock->remote_host, sock->remote_port, retry,
915 sig_info, sock->info.af, &ai);
916 }
917
918 if (status == 0)
919 {
920 sock->info.lsa->remote_list = ai;
921 sock->info.lsa->current_remote = ai;
922
923 dmsg(D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
924 flags, phase, retry, signal_received ? *signal_received : -1, status);
925 }
926 if (signal_received && *signal_received)
927 {
928 goto done;
929 }
930 if (status != 0)
931 {
932 if (signal_received)
933 {
934 /* potential overwrite of signal */
935 register_signal(sig_info, SIGUSR1, "socks-resolve-failure");
936 }
937 goto done;
938 }
939 }
940 }
941
942 /* should we re-use previous active remote address? */
944 {
945 msg(M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
947 }
948 else
949 {
950 CLEAR(sock->info.lsa->actual);
951 if (sock->info.lsa->current_remote)
952 {
954 }
955 }
956
957done:
958 gc_free(&gc);
959}
960
961
962struct link_socket *
964{
965 struct link_socket *sock;
966
967 ALLOC_OBJ_CLEAR(sock, struct link_socket);
968 sock->sd = SOCKET_UNDEFINED;
971 sock->ev_arg.u.sock = sock;
972
973 return sock;
974}
975
976void
977link_socket_init_phase1(struct context *c, int sock_index, int mode)
978{
979 struct link_socket *sock = c->c2.link_sockets[sock_index];
980 struct options *o = &c->options;
981 ASSERT(sock);
982
983 const char *host = o->ce.local_list->array[sock_index]->local;
984 const char *port = o->ce.local_list->array[sock_index]->port;
985 int proto = o->ce.local_list->array[sock_index]->proto;
986 const char *remote_host = o->ce.remote;
987 const char *remote_port = o->ce.remote_port;
988
989 if (remote_host)
990 {
991 proto = o->ce.proto;
992 }
993
994 /* If --lport is specified in a client connection block,
995 * it takes precedence over the global setting. */
997 {
998 port = o->ce.local_port;
999 }
1000
1001 if (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP)
1002 {
1003 struct link_socket *tmp_sock = NULL;
1004 if (c->mode == CM_CHILD_TCP)
1005 {
1006 tmp_sock = (struct link_socket *)c->c2.accept_from;
1007 }
1008 else if (c->mode == CM_CHILD_UDP)
1009 {
1010 tmp_sock = c->c2.link_sockets[0];
1011 }
1012
1013 host = tmp_sock->local_host;
1014 port = tmp_sock->local_port;
1015 proto = tmp_sock->info.proto;
1016 }
1017
1018 sock->local_host = host;
1019 sock->local_port = port;
1020 sock->remote_host = remote_host;
1021 sock->remote_port = remote_port;
1022 sock->dns_cache = c->c1.dns_cache;
1023 sock->http_proxy = c->c1.http_proxy;
1024 sock->socks_proxy = c->c1.socks_proxy;
1025 sock->bind_local = o->ce.bind_local;
1028
1029#ifdef ENABLE_DEBUG
1030 sock->gremlin = o->gremlin;
1031#endif
1032
1035
1036 sock->sockflags = o->sockflags;
1037
1038#if PORT_SHARE
1039 if (o->port_share_host && o->port_share_port)
1040 {
1041 sock->sockflags |= SF_PORT_SHARE;
1042 }
1043#endif
1044
1045 sock->mark = o->mark;
1046 sock->bind_dev = o->bind_dev;
1047 ASSERT(proto >= 0 && proto < PROTO_N);
1048 sock->info.proto = (uint8_t)proto;
1049 sock->info.af = o->ce.af;
1050 sock->info.remote_float = o->ce.remote_float;
1051 sock->info.lsa = &c->c1.link_socket_addrs[sock_index];
1053 sock->info.ipchange_command = o->ipchange;
1054 sock->info.plugins = c->plugins;
1056
1057 sock->mode = mode;
1059 {
1060 ASSERT(c->c2.accept_from);
1062 sock->sd = c->c2.accept_from->sd;
1063 /* inherit (possibly guessed) info AF from parent context */
1064 sock->info.af = c->c2.accept_from->info.af;
1065 }
1066
1067 /* are we running in HTTP proxy mode? */
1068 if (sock->http_proxy)
1069 {
1071
1072 /* the proxy server */
1074 sock->remote_port = c->c1.http_proxy->options.port;
1075
1076 /* the OpenVPN server we will use the proxy to connect to */
1079 }
1080 /* or in Socks proxy mode? */
1081 else if (sock->socks_proxy)
1082 {
1083 /* the proxy server */
1084 sock->remote_host = c->c1.socks_proxy->server;
1085 sock->remote_port = c->c1.socks_proxy->port;
1086
1087 /* the OpenVPN server we will use the proxy to connect to */
1090 }
1091 else
1092 {
1093 sock->remote_host = remote_host;
1094 sock->remote_port = remote_port;
1095 }
1096
1097 /* bind behavior for TCP server vs. client */
1098 if (sock->info.proto == PROTO_TCP_SERVER)
1099 {
1100 if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
1101 {
1102 sock->bind_local = false;
1103 }
1104 else
1105 {
1106 sock->bind_local = true;
1107 }
1108 }
1109
1111 {
1112 if (sock->bind_local)
1113 {
1114 resolve_bind_local(sock);
1115 }
1116 resolve_remote(sock, 1, NULL);
1117 }
1118}
1119
1120static void
1122{
1123 /* TCP_NODELAY is enabled by default on every TCP socket; dco-win is
1124 * skipped as it manages its own socket */
1125 if (proto_is_tcp(sock->info.proto) && !(sock->sockflags & SF_DCO_WIN))
1126 {
1127 socket_set_tcp_nodelay(sock->sd, 1);
1128 }
1129
1130 /* set socket to non-blocking mode */
1131 set_nonblock(sock->sd);
1132
1133 /* set Path MTU discovery options on the socket */
1134 set_mtu_discover_type(sock->sd, sock->mtu_discover_type, sock->info.af);
1135
1136#if EXTENDED_SOCKET_ERROR_CAPABILITY
1137 /* if the OS supports it, enable extended error passing on the socket */
1138 set_sock_extended_error_passing(sock->sd, sock->info.af);
1139#endif
1140}
1141
1142
1143static void
1145{
1146 struct gc_arena gc = gc_new();
1147 const msglvl_t msglevel = (sock->mode == LS_MODE_TCP_ACCEPT_FROM) ? D_INIT_MEDIUM : M_INFO;
1148
1149 /* print local address */
1150 if (sock->bind_local)
1151 {
1152 sa_family_t ai_family = sock->info.lsa->actual.dest.addr.sa.sa_family;
1153 /* Socket is always bound on the first matching address,
1154 * For bound sockets with no remote addr this is the element of
1155 * the list */
1156 const struct addrinfo *cur;
1157 for (cur = sock->info.lsa->bind_local; cur; cur = cur->ai_next)
1158 {
1159 if (!ai_family || ai_family == cur->ai_family)
1160 {
1161 break;
1162 }
1163 }
1164 ASSERT(cur);
1165 msg(msglevel, "%s link local (bound): %s",
1166 proto2ascii(sock->info.proto, sock->info.af, true), print_sockaddr(cur->ai_addr, &gc));
1167 }
1168 else
1169 {
1170 msg(msglevel, "%s link local: (not bound)",
1171 proto2ascii(sock->info.proto, sock->info.af, true));
1172 }
1173
1174 /* print active remote address */
1175 msg(msglevel, "%s link remote: %s", proto2ascii(sock->info.proto, sock->info.af, true),
1177 gc_free(&gc);
1178}
1179
1180static void
1181phase2_tcp_server(struct link_socket *sock, struct signal_info *sig_info)
1182{
1183 ASSERT(sig_info);
1184 volatile int *signal_received = &sig_info->signal_received;
1185 switch (sock->mode)
1186 {
1187 case LS_MODE_DEFAULT:
1188 sock->sd =
1189 socket_listen_accept(sock->sd, &sock->info.lsa->actual,
1190 sock->info.lsa->bind_local, true, false,
1191 signal_received);
1192 break;
1193
1194 case LS_MODE_TCP_LISTEN:
1195 socket_do_listen(sock->sd, sock->info.lsa->bind_local, true, false);
1196 break;
1197
1199 sock->sd = socket_do_accept(sock->sd, &sock->info.lsa->actual, false);
1200 if (!socket_defined(sock->sd))
1201 {
1202 register_signal(sig_info, SIGTERM, "socket-undefined");
1203 return;
1204 }
1206 break;
1207
1208 default:
1209 ASSERT(0);
1210 }
1211}
1212
1213
1214static void
1215phase2_tcp_client(struct link_socket *sock, struct signal_info *sig_info)
1216{
1217 bool proxy_retry = false;
1218 do
1219 {
1220 socket_connect(&sock->sd, sock->info.lsa->current_remote->ai_addr,
1222
1223 if (sig_info->signal_received)
1224 {
1225 return;
1226 }
1227
1228 if (sock->http_proxy)
1229 {
1230 proxy_retry = establish_http_proxy_passthru(
1231 sock->http_proxy, sock->sd, sock->proxy_dest_host, sock->proxy_dest_port,
1232 sock->server_poll_timeout, &sock->stream_buf.residual, sig_info);
1233 }
1234 else if (sock->socks_proxy)
1235 {
1238 sig_info);
1239 }
1240 if (proxy_retry)
1241 {
1242 openvpn_close_socket(sock->sd);
1243 sock->sd = create_socket_tcp(sock->info.lsa->current_remote);
1244 }
1245
1246 } while (proxy_retry);
1247}
1248
1249static void
1250phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info)
1251{
1252 socket_connect(&sock->ctrl_sd, sock->info.lsa->current_remote->ai_addr,
1254
1255 if (sig_info->signal_received)
1256 {
1257 return;
1258 }
1259
1261 sock->server_poll_timeout, sig_info);
1262
1263 if (sig_info->signal_received)
1264 {
1265 return;
1266 }
1267
1268 sock->remote_host = sock->proxy_dest_host;
1269 sock->remote_port = sock->proxy_dest_port;
1270
1272 if (sock->info.lsa->remote_list)
1273 {
1274 freeaddrinfo(sock->info.lsa->remote_list);
1275 sock->info.lsa->current_remote = NULL;
1276 sock->info.lsa->remote_list = NULL;
1277 }
1278
1279 resolve_remote(sock, 1, sig_info);
1280}
1281
1282#if defined(_WIN32)
1283static void
1284create_socket_dco_win(struct context *c, struct link_socket *sock, struct signal_info *sig_info)
1285{
1286 /* in P2P mode we must have remote resolved at this point */
1287 const struct addrinfo *remoteaddr = sock->info.lsa->current_remote;
1288 if ((c->options.mode == MODE_POINT_TO_POINT) && (!remoteaddr))
1289 {
1290 return;
1291 }
1292
1293 if (!c->c1.tuntap)
1294 {
1295 struct tuntap *tt;
1296 ALLOC_OBJ_CLEAR(tt, struct tuntap);
1297
1300
1301 const char *device_guid = NULL; /* not used */
1302 tun_open_device(tt, c->options.dev_node, &device_guid, &c->gc);
1303
1304 /* Ensure we can "safely" cast the handle to a socket */
1305 static_assert(sizeof(sock->sd) == sizeof(tt->hand), "HANDLE and SOCKET size differs");
1306
1307 c->c1.tuntap = tt;
1308 }
1309
1310 if (c->options.mode == MODE_SERVER)
1311 {
1312 dco_mp_start_vpn(c->c1.tuntap->hand, sock);
1313 }
1314 else
1315 {
1316 dco_p2p_new_peer(c->c1.tuntap->hand, &c->c1.tuntap->dco_new_peer_ov, sock, sig_info);
1317 }
1318 sock->sockflags |= SF_DCO_WIN;
1319
1320 if (sig_info->signal_received)
1321 {
1322 return;
1323 }
1324
1325 sock->sd = (SOCKET)c->c1.tuntap->hand;
1326 linksock_print_addr(sock);
1327}
1328#endif /* if defined(_WIN32) */
1329
1330/* finalize socket initialization */
1331void
1333{
1334 const struct frame *frame = &c->c2.frame;
1335 struct signal_info *sig_info = c->sig;
1336
1337 struct signal_info sig_save = { 0 };
1338
1339 ASSERT(sock);
1340 ASSERT(sig_info);
1341
1342 if (sig_info->signal_received)
1343 {
1344 sig_save = *sig_info;
1345 sig_save.signal_received = signal_reset(sig_info, 0);
1346 }
1347
1348 /* initialize buffers */
1349 socket_frame_init(frame, sock);
1350
1351 /* Second chance to resolv/create socket */
1352 resolve_remote(sock, 2, sig_info);
1353
1354 /* If a valid remote has been found, create the socket with its addrinfo */
1355#if defined(_WIN32)
1356 if (dco_enabled(&c->options))
1357 {
1358 create_socket_dco_win(c, sock, sig_info);
1359 goto done;
1360 }
1361#endif
1362 if (sock->info.lsa->current_remote)
1363 {
1364 create_socket(sock, sock->info.lsa->current_remote);
1365 }
1366
1367 /* If socket has not already been created create it now */
1368 if (sock->sd == SOCKET_UNDEFINED)
1369 {
1370 /* If we have no --remote and have still not figured out the
1371 * protocol family to use we will use the first of the bind */
1372
1373 if (sock->bind_local && !sock->remote_host && sock->info.lsa->bind_local)
1374 {
1375 /* Warn if this is because neither v4 or v6 was specified
1376 * and we should not connect a remote */
1377 if (sock->info.af == AF_UNSPEC)
1378 {
1379 sock->info.af = (sa_family_t)sock->info.lsa->bind_local->ai_family;
1380 msg(M_WARN, "Could not determine IPv4/IPv6 protocol. Using %s",
1381 addr_family_name(sock->info.af));
1382 }
1383 create_socket(sock, sock->info.lsa->bind_local);
1384 }
1385 }
1386
1387 /* Socket still undefined, give a warning and abort connection */
1388 if (sock->sd == SOCKET_UNDEFINED)
1389 {
1390 msg(M_WARN, "Could not determine IPv4/IPv6 protocol");
1391 register_signal(sig_info, SIGUSR1, "Could not determine IPv4/IPv6 protocol");
1392 goto done;
1393 }
1394
1395 if (sig_info->signal_received)
1396 {
1397 goto done;
1398 }
1399
1400 if (sock->info.proto == PROTO_TCP_SERVER)
1401 {
1402 phase2_tcp_server(sock, sig_info);
1403 }
1404 else if (sock->info.proto == PROTO_TCP_CLIENT)
1405 {
1406 phase2_tcp_client(sock, sig_info);
1407 }
1408 else if (sock->info.proto == PROTO_UDP && sock->socks_proxy)
1409 {
1410 phase2_socks_client(sock, sig_info);
1411 }
1412#ifdef TARGET_ANDROID
1413 if (sock->sd != -1)
1414 {
1415 protect_fd_nonlocal(sock->sd, &sock->info.lsa->actual.dest.addr.sa);
1416 }
1417#endif
1418 if (sig_info->signal_received)
1419 {
1420 goto done;
1421 }
1422
1424 linksock_print_addr(sock);
1425
1426done:
1427 if (sig_save.signal_received)
1428 {
1429 /* Always restore the saved signal -- register/throw_signal will handle priority */
1430 if (sig_save.source == SIG_SOURCE_HARD && sig_info == &siginfo_static)
1431 {
1432 throw_signal(sig_save.signal_received);
1433 }
1434 else
1435 {
1436 register_signal(sig_info, sig_save.signal_received, sig_save.signal_text);
1437 }
1438 }
1439}
1440
1441void
1443{
1444 if (sock)
1445 {
1446#ifdef ENABLE_DEBUG
1447 const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL(sock->gremlin);
1448#else
1449 const int gremlin = 0;
1450#endif
1451
1452 if (socket_defined(sock->sd))
1453 {
1454#ifdef _WIN32
1455 close_net_event_win32(&sock->listen_handle, sock->sd, 0);
1456#endif
1457 if (!gremlin)
1458 {
1459 msg(D_LOW, "TCP/UDP: Closing socket");
1460 if (openvpn_close_socket(sock->sd))
1461 {
1462 msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
1463 }
1464 }
1465 sock->sd = SOCKET_UNDEFINED;
1466#ifdef _WIN32
1467 if (!gremlin)
1468 {
1469 overlapped_io_close(&sock->reads);
1471 }
1472#endif
1473 }
1474
1475 if (socket_defined(sock->ctrl_sd))
1476 {
1477 if (openvpn_close_socket(sock->ctrl_sd))
1478 {
1479 msg(M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
1480 }
1481 sock->ctrl_sd = SOCKET_UNDEFINED;
1482 }
1483
1485 free_buf(&sock->stream_buf_data);
1486 if (!gremlin)
1487 {
1488 free(sock);
1489 }
1490 }
1491}
1492
1493void
1494setenv_trusted(struct env_set *es, const struct link_socket_info *info)
1495{
1496 setenv_link_socket_actual(es, "trusted", &info->lsa->actual, SA_IP_PORT);
1497}
1498
1499static void
1500ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_socket_info *info,
1501 struct gc_arena *gc)
1502{
1503 const char *host = print_sockaddr_ex(&info->lsa->actual.dest.addr.sa, " ", PS_SHOW_PORT, gc);
1504 if (include_cmd)
1505 {
1507 argv_printf_cat(argv, "%s", host);
1508 }
1509 else
1510 {
1511 argv_printf(argv, "%s", host);
1512 }
1513}
1514
1515void
1517 const struct link_socket_actual *act, const char *common_name,
1518 struct env_set *es)
1519{
1520 struct gc_arena gc = gc_new();
1521
1522 info->lsa->actual = *act; /* Note: skip this line for --force-dest */
1523 setenv_trusted(es, info);
1524 info->connection_established = true;
1525
1526 /* Print connection initiated message, with common name if available */
1527 {
1528 struct buffer out = alloc_buf_gc(256, &gc);
1529 if (common_name)
1530 {
1531 buf_printf(&out, "[%s] ", common_name);
1532 }
1533 buf_printf(&out, "Peer Connection Initiated with %s",
1535 msg(M_INFO, "%s", BSTR(&out));
1536 }
1537
1538 /* set environmental vars */
1539 setenv_str(es, "common_name", common_name);
1540
1541 /* Process --ipchange plugin */
1542 if (plugin_defined(info->plugins, OPENVPN_PLUGIN_IPCHANGE))
1543 {
1544 struct argv argv = argv_new();
1545 ipchange_fmt(false, &argv, info, &gc);
1546 if (plugin_call(info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es)
1547 != OPENVPN_PLUGIN_FUNC_SUCCESS)
1548 {
1549 msg(M_WARN, "WARNING: ipchange plugin call failed");
1550 }
1551 argv_free(&argv);
1552 }
1553
1554 /* Process --ipchange option */
1555 if (info->ipchange_command)
1556 {
1557 struct argv argv = argv_new();
1558 setenv_str(es, "script_type", "ipchange");
1559 ipchange_fmt(true, &argv, info, &gc);
1560 openvpn_run_script(&argv, es, 0, "--ipchange");
1561 argv_free(&argv);
1562 }
1563
1564 gc_free(&gc);
1565}
1566
1567void
1569 const struct link_socket_actual *from_addr)
1570{
1571 struct gc_arena gc = gc_new();
1572 const struct addrinfo *ai;
1573
1574 switch (from_addr->dest.addr.sa.sa_family)
1575 {
1576 case AF_INET:
1577 case AF_INET6:
1579 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
1580 print_link_socket_actual(from_addr, &gc), (int)from_addr->dest.addr.sa.sa_family,
1581 print_sockaddr_ex(info->lsa->remote_list->ai_addr, ":", PS_SHOW_PORT, &gc));
1582 /* print additional remote addresses */
1583 for (ai = info->lsa->remote_list->ai_next; ai; ai = ai->ai_next)
1584 {
1585 msg(D_LINK_ERRORS, "or from peer address: %s",
1586 print_sockaddr_ex(ai->ai_addr, ":", PS_SHOW_PORT, &gc));
1587 }
1588 break;
1589 }
1590 buf->len = 0;
1591 gc_free(&gc);
1592}
1593
1594void
1596{
1597 dmsg(D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
1598}
1599
1602{
1603 const struct link_socket_addr *lsa = info->lsa;
1604
1605 /*
1606 * This logic supports "redirect-gateway" semantic, which
1607 * makes sense only for PF_INET routes over PF_INET endpoints
1608 *
1609 * Maybe in the future consider PF_INET6 endpoints also ...
1610 * by now just ignore it
1611 *
1612 * For --remote entries with multiple addresses this
1613 * only return the actual endpoint we have successfully connected to
1614 */
1615 if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
1616 {
1617 return IPV4_INVALID_ADDR;
1618 }
1619
1621 {
1622 return ntohl(lsa->actual.dest.addr.in4.sin_addr.s_addr);
1623 }
1624 else if (lsa->current_remote)
1625 {
1626 return ntohl(((struct sockaddr_in *)lsa->current_remote->ai_addr)->sin_addr.s_addr);
1627 }
1628 else
1629 {
1630 return 0;
1631 }
1632}
1633
1634const struct in6_addr *
1636{
1637 const struct link_socket_addr *lsa = info->lsa;
1638
1639 /* This logic supports "redirect-gateway" semantic,
1640 * for PF_INET6 routes over PF_INET6 endpoints
1641 *
1642 * For --remote entries with multiple addresses this
1643 * only return the actual endpoint we have successfully connected to
1644 */
1645 if (lsa->actual.dest.addr.sa.sa_family != AF_INET6)
1646 {
1647 return NULL;
1648 }
1649
1651 {
1652 return &(lsa->actual.dest.addr.in6.sin6_addr);
1653 }
1654 else if (lsa->current_remote)
1655 {
1656 return &(((struct sockaddr_in6 *)lsa->current_remote->ai_addr)->sin6_addr);
1657 }
1658 else
1659 {
1660 return NULL;
1661 }
1662}
1663
1664/*
1665 * Return a status string describing socket state.
1666 */
1667const char *
1668socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
1669{
1670 struct buffer out = alloc_buf_gc(64, gc);
1671 if (s)
1672 {
1673 if (rwflags & EVENT_READ)
1674 {
1675 buf_printf(&out, "S%s", (s->rwflags_debug & EVENT_READ) ? "R" : "r");
1676#ifdef _WIN32
1677 buf_printf(&out, "%s", overlapped_io_state_ascii(&s->reads));
1678#endif
1679 }
1680 if (rwflags & EVENT_WRITE)
1681 {
1682 buf_printf(&out, "S%s", (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
1683#ifdef _WIN32
1685#endif
1686 }
1687 }
1688 else
1689 {
1690 buf_printf(&out, "S?");
1691 }
1692 return BSTR(&out);
1693}
1694
1695/*
1696 * Stream buffer functions, used to packetize a TCP
1697 * stream connection.
1698 */
1699
1707static inline void
1709{
1710 dmsg(D_STREAM_DEBUG, "STREAM: RESET");
1711 sb->residual_fully_formed = false;
1712 sb->buf = sb->buf_init;
1713 sb->len = -1;
1714}
1715
1716static void
1717stream_buf_init(struct stream_buf *sb, const struct buffer *buf, const unsigned int sockflags,
1718 const int proto)
1719{
1720 sb->buf_init = *buf;
1721 sb->maxlen = sb->buf_init.len;
1722 sb->buf_init.len = 0;
1723 sb->residual = alloc_buf(sb->maxlen);
1724 sb->error = false;
1725#if PORT_SHARE
1726 sb->port_share_state =
1727 ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCP_SERVER)) ? PS_ENABLED : PS_DISABLED;
1728#endif
1729 stream_buf_reset(sb);
1730
1731 dmsg(D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
1732}
1733
1740static inline struct buffer
1742{
1743 /* set up 'next' for next i/o read */
1744 struct buffer next;
1745 next = sb->buf;
1746 next.offset = sb->buf.offset + sb->buf.len;
1747 next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
1748 dmsg(D_STREAM_DEBUG, "STREAM: GET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
1749 sb->buf.offset, sb->buf.len, next.offset, next.len, sb->len, sb->maxlen);
1750 ASSERT(next.len > 0);
1751 ASSERT(buf_safe(&sb->buf, next.len));
1752 return next;
1753}
1754
1763static inline void
1765{
1766 dmsg(D_STREAM_DEBUG, "STREAM: GET FINAL len=%d", buf_defined(&sb->buf) ? sb->buf.len : -1);
1767 ASSERT(buf_defined(&sb->buf));
1768 *buf = sb->buf;
1769}
1770
1771bool
1773{
1774 if (sb->residual.len && !sb->residual_fully_formed)
1775 {
1776 ASSERT(buf_copy(&sb->buf, &sb->residual));
1777 ASSERT(buf_init(&sb->residual, 0));
1779 dmsg(D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
1780 sb->residual_fully_formed ? "YES" : "NO", sb->residual.len);
1781 }
1782
1783 return !sb->residual_fully_formed;
1784}
1785
1807static bool
1808stream_buf_added(struct stream_buf *sb, ssize_t length_added)
1809{
1810 dmsg(D_STREAM_DEBUG, "STREAM: ADD length_added=%zd", length_added);
1811 if (length_added > 0)
1812 {
1813 ASSERT(sb->buf.len + length_added <= INT_MAX);
1814 sb->buf.len += (int)length_added;
1815 }
1816
1817 /* if length unknown, see if we can get the length prefix from
1818 * the head of the buffer */
1819 if (sb->len < 0 && sb->buf.len >= (int)sizeof(packet_size_type))
1820 {
1821 packet_size_type net_size;
1822
1823#if PORT_SHARE
1824 if (sb->port_share_state == PS_ENABLED)
1825 {
1826 if (!is_openvpn_protocol(&sb->buf))
1827 {
1828 msg(D_PS_PROXY, "Non-OpenVPN client protocol detected");
1829 sb->port_share_state = PS_FOREIGN;
1830 sb->error = true;
1831 return false;
1832 }
1833 else
1834 {
1835 sb->port_share_state = PS_DISABLED;
1836 }
1837 }
1838#endif
1839
1840 ASSERT(buf_read(&sb->buf, &net_size, sizeof(net_size)));
1841 sb->len = ntohps(net_size);
1842
1843 if (sb->len < 1 || sb->len > sb->maxlen)
1844 {
1845 msg(M_WARN,
1846 "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...]",
1847 sb->len, sb->maxlen);
1848 stream_buf_reset(sb);
1849 sb->error = true;
1850 return false;
1851 }
1852 }
1853
1854 /* is our incoming packet fully read? */
1855 if (sb->len > 0 && sb->buf.len >= sb->len)
1856 {
1857 /* save any residual data that's part of the next packet */
1858 ASSERT(buf_init(&sb->residual, 0));
1859 if (sb->buf.len > sb->len)
1860 {
1861 ASSERT(buf_copy_excess(&sb->residual, &sb->buf, sb->len));
1862 }
1863 dmsg(D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
1864 BLEN(&sb->buf), BLEN(&sb->residual));
1865 return true;
1866 }
1867 else
1868 {
1869 dmsg(D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
1870 return false;
1871 }
1872}
1873
1874static void
1876{
1877 free_buf(&sb->residual);
1878}
1879
1880/*
1881 * The listen event is a special event whose sole purpose is
1882 * to tell us that there's a new incoming connection on a
1883 * TCP socket, for use in server mode.
1884 */
1885event_t
1887{
1888#ifdef _WIN32
1890 {
1891 init_net_event_win32(&s->listen_handle, FD_ACCEPT, s->sd, 0);
1892 }
1893 return &s->listen_handle;
1894#else /* ifdef _WIN32 */
1895 return s->sd;
1896#endif
1897}
1898
1899
1900/*
1901 * Bad incoming address lengths that differ from what
1902 * we expect are considered to be fatal errors.
1903 */
1904void
1905bad_address_length(int actual, int expected)
1906{
1907 msg(M_FATAL,
1908 "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
1909 actual, expected);
1910}
1911
1912/*
1913 * Socket Read Routines
1914 */
1915
1916ssize_t
1917link_socket_read_tcp(struct link_socket *sock, struct buffer *buf)
1918{
1919 ssize_t len = 0;
1920
1922 {
1923 /* with Linux-DCO, we sometimes try to access a socket that is
1924 * already installed in the kernel and has no valid file descriptor
1925 * anymore. This is a bug.
1926 * Handle by resetting client instance instead of crashing.
1927 */
1928 if (sock->sd == SOCKET_UNDEFINED)
1929 {
1930 msg(M_INFO, "BUG: link_socket_read_tcp(): sock->sd==-1, reset client instance");
1931 sock->stream_reset = true; /* reset client instance */
1932 return buf->len = 0; /* nothing to read */
1933 }
1934
1935#ifdef _WIN32
1936 sockethandle_t sh = { .s = sock->sd };
1937 len = sockethandle_finalize(sh, &sock->reads, buf, NULL);
1938#else
1939 struct buffer frag = stream_buf_get_next(&sock->stream_buf);
1940 len = recv(sock->sd, BPTR(&frag), BLENZ(&frag), MSG_NOSIGNAL);
1941#endif
1942
1943 if (!len)
1944 {
1945 sock->stream_reset = true;
1946 }
1947 if (len <= 0)
1948 {
1949 buf->len = 0;
1950 return len;
1951 }
1952 }
1953
1955 || stream_buf_added(&sock->stream_buf, len)) /* packet complete? */
1956 {
1957 stream_buf_get_final(&sock->stream_buf, buf);
1959 return buf->len;
1960 }
1961 else
1962 {
1963 return buf->len = 0; /* no error, but packet is still incomplete */
1964 }
1965}
1966
1967#ifndef _WIN32
1968
1969#if ENABLE_IP_PKTINFO
1970
1971/* make the buffer large enough to handle ancillary socket data for
1972 * both IPv4 and IPv6 destination addresses, plus padding (see RFC 2292)
1973 */
1974#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
1975#define PKTINFO_BUF_SIZE \
1976 max_int(CMSG_SPACE(sizeof(struct in6_pktinfo)), CMSG_SPACE(sizeof(struct in_pktinfo)))
1977#else
1978#define PKTINFO_BUF_SIZE \
1979 max_int(CMSG_SPACE(sizeof(struct in6_pktinfo)), CMSG_SPACE(sizeof(struct in_addr)))
1980#endif
1981
1982static ssize_t
1983link_socket_read_udp_posix_recvmsg(const struct link_socket *sock, struct buffer *buf,
1984 struct link_socket_actual *from, socklen_t *fromlen)
1985{
1986 struct iovec iov;
1987 uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];
1988 struct msghdr mesg = { 0 };
1989 *fromlen = sizeof(from->dest.addr);
1990
1991 ASSERT(sock->sd >= 0); /* can't happen */
1992
1993 iov.iov_base = BPTR(buf);
1994 iov.iov_len = buf_forward_capacity_total(buf);
1995 mesg.msg_iov = &iov;
1996 mesg.msg_iovlen = 1;
1997 mesg.msg_name = &from->dest.addr;
1998 mesg.msg_namelen = *fromlen;
1999 mesg.msg_control = pktinfo_buf;
2000 mesg.msg_controllen = (socklen_t)sizeof(pktinfo_buf);
2001 ssize_t len = recvmsg(sock->sd, &mesg, 0);
2002 if (len < 0)
2003 {
2004 buf->len = 0;
2005 return len;
2006 }
2007 ASSERT(len <= INT_MAX);
2008 buf->len = (int)len;
2009 struct cmsghdr *cmsg;
2010 *fromlen = mesg.msg_namelen;
2011 cmsg = CMSG_FIRSTHDR(&mesg);
2012 if (cmsg != NULL && CMSG_NXTHDR(&mesg, cmsg) == NULL
2013#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2014 && cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_PKTINFO
2015 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_pktinfo)))
2016#elif defined(IP_RECVDSTADDR)
2017 && cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_RECVDSTADDR
2018 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in_addr)))
2019#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2020#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2021#endif
2022 {
2023#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2024 struct in_pktinfo *pkti = (struct in_pktinfo *)CMSG_DATA(cmsg);
2025 from->pi.in4.ipi_ifindex =
2026 (sock->sockflags & SF_PKTINFO_COPY_IIF) ? pkti->ipi_ifindex : 0;
2027 from->pi.in4.ipi_spec_dst = pkti->ipi_spec_dst;
2028#elif defined(IP_RECVDSTADDR)
2029 from->pi.in4 = *(struct in_addr *)CMSG_DATA(cmsg);
2030#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2031#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2032#endif
2033 }
2034 else if (cmsg != NULL && CMSG_NXTHDR(&mesg, cmsg) == NULL
2035 && cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO
2036 && cmsg->cmsg_len >= CMSG_LEN(sizeof(struct in6_pktinfo)))
2037 {
2038 struct in6_pktinfo *pkti6 = (struct in6_pktinfo *)CMSG_DATA(cmsg);
2039 from->pi.in6.ipi6_ifindex =
2040 (sock->sockflags & SF_PKTINFO_COPY_IIF) ? pkti6->ipi6_ifindex : 0;
2041 from->pi.in6.ipi6_addr = pkti6->ipi6_addr;
2042 }
2043 else if (cmsg != NULL)
2044 {
2045 msg(M_WARN,
2046 "CMSG received that cannot be parsed (cmsg_level=%d, cmsg_type=%d, cmsg=len=%zu)",
2047 cmsg->cmsg_level, cmsg->cmsg_type, (size_t)cmsg->cmsg_len);
2048 }
2049
2050 return buf->len;
2051}
2052#endif /* if ENABLE_IP_PKTINFO */
2053
2054ssize_t
2055link_socket_read_udp_posix(const struct link_socket *sock, struct buffer *buf,
2056 struct link_socket_actual *from)
2057{
2058 ssize_t recvlen;
2059 socklen_t fromlen = sizeof(from->dest.addr);
2060 socklen_t expectedlen = af_addr_size(sock->info.af);
2061 addr_zero_host(&from->dest);
2062
2063 ASSERT(sock->sd >= 0); /* can't happen */
2064
2065#if ENABLE_IP_PKTINFO
2066 /* Both PROTO_UDPv4 and PROTO_UDPv6 */
2067 if (sock->info.proto == PROTO_UDP && sock->sockflags & SF_USE_IP_PKTINFO)
2068 {
2069 recvlen = link_socket_read_udp_posix_recvmsg(sock, buf, from, &fromlen);
2070 }
2071 else
2072#endif
2073 {
2074 recvlen = recvfrom(sock->sd, BPTR(buf), buf_forward_capacity(buf), 0,
2075 &from->dest.addr.sa, &fromlen);
2076 }
2077 if (recvlen < 0)
2078 {
2079 buf->len = 0;
2080 return recvlen;
2081 }
2082 ASSERT(recvlen <= INT_MAX);
2083 buf->len = (int)recvlen;
2084 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
2085 if (expectedlen && fromlen != expectedlen)
2086 {
2087 bad_address_length(fromlen, expectedlen);
2088 }
2089 return buf->len;
2090}
2091
2092#if defined(__GNUC__) || defined(__clang__)
2093#pragma GCC diagnostic pop
2094#endif
2095
2096#endif /* ifndef _WIN32 */
2097
2098/*
2099 * Socket Write Routines
2100 */
2101
2102ssize_t
2103link_socket_write_tcp(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *to)
2104{
2105 const int blen = BLEN(buf);
2106 ASSERT(blen >= 0 && blen <= PACKET_SIZE_MAX);
2108 dmsg(D_STREAM_DEBUG, "STREAM: WRITE %u offset=%d", len, buf->offset);
2109 ASSERT(len <= sock->stream_buf.maxlen);
2110 len = htonps(len);
2111 ASSERT(buf_write_prepend(buf, &len, sizeof(len)));
2112#ifdef _WIN32
2113 return link_socket_write_win32(sock, buf, to);
2114#else
2115 return link_socket_write_tcp_posix(sock, buf);
2116#endif
2117}
2118
2119#if ENABLE_IP_PKTINFO
2120
2121ssize_t
2122link_socket_write_udp_posix_sendmsg(const struct link_socket *sock, const struct buffer *buf,
2123 struct link_socket_actual *to)
2124{
2125 struct iovec iov;
2126 struct msghdr mesg;
2127 struct cmsghdr *cmsg;
2128 uint8_t pktinfo_buf[PKTINFO_BUF_SIZE];
2129
2130 /* sendmsg takes a const msghdr, but we can't construct that here
2131 directly, so cast */
2132 iov.iov_base = (char *)CBPTR(buf);
2133 iov.iov_len = BLENZ(buf);
2134 mesg.msg_iov = &iov;
2135 mesg.msg_iovlen = 1;
2136 switch (to->dest.addr.sa.sa_family)
2137 {
2138 case AF_INET:
2139 {
2140 mesg.msg_name = &to->dest.addr.sa;
2141 mesg.msg_namelen = sizeof(struct sockaddr_in);
2142 mesg.msg_control = pktinfo_buf;
2143 mesg.msg_flags = 0;
2144#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
2145 mesg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
2146 cmsg = CMSG_FIRSTHDR(&mesg);
2147 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
2148 cmsg->cmsg_level = SOL_IP;
2149 cmsg->cmsg_type = IP_PKTINFO;
2150 {
2151 struct in_pktinfo *pkti;
2152 pkti = (struct in_pktinfo *)CMSG_DATA(cmsg);
2153 pkti->ipi_ifindex = to->pi.in4.ipi_ifindex;
2154 pkti->ipi_spec_dst = to->pi.in4.ipi_spec_dst;
2155 pkti->ipi_addr.s_addr = 0;
2156 }
2157#elif defined(IP_RECVDSTADDR)
2158 ASSERT(CMSG_SPACE(sizeof(struct in_addr)) <= sizeof(pktinfo_buf));
2159 mesg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
2160 cmsg = CMSG_FIRSTHDR(&mesg);
2161 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
2162 cmsg->cmsg_level = IPPROTO_IP;
2163 cmsg->cmsg_type = IP_RECVDSTADDR;
2164 *(struct in_addr *)CMSG_DATA(cmsg) = to->pi.in4;
2165#else /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2166#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2167#endif /* if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST) */
2168 break;
2169 }
2170
2171 case AF_INET6:
2172 {
2173 struct in6_pktinfo *pkti6;
2174 mesg.msg_name = &to->dest.addr.sa;
2175 mesg.msg_namelen = sizeof(struct sockaddr_in6);
2176
2177 ASSERT(CMSG_SPACE(sizeof(struct in6_pktinfo)) <= sizeof(pktinfo_buf));
2178 mesg.msg_control = pktinfo_buf;
2179 mesg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
2180 mesg.msg_flags = 0;
2181 cmsg = CMSG_FIRSTHDR(&mesg);
2182 cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
2183 cmsg->cmsg_level = IPPROTO_IPV6;
2184 cmsg->cmsg_type = IPV6_PKTINFO;
2185
2186 pkti6 = (struct in6_pktinfo *)CMSG_DATA(cmsg);
2187 pkti6->ipi6_ifindex = to->pi.in6.ipi6_ifindex;
2188 pkti6->ipi6_addr = to->pi.in6.ipi6_addr;
2189 break;
2190 }
2191
2192 default:
2193 ASSERT(0);
2194 }
2195 return sendmsg(sock->sd, &mesg, 0);
2196}
2197
2198#endif /* if ENABLE_IP_PKTINFO */
2199
2200/*
2201 * Win32 overlapped socket I/O functions.
2202 */
2203
2204#ifdef _WIN32
2205
2206static int
2208{
2209 if (socket_is_dco_win(sock))
2210 {
2211 return GetLastError();
2212 }
2213
2214 return WSAGetLastError();
2215}
2216
2217int
2218socket_recv_queue(struct link_socket *sock, int maxsize)
2219{
2220 if (sock->reads.iostate == IOSTATE_INITIAL)
2221 {
2222 WSABUF wsabuf[1];
2223 int status;
2224
2225 /* reset buf to its initial state */
2226 if (proto_is_udp(sock->info.proto))
2227 {
2228 sock->reads.buf = sock->reads.buf_init;
2229 }
2230 else if (proto_is_tcp(sock->info.proto))
2231 {
2232 sock->reads.buf = stream_buf_get_next(&sock->stream_buf);
2233 }
2234 else
2235 {
2236 ASSERT(0);
2237 }
2238
2239 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
2240 wsabuf[0].buf = BSTR(&sock->reads.buf);
2241 /* make sure maxsize is sane */
2242 ASSERT(maxsize <= BLEN(&sock->reads.buf));
2243 wsabuf[0].len = maxsize ? maxsize : BLEN(&sock->reads.buf);
2244
2245 /* the overlapped read will signal this event on I/O completion */
2246 ASSERT(ResetEvent(sock->reads.overlapped.hEvent));
2247 sock->reads.flags = 0;
2248
2249 if (socket_is_dco_win(sock))
2250 {
2251 status = ReadFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0].len, &sock->reads.size,
2252 &sock->reads.overlapped);
2253 /* Readfile status is inverted from WSARecv */
2254 status = !status;
2255 }
2256 else if (proto_is_udp(sock->info.proto))
2257 {
2258 sock->reads.addr_defined = true;
2259 sock->reads.addrlen = sizeof(sock->reads.addr6);
2260 status = WSARecvFrom(sock->sd, wsabuf, 1, &sock->reads.size, &sock->reads.flags,
2261 (struct sockaddr *)&sock->reads.addr, &sock->reads.addrlen,
2262 &sock->reads.overlapped, NULL);
2263 }
2264 else if (proto_is_tcp(sock->info.proto))
2265 {
2266 sock->reads.addr_defined = false;
2267 status = WSARecv(sock->sd, wsabuf, 1, &sock->reads.size, &sock->reads.flags,
2268 &sock->reads.overlapped, NULL);
2269 }
2270 else
2271 {
2272 status = 0;
2273 ASSERT(0);
2274 }
2275
2276 if (!status) /* operation completed immediately? */
2277 {
2278 /* FIXME: won't do anything when sock->info.af == AF_UNSPEC */
2279 int af_len = af_addr_size(sock->info.af);
2280 if (sock->reads.addr_defined && af_len && sock->reads.addrlen != af_len)
2281 {
2282 bad_address_length(sock->reads.addrlen, af_len);
2283 }
2285
2286 /* since we got an immediate return, we must signal the event object ourselves */
2287 ASSERT(SetEvent(sock->reads.overlapped.hEvent));
2288 sock->reads.status = 0;
2289
2290 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
2291 (int)wsabuf[0].len, (int)sock->reads.size);
2292 }
2293 else
2294 {
2296 if (status == WSA_IO_PENDING) /* operation queued? */
2297 {
2299 sock->reads.status = status;
2300 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]", (int)wsabuf[0].len);
2301 }
2302 else /* error occurred */
2303 {
2304 struct gc_arena gc = gc_new();
2305 ASSERT(SetEvent(sock->reads.overlapped.hEvent));
2307 sock->reads.status = status;
2308 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s", (int)wsabuf[0].len,
2310 gc_free(&gc);
2311 }
2312 }
2313 }
2314 return sock->reads.iostate;
2315}
2316
2317int
2318socket_send_queue(struct link_socket *sock, const struct buffer *buf, const struct link_socket_actual *to)
2319{
2320 if (sock->writes.iostate == IOSTATE_INITIAL)
2321 {
2322 WSABUF wsabuf[1];
2323 int status;
2324
2325 /* make a private copy of buf */
2326 sock->writes.buf = sock->writes.buf_init;
2327 sock->writes.buf.len = 0;
2328 ASSERT(buf_copy(&sock->writes.buf, buf));
2329
2330 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
2331 wsabuf[0].buf = BSTR(&sock->writes.buf);
2332 wsabuf[0].len = BLEN(&sock->writes.buf);
2333
2334 /* the overlapped write will signal this event on I/O completion */
2335 ASSERT(ResetEvent(sock->writes.overlapped.hEvent));
2336 sock->writes.flags = 0;
2337
2338 if (socket_is_dco_win(sock))
2339 {
2340 status = WriteFile((HANDLE)sock->sd, wsabuf[0].buf, wsabuf[0].len, &sock->writes.size,
2341 &sock->writes.overlapped);
2342
2343 /* WriteFile status is inverted from WSASendTo */
2344 status = !status;
2345 }
2346 else if (proto_is_udp(sock->info.proto))
2347 {
2348 /* set destination address for UDP writes */
2349 sock->writes.addr_defined = true;
2350 if (to->dest.addr.sa.sa_family == AF_INET6)
2351 {
2352 sock->writes.addr6 = to->dest.addr.in6;
2353 sock->writes.addrlen = sizeof(sock->writes.addr6);
2354 }
2355 else
2356 {
2357 sock->writes.addr = to->dest.addr.in4;
2358 sock->writes.addrlen = sizeof(sock->writes.addr);
2359 }
2360
2361 status = WSASendTo(sock->sd, wsabuf, 1, &sock->writes.size, sock->writes.flags,
2362 (struct sockaddr *)&sock->writes.addr, sock->writes.addrlen,
2363 &sock->writes.overlapped, NULL);
2364 }
2365 else if (proto_is_tcp(sock->info.proto))
2366 {
2367 /* destination address for TCP writes was established on connection initiation */
2368 sock->writes.addr_defined = false;
2369
2370 status = WSASend(sock->sd, wsabuf, 1, &sock->writes.size, sock->writes.flags,
2371 &sock->writes.overlapped, NULL);
2372 }
2373 else
2374 {
2375 status = 0;
2376 ASSERT(0);
2377 }
2378
2379 if (!status) /* operation completed immediately? */
2380 {
2382
2383 /* since we got an immediate return, we must signal the event object ourselves */
2384 ASSERT(SetEvent(sock->writes.overlapped.hEvent));
2385
2386 sock->writes.status = 0;
2387
2388 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]", (int)wsabuf[0].len,
2389 (int)sock->writes.size);
2390 }
2391 else
2392 {
2394 /* both status code have the identical value */
2395 if (status == WSA_IO_PENDING || status == ERROR_IO_PENDING) /* operation queued? */
2396 {
2398 sock->writes.status = status;
2399 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]", (int)wsabuf[0].len);
2400 }
2401 else /* error occurred */
2402 {
2403 struct gc_arena gc = gc_new();
2404 ASSERT(SetEvent(sock->writes.overlapped.hEvent));
2406 sock->writes.status = status;
2407
2408 dmsg(D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s", (int)wsabuf[0].len,
2410
2411 gc_free(&gc);
2412 }
2413 }
2414 }
2415 return sock->writes.iostate;
2416}
2417
2418static void
2419read_sockaddr_from_overlapped(const struct overlapped_io *io, struct sockaddr *dst, int overlapped_ret)
2420{
2421 if (overlapped_ret >= 0 && io->addr_defined)
2422 {
2423 /* TODO(jjo): streamline this mess */
2424 /* in this func we don't have relevant info about the PF_ of this
2425 * endpoint, as link_socket_actual will be zero for the 1st received packet
2426 *
2427 * Test for inets PF_ possible sizes
2428 */
2429 switch (io->addrlen)
2430 {
2431 case sizeof(struct sockaddr_in):
2432 case sizeof(struct sockaddr_in6):
2433 /* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
2434 * under _WIN32*/
2435 case sizeof(struct sockaddr_in6) - 4:
2436 break;
2437
2438 default:
2439 bad_address_length(io->addrlen, af_addr_size(io->addr.sin_family));
2440 }
2441
2442 switch (io->addr.sin_family)
2443 {
2444 case AF_INET:
2445 memcpy(dst, &io->addr, sizeof(struct sockaddr_in));
2446 break;
2447
2448 case AF_INET6:
2449 memcpy(dst, &io->addr6, sizeof(struct sockaddr_in6));
2450 break;
2451 }
2452 }
2453 else
2454 {
2455 CLEAR(*dst);
2456 }
2457}
2458
2468static int
2469read_sockaddr_from_packet(struct buffer *buf, struct sockaddr *dst)
2470{
2471 int sa_len = 0;
2472
2473 /* In dco-win multipeer mode the kernel driver always prepends a full
2474 * sockaddr_in or sockaddr_in6 in front of the control-packet payload,
2475 * so the buffer must hold at least sizeof(struct sockaddr_in) bytes
2476 * before we may inspect sa_family. */
2477 ASSERT(buf_len(buf) >= (int)sizeof(struct sockaddr_in));
2478
2479 const struct sockaddr *sa = (const struct sockaddr *)BPTR(buf);
2480 switch (sa->sa_family)
2481 {
2482 case AF_INET:
2483 sa_len = sizeof(struct sockaddr_in);
2484 break;
2485
2486 case AF_INET6:
2487 sa_len = sizeof(struct sockaddr_in6);
2488 ASSERT(buf_len(buf) >= sa_len);
2489 break;
2490
2491 default:
2492 ASSERT(0); /* driver validates the family before writing */
2493 }
2494
2495 memcpy(dst, sa, sa_len);
2496 buf_advance(buf, sa_len);
2497
2498 return sa_len;
2499}
2500
2501/* Returns the number of bytes successfully read */
2502int
2504 struct link_socket_actual *from)
2505{
2506 int ret = -1;
2507 BOOL status;
2508
2509 switch (io->iostate)
2510 {
2511 case IOSTATE_QUEUED:
2513 if (status)
2514 {
2515 /* successful return for a queued operation */
2516 if (buf)
2517 {
2518 *buf = io->buf;
2519 }
2520 ret = io->size;
2522 ASSERT(ResetEvent(io->overlapped.hEvent));
2523
2524 dmsg(D_WIN32_IO, "WIN32 I/O: Completion success [%d]", ret);
2525 }
2526 else
2527 {
2528 /* error during a queued operation */
2529 ret = -1;
2530 if (SocketHandleGetLastError(sh) != ERROR_IO_INCOMPLETE)
2531 {
2532 /* if no error (i.e. just not finished yet), then DON'T execute this code */
2534 ASSERT(ResetEvent(io->overlapped.hEvent));
2535 msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion error");
2536 }
2537 }
2538 break;
2539
2542 ASSERT(ResetEvent(io->overlapped.hEvent));
2543 if (io->status)
2544 {
2545 /* error return for a non-queued operation */
2547 ret = -1;
2548 msg(D_WIN32_IO | M_ERRNO, "WIN32 I/O: Completion non-queued error");
2549 }
2550 else
2551 {
2552 /* successful return for a non-queued operation */
2553 if (buf)
2554 {
2555 *buf = io->buf;
2556 }
2557 ret = io->size;
2558 dmsg(D_WIN32_IO, "WIN32 I/O: Completion non-queued success [%d]", ret);
2559 }
2560 break;
2561
2562 case IOSTATE_INITIAL: /* were we called without proper queueing? */
2564 ret = -1;
2565 dmsg(D_WIN32_IO, "WIN32 I/O: Completion BAD STATE");
2566 break;
2567
2568 default:
2569 ASSERT(0);
2570 }
2571
2572 if (from && ret > 0 && sh.is_handle && sh.prepend_sa)
2573 {
2574 ret -= read_sockaddr_from_packet(buf, &from->dest.addr.sa);
2575 }
2576
2577 if (!sh.is_handle && from)
2578 {
2579 read_sockaddr_from_overlapped(io, &from->dest.addr.sa, ret);
2580 }
2581
2582 if (buf)
2583 {
2584 buf->len = ret;
2585 }
2586 return ret;
2587}
2588
2589#endif /* _WIN32 */
2590
2591/*
2592 * Socket event notification
2593 */
2594
2595unsigned int
2596socket_set(struct link_socket *s, struct event_set *es, unsigned int rwflags, void *arg,
2597 unsigned int *persistent)
2598{
2599 if (s)
2600 {
2601 if ((rwflags & EVENT_READ) && !stream_buf_read_setup(s))
2602 {
2603 ASSERT(!persistent);
2604 rwflags &= ~EVENT_READ;
2605 }
2606
2607#ifdef _WIN32
2608 if (rwflags & EVENT_READ)
2609 {
2610 socket_recv_queue(s, 0);
2611 }
2612#endif
2613
2614 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
2615 if (!persistent || *persistent != rwflags)
2616 {
2617 event_ctl(es, socket_event_handle(s), rwflags, arg);
2618 if (persistent)
2619 {
2620 *persistent = rwflags;
2621 }
2622 }
2623
2624 s->rwflags_debug = rwflags;
2625 }
2626 return rwflags;
2627}
2628
2629#if UNIX_SOCK_SUPPORT
2630
2631void
2633{
2634 if (sd && socket_defined(*sd))
2635 {
2637 *sd = SOCKET_UNDEFINED;
2638 }
2639}
2640
2641/*
2642 * code for unix domain sockets
2643 */
2644
2645const char *
2646sockaddr_unix_name(const struct sockaddr_un *local, const char *null)
2647{
2648 if (local && local->sun_family == PF_UNIX)
2649 {
2650 return local->sun_path;
2651 }
2652 else
2653 {
2654 return null;
2655 }
2656}
2657
2659create_socket_unix(void)
2660{
2662
2663 if ((sd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
2664 {
2665 msg(M_ERR, "Cannot create unix domain socket");
2666 }
2667
2668 /* set socket file descriptor to not pass across execs, so that
2669 * scripts don't have access to it */
2670 set_cloexec(sd);
2671
2672 return sd;
2673}
2674
2675void
2676socket_bind_unix(socket_descriptor_t sd, struct sockaddr_un *local, const char *prefix)
2677{
2678 const mode_t orig_umask = umask(0);
2679
2680 if (bind(sd, (struct sockaddr *)local, sizeof(struct sockaddr_un)))
2681 {
2682 msg(M_FATAL | M_ERRNO, "%s: Socket bind[%d] failed on unix domain socket %s", prefix,
2683 (int)sd, sockaddr_unix_name(local, "NULL"));
2684 }
2685
2686 umask(orig_umask);
2687}
2688
2690socket_accept_unix(socket_descriptor_t sd, struct sockaddr_un *remote)
2691{
2692 socklen_t remote_len = sizeof(struct sockaddr_un);
2694
2695 CLEAR(*remote);
2696 ret = accept(sd, (struct sockaddr *)remote, &remote_len);
2697 if (ret >= 0)
2698 {
2699 /* set socket file descriptor to not pass across execs, so that
2700 * scripts don't have access to it */
2701 set_cloexec(ret);
2702 }
2703 return ret;
2704}
2705
2706int
2707socket_connect_unix(socket_descriptor_t sd, struct sockaddr_un *remote)
2708{
2709 int status = connect(sd, (struct sockaddr *)remote, sizeof(struct sockaddr_un));
2710 if (status)
2711 {
2713 }
2714 return status;
2715}
2716
2717void
2718sockaddr_unix_init(struct sockaddr_un *local, const char *path)
2719{
2720 local->sun_family = PF_UNIX;
2721 strlcpy(local->sun_path, path, sizeof(local->sun_path));
2722}
2723
2724void
2725socket_delete_unix(const struct sockaddr_un *local)
2726{
2727 const char *name = sockaddr_unix_name(local, NULL);
2728 if (name && strlen(name))
2729 {
2730 unlink(name);
2731 }
2732}
2733
2734bool
2735unix_socket_get_peer_uid_gid(const socket_descriptor_t sd, uid_t *uid, gid_t *gid)
2736{
2737#ifdef HAVE_GETPEEREID
2738 uid_t u;
2739 gid_t g;
2740 if (getpeereid(sd, &u, &g) == -1)
2741 {
2742 return false;
2743 }
2744 if (uid)
2745 {
2746 *uid = u;
2747 }
2748 if (gid)
2749 {
2750 *gid = g;
2751 }
2752 return true;
2753#elif defined(SO_PEERCRED)
2754 struct ucred peercred;
2755 socklen_t so_len = sizeof(peercred);
2756 if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
2757 {
2758 return false;
2759 }
2760 if (uid)
2761 {
2762 *uid = peercred.uid;
2763 }
2764 if (gid)
2765 {
2766 *gid = peercred.gid;
2767 }
2768 return true;
2769#else /* ifdef HAVE_GETPEEREID */
2770 return false;
2771#endif /* ifdef HAVE_GETPEEREID */
2772}
2773
2774#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:490
void argv_free(struct argv *a)
Frees all memory allocations allocated by the struct argv related functions.
Definition argv.c:101
bool argv_printf(struct argv *argres, const char *format,...)
printf() variant which populates a struct argv.
Definition argv.c:447
bool argv_printf_cat(struct argv *argres, const char *format,...)
printf() inspired argv concatenation.
Definition argv.c:471
struct argv argv_new(void)
Allocates a new struct argv and ensures it is initialised.
Definition argv.c:87
void free_buf(struct buffer *buf)
Free the memory allocated for a buffer.
Definition buffer.c:174
bool buf_printf(struct buffer *buf, const char *format,...)
printf-style append to a buffer with overflow check.
Definition buffer.c:231
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Allocate a buffer of the given size under garbage collection.
Definition buffer.c:77
struct buffer alloc_buf(size_t size)
Allocate a buffer of the given size.
Definition buffer.c:60
#define BSTR(buf)
Return the buffer content pointer cast to char *.
Definition buffer.h:157
static bool buf_copy(struct buffer *dest, const struct buffer *src)
Copy the content of one buffer to the end of another.
Definition buffer.h:1347
#define BPTR(buf)
Return a pointer to the start of the buffer content.
Definition buffer.h:139
static bool buf_copy_excess(struct buffer *dest, struct buffer *src, int len)
Truncate src to len bytes and copy any excess to dest.
Definition buffer.h:1422
static bool buf_write_prepend(struct buffer *dest, const void *src, int size)
Prepend data to a buffer.
Definition buffer.h:1268
static size_t buf_forward_capacity_total(const struct buffer *buf)
Return the total number of bytes available from the current offset to the end of the allocated memory...
Definition buffer.h:1072
static bool buf_safe(const struct buffer *buf, size_t len)
Check whether len bytes can be appended to a buffer.
Definition buffer.h:999
static bool buf_read(struct buffer *src, void *dest, int size)
Read bytes from the front of a buffer into a caller-supplied destination.
Definition buffer.h:1456
static int buf_len(const struct buffer *buf)
Return the length of the buffer content.
Definition buffer.h:462
static int buf_forward_capacity(const struct buffer *buf)
Return the number of bytes that can still be appended to the buffer.
Definition buffer.h:1043
#define CBPTR(buf)
Return a const pointer to the start of the buffer content.
Definition buffer.h:141
static bool buf_advance(struct buffer *buf, ssize_t size)
Advance the content start of a buffer, consuming bytes from the front.
Definition buffer.h:1170
#define BLEN(buf)
Return the length of the buffer content in bytes.
Definition buffer.h:151
#define BLENZ(buf)
Return the length of the buffer content as a size_t.
Definition buffer.h:153
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1974
#define ALLOC_OBJ_CLEAR(dptr, type)
Allocate and zero-initialise memory for a single object of the given type.
Definition buffer.h:2036
static bool buf_defined(const struct buffer *buf)
Return true iff buf has a non-NULL data pointer.
Definition buffer.h:399
#define buf_init(buf, offset)
Definition buffer.h:364
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1958
size_t strlcpy(char *dest, const char *src, size_t maxlen)
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:279
void dco_p2p_new_peer(HANDLE handle, OVERLAPPED *ov, struct link_socket *sock, struct signal_info *sig_info)
Definition dco_win.c:323
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition env_set.c:305
#define D_PS_PROXY
Definition errlevel.h:90
#define D_WIN32_IO
Definition errlevel.h:168
#define D_SOCKET_DEBUG
Definition errlevel.h:137
#define D_STREAM_DEBUG
Definition errlevel.h:167
#define D_INIT_MEDIUM
Definition errlevel.h:101
#define D_READ_WRITE
Definition errlevel.h:163
#define D_OSBUF
Definition errlevel.h:89
#define D_LOW
Definition errlevel.h:95
#define M_INFO
Definition errlevel.h:54
#define D_LINK_ERRORS
Definition errlevel.h:56
const struct rw_handle * event_t
Definition event.h:89
#define EVENT_WRITE
Definition event.h:38
#define EVENT_READ
Definition event.h:37
@ EVENT_ARG_LINK_SOCKET
Definition event.h:135
static void event_ctl(struct event_set *es, event_t event, unsigned int rwflags, void *arg)
Definition event.h:180
void set_nonblock(socket_descriptor_t fd)
Definition fdmisc.c:77
void set_cloexec(socket_descriptor_t fd)
Definition fdmisc.c:87
static void openvpn_fd_set(socket_descriptor_t fd, fd_set *setp)
Definition fdmisc.h:44
int get_server_poll_remaining_time(const struct event_timeout *server_poll_timeout)
Definition forward.c:520
Interface functions to the internal and external multiplexers.
static SERVICE_STATUS status
Definition interactive.c:52
void management_set_state(struct management *man, const int state, const char *detail, const in_addr_t *tun_local_ip, const struct in6_addr *tun_local_ip6, const struct openvpn_sockaddr *local, const struct openvpn_sockaddr *remote)
Definition manage.c:2962
void management_sleep(const int n)
A sleep function that services the management layer for n seconds rather than doing nothing.
Definition manage.c:4353
#define OPENVPN_STATE_TCP_CONNECT
Definition manage.h:472
void alloc_buf_sock_tun(struct buffer *buf, const struct frame *frame)
Definition mtu.c:47
void set_mtu_discover_type(socket_descriptor_t sd, int mtu_type, sa_family_t proto_af)
Definition mtu.c:216
#define CLEAR(x)
Definition basic.h:32
const char * strerror_win32(DWORD errnum, struct gc_arena *gc)
Definition error.c:786
#define M_FATAL
Definition error.h:90
#define M_NONFATAL
Definition error.h:91
#define dmsg(flags,...)
Definition error.h:164
#define M_ERR
Definition error.h:106
#define openvpn_errno()
Definition error.h:71
#define msg(flags,...)
Definition error.h:152
unsigned int msglvl_t
Definition error.h:77
#define ASSERT(x)
Definition error.h:221
#define M_WARN
Definition error.h:92
#define M_ERRNO
Definition error.h:95
#define CM_CHILD_TCP
Definition openvpn.h:457
#define CM_CHILD_UDP
Definition openvpn.h:456
#define MODE_POINT_TO_POINT
Definition options.h:264
#define MODE_SERVER
Definition options.h:265
static bool dco_enabled(const struct options *o)
Returns whether the current configuration has dco enabled.
Definition options.h:981
bool plugin_defined(const struct plugin_list *pl, const int type)
Definition plugin.c:919
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:195
bool establish_http_proxy_passthru(struct http_proxy_info *p, socket_descriptor_t sd, const char *host, const char *port, const struct event_timeout *server_poll_timeout, struct buffer *lookahead, struct signal_info *sig_info)
Definition proxy.c:610
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 resolve.c:102
int get_cached_dns_entry(struct cached_dns_entry *dns_cache, const char *hostname, const char *servname, int ai_family, unsigned int resolve_flags, struct addrinfo **ai)
get_cached_dns_entry return 0 on success and -1 otherwise.
Definition resolve.c:506
unsigned int sf2gaf(const unsigned int getaddr_flags, const unsigned int sockflags)
Convert sockflags/getaddr_flags into getaddr_flags.
Definition resolve.c:42
DNS resolution.
#define GETADDR_TRY_ONCE
Definition resolve.h:45
#define GETADDR_PASSIVE
Definition resolve.h:48
#define GETADDR_FATAL
Definition resolve.h:39
#define GETADDR_UPDATE_MANAGEMENT_STATE
Definition resolve.h:46
#define GETADDR_DATAGRAM
Definition resolve.h:49
#define GETADDR_RESOLVE
Definition resolve.h:38
#define GETADDR_MENTION_RESOLVE_RETRY
Definition resolve.h:41
#define GETADDR_WARN_ON_SIGNAL
Definition resolve.h:43
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:89
int signal_reset(struct signal_info *si, int signum)
Clear the signal if its current value equals signum.
Definition sig.c:262
void throw_signal(const int signum)
Throw a hard signal.
Definition sig.c:175
struct signal_info siginfo_static
Definition sig.c:44
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:228
#define SIG_SOURCE_HARD
Definition sig.h:30
static void get_signal(volatile int *sig)
Copy the global signal_received (if non-zero) to the passed-in argument sig.
Definition sig.h:109
void link_socket_init_phase1(struct context *c, int sock_index, int mode)
Definition socket.c:977
static int socket_get_sndbuf(socket_descriptor_t sd)
Definition socket.c:59
static void socket_set_sndbuf(socket_descriptor_t sd, int size)
Definition socket.c:72
void socket_bind(socket_descriptor_t sd, const struct addrinfo *local, int ai_family, const char *prefix, bool ipv6only)
Definition socket.c:562
void link_socket_init_phase2(struct context *c, struct link_socket *sock)
Definition socket.c:1332
static void ipchange_fmt(const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
Definition socket.c:1500
static int socket_get_last_error(const struct link_socket *sock)
Definition socket.c:2207
static void stream_buf_init(struct stream_buf *sb, const struct buffer *buf, const unsigned int sockflags, const int proto)
Definition socket.c:1717
ssize_t link_socket_write_tcp(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *to)
Definition socket.c:2103
void link_socket_update_buffer_sizes(struct link_socket *sock, int rcvbuf, int sndbuf)
Definition socket.c:161
static socket_descriptor_t create_socket_udp(struct addrinfo *addrinfo, const unsigned int flags, bool optional)
Definition socket.c:209
static void create_socket(struct link_socket *sock, struct addrinfo *addr)
Definition socket.c:330
const struct in6_addr * link_socket_current_remote_ipv6(const struct link_socket_info *info)
Definition socket.c:1635
void set_actual_address(struct link_socket_actual *actual, struct addrinfo *ai)
Definition socket.c:703
const char * socket_stat(const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
Definition socket.c:1668
static void socket_apply_options(socket_descriptor_t sd, const struct socket_buffer_size *sbs, int mark, const char *bind_dev)
Definition socket.c:283
void bad_address_length(int actual, int expected)
Definition socket.c:1905
event_t socket_listen_event_handle(struct link_socket *s)
Definition socket.c:1886
static void linksock_print_addr(struct link_socket *sock)
Definition socket.c:1144
static socket_descriptor_t socket_listen_accept(socket_descriptor_t sd, struct link_socket_actual *act, const struct addrinfo *local, bool do_listen, bool nowait, volatile int *signal_received)
Definition socket.c:503
static void socket_set_mark(socket_descriptor_t sd, int mark)
Definition socket.c:150
static void socket_set_rcvbuf(socket_descriptor_t sd, int size)
Definition socket.c:94
static void stream_buf_close(struct stream_buf *sb)
Definition socket.c:1875
static void stream_buf_get_final(struct stream_buf *sb, struct buffer *buf)
Sets the parameter buf to the current buffer of sb->buf.
Definition socket.c:1764
static void socket_connect(socket_descriptor_t *sd, const struct sockaddr *dest, const int connect_timeout, struct signal_info *sig_info)
Definition socket.c:723
ssize_t link_socket_read_tcp(struct link_socket *sock, struct buffer *buf)
Definition socket.c:1917
static void phase2_socks_client(struct link_socket *sock, struct signal_info *sig_info)
Definition socket.c:1250
static bool socket_set_tcp_nodelay(socket_descriptor_t sd, int state)
Definition socket.c:130
socket_descriptor_t socket_do_accept(socket_descriptor_t sd, struct link_socket_actual *act, const bool nowait)
Definition socket.c:431
static void socket_do_listen(socket_descriptor_t sd, const struct addrinfo *local, bool do_listen, bool do_set_nonblock)
Definition socket.c:401
static void phase2_tcp_server(struct link_socket *sock, struct signal_info *sig_info)
Definition socket.c:1181
int socket_recv_queue(struct link_socket *sock, int maxsize)
Definition socket.c:2218
void link_socket_close(struct link_socket *sock)
Definition socket.c:1442
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:1516
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:103
bool stream_buf_read_setup_dowork(struct stream_buf *sb)
Will try to check if the buffers in stream form a full packet.
Definition socket.c:1772
static void resolve_remote(struct link_socket *sock, int phase, struct signal_info *sig_info)
Definition socket.c:852
static void bind_local(const struct link_socket *sock)
Definition socket.c:264
int socket_send_queue(struct link_socket *sock, const struct buffer *buf, const struct link_socket_actual *to)
Definition socket.c:2318
void link_socket_bad_outgoing_addr(void)
Definition socket.c:1595
int sockethandle_finalize(sockethandle_t sh, struct overlapped_io *io, struct buffer *buf, struct link_socket_actual *from)
Definition socket.c:2503
static void phase2_set_socket_flags(const struct link_socket *sock)
Definition socket.c:1121
in_addr_t link_socket_current_remote(const struct link_socket_info *info)
Definition socket.c:1601
static int socket_get_rcvbuf(socket_descriptor_t sd)
Definition socket.c:81
int openvpn_connect(socket_descriptor_t sd, const struct sockaddr *remote, int connect_timeout, volatile int *signal_received)
Definition socket.c:610
unsigned int socket_set(struct link_socket *s, struct event_set *es, unsigned int rwflags, void *arg, unsigned int *persistent)
Definition socket.c:2596
static struct buffer stream_buf_get_next(struct stream_buf *sb)
Return a buffer that is backed by the same backend as sb->buf that determines where the next read sho...
Definition socket.c:1741
static void read_sockaddr_from_overlapped(const struct overlapped_io *io, struct sockaddr *dst, int overlapped_ret)
Definition socket.c:2419
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:1568
static void phase2_tcp_client(struct link_socket *sock, struct signal_info *sig_info)
Definition socket.c:1215
socket_descriptor_t create_socket_tcp(struct addrinfo *addrinfo)
Definition socket.c:177
static void socket_frame_init(const struct frame *frame, struct link_socket *sock)
Definition socket.c:782
static void stream_buf_reset(struct stream_buf *sb)
resets the stream buffer to be set up for the next round of reassembling a packet
Definition socket.c:1708
static void create_socket_dco_win(struct context *c, struct link_socket *sock, struct signal_info *sig_info)
Definition socket.c:1284
static void resolve_bind_local(struct link_socket *sock)
Definition socket.c:806
static void tcp_connection_established(const struct link_socket_actual *act)
Definition socket.c:495
struct link_socket * link_socket_new(void)
Definition socket.c:963
static bool stream_buf_added(struct stream_buf *sb, ssize_t length_added)
This will determine if sb->buf contains a full packet.
Definition socket.c:1808
static int read_sockaddr_from_packet(struct buffer *buf, struct sockaddr *dst)
Extracts a sockaddr from a packet payload.
Definition socket.c:2469
bool sockets_read_residual(const struct context *c)
Definition socket.c:46
socket_descriptor_t create_socket_udp_configured(sa_family_t af, unsigned int sockflags, const struct socket_buffer_size *sbs, int mark, const char *bind_dev, struct addrinfo *bind_addr, bool bind_ipv6_only, bool optional)
Create a UDP socket for af set up the way a link socket is: –sndbuf/–rcvbuf, –mark,...
Definition socket.c:309
void setenv_trusted(struct env_set *es, const struct link_socket_info *info)
Definition socket.c:1494
static event_t socket_event_handle(const struct link_socket *sock)
Definition socket.h:824
#define IPV4_INVALID_ADDR
Definition socket.h:374
static BOOL SocketHandleGetOverlappedResult(sockethandle_t sh, struct overlapped_io *io)
Definition socket.h:278
#define PACKET_SIZE_MAX
Definition socket.h:57
#define LS_MODE_TCP_ACCEPT_FROM
Definition socket.h:189
#define SF_DCO_WIN
Definition socket.h:204
static bool link_socket_connection_oriented(const struct link_socket *sock)
Definition socket.h:437
static bool stream_buf_read_setup(struct link_socket *sock)
Definition socket.h:581
void sd_close(socket_descriptor_t *sd)
static void SocketHandleSetLastError(sockethandle_t sh, DWORD err)
Definition socket.h:297
static int SocketHandleGetLastError(sockethandle_t sh)
Definition socket.h:286
static void SocketHandleSetInvalError(sockethandle_t sh)
Definition socket.h:307
#define RESOLV_RETRY_INFINITE
Definition socket.h:48
#define SF_USE_IP_PKTINFO
Definition socket.h:199
#define LS_MODE_DEFAULT
Definition socket.h:187
#define MSG_NOSIGNAL
Definition socket.h:251
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:599
#define SF_GETADDRINFO_DGRAM
Definition socket.h:203
#define LS_MODE_TCP_LISTEN
Definition socket.h:188
#define SF_PORT_SHARE
Definition socket.h:201
#define ntohps(x)
Definition socket.h:63
static int openvpn_select(socket_descriptor_t nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
Definition socket.h:316
static int link_socket_write_win32(struct link_socket *sock, struct buffer *buf, struct link_socket_actual *to)
Definition socket.h:678
#define SF_PKTINFO_COPY_IIF
Definition socket.h:206
#define openvpn_close_socket(s)
Definition socket.h:256
#define htonps(x)
Definition socket.h:60
static int openvpn_bind(socket_descriptor_t sockfd, const struct sockaddr *addr, size_t addrlen)
Definition socket.h:331
const char * proto2ascii(int proto, sa_family_t af, bool display_form)
const char * print_sockaddr_ex(const struct sockaddr *sa, const char *separator, const unsigned int flags, struct gc_arena *gc)
Definition socket_util.c:38
void setenv_link_socket_actual(struct env_set *es, const char *name_prefix, const struct link_socket_actual *act, const unsigned int flags)
const char * print_link_socket_actual(const struct link_socket_actual *act, struct gc_arena *gc)
const char * print_link_socket_actual_ex(const struct link_socket_actual *act, const char *separator, const unsigned int flags, struct gc_arena *gc)
const char * addr_family_name(int af)
static const char * print_sockaddr(const struct sockaddr *addr, struct gc_arena *gc)
Definition socket_util.h:77
static bool link_socket_actual_defined(const struct link_socket_actual *act)
#define SA_IP_PORT
Definition socket_util.h:99
static bool proto_is_udp(int proto)
Returns if the protocol being used is UDP.
#define PS_SHOW_PORT
Definition socket_util.h:31
@ PROTO_UDP
@ PROTO_TCP_CLIENT
@ PROTO_N
@ PROTO_TCP_SERVER
#define PS_SHOW_PORT_IF_DEFINED
Definition socket_util.h:30
static bool proto_is_tcp(int proto)
returns if the proto is a TCP variant (tcp-server, tcp-client or tcp)
static void addr_zero_host(struct openvpn_sockaddr *addr)
static bool proto_is_dgram(int proto)
Return if the protocol is datagram (UDP).
static int af_addr_size(sa_family_t af)
void establish_socks_proxy_passthru(const struct socks_proxy_info *p, socket_descriptor_t sd, const char *host, const char *servname, const struct event_timeout *server_poll_timeout, struct signal_info *sig_info)
Definition socks.c:342
void establish_socks_proxy_udpassoc(const struct socks_proxy_info *p, socket_descriptor_t ctrl_sd, struct openvpn_sockaddr *relay_addr, const struct event_timeout *server_poll_timeout, struct signal_info *sig_info)
Definition socks.c:400
Definition argv.h:35
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:76
int offset
Offset in bytes of the actual content within the allocated memory.
Definition buffer.h:74
struct local_list * local_list
Definition options.h:110
bool bind_local
Definition options.h:120
const char * remote
Definition options.h:116
bool bind_ipv6_only
Definition options.h:119
bool remote_float
Definition options.h:117
const char * remote_port
Definition options.h:115
int mtu_discover_type
Definition options.h:141
int proto
Definition options.h:111
sa_family_t af
Definition options.h:112
bool local_port_defined
Definition options.h:114
const char * local_port
Definition options.h:113
struct link_socket_addr * link_socket_addrs
Local and remote addresses on the external network.
Definition openvpn.h:145
int link_sockets_num
Definition openvpn.h:144
struct http_proxy_info * http_proxy
Definition openvpn.h:172
struct socks_proxy_info * socks_proxy
Definition openvpn.h:176
struct cached_dns_entry * dns_cache
Definition openvpn.h:153
struct tuntap * tuntap
Tun/tap virtual network interface.
Definition openvpn.h:155
struct event_timeout server_poll_interval
Definition openvpn.h:382
const struct link_socket * accept_from
Definition openvpn.h:225
struct frame frame
Definition openvpn.h:231
struct link_socket ** link_sockets
Definition openvpn.h:220
Contains all state information for one tunnel.
Definition openvpn.h:445
int mode
Role of this context within the OpenVPN process.
Definition openvpn.h:458
struct signal_info * sig
Internal error signaling object.
Definition openvpn.h:474
struct plugin_list * plugins
List of plug-ins.
Definition openvpn.h:476
struct context_2 c2
Level 2 context.
Definition openvpn.h:490
struct options options
Options loaded from command line or configuration file.
Definition openvpn.h:446
struct gc_arena gc
Garbage collection arena for allocations done in the scope of this context structure.
Definition openvpn.h:466
struct context_1 c1
Level 1 context.
Definition openvpn.h:489
union event_arg::@352313260244035237115140212234220346176163201310 u
struct link_socket * sock
Definition event.h:145
event_arg_t type
Definition event.h:141
Packet geometry parameters.
Definition mtu.h:113
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
struct http_proxy_options options
Definition proxy.h:70
const char * port
Definition proxy.h:47
const char * server
Definition proxy.h:46
const char * port
Definition options.h:104
int proto
Definition options.h:105
const char * local
Definition options.h:103
struct local_entry ** array
Definition options.h:198
struct man_connection connection
Definition manage.h:346
union openvpn_sockaddr::@051240265251124304325377241125360350250341115171 addr
struct sockaddr sa
Definition socket_util.h:42
struct sockaddr_in in4
Definition socket_util.h:43
struct sockaddr_in6 in6
Definition socket_util.h:44
int resolve_retry_seconds
Definition options.h:367
int rcvbuf
Definition options.h:413
HANDLE msg_channel
Definition options.h:691
struct connection_entry ce
Definition options.h:294
const char * ipchange
Definition options.h:321
int mode
Definition options.h:266
char * bind_dev
Definition options.h:418
int sndbuf
Definition options.h:414
int mark
Definition options.h:417
unsigned int sockflags
Definition options.h:421
const char * dev_node
Definition options.h:324
DWORD flags
Definition win32.h:212
struct buffer buf
Definition win32.h:222
DWORD size
Definition win32.h:211
OVERLAPPED overlapped
Definition win32.h:210
struct buffer buf_init
Definition win32.h:221
int addrlen
Definition win32.h:220
bool addr_defined
Definition win32.h:214
int iostate
Definition win32.h:209
struct sockaddr_in6 addr6
Definition win32.h:218
struct sockaddr_in addr
Definition win32.h:217
HANDLE write
Definition win32.h:83
HANDLE read
Definition win32.h:82
const char * signal_text
Definition sig.h:44
volatile int signal_received
Definition sig.h:42
volatile int source
Definition sig.h:43
bool is_handle
Definition socket.h:270
bool prepend_sa
Definition socket.h:271
char server[128]
Definition socks.h:42
const char * port
Definition socks.h:43
struct used to extract packets encapsulated in streams into a buffer, in this case OpenVPN packets (d...
Definition socket.h:97
struct buffer buf
Holds the data of the current packet.
Definition socket.h:113
bool error
if true, a fatal TCP error has occurred, requiring that connection be restarted
Definition socket.h:122
struct buffer residual
buffer holding the excess bytes that are not part of the packet.
Definition socket.h:103
bool residual_fully_formed
The buffer in buf contains a full packet without a header.
Definition socket.h:110
int maxlen
Maximum length of a packet that we accept.
Definition socket.h:106
int len
-1 if not yet known.
Definition socket.h:118
struct buffer buf_init
Definition socket.h:99
HANDLE msg_channel
Definition tun.h:86
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:218
struct tuntap_options options
Definition tun.h:203
HANDLE hand
Definition tun.h:216
unsigned short sa_family_t
Definition syshead.h:405
#define SOCKET_UNDEFINED
Definition syshead.h:439
#define SIGTERM
Definition syshead.h:59
#define SOL_IP
Definition syshead.h:398
SOCKET socket_descriptor_t
Definition syshead.h:441
#define SIGUSR1
Definition syshead.h:57
uint32_t in_addr_t
Definition syshead.h:52
static int socket_defined(const socket_descriptor_t sd)
Definition syshead.h:449
#define ENABLE_IP_PKTINFO
Definition syshead.h:390
struct gc_arena gc
Definition test_ssl.c:138
void tun_open_device(struct tuntap *tt, const char *dev_node, const char **device_guid, struct gc_arena *gc)
Definition tun.c:5870
@ DRIVER_DCO
Definition tun.h:53
void init_net_event_win32(struct rw_handle *event, long network_events, socket_descriptor_t sd, unsigned int flags)
Definition win32.c:316
void overlapped_io_init(struct overlapped_io *o, const struct frame *frame, BOOL event_state)
Definition win32.c:266
void close_net_event_win32(struct rw_handle *event, socket_descriptor_t sd, unsigned int flags)
Definition win32.c:371
char * overlapped_io_state_ascii(const struct overlapped_io *o)
Definition win32.c:295
void overlapped_io_close(struct overlapped_io *o)
Definition win32.c:282
static bool defined_net_event_win32(const struct rw_handle *event)
Definition win32.h:94
#define IOSTATE_IMMEDIATE_RETURN
Definition win32.h:208
#define IOSTATE_INITIAL
Definition win32.h:206
#define IOSTATE_QUEUED
Definition win32.h:207