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