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