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
8
* Copyright (C) 2002-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
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.
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.
19
* You should have received a copy of the GNU General Public License
20
* along with this program (see the file COPYING included with this
21
* distribution); if not, write to the Free Software Foundation, Inc.,
22
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27
#elif defined(_MSC_VER)
28
#include "config-msvc.h"
44
const int proto_overhead[] = { /* indexed by PROTO_x */
46
IPv4_UDP_HEADER_SIZE, /* IPv4 */
49
IPv6_UDP_HEADER_SIZE, /* IPv6 */
56
* Convert sockflags/getaddr_flags into getaddr_flags
59
sf2gaf(const unsigned int getaddr_flags,
60
const unsigned int sockflags)
62
if (sockflags & SF_HOST_RANDOMIZE)
63
return getaddr_flags | GETADDR_RANDOMIZE;
69
* Functions related to the translation of DNS names to IP addresses.
73
h_errno_msg(int h_errno_err)
78
return "[HOST_NOT_FOUND] The specified host is unknown.";
80
return "[NO_DATA] The requested name is valid but does not have an IP address.";
82
return "[NO_RECOVERY] A non-recoverable name server error occurred.";
84
return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
86
return "[unknown h_errno value]";
90
* Translate IP addr or hostname to in_addr_t.
91
* If resolve error, try again for
92
* resolve_retry_seconds seconds.
95
getaddr (unsigned int flags,
97
int resolve_retry_seconds,
99
volatile int *signal_received)
103
status = openvpn_getaddrinfo(flags, hostname, resolve_retry_seconds,
104
signal_received, AF_INET, &ai);
109
ia = ((struct sockaddr_in*)ai->ai_addr)->sin_addr;
111
return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
121
* Translate IPv4/IPv6 addr or hostname into struct addrinfo
122
* If resolve error, try again for resolve_retry_seconds seconds.
125
openvpn_getaddrinfo (unsigned int flags,
126
const char *hostname,
127
int resolve_retry_seconds,
128
volatile int *signal_received,
130
struct addrinfo **res)
132
struct addrinfo hints;
135
int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
136
struct gc_arena gc = gc_new ();
140
#if defined(HAVE_RES_INIT)
147
if (flags & GETADDR_RANDOMIZE)
148
hostname = hostname_randomize(hostname, &gc);
150
if (flags & GETADDR_MSG_VIRT_OUT)
151
msglevel |= M_MSG_VIRT_OUT;
153
if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
155
signal_received = &sigrec;
157
/* try numeric ipv6 addr first */
159
hints.ai_family = ai_family;
160
hints.ai_flags = AI_NUMERICHOST;
161
hints.ai_socktype = SOCK_STREAM;
163
status = getaddrinfo(hostname, NULL, &hints, res);
165
if (status != 0) /* parse as numeric address failed? */
167
const int fail_wait_interval = 5; /* seconds */
168
int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 : (resolve_retry_seconds / fail_wait_interval);
172
fmt = "RESOLVE: Cannot resolve host address: %s: %s";
173
if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
174
&& !resolve_retry_seconds)
175
fmt = "RESOLVE: Cannot resolve host address: %s: %s (I would have retried this name query if you had specified the --resolv-retry option.)";
177
if (!(flags & GETADDR_RESOLVE) || status == EAI_FAIL)
179
msg (msglevel, "RESOLVE: Cannot parse IP address: %s", hostname);
183
#ifdef ENABLE_MANAGEMENT
184
if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
187
management_set_state (management,
188
OPENVPN_STATE_RESOLVE,
200
/* try hostname lookup */
202
dmsg (D_SOCKET_DEBUG, "GETADDRINFO flags=0x%04x ai_family=%d ai_socktype=%d",
203
flags, hints.ai_family, hints.ai_socktype);
204
status = getaddrinfo(hostname, NULL, &hints, res);
208
get_signal (signal_received);
209
if (*signal_received) /* were we interrupted by a signal? */
216
if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
218
msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
219
*signal_received = 0;
230
/* resolve lookup failed, should we
233
if (resolve_retries > 0)
234
level = D_RESOLVE_ERRORS;
239
gai_strerror(status));
241
if (--resolve_retries <= 0)
244
openvpn_sleep (fail_wait_interval);
249
/* hostname resolve succeeded */
251
/* Do not chose an IP Addresse by random or change the order *
252
* of IP addresses, doing so will break RFC 3484 address selection *
257
/* IP address parse succeeded */
261
if (signal_received && *signal_received)
264
if (flags & GETADDR_FATAL_ON_SIGNAL)
266
else if (flags & GETADDR_WARN_ON_SIGNAL)
268
msg (level, "RESOLVE: signal received during DNS resolution attempt");
276
* We do our own inet_aton because the glibc function
277
* isn't very good about error checking.
280
openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
282
unsigned int a, b, c, d;
285
if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
287
if (a < 256 && b < 256 && c < 256 && d < 256)
289
addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
290
return OIA_IP; /* good dotted quad */
293
if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
294
return OIA_ERROR; /* probably a badly formatted dotted quad */
296
return OIA_HOSTNAME; /* probably a hostname */
300
ip_addr_dotted_quad_safe (const char *dotted_quad)
302
/* verify non-NULL */
306
/* verify length is within limits */
307
if (strlen (dotted_quad) > 15)
310
/* verify that all chars are either numeric or '.' and that no numeric
311
substring is greater than 3 chars */
314
const char *p = dotted_quad;
319
if (c >= '0' && c <= '9')
334
/* verify that string will convert to IP address */
337
return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
342
ipv6_addr_safe (const char *ipv6_text_addr)
344
/* verify non-NULL */
348
/* verify length is within limits */
349
if (strlen (ipv6_text_addr) > INET6_ADDRSTRLEN )
352
/* verify that string will convert to IPv6 address */
355
return inet_pton( AF_INET6, ipv6_text_addr, &a6 ) == 1;
360
dns_addr_safe (const char *addr)
364
const size_t len = strlen (addr);
365
return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
372
ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
374
if (ip_addr_dotted_quad_safe (addr))
377
return dns_addr_safe (addr);
383
mac_addr_safe (const char *mac_addr)
385
/* verify non-NULL */
389
/* verify length is within limits */
390
if (strlen (mac_addr) > 17)
393
/* verify that all chars are either alphanumeric or ':' and that no
394
alphanumeric substring is greater than 2 chars */
397
const char *p = mac_addr;
402
if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
417
/* error-checking is left to script invoked in lladdr.c */
422
update_remote (const char* host,
423
struct openvpn_sockaddr *addr,
425
const unsigned int sockflags)
427
switch(addr->addr.sa.sa_family)
432
const in_addr_t new_addr = getaddr (
433
sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags),
438
if (new_addr && addr->addr.in4.sin_addr.s_addr != new_addr)
440
addr->addr.in4.sin_addr.s_addr = new_addr;
451
status = openvpn_getaddrinfo(sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags), host, 1, NULL, AF_INET6, &ai);
455
struct sockaddr_in6 sin6;
457
sin6 = *((struct sockaddr_in6*)ai->ai_addr);
458
if (!IN6_ARE_ADDR_EQUAL(&sin6.sin6_addr, &addr->addr.in6.sin6_addr))
460
int port = addr->addr.in6.sin6_port;
461
/* ipv6 requires also eg. sin6_scope_id => easier to fully copy and override port */
462
addr->addr.in6 = sin6;
463
addr->addr.in6.sin6_port = port;
475
socket_get_sndbuf (int sd)
477
#if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
482
if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
483
&& len == sizeof (val))
490
socket_set_sndbuf (int sd, int size)
492
#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
493
if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
495
if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
497
msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
504
socket_get_rcvbuf (int sd)
506
#if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
511
if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
512
&& len == sizeof (val))
519
socket_set_rcvbuf (int sd, int size)
521
#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
522
if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
524
if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
526
msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
535
socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
539
const int sndbuf_old = socket_get_sndbuf (fd);
540
const int rcvbuf_old = socket_get_rcvbuf (fd);
543
socket_set_sndbuf (fd, sbs->sndbuf);
546
socket_set_rcvbuf (fd, sbs->rcvbuf);
548
msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
550
socket_get_rcvbuf (fd),
552
socket_get_sndbuf (fd));
557
* Set other socket options
561
socket_set_tcp_nodelay (int sd, int state)
563
#if defined(WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
564
if (setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof (state)) != 0)
566
msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
571
dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
575
msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
581
socket_set_mark (int sd, int mark)
583
#if defined(TARGET_LINUX) && HAVE_DECL_SO_MARK
584
if (mark && setsockopt (sd, SOL_SOCKET, SO_MARK, &mark, sizeof (mark)) != 0)
585
msg (M_WARN, "NOTE: setsockopt SO_MARK=%d failed", mark);
590
socket_set_flags (int sd, unsigned int sockflags)
592
if (sockflags & SF_TCP_NODELAY)
593
return socket_set_tcp_nodelay (sd, 1);
599
link_socket_update_flags (struct link_socket *ls, unsigned int sockflags)
601
if (ls && socket_defined (ls->sd))
602
return socket_set_flags (ls->sd, ls->sockflags = sockflags);
608
link_socket_update_buffer_sizes (struct link_socket *ls, int rcvbuf, int sndbuf)
610
if (ls && socket_defined (ls->sd))
612
ls->socket_buffer_sizes.sndbuf = sndbuf;
613
ls->socket_buffer_sizes.rcvbuf = rcvbuf;
614
socket_set_buffers (ls->sd, &ls->socket_buffer_sizes);
619
* SOCKET INITALIZATION CODE.
620
* Create a TCP/UDP socket
624
create_socket_tcp (int af)
626
socket_descriptor_t sd;
628
if ((sd = socket (af, SOCK_STREAM, IPPROTO_TCP)) < 0)
629
msg (M_ERR, "Cannot create TCP socket");
631
#ifndef WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
632
/* set SO_REUSEADDR on socket */
635
if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
636
(void *) &on, sizeof (on)) < 0)
637
msg (M_ERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
644
static socket_descriptor_t
645
create_socket_udp (const unsigned int flags)
647
socket_descriptor_t sd;
649
if ((sd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
650
msg (M_ERR, "UDP: Cannot create UDP socket");
651
#if ENABLE_IP_PKTINFO
652
else if (flags & SF_USE_IP_PKTINFO)
656
if (setsockopt (sd, SOL_IP, IP_PKTINFO,
657
(void*)&pad, sizeof(pad)) < 0)
658
msg(M_ERR, "UDP: failed setsockopt for IP_PKTINFO");
659
#elif defined(IP_RECVDSTADDR)
660
if (setsockopt (sd, IPPROTO_IP, IP_RECVDSTADDR,
661
(void*)&pad, sizeof(pad)) < 0)
662
msg(M_ERR, "UDP: failed setsockopt for IP_RECVDSTADDR");
664
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
671
static socket_descriptor_t
672
create_socket_udp6 (const unsigned int flags)
674
socket_descriptor_t sd;
676
if ((sd = socket (PF_INET6, SOCK_DGRAM, IPPROTO_UDP)) < 0)
677
msg (M_ERR, "UDP: Cannot create UDP6 socket");
678
#if ENABLE_IP_PKTINFO
679
else if (flags & SF_USE_IP_PKTINFO)
682
#ifndef IPV6_RECVPKTINFO /* Some older Darwin platforms require this */
683
if (setsockopt (sd, IPPROTO_IPV6, IPV6_PKTINFO,
684
(void*)&pad, sizeof(pad)) < 0)
686
if (setsockopt (sd, IPPROTO_IPV6, IPV6_RECVPKTINFO,
687
(void*)&pad, sizeof(pad)) < 0)
689
msg(M_ERR, "UDP: failed setsockopt for IPV6_RECVPKTINFO");
696
create_socket (struct link_socket *sock)
699
if (sock->info.proto == PROTO_UDPv4)
701
sock->sd = create_socket_udp (sock->sockflags);
702
sock->sockflags |= SF_GETADDRINFO_DGRAM;
705
if (sock->socks_proxy)
706
sock->ctrl_sd = create_socket_tcp (AF_INET);
709
else if (sock->info.proto == PROTO_TCPv4_SERVER
710
|| sock->info.proto == PROTO_TCPv4_CLIENT)
712
sock->sd = create_socket_tcp (AF_INET);
714
else if (sock->info.proto == PROTO_TCPv6_SERVER
715
|| sock->info.proto == PROTO_TCPv6_CLIENT)
717
sock->sd = create_socket_tcp (AF_INET6);
719
else if (sock->info.proto == PROTO_UDPv6)
721
sock->sd = create_socket_udp6 (sock->sockflags);
722
sock->sockflags |= SF_GETADDRINFO_DGRAM;
731
* Functions used for establishing a TCP stream connection.
735
socket_do_listen (socket_descriptor_t sd,
736
const struct openvpn_sockaddr *local,
738
bool do_set_nonblock)
740
struct gc_arena gc = gc_new ();
743
msg (M_INFO, "Listening for incoming TCP connection on %s",
744
print_sockaddr (local, &gc));
746
msg (M_ERR, "TCP: listen() failed");
749
/* set socket to non-blocking mode */
757
socket_do_accept (socket_descriptor_t sd,
758
struct link_socket_actual *act,
761
/* af_addr_size WILL return 0 in this case if AFs other than AF_INET
762
* are compiled because act is empty here.
763
* could use getsockname() to support later remote_len check
765
socklen_t remote_len_af = af_addr_size(act->dest.addr.sa.sa_family);
766
socklen_t remote_len = sizeof(act->dest.addr);
767
socket_descriptor_t new_sd = SOCKET_UNDEFINED;
771
#ifdef HAVE_GETPEERNAME
774
new_sd = getpeername (sd, &act->dest.addr.sa, &remote_len);
776
if (!socket_defined (new_sd))
777
msg (D_LINK_ERRORS | M_ERRNO, "TCP: getpeername() failed");
783
msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
787
new_sd = accept (sd, &act->dest.addr.sa, &remote_len);
790
#if 0 /* For debugging only, test the effect of accept() failures */
799
if (!socket_defined (new_sd))
801
msg (D_LINK_ERRORS | M_ERRNO, "TCP: accept(%d) failed", sd);
803
/* only valid if we have remote_len_af!=0 */
804
else if (remote_len_af && remote_len != remote_len_af)
806
msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
807
openvpn_close_socket (new_sd);
808
new_sd = SOCKET_UNDEFINED;
814
tcp_connection_established (const struct link_socket_actual *act)
816
struct gc_arena gc = gc_new ();
817
msg (M_INFO, "TCP connection established with %s",
818
print_link_socket_actual (act, &gc));
823
socket_listen_accept (socket_descriptor_t sd,
824
struct link_socket_actual *act,
825
const char *remote_dynamic,
826
bool *remote_changed,
827
const struct openvpn_sockaddr *local,
830
volatile int *signal_received)
832
struct gc_arena gc = gc_new ();
833
/* struct openvpn_sockaddr *remote = &act->dest; */
834
struct openvpn_sockaddr remote_verify = act->dest;
835
int new_sd = SOCKET_UNDEFINED;
838
socket_do_listen (sd, local, do_listen, true);
851
status = select (sd + 1, &reads, NULL, NULL, &tv);
853
get_signal (signal_received);
854
if (*signal_received)
861
msg (D_LINK_ERRORS | M_ERRNO, "TCP: select() failed");
869
new_sd = socket_do_accept (sd, act, nowait);
871
if (socket_defined (new_sd))
873
update_remote (remote_dynamic, &remote_verify, remote_changed, 0);
874
if (addr_defined (&remote_verify)
875
&& !addr_match (&remote_verify, &act->dest))
878
"TCP NOTE: Rejected connection attempt from %s due to --remote setting",
879
print_link_socket_actual (act, &gc));
880
if (openvpn_close_socket (new_sd))
881
msg (M_ERR, "TCP: close socket failed (new_sd)");
889
if (!nowait && openvpn_close_socket (sd))
890
msg (M_ERR, "TCP: close socket failed (sd)");
892
tcp_connection_established (act);
899
socket_bind (socket_descriptor_t sd,
900
struct openvpn_sockaddr *local,
903
struct gc_arena gc = gc_new ();
905
if (bind (sd, &local->addr.sa, af_addr_size(local->addr.sa.sa_family)))
907
const int errnum = openvpn_errno ();
908
msg (M_FATAL, "%s: Socket bind failed on local address %s: %s",
910
print_sockaddr (local, &gc),
911
strerror_ts (errnum, &gc));
917
openvpn_connect (socket_descriptor_t sd,
918
struct openvpn_sockaddr *remote,
920
volatile int *signal_received)
924
#ifdef CONNECT_NONBLOCK
926
status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
928
status = openvpn_errno ();
931
status == WSAEWOULDBLOCK
933
status == EINPROGRESS
943
FD_SET (sd, &writes);
947
status = select (sd + 1, NULL, &writes, NULL, &tv);
951
get_signal (signal_received);
952
if (*signal_received)
960
status = openvpn_errno ();
965
if (--connect_timeout < 0)
980
if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
981
&& len == sizeof (val))
984
status = openvpn_errno ();
990
status = connect (sd, &remote->addr.sa, af_addr_size(remote->addr.sa.sa_family));
992
status = openvpn_errno ();
999
socket_connect (socket_descriptor_t *sd,
1000
struct openvpn_sockaddr *local,
1002
struct openvpn_sockaddr *remote,
1003
const bool connection_profiles_defined,
1004
const char *remote_dynamic,
1005
bool *remote_changed,
1006
const int connect_retry_seconds,
1007
const int connect_timeout,
1008
const int connect_retry_max,
1009
const unsigned int sockflags,
1010
volatile int *signal_received)
1012
struct gc_arena gc = gc_new ();
1015
#ifdef CONNECT_NONBLOCK
1016
msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]",
1017
print_sockaddr (remote, &gc));
1019
msg (M_INFO, "Attempting to establish TCP connection with %s",
1020
print_sockaddr (remote, &gc));
1027
#ifdef ENABLE_MANAGEMENT
1029
management_set_state (management,
1030
OPENVPN_STATE_TCP_CONNECT,
1036
status = openvpn_connect (*sd, remote, connect_timeout, signal_received);
1038
get_signal (signal_received);
1039
if (*signal_received)
1046
"TCP: connect to %s failed, will try again in %d seconds: %s",
1047
print_sockaddr (remote, &gc),
1048
connect_retry_seconds,
1049
strerror_ts (status, &gc));
1053
openvpn_close_socket (*sd);
1054
*sd = SOCKET_UNDEFINED;
1056
if ((connect_retry_max > 0 && ++retry >= connect_retry_max) || connection_profiles_defined)
1058
*signal_received = SIGUSR1;
1062
openvpn_sleep (connect_retry_seconds);
1064
get_signal (signal_received);
1065
if (*signal_received)
1068
*sd = create_socket_tcp (local->addr.sa.sa_family);
1071
socket_bind (*sd, local, "TCP Client");
1072
update_remote (remote_dynamic, remote, remote_changed, sockflags);
1075
msg (M_INFO, "TCP connection established with %s",
1076
print_sockaddr (remote, &gc));
1082
/* For stream protocols, allocate a buffer to build up packet.
1083
Called after frame has been finalized. */
1086
socket_frame_init (const struct frame *frame, struct link_socket *sock)
1089
overlapped_io_init (&sock->reads, frame, FALSE, false);
1090
overlapped_io_init (&sock->writes, frame, TRUE, false);
1091
sock->rw_handle.read = sock->reads.overlapped.hEvent;
1092
sock->rw_handle.write = sock->writes.overlapped.hEvent;
1095
if (link_socket_connection_oriented (sock))
1098
stream_buf_init (&sock->stream_buf,
1099
&sock->reads.buf_init,
1103
alloc_buf_sock_tun (&sock->stream_buf_data,
1106
FRAME_HEADROOM_MARKER_READ_STREAM);
1108
stream_buf_init (&sock->stream_buf,
1109
&sock->stream_buf_data,
1117
* Adjust frame structure based on a Path MTU value given
1121
frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
1123
frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
1127
resolve_bind_local (struct link_socket *sock)
1129
struct gc_arena gc = gc_new ();
1131
/* resolve local address if undefined */
1132
if (!addr_defined (&sock->info.lsa->local))
1134
/* may return AF_{INET|INET6} guessed from local_host */
1135
switch(addr_guess_family(sock->info.proto, sock->local_host))
1138
sock->info.lsa->local.addr.in4.sin_family = AF_INET;
1139
sock->info.lsa->local.addr.in4.sin_addr.s_addr =
1140
(sock->local_host ? getaddr (GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
1145
: htonl (INADDR_ANY));
1146
sock->info.lsa->local.addr.in4.sin_port = htons (sock->local_port);
1152
CLEAR(sock->info.lsa->local.addr.in6);
1153
if (sock->local_host)
1155
struct addrinfo *ai;
1157
status = openvpn_getaddrinfo(GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
1158
sock->local_host, 0, NULL, AF_INET6, &ai);
1160
sock->info.lsa->local.addr.in6 = *((struct sockaddr_in6*)(ai->ai_addr));
1166
sock->info.lsa->local.addr.in6.sin6_family = AF_INET6;
1167
sock->info.lsa->local.addr.in6.sin6_addr = in6addr_any;
1172
msg (M_FATAL, "getaddr6() failed for local \"%s\": %s",
1176
sock->info.lsa->local.addr.in6.sin6_port = htons (sock->local_port);
1182
/* bind to local address/port */
1183
if (sock->bind_local)
1186
if (sock->socks_proxy && sock->info.proto == PROTO_UDPv4)
1187
socket_bind (sock->ctrl_sd, &sock->info.lsa->local, "SOCKS");
1190
socket_bind (sock->sd, &sock->info.lsa->local, "TCP/UDP");
1196
resolve_remote (struct link_socket *sock,
1198
const char **remote_dynamic,
1199
volatile int *signal_received)
1201
struct gc_arena gc = gc_new ();
1204
if (!sock->did_resolve_remote)
1206
/* resolve remote address if undefined */
1207
if (!addr_defined (&sock->info.lsa->remote))
1209
af = addr_guess_family(sock->info.proto, sock->remote_host);
1213
sock->info.lsa->remote.addr.in4.sin_family = AF_INET;
1214
sock->info.lsa->remote.addr.in4.sin_addr.s_addr = 0;
1217
CLEAR(sock->info.lsa->remote.addr.in6);
1218
sock->info.lsa->remote.addr.in6.sin6_family = AF_INET6;
1219
sock->info.lsa->remote.addr.in6.sin6_addr = in6addr_any;
1223
if (sock->remote_host)
1225
unsigned int flags = sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
1229
if (sock->connection_profiles_defined && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
1232
flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
1235
else if (phase == 1)
1237
if (sock->resolve_retry_seconds)
1243
flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
1247
else if (phase == 2)
1249
if (sock->resolve_retry_seconds)
1251
flags |= GETADDR_FATAL;
1252
retry = sock->resolve_retry_seconds;
1264
struct addrinfo* ai;
1265
/* Temporary fix, this need to be changed for dual stack */
1266
status = openvpn_getaddrinfo(flags, sock->remote_host, retry,
1267
signal_received, af, &ai);
1269
sock->info.lsa->remote.addr.in6 = *((struct sockaddr_in6*)(ai->ai_addr));
1272
dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1276
signal_received ? *signal_received : -1,
1279
if (signal_received)
1281
if (*signal_received)
1286
if (signal_received)
1287
*signal_received = SIGUSR1;
1294
sock->info.lsa->remote.addr.in4.sin_port = htons (sock->remote_port);
1297
sock->info.lsa->remote.addr.in6.sin6_port = htons (sock->remote_port);
1302
/* should we re-use previous active remote address? */
1303
if (link_socket_actual_defined (&sock->info.lsa->actual))
1305
msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
1306
print_link_socket_actual (&sock->info.lsa->actual, &gc));
1308
*remote_dynamic = NULL;
1312
CLEAR (sock->info.lsa->actual);
1313
sock->info.lsa->actual.dest = sock->info.lsa->remote;
1316
/* remember that we finished */
1317
sock->did_resolve_remote = true;
1324
struct link_socket *
1325
link_socket_new (void)
1327
struct link_socket *sock;
1329
ALLOC_OBJ_CLEAR (sock, struct link_socket);
1330
sock->sd = SOCKET_UNDEFINED;
1332
sock->ctrl_sd = SOCKET_UNDEFINED;
1337
/* bind socket if necessary */
1339
link_socket_init_phase1 (struct link_socket *sock,
1340
const bool connection_profiles_defined,
1341
const char *local_host,
1343
const char *remote_host,
1347
const struct link_socket *accept_from,
1348
#ifdef ENABLE_HTTP_PROXY
1349
struct http_proxy_info *http_proxy,
1352
struct socks_proxy_info *socks_proxy,
1360
struct link_socket_addr *lsa,
1361
const char *ipchange_command,
1362
const struct plugin_list *plugins,
1363
int resolve_retry_seconds,
1364
int connect_retry_seconds,
1365
int connect_timeout,
1366
int connect_retry_max,
1367
int mtu_discover_type,
1371
unsigned int sockflags)
1375
sock->connection_profiles_defined = connection_profiles_defined;
1377
sock->local_host = local_host;
1378
sock->local_port = local_port;
1379
sock->remote_host = remote_host;
1380
sock->remote_port = remote_port;
1382
#ifdef ENABLE_HTTP_PROXY
1383
sock->http_proxy = http_proxy;
1387
sock->socks_proxy = socks_proxy;
1390
sock->bind_local = bind_local;
1391
sock->inetd = inetd;
1392
sock->resolve_retry_seconds = resolve_retry_seconds;
1393
sock->connect_retry_seconds = connect_retry_seconds;
1394
sock->connect_timeout = connect_timeout;
1395
sock->connect_retry_max = connect_retry_max;
1396
sock->mtu_discover_type = mtu_discover_type;
1399
sock->gremlin = gremlin;
1402
sock->socket_buffer_sizes.rcvbuf = rcvbuf;
1403
sock->socket_buffer_sizes.sndbuf = sndbuf;
1405
sock->sockflags = sockflags;
1407
sock->info.proto = proto;
1408
sock->info.remote_float = remote_float;
1409
sock->info.lsa = lsa;
1410
sock->info.ipchange_command = ipchange_command;
1411
sock->info.plugins = plugins;
1414
if (mode == LS_MODE_TCP_ACCEPT_FROM)
1416
ASSERT (accept_from);
1417
ASSERT (sock->info.proto == PROTO_TCPv4_SERVER
1418
|| sock->info.proto == PROTO_TCPv6_SERVER
1420
ASSERT (!sock->inetd);
1421
sock->sd = accept_from->sd;
1426
#ifdef ENABLE_HTTP_PROXY
1427
/* are we running in HTTP proxy mode? */
1428
else if (sock->http_proxy)
1430
ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT);
1431
ASSERT (!sock->inetd);
1433
/* the proxy server */
1434
sock->remote_host = http_proxy->options.server;
1435
sock->remote_port = http_proxy->options.port;
1437
/* the OpenVPN server we will use the proxy to connect to */
1438
sock->proxy_dest_host = remote_host;
1439
sock->proxy_dest_port = remote_port;
1443
/* or in Socks proxy mode? */
1444
else if (sock->socks_proxy)
1446
ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_UDPv4);
1447
ASSERT (!sock->inetd);
1449
/* the proxy server */
1450
sock->remote_host = socks_proxy->server;
1451
sock->remote_port = socks_proxy->port;
1453
/* the OpenVPN server we will use the proxy to connect to */
1454
sock->proxy_dest_host = remote_host;
1455
sock->proxy_dest_port = remote_port;
1460
sock->remote_host = remote_host;
1461
sock->remote_port = remote_port;
1464
/* bind behavior for TCP server vs. client */
1465
if (sock->info.proto == PROTO_TCPv4_SERVER)
1467
if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
1468
sock->bind_local = false;
1470
sock->bind_local = true;
1473
/* were we started by inetd or xinetd? */
1476
ASSERT (sock->info.proto != PROTO_TCPv4_CLIENT
1477
&& sock->info.proto != PROTO_TCPv6_CLIENT);
1478
ASSERT (socket_defined (inetd_socket_descriptor));
1479
sock->sd = inetd_socket_descriptor;
1481
else if (mode != LS_MODE_TCP_ACCEPT_FROM)
1483
create_socket (sock);
1485
/* set socket buffers based on --sndbuf and --rcvbuf options */
1486
socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
1488
/* set socket to --mark packets with given value */
1489
socket_set_mark (sock->sd, mark);
1491
resolve_bind_local (sock);
1492
resolve_remote (sock, 1, NULL, NULL);
1496
/* finalize socket initialization */
1498
link_socket_init_phase2 (struct link_socket *sock,
1499
const struct frame *frame,
1500
volatile int *signal_received)
1502
struct gc_arena gc = gc_new ();
1503
const char *remote_dynamic = NULL;
1504
bool remote_changed = false;
1509
if (signal_received && *signal_received)
1511
sig_save = *signal_received;
1512
*signal_received = 0;
1515
/* initialize buffers */
1516
socket_frame_init (frame, sock);
1519
* Pass a remote name to connect/accept so that
1520
* they can test for dynamic IP address changes
1521
* and throw a SIGUSR1 if appropriate.
1523
if (sock->resolve_retry_seconds)
1524
remote_dynamic = sock->remote_host;
1526
/* were we started by inetd or xinetd? */
1529
if (sock->info.proto == PROTO_TCPv4_SERVER
1530
|| sock->info.proto == PROTO_TCPv6_SERVER) {
1531
/* AF_INET as default (and fallback) for inetd */
1532
sock->info.lsa->actual.dest.addr.sa.sa_family = AF_INET;
1533
#ifdef HAVE_GETSOCKNAME
1535
/* inetd: hint family type for dest = local's */
1536
struct openvpn_sockaddr local_addr;
1537
socklen_t addrlen = sizeof(local_addr);
1538
if (getsockname (sock->sd, (struct sockaddr *)&local_addr, &addrlen) == 0) {
1539
sock->info.lsa->actual.dest.addr.sa.sa_family = local_addr.addr.sa.sa_family;
1540
dmsg (D_SOCKET_DEBUG, "inetd(%s): using sa_family=%d from getsockname(%d)",
1541
proto2ascii(sock->info.proto, false), local_addr.addr.sa.sa_family,
1544
msg (M_WARN, "inetd(%s): getsockname(%d) failed, using AF_INET",
1545
proto2ascii(sock->info.proto, false), sock->sd);
1548
msg (M_WARN, "inetd(%s): this OS does not provide the getsockname() "
1549
"function, using AF_INET",
1550
proto2ascii(sock->info.proto, false));
1553
socket_listen_accept (sock->sd,
1554
&sock->info.lsa->actual,
1557
&sock->info.lsa->local,
1559
sock->inetd == INETD_NOWAIT,
1562
ASSERT (!remote_changed);
1563
if (*signal_received)
1568
resolve_remote (sock, 2, &remote_dynamic, signal_received);
1570
if (*signal_received)
1573
/* TCP client/server */
1574
if (sock->info.proto == PROTO_TCPv4_SERVER
1575
||sock->info.proto == PROTO_TCPv6_SERVER)
1579
case LS_MODE_DEFAULT:
1580
sock->sd = socket_listen_accept (sock->sd,
1581
&sock->info.lsa->actual,
1584
&sock->info.lsa->local,
1589
case LS_MODE_TCP_LISTEN:
1590
socket_do_listen (sock->sd,
1591
&sock->info.lsa->local,
1595
case LS_MODE_TCP_ACCEPT_FROM:
1596
sock->sd = socket_do_accept (sock->sd,
1597
&sock->info.lsa->actual,
1599
if (!socket_defined (sock->sd))
1601
*signal_received = SIGTERM;
1604
tcp_connection_established (&sock->info.lsa->actual);
1610
else if (sock->info.proto == PROTO_TCPv4_CLIENT
1611
||sock->info.proto == PROTO_TCPv6_CLIENT)
1614
#ifdef GENERAL_PROXY_SUPPORT
1615
bool proxy_retry = false;
1617
const bool proxy_retry = false;
1620
socket_connect (&sock->sd,
1621
&sock->info.lsa->local,
1623
&sock->info.lsa->actual.dest,
1624
sock->connection_profiles_defined,
1627
sock->connect_retry_seconds,
1628
sock->connect_timeout,
1629
sock->connect_retry_max,
1633
if (*signal_received)
1638
#ifdef ENABLE_HTTP_PROXY
1639
else if (sock->http_proxy)
1641
proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
1643
sock->proxy_dest_host,
1644
sock->proxy_dest_port,
1645
&sock->stream_buf.residual,
1650
else if (sock->socks_proxy)
1652
establish_socks_proxy_passthru (sock->socks_proxy,
1654
sock->proxy_dest_host,
1655
sock->proxy_dest_port,
1661
openvpn_close_socket (sock->sd);
1662
sock->sd = create_socket_tcp (AF_INET);
1664
} while (proxy_retry);
1667
else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
1669
socket_connect (&sock->ctrl_sd,
1670
&sock->info.lsa->local,
1672
&sock->info.lsa->actual.dest,
1673
sock->connection_profiles_defined,
1676
sock->connect_retry_seconds,
1677
sock->connect_timeout,
1678
sock->connect_retry_max,
1682
if (*signal_received)
1685
establish_socks_proxy_udpassoc (sock->socks_proxy,
1688
&sock->socks_relay.dest,
1691
if (*signal_received)
1694
sock->remote_host = sock->proxy_dest_host;
1695
sock->remote_port = sock->proxy_dest_port;
1696
sock->did_resolve_remote = false;
1698
addr_zero_host(&sock->info.lsa->actual.dest);
1699
addr_zero_host(&sock->info.lsa->remote);
1701
resolve_remote (sock, 1, NULL, signal_received);
1703
if (*signal_received)
1708
if (*signal_received)
1713
msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
1714
addr_copy_host(&sock->info.lsa->remote, &sock->info.lsa->actual.dest);
1718
/* set misc socket parameters */
1719
socket_set_flags (sock->sd, sock->sockflags);
1721
/* set socket to non-blocking mode */
1722
set_nonblock (sock->sd);
1724
/* set socket file descriptor to not pass across execs, so that
1725
scripts don't have access to it */
1726
set_cloexec (sock->sd);
1729
if (socket_defined (sock->ctrl_sd))
1730
set_cloexec (sock->ctrl_sd);
1733
/* set Path MTU discovery options on the socket */
1734
set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
1736
#if EXTENDED_SOCKET_ERROR_CAPABILITY
1737
/* if the OS supports it, enable extended error passing on the socket */
1738
set_sock_extended_error_passing (sock->sd);
1741
/* print local address */
1743
const int msglevel = (sock->mode == LS_MODE_TCP_ACCEPT_FROM) ? D_INIT_MEDIUM : M_INFO;
1746
msg (msglevel, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
1748
msg (msglevel, "%s link local%s: %s",
1749
proto2ascii (sock->info.proto, true),
1750
(sock->bind_local ? " (bound)" : ""),
1751
print_sockaddr_ex (&sock->info.lsa->local, ":", sock->bind_local ? PS_SHOW_PORT : 0, &gc));
1753
/* print active remote address */
1754
msg (msglevel, "%s link remote: %s",
1755
proto2ascii (sock->info.proto, true),
1756
print_link_socket_actual_ex (&sock->info.lsa->actual,
1758
PS_SHOW_PORT_IF_DEFINED,
1763
if (sig_save && signal_received)
1765
if (!*signal_received)
1766
*signal_received = sig_save;
1772
link_socket_close (struct link_socket *sock)
1777
const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
1779
const int gremlin = 0;
1782
if (socket_defined (sock->sd))
1785
close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
1789
msg (D_LOW, "TCP/UDP: Closing socket");
1790
if (openvpn_close_socket (sock->sd))
1791
msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket failed");
1793
sock->sd = SOCKET_UNDEFINED;
1797
overlapped_io_close (&sock->reads);
1798
overlapped_io_close (&sock->writes);
1804
if (socket_defined (sock->ctrl_sd))
1806
if (openvpn_close_socket (sock->ctrl_sd))
1807
msg (M_WARN | M_ERRNO, "TCP/UDP: Close Socket (ctrl_sd) failed");
1808
sock->ctrl_sd = SOCKET_UNDEFINED;
1812
stream_buf_close (&sock->stream_buf);
1813
free_buf (&sock->stream_buf_data);
1819
/* for stream protocols, allow for packet length prefix */
1821
socket_adjust_frame_parameters (struct frame *frame, int proto)
1823
if (link_socket_proto_connection_oriented (proto))
1824
frame_add_to_extra_frame (frame, sizeof (packet_size_type));
1828
setenv_trusted (struct env_set *es, const struct link_socket_info *info)
1830
setenv_link_socket_actual (es, "trusted", &info->lsa->actual, SA_IP_PORT);
1834
ipchange_fmt (const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
1836
const char *ip = print_sockaddr_ex (&info->lsa->actual.dest, NULL, 0, gc);
1837
const char *port = print_sockaddr_ex (&info->lsa->actual.dest, NULL, PS_DONT_SHOW_ADDR|PS_SHOW_PORT, gc);
1839
argv_printf (argv, "%sc %s %s",
1840
info->ipchange_command,
1844
argv_printf (argv, "%s %s",
1850
link_socket_connection_initiated (const struct buffer *buf,
1851
struct link_socket_info *info,
1852
const struct link_socket_actual *act,
1853
const char *common_name,
1856
struct gc_arena gc = gc_new ();
1858
info->lsa->actual = *act; /* Note: skip this line for --force-dest */
1859
setenv_trusted (es, info);
1860
info->connection_established = true;
1862
/* Print connection initiated message, with common name if available */
1864
struct buffer out = alloc_buf_gc (256, &gc);
1866
buf_printf (&out, "[%s] ", common_name);
1867
buf_printf (&out, "Peer Connection Initiated with %s", print_link_socket_actual (&info->lsa->actual, &gc));
1868
msg (M_INFO, "%s", BSTR (&out));
1871
/* set environmental vars */
1872
setenv_str (es, "common_name", common_name);
1874
/* Process --ipchange plugin */
1875
if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
1877
struct argv argv = argv_new ();
1878
ipchange_fmt (false, &argv, info, &gc);
1879
if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1880
msg (M_WARN, "WARNING: ipchange plugin call failed");
1884
/* Process --ipchange option */
1885
if (info->ipchange_command)
1887
struct argv argv = argv_new ();
1888
setenv_str (es, "script_type", "ipchange");
1889
ipchange_fmt (true, &argv, info, &gc);
1890
openvpn_run_script (&argv, es, 0, "--ipchange");
1898
link_socket_bad_incoming_addr (struct buffer *buf,
1899
const struct link_socket_info *info,
1900
const struct link_socket_actual *from_addr)
1902
struct gc_arena gc = gc_new ();
1904
switch(from_addr->dest.addr.sa.sa_family)
1909
"TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
1910
print_link_socket_actual (from_addr, &gc),
1911
(int)from_addr->dest.addr.sa.sa_family,
1912
print_sockaddr (&info->lsa->remote, &gc));
1920
link_socket_bad_outgoing_addr (void)
1922
dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
1926
link_socket_current_remote (const struct link_socket_info *info)
1928
const struct link_socket_addr *lsa = info->lsa;
1931
* This logic supports "redirect-gateway" semantic, which
1932
* makes sense only for PF_INET routes over PF_INET endpoints
1934
* Maybe in the future consider PF_INET6 endpoints also ...
1935
* by now just ignore it
1938
if (lsa->actual.dest.addr.sa.sa_family != AF_INET)
1939
return IPV4_INVALID_ADDR;
1941
if (link_socket_actual_defined (&lsa->actual))
1942
return ntohl (lsa->actual.dest.addr.in4.sin_addr.s_addr);
1943
else if (addr_defined (&lsa->remote))
1944
return ntohl (lsa->remote.addr.in4.sin_addr.s_addr);
1950
* Return a status string describing socket state.
1953
socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
1955
struct buffer out = alloc_buf_gc (64, gc);
1958
if (rwflags & EVENT_READ)
1960
buf_printf (&out, "S%s",
1961
(s->rwflags_debug & EVENT_READ) ? "R" : "r");
1963
buf_printf (&out, "%s",
1964
overlapped_io_state_ascii (&s->reads));
1967
if (rwflags & EVENT_WRITE)
1969
buf_printf (&out, "S%s",
1970
(s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
1972
buf_printf (&out, "%s",
1973
overlapped_io_state_ascii (&s->writes));
1979
buf_printf (&out, "S?");
1985
* Stream buffer functions, used to packetize a TCP
1986
* stream connection.
1990
stream_buf_reset (struct stream_buf *sb)
1992
dmsg (D_STREAM_DEBUG, "STREAM: RESET");
1993
sb->residual_fully_formed = false;
1994
sb->buf = sb->buf_init;
1995
buf_reset (&sb->next);
2000
stream_buf_init (struct stream_buf *sb,
2002
const unsigned int sockflags,
2005
sb->buf_init = *buf;
2006
sb->maxlen = sb->buf_init.len;
2007
sb->buf_init.len = 0;
2008
sb->residual = alloc_buf (sb->maxlen);
2011
sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCPv4_SERVER))
2015
stream_buf_reset (sb);
2017
dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
2021
stream_buf_set_next (struct stream_buf *sb)
2023
/* set up 'next' for next i/o read */
2025
sb->next.offset = sb->buf.offset + sb->buf.len;
2026
sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
2027
dmsg (D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
2028
sb->buf.offset, sb->buf.len,
2029
sb->next.offset, sb->next.len,
2030
sb->len, sb->maxlen);
2031
ASSERT (sb->next.len > 0);
2032
ASSERT (buf_safe (&sb->buf, sb->next.len));
2036
stream_buf_get_final (struct stream_buf *sb, struct buffer *buf)
2038
dmsg (D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
2039
buf_defined (&sb->buf) ? sb->buf.len : -1);
2040
ASSERT (buf_defined (&sb->buf));
2045
stream_buf_get_next (struct stream_buf *sb, struct buffer *buf)
2047
dmsg (D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
2048
buf_defined (&sb->next) ? sb->next.len : -1);
2049
ASSERT (buf_defined (&sb->next));
2054
stream_buf_read_setup_dowork (struct link_socket* sock)
2056
if (sock->stream_buf.residual.len && !sock->stream_buf.residual_fully_formed)
2058
ASSERT (buf_copy (&sock->stream_buf.buf, &sock->stream_buf.residual));
2059
ASSERT (buf_init (&sock->stream_buf.residual, 0));
2060
sock->stream_buf.residual_fully_formed = stream_buf_added (&sock->stream_buf, 0);
2061
dmsg (D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
2062
sock->stream_buf.residual_fully_formed ? "YES" : "NO",
2063
sock->stream_buf.residual.len);
2066
if (!sock->stream_buf.residual_fully_formed)
2067
stream_buf_set_next (&sock->stream_buf);
2068
return !sock->stream_buf.residual_fully_formed;
2072
stream_buf_added (struct stream_buf *sb,
2075
dmsg (D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
2076
if (length_added > 0)
2077
sb->buf.len += length_added;
2079
/* if length unknown, see if we can get the length prefix from
2080
the head of the buffer */
2081
if (sb->len < 0 && sb->buf.len >= (int) sizeof (packet_size_type))
2083
packet_size_type net_size;
2086
if (sb->port_share_state == PS_ENABLED)
2088
if (!is_openvpn_protocol (&sb->buf))
2090
msg (D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
2091
sb->port_share_state = PS_FOREIGN;
2096
sb->port_share_state = PS_DISABLED;
2100
ASSERT (buf_read (&sb->buf, &net_size, sizeof (net_size)));
2101
sb->len = ntohps (net_size);
2103
if (sb->len < 1 || sb->len > sb->maxlen)
2105
msg (M_WARN, "WARNING: Bad encapsulated packet length from peer (%d), which must be > 0 and <= %d -- please ensure that --tun-mtu or --link-mtu is equal on both peers -- this condition could also indicate a possible active attack on the TCP link -- [Attempting restart...]", sb->len, sb->maxlen);
2106
stream_buf_reset (sb);
2112
/* is our incoming packet fully read? */
2113
if (sb->len > 0 && sb->buf.len >= sb->len)
2115
/* save any residual data that's part of the next packet */
2116
ASSERT (buf_init (&sb->residual, 0));
2117
if (sb->buf.len > sb->len)
2118
ASSERT (buf_copy_excess (&sb->residual, &sb->buf, sb->len));
2119
dmsg (D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
2121
BLEN (&sb->residual));
2126
dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
2127
stream_buf_set_next (sb);
2133
stream_buf_close (struct stream_buf* sb)
2135
free_buf (&sb->residual);
2139
* The listen event is a special event whose sole purpose is
2140
* to tell us that there's a new incoming connection on a
2141
* TCP socket, for use in server mode.
2144
socket_listen_event_handle (struct link_socket *s)
2147
if (!defined_net_event_win32 (&s->listen_handle))
2148
init_net_event_win32 (&s->listen_handle, FD_ACCEPT, s->sd, 0);
2149
return &s->listen_handle;
2156
* Format IP addresses in ascii
2160
print_sockaddr (const struct openvpn_sockaddr *addr, struct gc_arena *gc)
2162
return print_sockaddr_ex (addr, ":", PS_SHOW_PORT, gc);
2166
print_sockaddr_ex (const struct openvpn_sockaddr *addr,
2167
const char* separator,
2168
const unsigned int flags,
2169
struct gc_arena *gc)
2171
struct buffer out = alloc_buf_gc (128, gc);
2172
bool addr_is_defined;
2173
addr_is_defined = addr_defined (addr);
2174
if (!addr_is_defined) {
2177
switch(addr->addr.sa.sa_family)
2181
const int port= ntohs (addr->addr.in4.sin_port);
2182
buf_puts (&out, "[AF_INET]");
2184
if (!(flags & PS_DONT_SHOW_ADDR))
2185
buf_printf (&out, "%s", (addr_defined (addr) ? inet_ntoa (addr->addr.in4.sin_addr) : "[undef]"));
2187
if (((flags & PS_SHOW_PORT) || (addr_defined (addr) && (flags & PS_SHOW_PORT_IF_DEFINED)))
2191
buf_printf (&out, "%s", separator);
2193
buf_printf (&out, "%d", port);
2199
const int port= ntohs (addr->addr.in6.sin6_port);
2200
char buf[INET6_ADDRSTRLEN] = "";
2201
buf_puts (&out, "[AF_INET6]");
2202
if (addr_is_defined)
2204
getnameinfo(&addr->addr.sa, sizeof (struct sockaddr_in6),
2205
buf, sizeof (buf), NULL, 0, NI_NUMERICHOST);
2206
buf_puts (&out, buf);
2208
if (((flags & PS_SHOW_PORT) || (addr_is_defined && (flags & PS_SHOW_PORT_IF_DEFINED)))
2212
buf_puts (&out, separator);
2214
buf_printf (&out, "%d", port);
2225
print_link_socket_actual (const struct link_socket_actual *act, struct gc_arena *gc)
2227
return print_link_socket_actual_ex (act, ":", PS_SHOW_PORT|PS_SHOW_PKTINFO, gc);
2231
#define IF_NAMESIZE 16
2235
print_link_socket_actual_ex (const struct link_socket_actual *act,
2236
const char *separator,
2237
const unsigned int flags,
2238
struct gc_arena *gc)
2242
char ifname[IF_NAMESIZE] = "[undef]";
2243
struct buffer out = alloc_buf_gc (128, gc);
2244
buf_printf (&out, "%s", print_sockaddr_ex (&act->dest, separator, flags, gc));
2245
#if ENABLE_IP_PKTINFO
2246
if ((flags & PS_SHOW_PKTINFO) && addr_defined_ipi(act))
2248
switch(act->dest.addr.sa.sa_family)
2252
struct openvpn_sockaddr sa;
2254
sa.addr.in4.sin_family = AF_INET;
2256
sa.addr.in4.sin_addr = act->pi.in4.ipi_spec_dst;
2257
if_indextoname(act->pi.in4.ipi_ifindex, ifname);
2258
#elif defined(IP_RECVDSTADDR)
2259
sa.addr.in4.sin_addr = act->pi.in4;
2262
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2264
buf_printf (&out, " (via %s%%%s)",
2265
print_sockaddr_ex (&sa, separator, 0, gc),
2271
struct sockaddr_in6 sin6;
2272
char buf[INET6_ADDRSTRLEN] = "[undef]";
2274
sin6.sin6_family = AF_INET6;
2275
sin6.sin6_addr = act->pi.in6.ipi6_addr;
2276
if_indextoname(act->pi.in6.ipi6_ifindex, ifname);
2277
if (getnameinfo((struct sockaddr *)&sin6, sizeof (struct sockaddr_in6),
2278
buf, sizeof (buf), NULL, 0, NI_NUMERICHOST) == 0)
2279
buf_printf (&out, " (via %s%%%s)", buf, ifname);
2281
buf_printf (&out, " (via [getnameinfo() err]%%%s)", ifname);
2294
* Convert an in_addr_t in host byte order
2295
* to an ascii dotted quad.
2298
print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
2301
struct buffer out = alloc_buf_gc (64, gc);
2303
if (addr || !(flags & IA_EMPTY_IF_UNDEF))
2306
ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
2308
buf_printf (&out, "%s", inet_ntoa (ia));
2314
* Convert an in6_addr in host byte order
2315
* to an ascii representation of an IPv6 address
2318
print_in6_addr (struct in6_addr a6, unsigned int flags, struct gc_arena *gc)
2320
struct buffer out = alloc_buf_gc (64, gc);
2321
char tmp_out_buf[64]; /* inet_ntop wants pointer to buffer */
2323
if ( memcmp(&a6, &in6addr_any, sizeof(a6)) != 0 ||
2324
!(flags & IA_EMPTY_IF_UNDEF))
2326
inet_ntop (AF_INET6, &a6, tmp_out_buf, sizeof(tmp_out_buf)-1);
2327
buf_printf (&out, "%s", tmp_out_buf );
2333
# define UINT8_MAX 0xff
2336
/* add some offset to an ipv6 address
2337
* (add in steps of 8 bits, taking overflow into next round)
2339
struct in6_addr add_in6_addr( struct in6_addr base, uint32_t add )
2343
for( i=15; i>=0 && add > 0 ; i-- )
2346
register uint32_t h;
2348
h = (unsigned char) base.s6_addr[i];
2349
base.s6_addr[i] = (h+add) & UINT8_MAX;
2351
/* using explicit carry for the 8-bit additions will catch
2352
* 8-bit and(!) 32-bit overruns nicely
2354
carry = ((h & 0xff) + (add & 0xff)) >> 8;
2355
add = (add>>8) + carry;
2360
/* set environmental variables for ip/port in *addr */
2362
setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const unsigned int flags)
2367
switch(addr->addr.sa.sa_family)
2370
if (flags & SA_IP_PORT)
2371
openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
2373
openvpn_snprintf (name_buf, sizeof (name_buf), "%s", name_prefix);
2375
setenv_str (es, name_buf, inet_ntoa (addr->addr.in4.sin_addr));
2377
if ((flags & SA_IP_PORT) && addr->addr.in4.sin_port)
2379
openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
2380
setenv_int (es, name_buf, ntohs (addr->addr.in4.sin_port));
2384
openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip6", name_prefix);
2385
getnameinfo(&addr->addr.sa, sizeof (struct sockaddr_in6),
2386
buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
2387
setenv_str (es, name_buf, buf);
2389
if ((flags & SA_IP_PORT) && addr->addr.in6.sin6_port)
2391
openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
2392
setenv_int (es, name_buf, ntohs (addr->addr.in6.sin6_port));
2399
setenv_in_addr_t (struct env_set *es, const char *name_prefix, in_addr_t addr, const unsigned int flags)
2401
if (addr || !(flags & SA_SET_IF_NONZERO))
2403
struct openvpn_sockaddr si;
2405
si.addr.in4.sin_family = AF_INET;
2406
si.addr.in4.sin_addr.s_addr = htonl (addr);
2407
setenv_sockaddr (es, name_prefix, &si, flags);
2412
setenv_link_socket_actual (struct env_set *es,
2413
const char *name_prefix,
2414
const struct link_socket_actual *act,
2415
const unsigned int flags)
2417
setenv_sockaddr (es, name_prefix, &act->dest, flags);
2421
* Convert protocol names between index and ascii form.
2424
struct proto_names {
2425
const char *short_form;
2426
const char *display_form;
2429
unsigned short proto_af;
2432
/* Indexed by PROTO_x */
2433
static const struct proto_names proto_names[PROTO_N] = {
2434
{"proto-uninitialized", "proto-NONE",0,0, AF_UNSPEC},
2435
{"udp", "UDPv4",1,1, AF_INET},
2436
{"tcp-server", "TCPv4_SERVER",0,1, AF_INET},
2437
{"tcp-client", "TCPv4_CLIENT",0,1, AF_INET},
2438
{"tcp", "TCPv4",0,1, AF_INET},
2439
{"udp6" ,"UDPv6",1,1, AF_INET6},
2440
{"tcp6-server","TCPv6_SERVER",0,1, AF_INET6},
2441
{"tcp6-client","TCPv6_CLIENT",0,1, AF_INET6},
2442
{"tcp6" ,"TCPv6",0,1, AF_INET6},
2446
proto_is_net(int proto)
2448
if (proto < 0 || proto >= PROTO_N)
2450
return proto_names[proto].is_net;
2453
proto_is_dgram(int proto)
2455
if (proto < 0 || proto >= PROTO_N)
2457
return proto_names[proto].is_dgram;
2460
proto_is_udp(int proto)
2462
if (proto < 0 || proto >= PROTO_N)
2464
return proto_names[proto].is_dgram&&proto_names[proto].is_net;
2467
proto_is_tcp(int proto)
2469
if (proto < 0 || proto >= PROTO_N)
2471
return (!proto_names[proto].is_dgram)&&proto_names[proto].is_net;
2475
proto_sa_family(int proto)
2477
if (proto < 0 || proto >= PROTO_N)
2479
return proto_names[proto].proto_af;
2483
ascii2proto (const char* proto_name)
2486
ASSERT (PROTO_N == SIZE (proto_names));
2487
for (i = 0; i < PROTO_N; ++i)
2488
if (!strcmp (proto_name, proto_names[i].short_form))
2494
proto2ascii (int proto, bool display_form)
2496
ASSERT (PROTO_N == SIZE (proto_names));
2497
if (proto < 0 || proto >= PROTO_N)
2498
return "[unknown protocol]";
2499
else if (display_form)
2500
return proto_names[proto].display_form;
2502
return proto_names[proto].short_form;
2506
proto2ascii_all (struct gc_arena *gc)
2508
struct buffer out = alloc_buf_gc (256, gc);
2511
ASSERT (PROTO_N == SIZE (proto_names));
2512
for (i = 0; i < PROTO_N; ++i)
2515
buf_printf(&out, " ");
2516
buf_printf(&out, "[%s]", proto2ascii(i, false));
2522
addr_guess_family(int proto, const char *name)
2527
return proto_sa_family(proto); /* already stamped */
2531
struct addrinfo hints , *ai;
2534
hints.ai_flags = AI_NUMERICHOST;
2535
err = getaddrinfo(name, NULL, &hints, &ai);
2543
return AF_INET; /* default */
2546
addr_family_name (int af)
2550
case AF_INET: return "AF_INET";
2551
case AF_INET6: return "AF_INET6";
2557
* Given a local proto, return local proto
2558
* if !remote, or compatible remote proto
2561
* This is used for options compatibility
2564
* IPv6 and IPv4 protocols are comptabile but OpenVPN
2565
* has always sent UDPv4, TCPv4 over the wire. Keep these
2566
* strings for backward compatbility
2569
proto_remote (int proto, bool remote)
2571
ASSERT (proto >= 0 && proto < PROTO_N);
2576
case PROTO_TCPv4_SERVER: return PROTO_TCPv4_CLIENT;
2577
case PROTO_TCPv4_CLIENT: return PROTO_TCPv4_SERVER;
2578
case PROTO_TCPv6_SERVER: return PROTO_TCPv4_CLIENT;
2579
case PROTO_TCPv6_CLIENT: return PROTO_TCPv4_SERVER;
2580
case PROTO_UDPv6: return PROTO_UDPv4;
2587
case PROTO_TCPv6_SERVER: return PROTO_TCPv4_SERVER;
2588
case PROTO_TCPv6_CLIENT: return PROTO_TCPv4_CLIENT;
2589
case PROTO_UDPv6: return PROTO_UDPv4;
2596
* Bad incoming address lengths that differ from what
2597
* we expect are considered to be fatal errors.
2600
bad_address_length (int actual, int expected)
2602
msg (M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
2608
* Socket Read Routines
2612
link_socket_read_tcp (struct link_socket *sock,
2617
if (!sock->stream_buf.residual_fully_formed)
2620
len = socket_finalize (sock->sd, &sock->reads, buf, NULL);
2623
stream_buf_get_next (&sock->stream_buf, &frag);
2624
len = recv (sock->sd, BPTR (&frag), BLEN (&frag), MSG_NOSIGNAL);
2628
sock->stream_reset = true;
2630
return buf->len = len;
2633
if (sock->stream_buf.residual_fully_formed
2634
|| stream_buf_added (&sock->stream_buf, len)) /* packet complete? */
2636
stream_buf_get_final (&sock->stream_buf, buf);
2637
stream_buf_reset (&sock->stream_buf);
2641
return buf->len = 0; /* no error, but packet is still incomplete */
2646
#if ENABLE_IP_PKTINFO
2648
#pragma pack(1) /* needed to keep structure size consistent for 32 vs. 64-bit architectures */
2649
struct openvpn_in4_pktinfo
2651
struct cmsghdr cmsghdr;
2652
#ifdef HAVE_IN_PKTINFO
2653
struct in_pktinfo pi4;
2654
#elif defined(IP_RECVDSTADDR)
2658
struct openvpn_in6_pktinfo
2660
struct cmsghdr cmsghdr;
2661
struct in6_pktinfo pi6;
2664
union openvpn_pktinfo {
2665
struct openvpn_in4_pktinfo msgpi4;
2666
struct openvpn_in6_pktinfo msgpi6;
2671
link_socket_read_udp_posix_recvmsg (struct link_socket *sock,
2674
struct link_socket_actual *from)
2677
union openvpn_pktinfo opi;
2679
socklen_t fromlen = sizeof (from->dest.addr);
2681
iov.iov_base = BPTR (buf);
2682
iov.iov_len = maxsize;
2683
mesg.msg_iov = &iov;
2684
mesg.msg_iovlen = 1;
2685
mesg.msg_name = &from->dest.addr;
2686
mesg.msg_namelen = fromlen;
2687
mesg.msg_control = &opi;
2688
mesg.msg_controllen = sizeof opi;
2689
buf->len = recvmsg (sock->sd, &mesg, 0);
2692
struct cmsghdr *cmsg;
2693
fromlen = mesg.msg_namelen;
2694
cmsg = CMSG_FIRSTHDR (&mesg);
2696
&& CMSG_NXTHDR (&mesg, cmsg) == NULL
2698
&& cmsg->cmsg_level == SOL_IP
2699
&& cmsg->cmsg_type == IP_PKTINFO
2700
#elif defined(IP_RECVDSTADDR)
2701
&& cmsg->cmsg_level == IPPROTO_IP
2702
&& cmsg->cmsg_type == IP_RECVDSTADDR
2704
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2706
&& cmsg->cmsg_len >= sizeof (struct openvpn_in4_pktinfo))
2709
struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
2710
from->pi.in4.ipi_ifindex = pkti->ipi_ifindex;
2711
from->pi.in4.ipi_spec_dst = pkti->ipi_spec_dst;
2712
#elif defined(IP_RECVDSTADDR)
2713
from->pi.in4 = *(struct in_addr*) CMSG_DATA (cmsg);
2715
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2718
else if (cmsg != NULL
2719
&& CMSG_NXTHDR (&mesg, cmsg) == NULL
2720
&& cmsg->cmsg_level == IPPROTO_IPV6
2721
&& cmsg->cmsg_type == IPV6_PKTINFO
2722
&& cmsg->cmsg_len >= sizeof (struct openvpn_in6_pktinfo))
2724
struct in6_pktinfo *pkti6 = (struct in6_pktinfo *) CMSG_DATA (cmsg);
2725
from->pi.in6.ipi6_ifindex = pkti6->ipi6_ifindex;
2726
from->pi.in6.ipi6_addr = pkti6->ipi6_addr;
2734
link_socket_read_udp_posix (struct link_socket *sock,
2737
struct link_socket_actual *from)
2739
socklen_t fromlen = sizeof (from->dest.addr);
2740
socklen_t expectedlen = af_addr_size(proto_sa_family(sock->info.proto));
2741
addr_zero_host(&from->dest);
2742
ASSERT (buf_safe (buf, maxsize));
2743
#if ENABLE_IP_PKTINFO
2744
/* Both PROTO_UDPv4 and PROTO_UDPv6 */
2745
if (proto_is_udp(sock->info.proto) && sock->sockflags & SF_USE_IP_PKTINFO)
2746
fromlen = link_socket_read_udp_posix_recvmsg (sock, buf, maxsize, from);
2749
buf->len = recvfrom (sock->sd, BPTR (buf), maxsize, 0,
2750
&from->dest.addr.sa, &fromlen);
2751
if (buf->len >= 0 && expectedlen && fromlen != expectedlen)
2752
bad_address_length (fromlen, expectedlen);
2759
* Socket Write Routines
2763
link_socket_write_tcp (struct link_socket *sock,
2765
struct link_socket_actual *to)
2767
packet_size_type len = BLEN (buf);
2768
dmsg (D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
2769
ASSERT (len <= sock->stream_buf.maxlen);
2771
ASSERT (buf_write_prepend (buf, &len, sizeof (len)));
2773
return link_socket_write_win32 (sock, buf, to);
2775
return link_socket_write_tcp_posix (sock, buf, to);
2779
#if ENABLE_IP_PKTINFO
2782
link_socket_write_udp_posix_sendmsg (struct link_socket *sock,
2784
struct link_socket_actual *to)
2788
struct cmsghdr *cmsg;
2790
iov.iov_base = BPTR (buf);
2791
iov.iov_len = BLEN (buf);
2792
mesg.msg_iov = &iov;
2793
mesg.msg_iovlen = 1;
2794
switch (sock->info.lsa->remote.addr.sa.sa_family)
2798
struct openvpn_in4_pktinfo msgpi4;
2799
mesg.msg_name = &to->dest.addr.sa;
2800
mesg.msg_namelen = sizeof (struct sockaddr_in);
2801
mesg.msg_control = &msgpi4;
2802
mesg.msg_controllen = sizeof msgpi4;
2804
cmsg = CMSG_FIRSTHDR (&mesg);
2805
cmsg->cmsg_len = sizeof (struct openvpn_in4_pktinfo);
2806
#ifdef HAVE_IN_PKTINFO
2807
cmsg->cmsg_level = SOL_IP;
2808
cmsg->cmsg_type = IP_PKTINFO;
2810
struct in_pktinfo *pkti;
2811
pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
2812
pkti->ipi_ifindex = to->pi.in4.ipi_ifindex;
2813
pkti->ipi_spec_dst = to->pi.in4.ipi_spec_dst;
2814
pkti->ipi_addr.s_addr = 0;
2816
#elif defined(IP_RECVDSTADDR)
2817
cmsg->cmsg_level = IPPROTO_IP;
2818
cmsg->cmsg_type = IP_RECVDSTADDR;
2819
*(struct in_addr *) CMSG_DATA (cmsg) = to->pi.in4;
2821
#error ENABLE_IP_PKTINFO is set without IP_PKTINFO xor IP_RECVDSTADDR (fix syshead.h)
2827
struct openvpn_in6_pktinfo msgpi6;
2828
struct in6_pktinfo *pkti6;
2829
mesg.msg_name = &to->dest.addr.sa;
2830
mesg.msg_namelen = sizeof (struct sockaddr_in6);
2831
mesg.msg_control = &msgpi6;
2832
mesg.msg_controllen = sizeof msgpi6;
2834
cmsg = CMSG_FIRSTHDR (&mesg);
2835
cmsg->cmsg_len = sizeof (struct openvpn_in6_pktinfo);
2836
cmsg->cmsg_level = IPPROTO_IPV6;
2837
cmsg->cmsg_type = IPV6_PKTINFO;
2838
pkti6 = (struct in6_pktinfo *) CMSG_DATA (cmsg);
2839
pkti6->ipi6_ifindex = to->pi.in6.ipi6_ifindex;
2840
pkti6->ipi6_addr = to->pi.in6.ipi6_addr;
2845
return sendmsg (sock->sd, &mesg, 0);
2851
* Win32 overlapped socket I/O functions.
2857
socket_recv_queue (struct link_socket *sock, int maxsize)
2859
if (sock->reads.iostate == IOSTATE_INITIAL)
2864
/* reset buf to its initial state */
2865
if (proto_is_udp(sock->info.proto))
2867
sock->reads.buf = sock->reads.buf_init;
2869
else if (proto_is_tcp(sock->info.proto))
2871
stream_buf_get_next (&sock->stream_buf, &sock->reads.buf);
2878
/* Win32 docs say it's okay to allocate the wsabuf on the stack */
2879
wsabuf[0].buf = BPTR (&sock->reads.buf);
2880
wsabuf[0].len = maxsize ? maxsize : BLEN (&sock->reads.buf);
2882
/* check for buffer overflow */
2883
ASSERT (wsabuf[0].len <= BLEN (&sock->reads.buf));
2885
/* the overlapped read will signal this event on I/O completion */
2886
ASSERT (ResetEvent (sock->reads.overlapped.hEvent));
2887
sock->reads.flags = 0;
2889
if (proto_is_udp(sock->info.proto))
2891
sock->reads.addr_defined = true;
2892
if (sock->info.proto == PROTO_UDPv6)
2893
sock->reads.addrlen = sizeof (sock->reads.addr6);
2895
sock->reads.addrlen = sizeof (sock->reads.addr);
2896
status = WSARecvFrom(
2902
(struct sockaddr *) &sock->reads.addr,
2903
&sock->reads.addrlen,
2904
&sock->reads.overlapped,
2907
else if (proto_is_tcp(sock->info.proto))
2909
sock->reads.addr_defined = false;
2916
&sock->reads.overlapped,
2925
if (!status) /* operation completed immediately? */
2927
int addrlen = af_addr_size(sock->info.lsa->local.addr.sa.sa_family);
2928
if (sock->reads.addr_defined && sock->reads.addrlen != addrlen)
2929
bad_address_length (sock->reads.addrlen, addrlen);
2930
sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
2932
/* since we got an immediate return, we must signal the event object ourselves */
2933
ASSERT (SetEvent (sock->reads.overlapped.hEvent));
2934
sock->reads.status = 0;
2936
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
2937
(int) wsabuf[0].len,
2938
(int) sock->reads.size);
2942
status = WSAGetLastError ();
2943
if (status == WSA_IO_PENDING) /* operation queued? */
2945
sock->reads.iostate = IOSTATE_QUEUED;
2946
sock->reads.status = status;
2947
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
2948
(int) wsabuf[0].len);
2950
else /* error occurred */
2952
struct gc_arena gc = gc_new ();
2953
ASSERT (SetEvent (sock->reads.overlapped.hEvent));
2954
sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
2955
sock->reads.status = status;
2956
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
2957
(int) wsabuf[0].len,
2958
strerror_win32 (status, &gc));
2963
return sock->reads.iostate;
2967
socket_send_queue (struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
2969
if (sock->writes.iostate == IOSTATE_INITIAL)
2974
/* make a private copy of buf */
2975
sock->writes.buf = sock->writes.buf_init;
2976
sock->writes.buf.len = 0;
2977
ASSERT (buf_copy (&sock->writes.buf, buf));
2979
/* Win32 docs say it's okay to allocate the wsabuf on the stack */
2980
wsabuf[0].buf = BPTR (&sock->writes.buf);
2981
wsabuf[0].len = BLEN (&sock->writes.buf);
2983
/* the overlapped write will signal this event on I/O completion */
2984
ASSERT (ResetEvent (sock->writes.overlapped.hEvent));
2985
sock->writes.flags = 0;
2987
if (proto_is_udp(sock->info.proto))
2989
/* set destination address for UDP writes */
2990
sock->writes.addr_defined = true;
2991
if (sock->info.proto == PROTO_UDPv6)
2993
sock->writes.addr6 = to->dest.addr.in6;
2994
sock->writes.addrlen = sizeof (sock->writes.addr6);
2998
sock->writes.addr = to->dest.addr.in4;
2999
sock->writes.addrlen = sizeof (sock->writes.addr);
3008
(struct sockaddr *) &sock->writes.addr,
3009
sock->writes.addrlen,
3010
&sock->writes.overlapped,
3013
else if (proto_is_tcp(sock->info.proto))
3015
/* destination address for TCP writes was established on connection initiation */
3016
sock->writes.addr_defined = false;
3024
&sock->writes.overlapped,
3033
if (!status) /* operation completed immediately? */
3035
sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
3037
/* since we got an immediate return, we must signal the event object ourselves */
3038
ASSERT (SetEvent (sock->writes.overlapped.hEvent));
3040
sock->writes.status = 0;
3042
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
3043
(int) wsabuf[0].len,
3044
(int) sock->writes.size);
3048
status = WSAGetLastError ();
3049
if (status == WSA_IO_PENDING) /* operation queued? */
3051
sock->writes.iostate = IOSTATE_QUEUED;
3052
sock->writes.status = status;
3053
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
3054
(int) wsabuf[0].len);
3056
else /* error occurred */
3058
struct gc_arena gc = gc_new ();
3059
ASSERT (SetEvent (sock->writes.overlapped.hEvent));
3060
sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
3061
sock->writes.status = status;
3063
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
3064
(int) wsabuf[0].len,
3065
strerror_win32 (status, &gc));
3071
return sock->writes.iostate;
3075
socket_finalize (SOCKET s,
3076
struct overlapped_io *io,
3078
struct link_socket_actual *from)
3083
switch (io->iostate)
3085
case IOSTATE_QUEUED:
3086
status = WSAGetOverlappedResult(
3095
/* successful return for a queued operation */
3099
io->iostate = IOSTATE_INITIAL;
3100
ASSERT (ResetEvent (io->overlapped.hEvent));
3102
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
3106
/* error during a queued operation */
3108
if (WSAGetLastError() != WSA_IO_INCOMPLETE)
3110
/* if no error (i.e. just not finished yet), then DON'T execute this code */
3111
io->iostate = IOSTATE_INITIAL;
3112
ASSERT (ResetEvent (io->overlapped.hEvent));
3113
msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion error");
3118
case IOSTATE_IMMEDIATE_RETURN:
3119
io->iostate = IOSTATE_INITIAL;
3120
ASSERT (ResetEvent (io->overlapped.hEvent));
3123
/* error return for a non-queued operation */
3124
WSASetLastError (io->status);
3126
msg (D_WIN32_IO | M_ERRNO, "WIN32 I/O: Socket Completion non-queued error");
3130
/* successful return for a non-queued operation */
3134
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
3138
case IOSTATE_INITIAL: /* were we called without proper queueing? */
3139
WSASetLastError (WSAEINVAL);
3141
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
3148
/* return from address if requested */
3151
if (ret >= 0 && io->addr_defined)
3153
/* TODO(jjo): streamline this mess */
3154
/* in this func we dont have relevant info about the PF_ of this
3155
* endpoint, as link_socket_actual will be zero for the 1st received packet
3157
* Test for inets PF_ possible sizes
3159
switch (io->addrlen)
3161
case sizeof(struct sockaddr_in):
3162
case sizeof(struct sockaddr_in6):
3163
/* TODO(jjo): for some reason (?) I'm getting 24,28 for AF_INET6
3165
case sizeof(struct sockaddr_in6)-4:
3168
bad_address_length (io->addrlen, af_addr_size(io->addr.sin_family));
3171
switch (io->addr.sin_family)
3174
from->dest.addr.in4 = io->addr;
3177
from->dest.addr.in6 = io->addr6;
3182
CLEAR (from->dest.addr);
3193
* Socket event notification
3197
socket_set (struct link_socket *s,
3198
struct event_set *es,
3199
unsigned int rwflags,
3201
unsigned int *persistent)
3205
if ((rwflags & EVENT_READ) && !stream_buf_read_setup (s))
3207
ASSERT (!persistent);
3208
rwflags &= ~EVENT_READ;
3212
if (rwflags & EVENT_READ)
3213
socket_recv_queue (s, 0);
3216
/* if persistent is defined, call event_ctl only if rwflags has changed since last call */
3217
if (!persistent || *persistent != rwflags)
3219
event_ctl (es, socket_event_handle (s), rwflags, arg);
3221
*persistent = rwflags;
3224
s->rwflags_debug = rwflags;
3230
sd_close (socket_descriptor_t *sd)
3232
if (sd && socket_defined (*sd))
3234
openvpn_close_socket (*sd);
3235
*sd = SOCKET_UNDEFINED;
3239
#if UNIX_SOCK_SUPPORT
3242
* code for unix domain sockets
3246
sockaddr_unix_name (const struct sockaddr_un *local, const char *null)
3248
if (local && local->sun_family == PF_UNIX)
3249
return local->sun_path;
3255
create_socket_unix (void)
3257
socket_descriptor_t sd;
3259
if ((sd = socket (PF_UNIX, SOCK_STREAM, 0)) < 0)
3260
msg (M_ERR, "Cannot create unix domain socket");
3265
socket_bind_unix (socket_descriptor_t sd,
3266
struct sockaddr_un *local,
3269
struct gc_arena gc = gc_new ();
3272
const mode_t orig_umask = umask (0);
3275
if (bind (sd, (struct sockaddr *) local, sizeof (struct sockaddr_un)))
3277
const int errnum = openvpn_errno ();
3278
msg (M_FATAL, "%s: Socket bind[%d] failed on unix domain socket %s: %s",
3281
sockaddr_unix_name (local, "NULL"),
3282
strerror_ts (errnum, &gc));
3293
socket_accept_unix (socket_descriptor_t sd,
3294
struct sockaddr_un *remote)
3296
socklen_t remote_len = sizeof (struct sockaddr_un);
3297
socket_descriptor_t ret;
3300
ret = accept (sd, (struct sockaddr *) remote, &remote_len);
3305
socket_connect_unix (socket_descriptor_t sd,
3306
struct sockaddr_un *remote)
3308
int status = connect (sd, (struct sockaddr *) remote, sizeof (struct sockaddr_un));
3310
status = openvpn_errno ();
3315
sockaddr_unix_init (struct sockaddr_un *local, const char *path)
3317
local->sun_family = PF_UNIX;
3318
strncpynt (local->sun_path, path, sizeof (local->sun_path));
3322
socket_delete_unix (const struct sockaddr_un *local)
3324
const char *name = sockaddr_unix_name (local, NULL);
3326
if (name && strlen (name))
3332
unix_socket_get_peer_uid_gid (const socket_descriptor_t sd, int *uid, int *gid)
3334
#ifdef HAVE_GETPEEREID
3337
if (getpeereid (sd, &u, &g) == -1)
3344
#elif defined(SO_PEERCRED)
3345
struct ucred peercred;
3346
socklen_t so_len = sizeof(peercred);
3347
if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
3350
*uid = peercred.uid;
3352
*gid = peercred.gid;