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
38
const int proto_overhead[] = { /* indexed by PROTO_x */
46
* Convert sockflags/getaddr_flags into getaddr_flags
49
sf2gaf(const unsigned int getaddr_flags,
50
const unsigned int sockflags)
52
if (sockflags & SF_HOST_RANDOMIZE)
53
return getaddr_flags | GETADDR_RANDOMIZE;
59
* Functions related to the translation of DNS names to IP addresses.
63
h_errno_msg(int h_errno_err)
68
return "[HOST_NOT_FOUND] The specified host is unknown.";
70
return "[NO_DATA] The requested name is valid but does not have an IP address.";
72
return "[NO_RECOVERY] A non-recoverable name server error occurred.";
74
return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
76
return "[unknown h_errno value]";
80
* Translate IP addr or hostname to in_addr_t.
81
* If resolve error, try again for
82
* resolve_retry_seconds seconds.
85
getaddr (unsigned int flags,
87
int resolve_retry_seconds,
89
volatile int *signal_received)
91
return getaddr_multi (flags, hostname, resolve_retry_seconds, succeeded, signal_received, NULL);
95
getaddr_multi (unsigned int flags,
97
int resolve_retry_seconds,
99
volatile int *signal_received,
100
struct resolve_list *reslist)
105
int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
106
struct gc_arena gc = gc_new ();
111
if (flags & GETADDR_RANDOMIZE)
112
hostname = hostname_randomize(hostname, &gc);
114
if (flags & GETADDR_MSG_VIRT_OUT)
115
msglevel |= M_MSG_VIRT_OUT;
121
if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
123
signal_received = &sigrec;
125
status = openvpn_inet_aton (hostname, &ia); /* parse ascii IP address */
127
if (status != OIA_IP) /* parse as IP address failed? */
129
const int fail_wait_interval = 5; /* seconds */
130
int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 : (resolve_retry_seconds / fail_wait_interval);
137
fmt = "RESOLVE: Cannot resolve host address: %s: %s";
138
if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
139
&& !resolve_retry_seconds)
140
fmt = "RESOLVE: Cannot resolve host address: %s: %s (I would have retried this name query if you had specified the --resolv-retry option.)";
142
if (!(flags & GETADDR_RESOLVE) || status == OIA_ERROR)
144
msg (msglevel, "RESOLVE: Cannot parse IP address: %s", hostname);
148
#ifdef ENABLE_MANAGEMENT
149
if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
152
management_set_state (management,
153
OPENVPN_STATE_RESOLVE,
165
/* try hostname lookup */
166
#if defined(HAVE_RES_INIT)
169
h = gethostbyname (hostname);
173
get_signal (signal_received);
174
if (*signal_received) /* were we interrupted by a signal? */
177
if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
179
msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
180
*signal_received = 0;
191
/* resolve lookup failed, should we
195
if (resolve_retries > 0)
196
level = D_RESOLVE_ERRORS;
201
h_errno_msg (h_errno));
203
if (--resolve_retries <= 0)
206
openvpn_sleep (fail_wait_interval);
209
if (h->h_addrtype != AF_INET || h->h_length != 4)
211
msg (msglevel, "RESOLVE: Sorry, but we only accept IPv4 DNS names: %s", hostname);
215
ia.s_addr = *(in_addr_t *) (h->h_addr_list[0]);
219
if (h->h_addr_list[1]) /* more than one address returned */
223
/* count address list */
224
while (h->h_addr_list[n])
228
msg (D_RESOLVE_ERRORS, "RESOLVE: NOTE: %s resolves to %d addresses",
232
/* choose address randomly, for basic load-balancing capability */
233
/*ia.s_addr = *(in_addr_t *) (h->h_addr_list[get_random () % n]);*/
235
/* choose first address */
236
ia.s_addr = *(in_addr_t *) (h->h_addr_list[0]);
241
for (i = 0; i < n && i < SIZE(reslist->data); ++i)
243
in_addr_t a = *(in_addr_t *) (h->h_addr_list[i]);
244
if (flags & GETADDR_HOST_ORDER)
246
reslist->data[i] = a;
253
/* hostname resolve succeeded */
259
/* IP address parse succeeded */
265
if (signal_received && *signal_received)
268
if (flags & GETADDR_FATAL_ON_SIGNAL)
270
else if (flags & GETADDR_WARN_ON_SIGNAL)
272
msg (level, "RESOLVE: signal received during DNS resolution attempt");
276
return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
280
* We do our own inet_aton because the glibc function
281
* isn't very good about error checking.
284
openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
286
unsigned int a, b, c, d;
289
if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
291
if (a < 256 && b < 256 && c < 256 && d < 256)
293
addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
294
return OIA_IP; /* good dotted quad */
297
if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
298
return OIA_ERROR; /* probably a badly formatted dotted quad */
300
return OIA_HOSTNAME; /* probably a hostname */
304
ip_addr_dotted_quad_safe (const char *dotted_quad)
306
/* verify non-NULL */
310
/* verify length is within limits */
311
if (strlen (dotted_quad) > 15)
314
/* verify that all chars are either numeric or '.' and that no numeric
315
substring is greater than 3 chars */
318
const char *p = dotted_quad;
323
if (c >= '0' && c <= '9')
338
/* verify that string will convert to IP address */
341
return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
346
dns_addr_safe (const char *addr)
350
const size_t len = strlen (addr);
351
return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
358
ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
360
if (ip_addr_dotted_quad_safe (addr))
363
return dns_addr_safe (addr);
369
mac_addr_safe (const char *mac_addr)
371
/* verify non-NULL */
375
/* verify length is within limits */
376
if (strlen (mac_addr) > 17)
379
/* verify that all chars are either alphanumeric or ':' and that no
380
alphanumeric substring is greater than 2 chars */
383
const char *p = mac_addr;
388
if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
403
/* error-checking is left to script invoked in lladdr.c */
408
update_remote (const char* host,
409
struct openvpn_sockaddr *addr,
411
const unsigned int sockflags)
415
const in_addr_t new_addr = getaddr (
416
sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags),
421
if (new_addr && addr->sa.sin_addr.s_addr != new_addr)
423
addr->sa.sin_addr.s_addr = new_addr;
430
socket_get_sndbuf (int sd)
432
#if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
437
if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
438
&& len == sizeof (val))
445
socket_set_sndbuf (int sd, int size)
447
#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
448
if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
450
if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
452
msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
459
socket_get_rcvbuf (int sd)
461
#if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
466
if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
467
&& len == sizeof (val))
474
socket_set_rcvbuf (int sd, int size)
476
#if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
477
if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
479
if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
481
msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
490
socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
494
const int sndbuf_old = socket_get_sndbuf (fd);
495
const int rcvbuf_old = socket_get_rcvbuf (fd);
498
socket_set_sndbuf (fd, sbs->sndbuf);
501
socket_set_rcvbuf (fd, sbs->rcvbuf);
503
msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
505
socket_get_rcvbuf (fd),
507
socket_get_sndbuf (fd));
512
* Set other socket options
516
socket_set_tcp_nodelay (int sd, int state)
518
#if defined(WIN32) || (defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY))
519
if (setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof (state)) != 0)
521
msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
526
dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
530
msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
536
socket_set_flags (int sd, unsigned int sockflags)
538
if (sockflags & SF_TCP_NODELAY)
539
return socket_set_tcp_nodelay (sd, 1);
545
link_socket_update_flags (struct link_socket *ls, unsigned int sockflags)
547
if (ls && socket_defined (ls->sd))
548
return socket_set_flags (ls->sd, ls->sockflags = sockflags);
554
link_socket_update_buffer_sizes (struct link_socket *ls, int rcvbuf, int sndbuf)
556
if (ls && socket_defined (ls->sd))
558
ls->socket_buffer_sizes.sndbuf = sndbuf;
559
ls->socket_buffer_sizes.rcvbuf = rcvbuf;
560
socket_set_buffers (ls->sd, &ls->socket_buffer_sizes);
565
* SOCKET INITALIZATION CODE.
566
* Create a TCP/UDP socket
570
create_socket_tcp (void)
572
socket_descriptor_t sd;
574
if ((sd = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
575
msg (M_SOCKERR, "Cannot create TCP socket");
577
#ifndef WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
578
/* set SO_REUSEADDR on socket */
581
if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
582
(void *) &on, sizeof (on)) < 0)
583
msg (M_SOCKERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
588
/* set socket linger options */
590
struct linger linger;
593
if (setsockopt (sd, SOL_SOCKET, SO_LINGER,
594
(void *) &linger, sizeof (linger)) < 0)
595
msg (M_SOCKERR, "TCP: Cannot setsockopt SO_LINGER on TCP socket");
602
static socket_descriptor_t
603
create_socket_udp (const unsigned int flags)
605
socket_descriptor_t sd;
607
if ((sd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
608
msg (M_SOCKERR, "UDP: Cannot create UDP socket");
609
#if ENABLE_IP_PKTINFO
610
else if (flags & SF_USE_IP_PKTINFO)
613
setsockopt (sd, SOL_IP, IP_PKTINFO, (void*)&pad, sizeof(pad));
620
create_socket (struct link_socket *sock)
623
if (sock->info.proto == PROTO_UDPv4)
625
sock->sd = create_socket_udp (sock->sockflags);
628
if (sock->socks_proxy)
629
sock->ctrl_sd = create_socket_tcp ();
632
else if (sock->info.proto == PROTO_TCPv4_SERVER
633
|| sock->info.proto == PROTO_TCPv4_CLIENT)
635
sock->sd = create_socket_tcp ();
644
* Functions used for establishing a TCP stream connection.
648
socket_do_listen (socket_descriptor_t sd,
649
const struct openvpn_sockaddr *local,
651
bool do_set_nonblock)
653
struct gc_arena gc = gc_new ();
656
msg (M_INFO, "Listening for incoming TCP connection on %s",
657
print_sockaddr (local, &gc));
659
msg (M_SOCKERR, "TCP: listen() failed");
662
/* set socket to non-blocking mode */
670
socket_do_accept (socket_descriptor_t sd,
671
struct link_socket_actual *act,
674
socklen_t remote_len = sizeof (act->dest.sa);
675
socket_descriptor_t new_sd = SOCKET_UNDEFINED;
679
#ifdef HAVE_GETPEERNAME
682
new_sd = getpeername (sd, (struct sockaddr *) &act->dest.sa, &remote_len);
684
if (!socket_defined (new_sd))
685
msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: getpeername() failed");
691
msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
695
new_sd = accept (sd, (struct sockaddr *) &act->dest.sa, &remote_len);
698
#if 0 /* For debugging only, test the effect of accept() failures */
707
if (!socket_defined (new_sd))
709
msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: accept(%d) failed", sd);
711
else if (remote_len != sizeof (act->dest.sa))
713
msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
714
openvpn_close_socket (new_sd);
715
new_sd = SOCKET_UNDEFINED;
721
tcp_connection_established (const struct link_socket_actual *act)
723
struct gc_arena gc = gc_new ();
724
msg (M_INFO, "TCP connection established with %s",
725
print_link_socket_actual (act, &gc));
730
socket_listen_accept (socket_descriptor_t sd,
731
struct link_socket_actual *act,
732
const char *remote_dynamic,
733
bool *remote_changed,
734
const struct openvpn_sockaddr *local,
737
volatile int *signal_received)
739
struct gc_arena gc = gc_new ();
740
/* struct openvpn_sockaddr *remote = &act->dest; */
741
struct openvpn_sockaddr remote_verify = act->dest;
742
int new_sd = SOCKET_UNDEFINED;
745
socket_do_listen (sd, local, do_listen, true);
758
status = select (sd + 1, &reads, NULL, NULL, &tv);
760
get_signal (signal_received);
761
if (*signal_received)
768
msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: select() failed");
776
new_sd = socket_do_accept (sd, act, nowait);
778
if (socket_defined (new_sd))
780
update_remote (remote_dynamic, &remote_verify, remote_changed, 0);
781
if (addr_defined (&remote_verify)
782
&& !addr_match (&remote_verify, &act->dest))
785
"TCP NOTE: Rejected connection attempt from %s due to --remote setting",
786
print_link_socket_actual (act, &gc));
787
if (openvpn_close_socket (new_sd))
788
msg (M_SOCKERR, "TCP: close socket failed (new_sd)");
796
if (!nowait && openvpn_close_socket (sd))
797
msg (M_SOCKERR, "TCP: close socket failed (sd)");
799
tcp_connection_established (act);
806
socket_bind (socket_descriptor_t sd,
807
struct openvpn_sockaddr *local,
810
struct gc_arena gc = gc_new ();
812
if (bind (sd, (struct sockaddr *) &local->sa, sizeof (local->sa)))
814
const int errnum = openvpn_errno_socket ();
815
msg (M_FATAL, "%s: Socket bind failed on local address %s: %s",
817
print_sockaddr (local, &gc),
818
strerror_ts (errnum, &gc));
824
openvpn_connect (socket_descriptor_t sd,
825
struct openvpn_sockaddr *remote,
827
volatile int *signal_received)
831
#ifdef CONNECT_NONBLOCK
833
status = connect (sd, (struct sockaddr *) &remote->sa, sizeof (remote->sa));
835
status = openvpn_errno_socket ();
836
if (status == EINPROGRESS)
844
FD_SET (sd, &writes);
848
status = select (sd + 1, NULL, &writes, NULL, &tv);
852
get_signal (signal_received);
853
if (*signal_received)
861
status = openvpn_errno_socket ();
866
if (--connect_timeout < 0)
881
if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
882
&& len == sizeof (val))
885
status = openvpn_errno_socket ();
891
status = connect (sd, (struct sockaddr *) &remote->sa, sizeof (remote->sa));
893
status = openvpn_errno_socket ();
900
socket_connect (socket_descriptor_t *sd,
901
struct openvpn_sockaddr *local,
903
struct openvpn_sockaddr *remote,
904
const bool connection_profiles_defined,
905
const char *remote_dynamic,
906
bool *remote_changed,
907
const int connect_retry_seconds,
908
const int connect_timeout,
909
const int connect_retry_max,
910
const unsigned int sockflags,
911
volatile int *signal_received)
913
struct gc_arena gc = gc_new ();
916
#ifdef CONNECT_NONBLOCK
917
msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]",
918
print_sockaddr (remote, &gc));
920
msg (M_INFO, "Attempting to establish TCP connection with %s",
921
print_sockaddr (remote, &gc));
928
#ifdef ENABLE_MANAGEMENT
930
management_set_state (management,
931
OPENVPN_STATE_TCP_CONNECT,
937
status = openvpn_connect (*sd, remote, connect_timeout, signal_received);
939
get_signal (signal_received);
940
if (*signal_received)
947
"TCP: connect to %s failed, will try again in %d seconds: %s",
948
print_sockaddr (remote, &gc),
949
connect_retry_seconds,
950
strerror_ts (status, &gc));
954
openvpn_close_socket (*sd);
955
*sd = SOCKET_UNDEFINED;
957
if ((connect_retry_max > 0 && ++retry >= connect_retry_max) || connection_profiles_defined)
959
*signal_received = SIGUSR1;
963
openvpn_sleep (connect_retry_seconds);
965
get_signal (signal_received);
966
if (*signal_received)
969
*sd = create_socket_tcp ();
971
socket_bind (*sd, local, "TCP Client");
972
update_remote (remote_dynamic, remote, remote_changed, sockflags);
975
msg (M_INFO, "TCP connection established with %s",
976
print_sockaddr (remote, &gc));
982
/* For stream protocols, allocate a buffer to build up packet.
983
Called after frame has been finalized. */
986
socket_frame_init (const struct frame *frame, struct link_socket *sock)
989
overlapped_io_init (&sock->reads, frame, FALSE, false);
990
overlapped_io_init (&sock->writes, frame, TRUE, false);
991
sock->rw_handle.read = sock->reads.overlapped.hEvent;
992
sock->rw_handle.write = sock->writes.overlapped.hEvent;
995
if (link_socket_connection_oriented (sock))
998
stream_buf_init (&sock->stream_buf,
999
&sock->reads.buf_init,
1003
alloc_buf_sock_tun (&sock->stream_buf_data,
1006
FRAME_HEADROOM_MARKER_READ_STREAM);
1008
stream_buf_init (&sock->stream_buf,
1009
&sock->stream_buf_data,
1017
* Adjust frame structure based on a Path MTU value given
1021
frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
1023
frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
1027
resolve_bind_local (struct link_socket *sock)
1029
struct gc_arena gc = gc_new ();
1031
/* resolve local address if undefined */
1032
if (!addr_defined (&sock->info.lsa->local))
1034
sock->info.lsa->local.sa.sin_family = AF_INET;
1035
sock->info.lsa->local.sa.sin_addr.s_addr =
1036
(sock->local_host ? getaddr (GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
1041
: htonl (INADDR_ANY));
1042
sock->info.lsa->local.sa.sin_port = htons (sock->local_port);
1045
/* bind to local address/port */
1046
if (sock->bind_local)
1049
if (sock->socks_proxy && sock->info.proto == PROTO_UDPv4)
1050
socket_bind (sock->ctrl_sd, &sock->info.lsa->local, "SOCKS");
1053
socket_bind (sock->sd, &sock->info.lsa->local, "TCP/UDP");
1059
resolve_remote (struct link_socket *sock,
1061
const char **remote_dynamic,
1062
volatile int *signal_received)
1064
struct gc_arena gc = gc_new ();
1066
if (!sock->did_resolve_remote)
1068
/* resolve remote address if undefined */
1069
if (!addr_defined (&sock->info.lsa->remote))
1071
sock->info.lsa->remote.sa.sin_family = AF_INET;
1072
sock->info.lsa->remote.sa.sin_addr.s_addr = 0;
1074
if (sock->remote_host)
1076
unsigned int flags = sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
1078
bool status = false;
1080
if (sock->connection_profiles_defined && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
1083
flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
1086
else if (phase == 1)
1088
if (sock->resolve_retry_seconds)
1094
flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
1098
else if (phase == 2)
1100
if (sock->resolve_retry_seconds)
1102
flags |= GETADDR_FATAL;
1103
retry = sock->resolve_retry_seconds;
1115
sock->info.lsa->remote.sa.sin_addr.s_addr = getaddr (
1122
dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1126
signal_received ? *signal_received : -1,
1129
if (signal_received)
1131
if (*signal_received)
1136
if (signal_received)
1137
*signal_received = SIGUSR1;
1142
sock->info.lsa->remote.sa.sin_port = htons (sock->remote_port);
1145
/* should we re-use previous active remote address? */
1146
if (link_socket_actual_defined (&sock->info.lsa->actual))
1148
msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
1149
print_link_socket_actual (&sock->info.lsa->actual, &gc));
1151
*remote_dynamic = NULL;
1155
CLEAR (sock->info.lsa->actual);
1156
sock->info.lsa->actual.dest = sock->info.lsa->remote;
1159
/* remember that we finished */
1160
sock->did_resolve_remote = true;
1167
struct link_socket *
1168
link_socket_new (void)
1170
struct link_socket *sock;
1172
ALLOC_OBJ_CLEAR (sock, struct link_socket);
1173
sock->sd = SOCKET_UNDEFINED;
1175
sock->ctrl_sd = SOCKET_UNDEFINED;
1180
/* bind socket if necessary */
1182
link_socket_init_phase1 (struct link_socket *sock,
1183
const bool connection_profiles_defined,
1184
const char *local_host,
1186
const char *remote_host,
1190
const struct link_socket *accept_from,
1191
#ifdef ENABLE_HTTP_PROXY
1192
struct http_proxy_info *http_proxy,
1195
struct socks_proxy_info *socks_proxy,
1203
struct link_socket_addr *lsa,
1204
const char *ipchange_command,
1205
const struct plugin_list *plugins,
1206
int resolve_retry_seconds,
1207
int connect_retry_seconds,
1208
int connect_timeout,
1209
int connect_retry_max,
1210
int mtu_discover_type,
1213
unsigned int sockflags)
1217
sock->connection_profiles_defined = connection_profiles_defined;
1219
sock->local_host = local_host;
1220
sock->local_port = local_port;
1221
sock->remote_host = remote_host;
1222
sock->remote_port = remote_port;
1224
#ifdef ENABLE_HTTP_PROXY
1225
sock->http_proxy = http_proxy;
1229
sock->socks_proxy = socks_proxy;
1232
sock->bind_local = bind_local;
1233
sock->inetd = inetd;
1234
sock->resolve_retry_seconds = resolve_retry_seconds;
1235
sock->connect_retry_seconds = connect_retry_seconds;
1236
sock->connect_timeout = connect_timeout;
1237
sock->connect_retry_max = connect_retry_max;
1238
sock->mtu_discover_type = mtu_discover_type;
1241
sock->gremlin = gremlin;
1244
sock->socket_buffer_sizes.rcvbuf = rcvbuf;
1245
sock->socket_buffer_sizes.sndbuf = sndbuf;
1247
sock->sockflags = sockflags;
1249
sock->info.proto = proto;
1250
sock->info.remote_float = remote_float;
1251
sock->info.lsa = lsa;
1252
sock->info.ipchange_command = ipchange_command;
1253
sock->info.plugins = plugins;
1256
if (mode == LS_MODE_TCP_ACCEPT_FROM)
1258
ASSERT (accept_from);
1259
ASSERT (sock->info.proto == PROTO_TCPv4_SERVER);
1260
ASSERT (!sock->inetd);
1261
sock->sd = accept_from->sd;
1266
#ifdef ENABLE_HTTP_PROXY
1267
/* are we running in HTTP proxy mode? */
1268
else if (sock->http_proxy)
1270
ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT);
1271
ASSERT (!sock->inetd);
1273
/* the proxy server */
1274
sock->remote_host = http_proxy->options.server;
1275
sock->remote_port = http_proxy->options.port;
1277
/* the OpenVPN server we will use the proxy to connect to */
1278
sock->proxy_dest_host = remote_host;
1279
sock->proxy_dest_port = remote_port;
1283
/* or in Socks proxy mode? */
1284
else if (sock->socks_proxy)
1286
ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_UDPv4);
1287
ASSERT (!sock->inetd);
1289
/* the proxy server */
1290
sock->remote_host = socks_proxy->server;
1291
sock->remote_port = socks_proxy->port;
1293
/* the OpenVPN server we will use the proxy to connect to */
1294
sock->proxy_dest_host = remote_host;
1295
sock->proxy_dest_port = remote_port;
1300
sock->remote_host = remote_host;
1301
sock->remote_port = remote_port;
1304
/* bind behavior for TCP server vs. client */
1305
if (sock->info.proto == PROTO_TCPv4_SERVER)
1307
if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
1308
sock->bind_local = false;
1310
sock->bind_local = true;
1313
/* were we started by inetd or xinetd? */
1316
ASSERT (sock->info.proto != PROTO_TCPv4_CLIENT);
1317
ASSERT (socket_defined (inetd_socket_descriptor));
1318
sock->sd = inetd_socket_descriptor;
1320
else if (mode != LS_MODE_TCP_ACCEPT_FROM)
1322
create_socket (sock);
1324
/* set socket buffers based on --sndbuf and --rcvbuf options */
1325
socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
1327
resolve_bind_local (sock);
1328
resolve_remote (sock, 1, NULL, NULL);
1331
/* set socket file descriptor to not pass across execs, so that
1332
scripts don't have access to it */
1333
set_cloexec (sock->sd);
1336
/* finalize socket initialization */
1338
link_socket_init_phase2 (struct link_socket *sock,
1339
const struct frame *frame,
1340
volatile int *signal_received)
1342
struct gc_arena gc = gc_new ();
1343
const char *remote_dynamic = NULL;
1344
bool remote_changed = false;
1349
if (signal_received && *signal_received)
1351
sig_save = *signal_received;
1352
*signal_received = 0;
1355
/* initialize buffers */
1356
socket_frame_init (frame, sock);
1359
* Pass a remote name to connect/accept so that
1360
* they can test for dynamic IP address changes
1361
* and throw a SIGUSR1 if appropriate.
1363
if (sock->resolve_retry_seconds)
1364
remote_dynamic = sock->remote_host;
1366
/* were we started by inetd or xinetd? */
1369
if (sock->info.proto == PROTO_TCPv4_SERVER)
1371
socket_listen_accept (sock->sd,
1372
&sock->info.lsa->actual,
1375
&sock->info.lsa->local,
1377
sock->inetd == INETD_NOWAIT,
1379
ASSERT (!remote_changed);
1380
if (*signal_received)
1385
resolve_remote (sock, 2, &remote_dynamic, signal_received);
1387
if (*signal_received)
1390
/* TCP client/server */
1391
if (sock->info.proto == PROTO_TCPv4_SERVER)
1395
case LS_MODE_DEFAULT:
1396
sock->sd = socket_listen_accept (sock->sd,
1397
&sock->info.lsa->actual,
1400
&sock->info.lsa->local,
1405
case LS_MODE_TCP_LISTEN:
1406
socket_do_listen (sock->sd,
1407
&sock->info.lsa->local,
1411
case LS_MODE_TCP_ACCEPT_FROM:
1412
sock->sd = socket_do_accept (sock->sd,
1413
&sock->info.lsa->actual,
1415
if (!socket_defined (sock->sd))
1417
*signal_received = SIGTERM;
1420
tcp_connection_established (&sock->info.lsa->actual);
1426
else if (sock->info.proto == PROTO_TCPv4_CLIENT)
1429
#ifdef GENERAL_PROXY_SUPPORT
1430
bool proxy_retry = false;
1432
const bool proxy_retry = false;
1435
socket_connect (&sock->sd,
1436
&sock->info.lsa->local,
1438
&sock->info.lsa->actual.dest,
1439
sock->connection_profiles_defined,
1442
sock->connect_retry_seconds,
1443
sock->connect_timeout,
1444
sock->connect_retry_max,
1448
if (*signal_received)
1453
#ifdef ENABLE_HTTP_PROXY
1454
else if (sock->http_proxy)
1456
proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
1458
sock->proxy_dest_host,
1459
sock->proxy_dest_port,
1460
&sock->stream_buf.residual,
1465
else if (sock->socks_proxy)
1467
establish_socks_proxy_passthru (sock->socks_proxy,
1469
sock->proxy_dest_host,
1470
sock->proxy_dest_port,
1476
openvpn_close_socket (sock->sd);
1477
sock->sd = create_socket_tcp ();
1479
} while (proxy_retry);
1482
else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
1484
socket_connect (&sock->ctrl_sd,
1485
&sock->info.lsa->local,
1487
&sock->info.lsa->actual.dest,
1488
sock->connection_profiles_defined,
1491
sock->connect_retry_seconds,
1492
sock->connect_timeout,
1493
sock->connect_retry_max,
1497
if (*signal_received)
1500
establish_socks_proxy_udpassoc (sock->socks_proxy,
1503
&sock->socks_relay.dest,
1506
if (*signal_received)
1509
sock->remote_host = sock->proxy_dest_host;
1510
sock->remote_port = sock->proxy_dest_port;
1511
sock->did_resolve_remote = false;
1513
sock->info.lsa->actual.dest.sa.sin_addr.s_addr = 0;
1514
sock->info.lsa->remote.sa.sin_addr.s_addr = 0;
1516
resolve_remote (sock, 1, NULL, signal_received);
1518
if (*signal_received)
1523
if (*signal_received)
1528
msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
1529
sock->info.lsa->remote.sa.sin_addr.s_addr = sock->info.lsa->actual.dest.sa.sin_addr.s_addr;
1533
/* set misc socket parameters */
1534
socket_set_flags (sock->sd, sock->sockflags);
1536
/* set socket to non-blocking mode */
1537
set_nonblock (sock->sd);
1540
if (socket_defined (sock->ctrl_sd))
1541
set_cloexec (sock->ctrl_sd);
1544
/* set Path MTU discovery options on the socket */
1545
set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
1547
#if EXTENDED_SOCKET_ERROR_CAPABILITY
1548
/* if the OS supports it, enable extended error passing on the socket */
1549
set_sock_extended_error_passing (sock->sd);
1552
/* print local address */
1554
msg (M_INFO, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
1556
msg (M_INFO, "%s link local%s: %s",
1557
proto2ascii (sock->info.proto, true),
1558
(sock->bind_local ? " (bound)" : ""),
1559
print_sockaddr_ex (&sock->info.lsa->local, ":", sock->bind_local ? PS_SHOW_PORT : 0, &gc));
1561
/* print active remote address */
1562
msg (M_INFO, "%s link remote: %s",
1563
proto2ascii (sock->info.proto, true),
1564
print_link_socket_actual_ex (&sock->info.lsa->actual,
1566
PS_SHOW_PORT_IF_DEFINED,
1570
if (sig_save && signal_received)
1572
if (!*signal_received)
1573
*signal_received = sig_save;
1579
link_socket_close (struct link_socket *sock)
1584
const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
1586
const int gremlin = 0;
1589
if (socket_defined (sock->sd))
1592
close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
1596
msg (D_CLOSE, "TCP/UDP: Closing socket");
1597
if (openvpn_close_socket (sock->sd))
1598
msg (M_WARN | M_ERRNO_SOCK, "TCP/UDP: Close Socket failed");
1600
sock->sd = SOCKET_UNDEFINED;
1604
overlapped_io_close (&sock->reads);
1605
overlapped_io_close (&sock->writes);
1611
if (socket_defined (sock->ctrl_sd))
1613
if (openvpn_close_socket (sock->ctrl_sd))
1614
msg (M_WARN | M_ERRNO_SOCK, "TCP/UDP: Close Socket (ctrl_sd) failed");
1615
sock->ctrl_sd = SOCKET_UNDEFINED;
1619
stream_buf_close (&sock->stream_buf);
1620
free_buf (&sock->stream_buf_data);
1626
/* for stream protocols, allow for packet length prefix */
1628
socket_adjust_frame_parameters (struct frame *frame, int proto)
1630
if (link_socket_proto_connection_oriented (proto))
1631
frame_add_to_extra_frame (frame, sizeof (packet_size_type));
1635
setenv_trusted (struct env_set *es, const struct link_socket_info *info)
1637
setenv_link_socket_actual (es, "trusted", &info->lsa->actual, SA_IP_PORT);
1641
ipchange_fmt (const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
1643
const char *ip = print_sockaddr_ex (&info->lsa->actual.dest, NULL, 0, gc);
1644
const char *port = print_sockaddr_ex (&info->lsa->actual.dest, NULL, PS_DONT_SHOW_ADDR|PS_SHOW_PORT, gc);
1646
argv_printf (argv, "%sc %s %s",
1647
info->ipchange_command,
1651
argv_printf (argv, "%s %s",
1657
link_socket_connection_initiated (const struct buffer *buf,
1658
struct link_socket_info *info,
1659
const struct link_socket_actual *act,
1660
const char *common_name,
1663
struct gc_arena gc = gc_new ();
1665
info->lsa->actual = *act; /* Note: skip this line for --force-dest */
1666
setenv_trusted (es, info);
1667
info->connection_established = true;
1669
/* Print connection initiated message, with common name if available */
1671
struct buffer out = alloc_buf_gc (256, &gc);
1673
buf_printf (&out, "[%s] ", common_name);
1674
buf_printf (&out, "Peer Connection Initiated with %s", print_link_socket_actual (&info->lsa->actual, &gc));
1675
msg (M_INFO, "%s", BSTR (&out));
1678
/* set environmental vars */
1679
setenv_str (es, "common_name", common_name);
1681
/* Process --ipchange plugin */
1682
if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
1684
struct argv argv = argv_new ();
1685
ipchange_fmt (false, &argv, info, &gc);
1686
if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1687
msg (M_WARN, "WARNING: ipchange plugin call failed");
1691
/* Process --ipchange option */
1692
if (info->ipchange_command)
1694
struct argv argv = argv_new ();
1695
setenv_str (es, "script_type", "ipchange");
1696
ipchange_fmt (true, &argv, info, &gc);
1697
openvpn_run_script (&argv, es, 0, "--ipchange");
1705
link_socket_bad_incoming_addr (struct buffer *buf,
1706
const struct link_socket_info *info,
1707
const struct link_socket_actual *from_addr)
1709
struct gc_arena gc = gc_new ();
1712
"TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
1713
print_link_socket_actual (from_addr, &gc),
1714
(int)from_addr->dest.sa.sin_family,
1715
print_sockaddr (&info->lsa->remote, &gc));
1722
link_socket_bad_outgoing_addr (void)
1724
dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
1728
link_socket_current_remote (const struct link_socket_info *info)
1730
const struct link_socket_addr *lsa = info->lsa;
1732
if (link_socket_actual_defined (&lsa->actual))
1733
return ntohl (lsa->actual.dest.sa.sin_addr.s_addr);
1734
else if (addr_defined (&lsa->remote))
1735
return ntohl (lsa->remote.sa.sin_addr.s_addr);
1741
* Return a status string describing socket state.
1744
socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
1746
struct buffer out = alloc_buf_gc (64, gc);
1749
if (rwflags & EVENT_READ)
1751
buf_printf (&out, "S%s",
1752
(s->rwflags_debug & EVENT_READ) ? "R" : "r");
1754
buf_printf (&out, "%s",
1755
overlapped_io_state_ascii (&s->reads));
1758
if (rwflags & EVENT_WRITE)
1760
buf_printf (&out, "S%s",
1761
(s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
1763
buf_printf (&out, "%s",
1764
overlapped_io_state_ascii (&s->writes));
1770
buf_printf (&out, "S?");
1776
* Stream buffer functions, used to packetize a TCP
1777
* stream connection.
1781
stream_buf_reset (struct stream_buf *sb)
1783
dmsg (D_STREAM_DEBUG, "STREAM: RESET");
1784
sb->residual_fully_formed = false;
1785
sb->buf = sb->buf_init;
1786
buf_reset (&sb->next);
1791
stream_buf_init (struct stream_buf *sb,
1793
const unsigned int sockflags,
1796
sb->buf_init = *buf;
1797
sb->maxlen = sb->buf_init.len;
1798
sb->buf_init.len = 0;
1799
sb->residual = alloc_buf (sb->maxlen);
1802
sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCPv4_SERVER))
1806
stream_buf_reset (sb);
1808
dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
1812
stream_buf_set_next (struct stream_buf *sb)
1814
/* set up 'next' for next i/o read */
1816
sb->next.offset = sb->buf.offset + sb->buf.len;
1817
sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
1818
dmsg (D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
1819
sb->buf.offset, sb->buf.len,
1820
sb->next.offset, sb->next.len,
1821
sb->len, sb->maxlen);
1822
ASSERT (sb->next.len > 0);
1823
ASSERT (buf_safe (&sb->buf, sb->next.len));
1827
stream_buf_get_final (struct stream_buf *sb, struct buffer *buf)
1829
dmsg (D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
1830
buf_defined (&sb->buf) ? sb->buf.len : -1);
1831
ASSERT (buf_defined (&sb->buf));
1836
stream_buf_get_next (struct stream_buf *sb, struct buffer *buf)
1838
dmsg (D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
1839
buf_defined (&sb->next) ? sb->next.len : -1);
1840
ASSERT (buf_defined (&sb->next));
1845
stream_buf_read_setup_dowork (struct link_socket* sock)
1847
if (sock->stream_buf.residual.len && !sock->stream_buf.residual_fully_formed)
1849
ASSERT (buf_copy (&sock->stream_buf.buf, &sock->stream_buf.residual));
1850
ASSERT (buf_init (&sock->stream_buf.residual, 0));
1851
sock->stream_buf.residual_fully_formed = stream_buf_added (&sock->stream_buf, 0);
1852
dmsg (D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
1853
sock->stream_buf.residual_fully_formed ? "YES" : "NO",
1854
sock->stream_buf.residual.len);
1857
if (!sock->stream_buf.residual_fully_formed)
1858
stream_buf_set_next (&sock->stream_buf);
1859
return !sock->stream_buf.residual_fully_formed;
1863
stream_buf_added (struct stream_buf *sb,
1866
dmsg (D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
1867
if (length_added > 0)
1868
sb->buf.len += length_added;
1870
/* if length unknown, see if we can get the length prefix from
1871
the head of the buffer */
1872
if (sb->len < 0 && sb->buf.len >= (int) sizeof (packet_size_type))
1874
packet_size_type net_size;
1877
if (sb->port_share_state == PS_ENABLED)
1879
if (!is_openvpn_protocol (&sb->buf))
1881
msg (D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
1882
sb->port_share_state = PS_FOREIGN;
1887
sb->port_share_state = PS_DISABLED;
1891
ASSERT (buf_read (&sb->buf, &net_size, sizeof (net_size)));
1892
sb->len = ntohps (net_size);
1894
if (sb->len < 1 || sb->len > sb->maxlen)
1896
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);
1897
stream_buf_reset (sb);
1903
/* is our incoming packet fully read? */
1904
if (sb->len > 0 && sb->buf.len >= sb->len)
1906
/* save any residual data that's part of the next packet */
1907
ASSERT (buf_init (&sb->residual, 0));
1908
if (sb->buf.len > sb->len)
1909
ASSERT (buf_copy_excess (&sb->residual, &sb->buf, sb->len));
1910
dmsg (D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
1912
BLEN (&sb->residual));
1917
dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
1918
stream_buf_set_next (sb);
1924
stream_buf_close (struct stream_buf* sb)
1926
free_buf (&sb->residual);
1930
* The listen event is a special event whose sole purpose is
1931
* to tell us that there's a new incoming connection on a
1932
* TCP socket, for use in server mode.
1935
socket_listen_event_handle (struct link_socket *s)
1938
if (!defined_net_event_win32 (&s->listen_handle))
1939
init_net_event_win32 (&s->listen_handle, FD_ACCEPT, s->sd, 0);
1940
return &s->listen_handle;
1947
* Format IP addresses in ascii
1951
print_sockaddr (const struct openvpn_sockaddr *addr, struct gc_arena *gc)
1953
return print_sockaddr_ex (addr, ":", PS_SHOW_PORT, gc);
1957
print_sockaddr_ex (const struct openvpn_sockaddr *addr,
1958
const char* separator,
1959
const unsigned int flags,
1960
struct gc_arena *gc)
1964
struct buffer out = alloc_buf_gc (64, gc);
1965
const int port = ntohs (addr->sa.sin_port);
1967
if (!(flags & PS_DONT_SHOW_ADDR))
1968
buf_printf (&out, "%s", (addr_defined (addr) ? inet_ntoa (addr->sa.sin_addr) : "[undef]"));
1970
if (((flags & PS_SHOW_PORT) || (addr_defined (addr) && (flags & PS_SHOW_PORT_IF_DEFINED)))
1974
buf_printf (&out, "%s", separator);
1976
buf_printf (&out, "%d", port);
1985
print_link_socket_actual (const struct link_socket_actual *act, struct gc_arena *gc)
1987
return print_link_socket_actual_ex (act, ":", PS_SHOW_PORT|PS_SHOW_PKTINFO, gc);
1991
print_link_socket_actual_ex (const struct link_socket_actual *act,
1992
const char *separator,
1993
const unsigned int flags,
1994
struct gc_arena *gc)
1998
struct buffer out = alloc_buf_gc (128, gc);
1999
buf_printf (&out, "%s", print_sockaddr_ex (&act->dest, separator, flags, gc));
2000
#if ENABLE_IP_PKTINFO
2001
if ((flags & PS_SHOW_PKTINFO) && act->pi.ipi_spec_dst.s_addr)
2003
struct openvpn_sockaddr sa;
2005
sa.sa.sin_addr = act->pi.ipi_spec_dst;
2006
buf_printf (&out, " (via %s)", print_sockaddr_ex (&sa, separator, 0, gc));
2016
* Convert an in_addr_t in host byte order
2017
* to an ascii dotted quad.
2020
print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
2023
struct buffer out = alloc_buf_gc (64, gc);
2025
if (addr || !(flags & IA_EMPTY_IF_UNDEF))
2028
ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
2030
buf_printf (&out, "%s", inet_ntoa (ia));
2035
/* set environmental variables for ip/port in *addr */
2037
setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const bool flags)
2041
if (flags & SA_IP_PORT)
2042
openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
2044
openvpn_snprintf (name_buf, sizeof (name_buf), "%s", name_prefix);
2046
setenv_str (es, name_buf, inet_ntoa (addr->sa.sin_addr));
2048
if ((flags & SA_IP_PORT) && addr->sa.sin_port)
2050
openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
2051
setenv_int (es, name_buf, ntohs (addr->sa.sin_port));
2056
setenv_in_addr_t (struct env_set *es, const char *name_prefix, in_addr_t addr, const bool flags)
2058
if (addr || !(flags & SA_SET_IF_NONZERO))
2060
struct openvpn_sockaddr si;
2062
si.sa.sin_addr.s_addr = htonl (addr);
2063
setenv_sockaddr (es, name_prefix, &si, flags);
2068
setenv_link_socket_actual (struct env_set *es,
2069
const char *name_prefix,
2070
const struct link_socket_actual *act,
2073
setenv_sockaddr (es, name_prefix, &act->dest, flags);
2077
* Convert protocol names between index and ascii form.
2080
struct proto_names {
2081
const char *short_form;
2082
const char *display_form;
2085
/* Indexed by PROTO_x */
2086
static const struct proto_names proto_names[] = {
2088
{"tcp-server", "TCPv4_SERVER"},
2089
{"tcp-client", "TCPv4_CLIENT"},
2094
ascii2proto (const char* proto_name)
2097
ASSERT (PROTO_N == SIZE (proto_names));
2098
for (i = 0; i < PROTO_N; ++i)
2099
if (!strcmp (proto_name, proto_names[i].short_form))
2105
proto2ascii (int proto, bool display_form)
2107
ASSERT (PROTO_N == SIZE (proto_names));
2108
if (proto < 0 || proto >= PROTO_N)
2109
return "[unknown protocol]";
2110
else if (display_form)
2111
return proto_names[proto].display_form;
2113
return proto_names[proto].short_form;
2117
proto2ascii_all (struct gc_arena *gc)
2119
struct buffer out = alloc_buf_gc (256, gc);
2122
ASSERT (PROTO_N == SIZE (proto_names));
2123
for (i = 0; i < PROTO_N; ++i)
2126
buf_printf(&out, " ");
2127
buf_printf(&out, "[%s]", proto2ascii(i, false));
2133
* Given a local proto, return local proto
2134
* if !remote, or compatible remote proto
2137
* This is used for options compatibility
2141
proto_remote (int proto, bool remote)
2143
ASSERT (proto >= 0 && proto < PROTO_N);
2146
if (proto == PROTO_TCPv4_SERVER)
2147
return PROTO_TCPv4_CLIENT;
2148
if (proto == PROTO_TCPv4_CLIENT)
2149
return PROTO_TCPv4_SERVER;
2155
* Bad incoming address lengths that differ from what
2156
* we expect are considered to be fatal errors.
2159
bad_address_length (int actual, int expected)
2161
msg (M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
2167
* Socket Read Routines
2171
link_socket_read_tcp (struct link_socket *sock,
2176
if (!sock->stream_buf.residual_fully_formed)
2179
len = socket_finalize (sock->sd, &sock->reads, buf, NULL);
2182
stream_buf_get_next (&sock->stream_buf, &frag);
2183
len = recv (sock->sd, BPTR (&frag), BLEN (&frag), MSG_NOSIGNAL);
2187
sock->stream_reset = true;
2189
return buf->len = len;
2192
if (sock->stream_buf.residual_fully_formed
2193
|| stream_buf_added (&sock->stream_buf, len)) /* packet complete? */
2195
stream_buf_get_final (&sock->stream_buf, buf);
2196
stream_buf_reset (&sock->stream_buf);
2200
return buf->len = 0; /* no error, but packet is still incomplete */
2205
#if ENABLE_IP_PKTINFO
2207
#pragma pack(1) /* needed to keep structure size consistent for 32 vs. 64-bit architectures */
2208
struct openvpn_pktinfo
2210
struct cmsghdr cmsghdr;
2211
struct in_pktinfo in_pktinfo;
2216
link_socket_read_udp_posix_recvmsg (struct link_socket *sock,
2219
struct link_socket_actual *from)
2222
struct openvpn_pktinfo opi;
2224
socklen_t fromlen = sizeof (from->dest.sa);
2226
iov.iov_base = BPTR (buf);
2227
iov.iov_len = maxsize;
2228
mesg.msg_iov = &iov;
2229
mesg.msg_iovlen = 1;
2230
mesg.msg_name = &from->dest.sa;
2231
mesg.msg_namelen = fromlen;
2232
mesg.msg_control = &opi;
2233
mesg.msg_controllen = sizeof (opi);
2234
buf->len = recvmsg (sock->sd, &mesg, 0);
2237
struct cmsghdr *cmsg;
2238
fromlen = mesg.msg_namelen;
2239
cmsg = CMSG_FIRSTHDR (&mesg);
2241
&& CMSG_NXTHDR (&mesg, cmsg) == NULL
2242
&& cmsg->cmsg_level == SOL_IP
2243
&& cmsg->cmsg_type == IP_PKTINFO
2244
&& cmsg->cmsg_len >= sizeof (opi))
2246
struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
2247
from->pi.ipi_ifindex = pkti->ipi_ifindex;
2248
from->pi.ipi_spec_dst = pkti->ipi_spec_dst;
2256
link_socket_read_udp_posix (struct link_socket *sock,
2259
struct link_socket_actual *from)
2261
socklen_t fromlen = sizeof (from->dest.sa);
2262
from->dest.sa.sin_addr.s_addr = 0;
2263
ASSERT (buf_safe (buf, maxsize));
2264
#if ENABLE_IP_PKTINFO
2265
if (sock->sockflags & SF_USE_IP_PKTINFO)
2266
fromlen = link_socket_read_udp_posix_recvmsg (sock, buf, maxsize, from);
2269
buf->len = recvfrom (sock->sd, BPTR (buf), maxsize, 0,
2270
(struct sockaddr *) &from->dest.sa, &fromlen);
2271
if (fromlen != sizeof (from->dest.sa))
2272
bad_address_length (fromlen, sizeof (from->dest.sa));
2279
* Socket Write Routines
2283
link_socket_write_tcp (struct link_socket *sock,
2285
struct link_socket_actual *to)
2287
packet_size_type len = BLEN (buf);
2288
dmsg (D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
2289
ASSERT (len <= sock->stream_buf.maxlen);
2291
ASSERT (buf_write_prepend (buf, &len, sizeof (len)));
2293
return link_socket_write_win32 (sock, buf, to);
2295
return link_socket_write_tcp_posix (sock, buf, to);
2299
#if ENABLE_IP_PKTINFO
2302
link_socket_write_udp_posix_sendmsg (struct link_socket *sock,
2304
struct link_socket_actual *to)
2308
struct cmsghdr *cmsg;
2309
struct in_pktinfo *pkti;
2310
struct openvpn_pktinfo opi;
2312
iov.iov_base = BPTR (buf);
2313
iov.iov_len = BLEN (buf);
2314
mesg.msg_iov = &iov;
2315
mesg.msg_iovlen = 1;
2316
mesg.msg_name = &to->dest.sa;
2317
mesg.msg_namelen = sizeof (to->dest.sa);
2318
mesg.msg_control = &opi;
2319
mesg.msg_controllen = sizeof (opi);
2321
cmsg = CMSG_FIRSTHDR (&mesg);
2322
cmsg->cmsg_len = sizeof (opi);
2323
cmsg->cmsg_level = SOL_IP;
2324
cmsg->cmsg_type = IP_PKTINFO;
2325
pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
2326
pkti->ipi_ifindex = to->pi.ipi_ifindex;
2327
pkti->ipi_spec_dst = to->pi.ipi_spec_dst;
2328
pkti->ipi_addr.s_addr = 0;
2329
return sendmsg (sock->sd, &mesg, 0);
2335
* Win32 overlapped socket I/O functions.
2341
socket_recv_queue (struct link_socket *sock, int maxsize)
2343
if (sock->reads.iostate == IOSTATE_INITIAL)
2348
/* reset buf to its initial state */
2349
if (sock->info.proto == PROTO_UDPv4)
2351
sock->reads.buf = sock->reads.buf_init;
2353
else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
2355
stream_buf_get_next (&sock->stream_buf, &sock->reads.buf);
2362
/* Win32 docs say it's okay to allocate the wsabuf on the stack */
2363
wsabuf[0].buf = BPTR (&sock->reads.buf);
2364
wsabuf[0].len = maxsize ? maxsize : BLEN (&sock->reads.buf);
2366
/* check for buffer overflow */
2367
ASSERT (wsabuf[0].len <= BLEN (&sock->reads.buf));
2369
/* the overlapped read will signal this event on I/O completion */
2370
ASSERT (ResetEvent (sock->reads.overlapped.hEvent));
2371
sock->reads.flags = 0;
2373
if (sock->info.proto == PROTO_UDPv4)
2375
sock->reads.addr_defined = true;
2376
sock->reads.addrlen = sizeof (sock->reads.addr);
2377
status = WSARecvFrom(
2383
(struct sockaddr *) &sock->reads.addr,
2384
&sock->reads.addrlen,
2385
&sock->reads.overlapped,
2388
else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
2390
sock->reads.addr_defined = false;
2397
&sock->reads.overlapped,
2406
if (!status) /* operation completed immediately? */
2408
if (sock->reads.addr_defined && sock->reads.addrlen != sizeof (sock->reads.addr))
2409
bad_address_length (sock->reads.addrlen, sizeof (sock->reads.addr));
2411
sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
2413
/* since we got an immediate return, we must signal the event object ourselves */
2414
ASSERT (SetEvent (sock->reads.overlapped.hEvent));
2415
sock->reads.status = 0;
2417
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
2418
(int) wsabuf[0].len,
2419
(int) sock->reads.size);
2423
status = WSAGetLastError ();
2424
if (status == WSA_IO_PENDING) /* operation queued? */
2426
sock->reads.iostate = IOSTATE_QUEUED;
2427
sock->reads.status = status;
2428
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
2429
(int) wsabuf[0].len);
2431
else /* error occurred */
2433
struct gc_arena gc = gc_new ();
2434
ASSERT (SetEvent (sock->reads.overlapped.hEvent));
2435
sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
2436
sock->reads.status = status;
2437
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
2438
(int) wsabuf[0].len,
2439
strerror_win32 (status, &gc));
2444
return sock->reads.iostate;
2448
socket_send_queue (struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
2450
if (sock->writes.iostate == IOSTATE_INITIAL)
2455
/* make a private copy of buf */
2456
sock->writes.buf = sock->writes.buf_init;
2457
sock->writes.buf.len = 0;
2458
ASSERT (buf_copy (&sock->writes.buf, buf));
2460
/* Win32 docs say it's okay to allocate the wsabuf on the stack */
2461
wsabuf[0].buf = BPTR (&sock->writes.buf);
2462
wsabuf[0].len = BLEN (&sock->writes.buf);
2464
/* the overlapped write will signal this event on I/O completion */
2465
ASSERT (ResetEvent (sock->writes.overlapped.hEvent));
2466
sock->writes.flags = 0;
2468
if (sock->info.proto == PROTO_UDPv4)
2470
/* set destination address for UDP writes */
2471
sock->writes.addr_defined = true;
2472
sock->writes.addr = to->dest.sa;
2473
sock->writes.addrlen = sizeof (sock->writes.addr);
2481
(struct sockaddr *) &sock->writes.addr,
2482
sock->writes.addrlen,
2483
&sock->writes.overlapped,
2486
else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
2488
/* destination address for TCP writes was established on connection initiation */
2489
sock->writes.addr_defined = false;
2497
&sock->writes.overlapped,
2506
if (!status) /* operation completed immediately? */
2508
sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
2510
/* since we got an immediate return, we must signal the event object ourselves */
2511
ASSERT (SetEvent (sock->writes.overlapped.hEvent));
2513
sock->writes.status = 0;
2515
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
2516
(int) wsabuf[0].len,
2517
(int) sock->writes.size);
2521
status = WSAGetLastError ();
2522
if (status == WSA_IO_PENDING) /* operation queued? */
2524
sock->writes.iostate = IOSTATE_QUEUED;
2525
sock->writes.status = status;
2526
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
2527
(int) wsabuf[0].len);
2529
else /* error occurred */
2531
struct gc_arena gc = gc_new ();
2532
ASSERT (SetEvent (sock->writes.overlapped.hEvent));
2533
sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
2534
sock->writes.status = status;
2536
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
2537
(int) wsabuf[0].len,
2538
strerror_win32 (status, &gc));
2544
return sock->writes.iostate;
2548
socket_finalize (SOCKET s,
2549
struct overlapped_io *io,
2551
struct link_socket_actual *from)
2556
switch (io->iostate)
2558
case IOSTATE_QUEUED:
2559
status = WSAGetOverlappedResult(
2568
/* successful return for a queued operation */
2572
io->iostate = IOSTATE_INITIAL;
2573
ASSERT (ResetEvent (io->overlapped.hEvent));
2575
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
2579
/* error during a queued operation */
2581
if (WSAGetLastError() != WSA_IO_INCOMPLETE)
2583
/* if no error (i.e. just not finished yet), then DON'T execute this code */
2584
io->iostate = IOSTATE_INITIAL;
2585
ASSERT (ResetEvent (io->overlapped.hEvent));
2586
msg (D_WIN32_IO | M_ERRNO_SOCK, "WIN32 I/O: Socket Completion error");
2591
case IOSTATE_IMMEDIATE_RETURN:
2592
io->iostate = IOSTATE_INITIAL;
2593
ASSERT (ResetEvent (io->overlapped.hEvent));
2596
/* error return for a non-queued operation */
2597
WSASetLastError (io->status);
2599
msg (D_WIN32_IO | M_ERRNO_SOCK, "WIN32 I/O: Socket Completion non-queued error");
2603
/* successful return for a non-queued operation */
2607
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
2611
case IOSTATE_INITIAL: /* were we called without proper queueing? */
2612
WSASetLastError (WSAEINVAL);
2614
dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
2621
/* return from address if requested */
2624
if (ret >= 0 && io->addr_defined)
2626
if (io->addrlen != sizeof (io->addr))
2627
bad_address_length (io->addrlen, sizeof (io->addr));
2628
from->dest.sa = io->addr;
2631
CLEAR (from->dest.sa);
2642
* Socket event notification
2646
socket_set (struct link_socket *s,
2647
struct event_set *es,
2648
unsigned int rwflags,
2650
unsigned int *persistent)
2654
if ((rwflags & EVENT_READ) && !stream_buf_read_setup (s))
2656
ASSERT (!persistent);
2657
rwflags &= ~EVENT_READ;
2661
if (rwflags & EVENT_READ)
2662
socket_recv_queue (s, 0);
2665
/* if persistent is defined, call event_ctl only if rwflags has changed since last call */
2666
if (!persistent || *persistent != rwflags)
2668
event_ctl (es, socket_event_handle (s), rwflags, arg);
2670
*persistent = rwflags;
2673
s->rwflags_debug = rwflags;
2679
sd_close (socket_descriptor_t *sd)
2681
if (sd && socket_defined (*sd))
2683
openvpn_close_socket (*sd);
2684
*sd = SOCKET_UNDEFINED;
2688
#if UNIX_SOCK_SUPPORT
2691
* code for unix domain sockets
2695
sockaddr_unix_name (const struct sockaddr_un *local, const char *null)
2697
if (local && local->sun_family == PF_UNIX)
2698
return local->sun_path;
2704
create_socket_unix (void)
2706
socket_descriptor_t sd;
2708
if ((sd = socket (PF_UNIX, SOCK_STREAM, 0)) < 0)
2709
msg (M_SOCKERR, "Cannot create unix domain socket");
2714
socket_bind_unix (socket_descriptor_t sd,
2715
struct sockaddr_un *local,
2718
struct gc_arena gc = gc_new ();
2721
const mode_t orig_umask = umask (0);
2724
if (bind (sd, (struct sockaddr *) local, sizeof (struct sockaddr_un)))
2726
const int errnum = openvpn_errno_socket ();
2727
msg (M_FATAL, "%s: Socket bind[%d] failed on unix domain socket %s: %s",
2730
sockaddr_unix_name (local, "NULL"),
2731
strerror_ts (errnum, &gc));
2742
socket_accept_unix (socket_descriptor_t sd,
2743
struct sockaddr_un *remote)
2745
socklen_t remote_len = sizeof (struct sockaddr_un);
2746
socket_descriptor_t ret;
2749
ret = accept (sd, (struct sockaddr *) remote, &remote_len);
2754
socket_connect_unix (socket_descriptor_t sd,
2755
struct sockaddr_un *remote)
2757
int status = connect (sd, (struct sockaddr *) remote, sizeof (struct sockaddr_un));
2759
status = openvpn_errno_socket ();
2764
sockaddr_unix_init (struct sockaddr_un *local, const char *path)
2766
local->sun_family = PF_UNIX;
2767
strncpynt (local->sun_path, path, sizeof (local->sun_path));
2771
socket_delete_unix (const struct sockaddr_un *local)
2773
const char *name = sockaddr_unix_name (local, NULL);
2775
if (name && strlen (name))
2781
unix_socket_get_peer_uid_gid (const socket_descriptor_t sd, int *uid, int *gid)
2783
#ifdef HAVE_GETPEEREID
2786
if (getpeereid (sd, &u, &g) == -1)
2793
#elif defined(SO_PEERCRED)
2794
struct ucred peercred;
2795
socklen_t so_len = sizeof(peercred);
2796
if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
2799
*uid = peercred.uid;
2801
*gid = peercred.gid;