cosmetics
[tomato.git] / release / src / router / openvpn / socket.c
blobfecc39837b0353cfa31564518ee034bdb625185f
1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
8 * Copyright (C) 2002-2009 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
25 #include "syshead.h"
27 #include "socket.h"
28 #include "fdmisc.h"
29 #include "thread.h"
30 #include "misc.h"
31 #include "gremlin.h"
32 #include "plugin.h"
33 #include "ps.h"
34 #include "manage.h"
35 #include "misc.h"
37 #include "memdbg.h"
39 const int proto_overhead[] = { /* indexed by PROTO_x */
40 IPv4_UDP_HEADER_SIZE,
41 IPv4_TCP_HEADER_SIZE,
42 IPv4_TCP_HEADER_SIZE,
43 IPv4_TCP_HEADER_SIZE
47 * Convert sockflags/getaddr_flags into getaddr_flags
49 static unsigned int
50 sf2gaf(const unsigned int getaddr_flags,
51 const unsigned int sockflags)
53 if (sockflags & SF_HOST_RANDOMIZE)
54 return getaddr_flags | GETADDR_RANDOMIZE;
55 else
56 return getaddr_flags;
60 * Functions related to the translation of DNS names to IP addresses.
63 static const char*
64 h_errno_msg(int h_errno_err)
66 switch (h_errno_err)
68 case HOST_NOT_FOUND:
69 return "[HOST_NOT_FOUND] The specified host is unknown.";
70 case NO_DATA:
71 return "[NO_DATA] The requested name is valid but does not have an IP address.";
72 case NO_RECOVERY:
73 return "[NO_RECOVERY] A non-recoverable name server error occurred.";
74 case TRY_AGAIN:
75 return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
77 return "[unknown h_errno value]";
81 * Translate IP addr or hostname to in_addr_t.
82 * If resolve error, try again for
83 * resolve_retry_seconds seconds.
85 in_addr_t
86 getaddr (unsigned int flags,
87 const char *hostname,
88 int resolve_retry_seconds,
89 bool *succeeded,
90 volatile int *signal_received)
92 struct in_addr ia;
93 int status;
94 int sigrec = 0;
95 int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
96 struct gc_arena gc = gc_new ();
98 if (flags & GETADDR_RANDOMIZE)
99 hostname = hostname_randomize(hostname, &gc);
101 if (flags & GETADDR_MSG_VIRT_OUT)
102 msglevel |= M_MSG_VIRT_OUT;
104 CLEAR (ia);
105 if (succeeded)
106 *succeeded = false;
108 if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
109 && !signal_received)
110 signal_received = &sigrec;
112 status = openvpn_inet_aton (hostname, &ia); /* parse ascii IP address */
114 if (status != OIA_IP) /* parse as IP address failed? */
116 const int fail_wait_interval = 5; /* seconds */
117 int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 : (resolve_retry_seconds / fail_wait_interval);
118 struct hostent *h;
119 const char *fmt;
120 int level = 0;
122 CLEAR (ia);
124 fmt = "RESOLVE: Cannot resolve host address: %s: %s";
125 if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
126 && !resolve_retry_seconds)
127 fmt = "RESOLVE: Cannot resolve host address: %s: %s (I would have retried this name query if you had specified the --resolv-retry option.)";
129 if (!(flags & GETADDR_RESOLVE) || status == OIA_ERROR)
131 msg (msglevel, "RESOLVE: Cannot parse IP address: %s", hostname);
132 goto done;
135 #ifdef ENABLE_MANAGEMENT
136 if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
138 if (management)
139 management_set_state (management,
140 OPENVPN_STATE_RESOLVE,
141 NULL,
142 (in_addr_t)0,
143 (in_addr_t)0);
145 #endif
148 * Resolve hostname
150 while (true)
152 /* try hostname lookup */
153 #if defined(HAVE_RES_INIT)
154 res_init ();
155 #endif
156 h = gethostbyname (hostname);
158 if (signal_received)
160 get_signal (signal_received);
161 if (*signal_received) /* were we interrupted by a signal? */
163 h = NULL;
164 if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
166 msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
167 *signal_received = 0;
169 else
170 goto done;
174 /* success? */
175 if (h)
176 break;
178 /* resolve lookup failed, should we
179 continue or fail? */
181 level = msglevel;
182 if (resolve_retries > 0)
183 level = D_RESOLVE_ERRORS;
185 msg (level,
186 fmt,
187 hostname,
188 h_errno_msg (h_errno));
190 if (--resolve_retries <= 0)
191 goto done;
193 openvpn_sleep (fail_wait_interval);
196 if (h->h_addrtype != AF_INET || h->h_length != 4)
198 msg (msglevel, "RESOLVE: Sorry, but we only accept IPv4 DNS names: %s", hostname);
199 goto done;
202 ia.s_addr = *(in_addr_t *) (h->h_addr_list[0]);
204 if (ia.s_addr)
206 if (h->h_addr_list[1]) /* more than one address returned */
208 int n = 0;
210 /* count address list */
211 while (h->h_addr_list[n])
212 ++n;
213 ASSERT (n >= 2);
215 msg (D_RESOLVE_ERRORS, "RESOLVE: NOTE: %s resolves to %d addresses, choosing one by random",
216 hostname,
219 /* choose address randomly, for basic load-balancing capability */
220 ia.s_addr = *(in_addr_t *) (h->h_addr_list[get_random () % n]);
224 /* hostname resolve succeeded */
225 if (succeeded)
226 *succeeded = true;
228 else
230 /* IP address parse succeeded */
231 if (succeeded)
232 *succeeded = true;
235 done:
236 if (signal_received && *signal_received)
238 int level = 0;
239 if (flags & GETADDR_FATAL_ON_SIGNAL)
240 level = M_FATAL;
241 else if (flags & GETADDR_WARN_ON_SIGNAL)
242 level = M_WARN;
243 msg (level, "RESOLVE: signal received during DNS resolution attempt");
246 gc_free (&gc);
247 return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
251 * We do our own inet_aton because the glibc function
252 * isn't very good about error checking.
255 openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
257 unsigned int a, b, c, d;
259 CLEAR (*addr);
260 if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
262 if (a < 256 && b < 256 && c < 256 && d < 256)
264 addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
265 return OIA_IP; /* good dotted quad */
268 if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
269 return OIA_ERROR; /* probably a badly formatted dotted quad */
270 else
271 return OIA_HOSTNAME; /* probably a hostname */
274 bool
275 ip_addr_dotted_quad_safe (const char *dotted_quad)
277 /* verify non-NULL */
278 if (!dotted_quad)
279 return false;
281 /* verify length is within limits */
282 if (strlen (dotted_quad) > 15)
283 return false;
285 /* verify that all chars are either numeric or '.' and that no numeric
286 substring is greater than 3 chars */
288 int nnum = 0;
289 const char *p = dotted_quad;
290 int c;
292 while ((c = *p++))
294 if (c >= '0' && c <= '9')
296 ++nnum;
297 if (nnum > 3)
298 return false;
300 else if (c == '.')
302 nnum = 0;
304 else
305 return false;
309 /* verify that string will convert to IP address */
311 struct in_addr a;
312 return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
316 static bool
317 dns_addr_safe (const char *addr)
319 if (addr)
321 const size_t len = strlen (addr);
322 return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
324 else
325 return false;
328 bool
329 ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
331 if (ip_addr_dotted_quad_safe (addr))
332 return true;
333 else if (allow_fqdn)
334 return dns_addr_safe (addr);
335 else
336 return false;
339 bool
340 mac_addr_safe (const char *mac_addr)
342 /* verify non-NULL */
343 if (!mac_addr)
344 return false;
346 /* verify length is within limits */
347 if (strlen (mac_addr) > 17)
348 return false;
350 /* verify that all chars are either alphanumeric or ':' and that no
351 alphanumeric substring is greater than 2 chars */
353 int nnum = 0;
354 const char *p = mac_addr;
355 int c;
357 while ((c = *p++))
359 if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
361 ++nnum;
362 if (nnum > 2)
363 return false;
365 else if (c == ':')
367 nnum = 0;
369 else
370 return false;
374 /* error-checking is left to script invoked in lladdr.c */
375 return true;
378 static void
379 update_remote (const char* host,
380 struct openvpn_sockaddr *addr,
381 bool *changed,
382 const unsigned int sockflags)
384 if (host && addr)
386 const in_addr_t new_addr = getaddr (
387 sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags),
388 host,
390 NULL,
391 NULL);
392 if (new_addr && addr->sa.sin_addr.s_addr != new_addr)
394 addr->sa.sin_addr.s_addr = new_addr;
395 *changed = true;
400 static int
401 socket_get_sndbuf (int sd)
403 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
404 int val;
405 socklen_t len;
407 len = sizeof (val);
408 if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
409 && len == sizeof (val))
410 return val;
411 #endif
412 return 0;
415 static void
416 socket_set_sndbuf (int sd, int size)
418 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
419 if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
421 if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
423 msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
426 #endif
429 static int
430 socket_get_rcvbuf (int sd)
432 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
433 int val;
434 socklen_t len;
436 len = sizeof (val);
437 if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
438 && len == sizeof (val))
439 return val;
440 #endif
441 return 0;
444 static bool
445 socket_set_rcvbuf (int sd, int size)
447 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
448 if (size > 0 && size < SOCKET_SND_RCV_BUF_MAX)
450 if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
452 msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
453 return false;
456 return true;
457 #endif
460 static void
461 socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
463 if (sbs)
465 const int sndbuf_old = socket_get_sndbuf (fd);
466 const int rcvbuf_old = socket_get_rcvbuf (fd);
468 if (sbs->sndbuf)
469 socket_set_sndbuf (fd, sbs->sndbuf);
471 if (sbs->rcvbuf)
472 socket_set_rcvbuf (fd, sbs->rcvbuf);
474 msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
475 rcvbuf_old,
476 socket_get_rcvbuf (fd),
477 sndbuf_old,
478 socket_get_sndbuf (fd));
483 * Set other socket options
486 static bool
487 socket_set_tcp_nodelay (int sd, int state)
489 #if defined(HAVE_SETSOCKOPT) && defined(IPPROTO_TCP) && defined(TCP_NODELAY)
490 if (setsockopt (sd, IPPROTO_TCP, TCP_NODELAY, (void *) &state, sizeof (state)) != 0)
492 msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed", state);
493 return false;
495 else
497 dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
498 return true;
500 #else
501 msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
502 return false;
503 #endif
506 static bool
507 socket_set_flags (int sd, unsigned int sockflags)
509 if (sockflags & SF_TCP_NODELAY)
510 return socket_set_tcp_nodelay (sd, 1);
511 else
512 return true;
515 bool
516 link_socket_update_flags (struct link_socket *ls, unsigned int sockflags)
518 if (ls && socket_defined (ls->sd))
519 return socket_set_flags (ls->sd, ls->sockflags = sockflags);
520 else
521 return false;
524 void
525 link_socket_update_buffer_sizes (struct link_socket *ls, int rcvbuf, int sndbuf)
527 if (ls && socket_defined (ls->sd))
529 ls->socket_buffer_sizes.sndbuf = sndbuf;
530 ls->socket_buffer_sizes.rcvbuf = rcvbuf;
531 socket_set_buffers (ls->sd, &ls->socket_buffer_sizes);
536 * SOCKET INITALIZATION CODE.
537 * Create a TCP/UDP socket
540 socket_descriptor_t
541 create_socket_tcp (void)
543 socket_descriptor_t sd;
545 if ((sd = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
546 msg (M_SOCKERR, "Cannot create TCP socket");
548 #ifndef WIN32 /* using SO_REUSEADDR on Windows will cause bind to succeed on port conflicts! */
549 /* set SO_REUSEADDR on socket */
551 int on = 1;
552 if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
553 (void *) &on, sizeof (on)) < 0)
554 msg (M_SOCKERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
556 #endif
558 #if 0
559 /* set socket linger options */
561 struct linger linger;
562 linger.l_onoff = 1;
563 linger.l_linger = 2;
564 if (setsockopt (sd, SOL_SOCKET, SO_LINGER,
565 (void *) &linger, sizeof (linger)) < 0)
566 msg (M_SOCKERR, "TCP: Cannot setsockopt SO_LINGER on TCP socket");
568 #endif
570 return sd;
573 static socket_descriptor_t
574 create_socket_udp (const unsigned int flags)
576 socket_descriptor_t sd;
578 if ((sd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
579 msg (M_SOCKERR, "UDP: Cannot create UDP socket");
580 #if ENABLE_IP_PKTINFO
581 else if (flags & SF_USE_IP_PKTINFO)
583 int pad = 1;
584 setsockopt (sd, SOL_IP, IP_PKTINFO, (void*)&pad, sizeof(pad));
586 #endif
587 return sd;
590 static void
591 create_socket (struct link_socket *sock)
593 /* create socket */
594 if (sock->info.proto == PROTO_UDPv4)
596 sock->sd = create_socket_udp (sock->sockflags);
598 #ifdef ENABLE_SOCKS
599 if (sock->socks_proxy)
600 sock->ctrl_sd = create_socket_tcp ();
601 #endif
603 else if (sock->info.proto == PROTO_TCPv4_SERVER
604 || sock->info.proto == PROTO_TCPv4_CLIENT)
606 sock->sd = create_socket_tcp ();
608 else
610 ASSERT (0);
615 * Functions used for establishing a TCP stream connection.
618 static void
619 socket_do_listen (socket_descriptor_t sd,
620 const struct openvpn_sockaddr *local,
621 bool do_listen,
622 bool do_set_nonblock)
624 struct gc_arena gc = gc_new ();
625 if (do_listen)
627 msg (M_INFO, "Listening for incoming TCP connection on %s",
628 print_sockaddr (local, &gc));
629 if (listen (sd, 1))
630 msg (M_SOCKERR, "TCP: listen() failed");
633 /* set socket to non-blocking mode */
634 if (do_set_nonblock)
635 set_nonblock (sd);
637 gc_free (&gc);
640 socket_descriptor_t
641 socket_do_accept (socket_descriptor_t sd,
642 struct link_socket_actual *act,
643 const bool nowait)
645 socklen_t remote_len = sizeof (act->dest.sa);
646 socket_descriptor_t new_sd = SOCKET_UNDEFINED;
648 CLEAR (*act);
650 #ifdef HAVE_GETPEERNAME
651 if (nowait)
653 new_sd = getpeername (sd, (struct sockaddr *) &act->dest.sa, &remote_len);
655 if (!socket_defined (new_sd))
656 msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: getpeername() failed");
657 else
658 new_sd = sd;
660 #else
661 if (nowait)
662 msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
663 #endif
664 else
666 new_sd = accept (sd, (struct sockaddr *) &act->dest.sa, &remote_len);
669 #if 0 /* For debugging only, test the effect of accept() failures */
671 static int foo = 0;
672 ++foo;
673 if (foo & 1)
674 new_sd = -1;
676 #endif
678 if (!socket_defined (new_sd))
680 msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: accept(%d) failed", sd);
682 else if (remote_len != sizeof (act->dest.sa))
684 msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
685 openvpn_close_socket (new_sd);
686 new_sd = SOCKET_UNDEFINED;
688 return new_sd;
691 static void
692 tcp_connection_established (const struct link_socket_actual *act)
694 struct gc_arena gc = gc_new ();
695 msg (M_INFO, "TCP connection established with %s",
696 print_link_socket_actual (act, &gc));
697 gc_free (&gc);
700 static int
701 socket_listen_accept (socket_descriptor_t sd,
702 struct link_socket_actual *act,
703 const char *remote_dynamic,
704 bool *remote_changed,
705 const struct openvpn_sockaddr *local,
706 bool do_listen,
707 bool nowait,
708 volatile int *signal_received)
710 struct gc_arena gc = gc_new ();
711 /* struct openvpn_sockaddr *remote = &act->dest; */
712 struct openvpn_sockaddr remote_verify = act->dest;
713 int new_sd = SOCKET_UNDEFINED;
715 CLEAR (*act);
716 socket_do_listen (sd, local, do_listen, true);
718 while (true)
720 int status;
721 fd_set reads;
722 struct timeval tv;
724 FD_ZERO (&reads);
725 FD_SET (sd, &reads);
726 tv.tv_sec = 0;
727 tv.tv_usec = 0;
729 status = select (sd + 1, &reads, NULL, NULL, &tv);
731 get_signal (signal_received);
732 if (*signal_received)
734 gc_free (&gc);
735 return sd;
738 if (status < 0)
739 msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: select() failed");
741 if (status <= 0)
743 openvpn_sleep (1);
744 continue;
747 new_sd = socket_do_accept (sd, act, nowait);
749 if (socket_defined (new_sd))
751 update_remote (remote_dynamic, &remote_verify, remote_changed, 0);
752 if (addr_defined (&remote_verify)
753 && !addr_match (&remote_verify, &act->dest))
755 msg (M_WARN,
756 "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
757 print_link_socket_actual (act, &gc));
758 if (openvpn_close_socket (new_sd))
759 msg (M_SOCKERR, "TCP: close socket failed (new_sd)");
761 else
762 break;
764 openvpn_sleep (1);
767 if (!nowait && openvpn_close_socket (sd))
768 msg (M_SOCKERR, "TCP: close socket failed (sd)");
770 tcp_connection_established (act);
772 gc_free (&gc);
773 return new_sd;
776 void
777 socket_bind (socket_descriptor_t sd,
778 struct openvpn_sockaddr *local,
779 const char *prefix)
781 struct gc_arena gc = gc_new ();
783 if (bind (sd, (struct sockaddr *) &local->sa, sizeof (local->sa)))
785 const int errnum = openvpn_errno_socket ();
786 msg (M_FATAL, "%s: Socket bind failed on local address %s: %s",
787 prefix,
788 print_sockaddr (local, &gc),
789 strerror_ts (errnum, &gc));
791 gc_free (&gc);
795 openvpn_connect (socket_descriptor_t sd,
796 struct openvpn_sockaddr *remote,
797 int connect_timeout,
798 volatile int *signal_received)
800 int status = 0;
802 #ifdef CONNECT_NONBLOCK
803 set_nonblock (sd);
804 status = connect (sd, (struct sockaddr *) &remote->sa, sizeof (remote->sa));
805 if (status)
806 status = openvpn_errno_socket ();
807 if (status == EINPROGRESS)
809 while (true)
811 fd_set writes;
812 struct timeval tv;
814 FD_ZERO (&writes);
815 FD_SET (sd, &writes);
816 tv.tv_sec = 0;
817 tv.tv_usec = 0;
819 status = select (sd + 1, NULL, &writes, NULL, &tv);
821 if (signal_received)
823 get_signal (signal_received);
824 if (*signal_received)
826 status = 0;
827 break;
830 if (status < 0)
832 status = openvpn_errno_socket ();
833 break;
835 if (status <= 0)
837 if (--connect_timeout < 0)
839 status = ETIMEDOUT;
840 break;
842 openvpn_sleep (1);
843 continue;
846 /* got it */
848 int val = 0;
849 socklen_t len;
851 len = sizeof (val);
852 if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
853 && len == sizeof (val))
854 status = val;
855 else
856 status = openvpn_errno_socket ();
857 break;
861 #else
862 status = connect (sd, (struct sockaddr *) &remote->sa, sizeof (remote->sa));
863 if (status)
864 status = openvpn_errno_socket ();
865 #endif
867 return status;
870 void
871 socket_connect (socket_descriptor_t *sd,
872 struct openvpn_sockaddr *local,
873 bool bind_local,
874 struct openvpn_sockaddr *remote,
875 const bool connection_profiles_defined,
876 const char *remote_dynamic,
877 bool *remote_changed,
878 const int connect_retry_seconds,
879 const int connect_timeout,
880 const int connect_retry_max,
881 const unsigned int sockflags,
882 volatile int *signal_received)
884 struct gc_arena gc = gc_new ();
885 int retry = 0;
887 #ifdef CONNECT_NONBLOCK
888 msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]",
889 print_sockaddr (remote, &gc));
890 #else
891 msg (M_INFO, "Attempting to establish TCP connection with %s",
892 print_sockaddr (remote, &gc));
893 #endif
895 while (true)
897 int status;
899 #ifdef ENABLE_MANAGEMENT
900 if (management)
901 management_set_state (management,
902 OPENVPN_STATE_TCP_CONNECT,
903 NULL,
904 (in_addr_t)0,
905 (in_addr_t)0);
906 #endif
908 status = openvpn_connect (*sd, remote, connect_timeout, signal_received);
910 get_signal (signal_received);
911 if (*signal_received)
912 goto done;
914 if (!status)
915 break;
917 msg (D_LINK_ERRORS,
918 "TCP: connect to %s failed, will try again in %d seconds: %s",
919 print_sockaddr (remote, &gc),
920 connect_retry_seconds,
921 strerror_ts (status, &gc));
923 gc_reset (&gc);
925 openvpn_close_socket (*sd);
926 *sd = SOCKET_UNDEFINED;
928 if ((connect_retry_max > 0 && ++retry >= connect_retry_max) || connection_profiles_defined)
930 *signal_received = SIGUSR1;
931 goto done;
934 openvpn_sleep (connect_retry_seconds);
936 get_signal (signal_received);
937 if (*signal_received)
938 goto done;
940 *sd = create_socket_tcp ();
941 if (bind_local)
942 socket_bind (*sd, local, "TCP Client");
943 update_remote (remote_dynamic, remote, remote_changed, sockflags);
946 msg (M_INFO, "TCP connection established with %s",
947 print_sockaddr (remote, &gc));
949 done:
950 gc_free (&gc);
953 /* For stream protocols, allocate a buffer to build up packet.
954 Called after frame has been finalized. */
956 static void
957 socket_frame_init (const struct frame *frame, struct link_socket *sock)
959 #ifdef WIN32
960 overlapped_io_init (&sock->reads, frame, FALSE, false);
961 overlapped_io_init (&sock->writes, frame, TRUE, false);
962 sock->rw_handle.read = sock->reads.overlapped.hEvent;
963 sock->rw_handle.write = sock->writes.overlapped.hEvent;
964 #endif
966 if (link_socket_connection_oriented (sock))
968 #ifdef WIN32
969 stream_buf_init (&sock->stream_buf,
970 &sock->reads.buf_init,
971 sock->sockflags,
972 sock->info.proto);
973 #else
974 alloc_buf_sock_tun (&sock->stream_buf_data,
975 frame,
976 false,
977 FRAME_HEADROOM_MARKER_READ_STREAM);
979 stream_buf_init (&sock->stream_buf,
980 &sock->stream_buf_data,
981 sock->sockflags,
982 sock->info.proto);
983 #endif
988 * Adjust frame structure based on a Path MTU value given
989 * to us by the OS.
991 void
992 frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
994 frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
997 static void
998 resolve_bind_local (struct link_socket *sock)
1000 struct gc_arena gc = gc_new ();
1002 /* resolve local address if undefined */
1003 if (!addr_defined (&sock->info.lsa->local))
1005 sock->info.lsa->local.sa.sin_family = AF_INET;
1006 sock->info.lsa->local.sa.sin_addr.s_addr =
1007 (sock->local_host ? getaddr (GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
1008 sock->local_host,
1010 NULL,
1011 NULL)
1012 : htonl (INADDR_ANY));
1013 sock->info.lsa->local.sa.sin_port = htons (sock->local_port);
1016 /* bind to local address/port */
1017 if (sock->bind_local)
1019 #ifdef ENABLE_SOCKS
1020 if (sock->socks_proxy && sock->info.proto == PROTO_UDPv4)
1021 socket_bind (sock->ctrl_sd, &sock->info.lsa->local, "SOCKS");
1022 else
1023 #endif
1024 socket_bind (sock->sd, &sock->info.lsa->local, "TCP/UDP");
1026 gc_free (&gc);
1029 static void
1030 resolve_remote (struct link_socket *sock,
1031 int phase,
1032 const char **remote_dynamic,
1033 volatile int *signal_received)
1035 struct gc_arena gc = gc_new ();
1037 if (!sock->did_resolve_remote)
1039 /* resolve remote address if undefined */
1040 if (!addr_defined (&sock->info.lsa->remote))
1042 sock->info.lsa->remote.sa.sin_family = AF_INET;
1043 sock->info.lsa->remote.sa.sin_addr.s_addr = 0;
1045 if (sock->remote_host)
1047 unsigned int flags = sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sock->sockflags);
1048 int retry = 0;
1049 bool status = false;
1051 if (sock->connection_profiles_defined && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
1053 if (phase == 2)
1054 flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
1055 retry = 0;
1057 else if (phase == 1)
1059 if (sock->resolve_retry_seconds)
1061 retry = 0;
1063 else
1065 flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
1066 retry = 0;
1069 else if (phase == 2)
1071 if (sock->resolve_retry_seconds)
1073 flags |= GETADDR_FATAL;
1074 retry = sock->resolve_retry_seconds;
1076 else
1078 ASSERT (0);
1081 else
1083 ASSERT (0);
1086 sock->info.lsa->remote.sa.sin_addr.s_addr = getaddr (
1087 flags,
1088 sock->remote_host,
1089 retry,
1090 &status,
1091 signal_received);
1093 dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1094 flags,
1095 phase,
1096 retry,
1097 signal_received ? *signal_received : -1,
1098 status);
1100 if (signal_received)
1102 if (*signal_received)
1103 goto done;
1105 if (!status)
1107 if (signal_received)
1108 *signal_received = SIGUSR1;
1109 goto done;
1113 sock->info.lsa->remote.sa.sin_port = htons (sock->remote_port);
1116 /* should we re-use previous active remote address? */
1117 if (link_socket_actual_defined (&sock->info.lsa->actual))
1119 msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
1120 print_link_socket_actual (&sock->info.lsa->actual, &gc));
1121 if (remote_dynamic)
1122 *remote_dynamic = NULL;
1124 else
1126 CLEAR (sock->info.lsa->actual);
1127 sock->info.lsa->actual.dest = sock->info.lsa->remote;
1130 /* remember that we finished */
1131 sock->did_resolve_remote = true;
1134 done:
1135 gc_free (&gc);
1138 struct link_socket *
1139 link_socket_new (void)
1141 struct link_socket *sock;
1143 ALLOC_OBJ_CLEAR (sock, struct link_socket);
1144 sock->sd = SOCKET_UNDEFINED;
1145 #ifdef ENABLE_SOCKS
1146 sock->ctrl_sd = SOCKET_UNDEFINED;
1147 #endif
1148 return sock;
1151 /* bind socket if necessary */
1152 void
1153 link_socket_init_phase1 (struct link_socket *sock,
1154 const bool connection_profiles_defined,
1155 const char *local_host,
1156 int local_port,
1157 const char *remote_host,
1158 int remote_port,
1159 int proto,
1160 int mode,
1161 const struct link_socket *accept_from,
1162 #ifdef ENABLE_HTTP_PROXY
1163 struct http_proxy_info *http_proxy,
1164 #endif
1165 #ifdef ENABLE_SOCKS
1166 struct socks_proxy_info *socks_proxy,
1167 #endif
1168 #ifdef ENABLE_DEBUG
1169 int gremlin,
1170 #endif
1171 bool bind_local,
1172 bool remote_float,
1173 int inetd,
1174 struct link_socket_addr *lsa,
1175 const char *ipchange_command,
1176 const struct plugin_list *plugins,
1177 int resolve_retry_seconds,
1178 int connect_retry_seconds,
1179 int connect_timeout,
1180 int connect_retry_max,
1181 int mtu_discover_type,
1182 int rcvbuf,
1183 int sndbuf,
1184 unsigned int sockflags)
1186 ASSERT (sock);
1188 sock->connection_profiles_defined = connection_profiles_defined;
1190 sock->local_host = local_host;
1191 sock->local_port = local_port;
1192 sock->remote_host = remote_host;
1193 sock->remote_port = remote_port;
1195 #ifdef ENABLE_HTTP_PROXY
1196 sock->http_proxy = http_proxy;
1197 #endif
1199 #ifdef ENABLE_SOCKS
1200 sock->socks_proxy = socks_proxy;
1201 #endif
1203 sock->bind_local = bind_local;
1204 sock->inetd = inetd;
1205 sock->resolve_retry_seconds = resolve_retry_seconds;
1206 sock->connect_retry_seconds = connect_retry_seconds;
1207 sock->connect_timeout = connect_timeout;
1208 sock->connect_retry_max = connect_retry_max;
1209 sock->mtu_discover_type = mtu_discover_type;
1211 #ifdef ENABLE_DEBUG
1212 sock->gremlin = gremlin;
1213 #endif
1215 sock->socket_buffer_sizes.rcvbuf = rcvbuf;
1216 sock->socket_buffer_sizes.sndbuf = sndbuf;
1218 sock->sockflags = sockflags;
1220 sock->info.proto = proto;
1221 sock->info.remote_float = remote_float;
1222 sock->info.lsa = lsa;
1223 sock->info.ipchange_command = ipchange_command;
1224 sock->info.plugins = plugins;
1226 sock->mode = mode;
1227 if (mode == LS_MODE_TCP_ACCEPT_FROM)
1229 ASSERT (accept_from);
1230 ASSERT (sock->info.proto == PROTO_TCPv4_SERVER);
1231 ASSERT (!sock->inetd);
1232 sock->sd = accept_from->sd;
1235 if (false)
1237 #ifdef ENABLE_HTTP_PROXY
1238 /* are we running in HTTP proxy mode? */
1239 else if (sock->http_proxy)
1241 ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT);
1242 ASSERT (!sock->inetd);
1244 /* the proxy server */
1245 sock->remote_host = http_proxy->options.server;
1246 sock->remote_port = http_proxy->options.port;
1248 /* the OpenVPN server we will use the proxy to connect to */
1249 sock->proxy_dest_host = remote_host;
1250 sock->proxy_dest_port = remote_port;
1252 #endif
1253 #ifdef ENABLE_SOCKS
1254 /* or in Socks proxy mode? */
1255 else if (sock->socks_proxy)
1257 ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_UDPv4);
1258 ASSERT (!sock->inetd);
1260 /* the proxy server */
1261 sock->remote_host = socks_proxy->server;
1262 sock->remote_port = socks_proxy->port;
1264 /* the OpenVPN server we will use the proxy to connect to */
1265 sock->proxy_dest_host = remote_host;
1266 sock->proxy_dest_port = remote_port;
1268 #endif
1269 else
1271 sock->remote_host = remote_host;
1272 sock->remote_port = remote_port;
1275 /* bind behavior for TCP server vs. client */
1276 if (sock->info.proto == PROTO_TCPv4_SERVER)
1278 if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
1279 sock->bind_local = false;
1280 else
1281 sock->bind_local = true;
1284 /* were we started by inetd or xinetd? */
1285 if (sock->inetd)
1287 ASSERT (sock->info.proto != PROTO_TCPv4_CLIENT);
1288 ASSERT (socket_defined (inetd_socket_descriptor));
1289 sock->sd = inetd_socket_descriptor;
1291 else if (mode != LS_MODE_TCP_ACCEPT_FROM)
1293 create_socket (sock);
1294 resolve_bind_local (sock);
1295 resolve_remote (sock, 1, NULL, NULL);
1299 /* finalize socket initialization */
1300 void
1301 link_socket_init_phase2 (struct link_socket *sock,
1302 const struct frame *frame,
1303 volatile int *signal_received)
1305 struct gc_arena gc = gc_new ();
1306 const char *remote_dynamic = NULL;
1307 bool remote_changed = false;
1308 int sig_save = 0;
1310 ASSERT (sock);
1312 if (signal_received && *signal_received)
1314 sig_save = *signal_received;
1315 *signal_received = 0;
1318 /* initialize buffers */
1319 socket_frame_init (frame, sock);
1322 * Pass a remote name to connect/accept so that
1323 * they can test for dynamic IP address changes
1324 * and throw a SIGUSR1 if appropriate.
1326 if (sock->resolve_retry_seconds)
1327 remote_dynamic = sock->remote_host;
1329 /* were we started by inetd or xinetd? */
1330 if (sock->inetd)
1332 if (sock->info.proto == PROTO_TCPv4_SERVER)
1333 sock->sd =
1334 socket_listen_accept (sock->sd,
1335 &sock->info.lsa->actual,
1336 remote_dynamic,
1337 &remote_changed,
1338 &sock->info.lsa->local,
1339 false,
1340 sock->inetd == INETD_NOWAIT,
1341 signal_received);
1342 ASSERT (!remote_changed);
1343 if (*signal_received)
1344 goto done;
1346 else
1348 resolve_remote (sock, 2, &remote_dynamic, signal_received);
1350 if (*signal_received)
1351 goto done;
1353 /* TCP client/server */
1354 if (sock->info.proto == PROTO_TCPv4_SERVER)
1356 switch (sock->mode)
1358 case LS_MODE_DEFAULT:
1359 sock->sd = socket_listen_accept (sock->sd,
1360 &sock->info.lsa->actual,
1361 remote_dynamic,
1362 &remote_changed,
1363 &sock->info.lsa->local,
1364 true,
1365 false,
1366 signal_received);
1367 break;
1368 case LS_MODE_TCP_LISTEN:
1369 socket_do_listen (sock->sd,
1370 &sock->info.lsa->local,
1371 true,
1372 false);
1373 break;
1374 case LS_MODE_TCP_ACCEPT_FROM:
1375 sock->sd = socket_do_accept (sock->sd,
1376 &sock->info.lsa->actual,
1377 false);
1378 if (!socket_defined (sock->sd))
1380 *signal_received = SIGTERM;
1381 goto done;
1383 tcp_connection_established (&sock->info.lsa->actual);
1384 break;
1385 default:
1386 ASSERT (0);
1389 else if (sock->info.proto == PROTO_TCPv4_CLIENT)
1392 #ifdef GENERAL_PROXY_SUPPORT
1393 bool proxy_retry = false;
1394 #else
1395 const bool proxy_retry = false;
1396 #endif
1397 do {
1398 socket_connect (&sock->sd,
1399 &sock->info.lsa->local,
1400 sock->bind_local,
1401 &sock->info.lsa->actual.dest,
1402 sock->connection_profiles_defined,
1403 remote_dynamic,
1404 &remote_changed,
1405 sock->connect_retry_seconds,
1406 sock->connect_timeout,
1407 sock->connect_retry_max,
1408 sock->sockflags,
1409 signal_received);
1411 if (*signal_received)
1412 goto done;
1414 if (false)
1416 #ifdef ENABLE_HTTP_PROXY
1417 else if (sock->http_proxy)
1419 proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
1420 sock->sd,
1421 sock->proxy_dest_host,
1422 sock->proxy_dest_port,
1423 &sock->stream_buf.residual,
1424 signal_received);
1426 #endif
1427 #ifdef ENABLE_SOCKS
1428 else if (sock->socks_proxy)
1430 establish_socks_proxy_passthru (sock->socks_proxy,
1431 sock->sd,
1432 sock->proxy_dest_host,
1433 sock->proxy_dest_port,
1434 signal_received);
1436 #endif
1437 if (proxy_retry)
1439 openvpn_close_socket (sock->sd);
1440 sock->sd = create_socket_tcp ();
1442 } while (proxy_retry);
1444 #ifdef ENABLE_SOCKS
1445 else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
1447 socket_connect (&sock->ctrl_sd,
1448 &sock->info.lsa->local,
1449 sock->bind_local,
1450 &sock->info.lsa->actual.dest,
1451 sock->connection_profiles_defined,
1452 remote_dynamic,
1453 &remote_changed,
1454 sock->connect_retry_seconds,
1455 sock->connect_timeout,
1456 sock->connect_retry_max,
1457 sock->sockflags,
1458 signal_received);
1460 if (*signal_received)
1461 goto done;
1463 establish_socks_proxy_udpassoc (sock->socks_proxy,
1464 sock->ctrl_sd,
1465 sock->sd,
1466 &sock->socks_relay.dest,
1467 signal_received);
1469 if (*signal_received)
1470 goto done;
1472 sock->remote_host = sock->proxy_dest_host;
1473 sock->remote_port = sock->proxy_dest_port;
1474 sock->did_resolve_remote = false;
1476 sock->info.lsa->actual.dest.sa.sin_addr.s_addr = 0;
1477 sock->info.lsa->remote.sa.sin_addr.s_addr = 0;
1479 resolve_remote (sock, 1, NULL, signal_received);
1481 if (*signal_received)
1482 goto done;
1484 #endif
1486 if (*signal_received)
1487 goto done;
1489 if (remote_changed)
1491 msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
1492 sock->info.lsa->remote.sa.sin_addr.s_addr = sock->info.lsa->actual.dest.sa.sin_addr.s_addr;
1496 /* set socket buffers based on --sndbuf and --rcvbuf options */
1497 socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
1499 /* set misc socket parameters */
1500 socket_set_flags (sock->sd, sock->sockflags);
1502 /* set socket to non-blocking mode */
1503 set_nonblock (sock->sd);
1505 /* set socket file descriptor to not pass across execs, so that
1506 scripts don't have access to it */
1507 set_cloexec (sock->sd);
1509 #ifdef ENABLE_SOCKS
1510 if (socket_defined (sock->ctrl_sd))
1511 set_cloexec (sock->ctrl_sd);
1512 #endif
1514 /* set Path MTU discovery options on the socket */
1515 set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
1517 #if EXTENDED_SOCKET_ERROR_CAPABILITY
1518 /* if the OS supports it, enable extended error passing on the socket */
1519 set_sock_extended_error_passing (sock->sd);
1520 #endif
1522 /* print local address */
1523 if (sock->inetd)
1524 msg (M_INFO, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
1525 else
1526 msg (M_INFO, "%s link local%s: %s",
1527 proto2ascii (sock->info.proto, true),
1528 (sock->bind_local ? " (bound)" : ""),
1529 print_sockaddr_ex (&sock->info.lsa->local, ":", sock->bind_local ? PS_SHOW_PORT : 0, &gc));
1531 /* print active remote address */
1532 msg (M_INFO, "%s link remote: %s",
1533 proto2ascii (sock->info.proto, true),
1534 print_link_socket_actual_ex (&sock->info.lsa->actual,
1535 ":",
1536 PS_SHOW_PORT_IF_DEFINED,
1537 &gc));
1539 done:
1540 if (sig_save && signal_received)
1542 if (!*signal_received)
1543 *signal_received = sig_save;
1545 gc_free (&gc);
1548 void
1549 link_socket_close (struct link_socket *sock)
1551 if (sock)
1553 #ifdef ENABLE_DEBUG
1554 const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
1555 #else
1556 const int gremlin = 0;
1557 #endif
1559 if (socket_defined (sock->sd))
1561 #ifdef WIN32
1562 close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
1563 #endif
1564 if (!gremlin)
1566 msg (D_CLOSE, "TCP/UDP: Closing socket");
1567 if (openvpn_close_socket (sock->sd))
1568 msg (M_WARN | M_ERRNO_SOCK, "TCP/UDP: Close Socket failed");
1570 sock->sd = SOCKET_UNDEFINED;
1571 #ifdef WIN32
1572 if (!gremlin)
1574 overlapped_io_close (&sock->reads);
1575 overlapped_io_close (&sock->writes);
1577 #endif
1580 #ifdef ENABLE_SOCKS
1581 if (socket_defined (sock->ctrl_sd))
1583 if (openvpn_close_socket (sock->ctrl_sd))
1584 msg (M_WARN | M_ERRNO_SOCK, "TCP/UDP: Close Socket (ctrl_sd) failed");
1585 sock->ctrl_sd = SOCKET_UNDEFINED;
1587 #endif
1589 stream_buf_close (&sock->stream_buf);
1590 free_buf (&sock->stream_buf_data);
1591 if (!gremlin)
1592 free (sock);
1596 /* for stream protocols, allow for packet length prefix */
1597 void
1598 socket_adjust_frame_parameters (struct frame *frame, int proto)
1600 if (link_socket_proto_connection_oriented (proto))
1601 frame_add_to_extra_frame (frame, sizeof (packet_size_type));
1604 void
1605 setenv_trusted (struct env_set *es, const struct link_socket_info *info)
1607 setenv_link_socket_actual (es, "trusted", &info->lsa->actual, SA_IP_PORT);
1610 static void
1611 ipchange_fmt (const bool include_cmd, struct argv *argv, const struct link_socket_info *info, struct gc_arena *gc)
1613 const char *ip = print_sockaddr_ex (&info->lsa->actual.dest, NULL, 0, gc);
1614 const char *port = print_sockaddr_ex (&info->lsa->actual.dest, NULL, PS_DONT_SHOW_ADDR|PS_SHOW_PORT, gc);
1615 if (include_cmd)
1616 argv_printf (argv, "%sc %s %s",
1617 info->ipchange_command,
1619 port);
1620 else
1621 argv_printf (argv, "%s %s",
1623 port);
1626 void
1627 link_socket_connection_initiated (const struct buffer *buf,
1628 struct link_socket_info *info,
1629 const struct link_socket_actual *act,
1630 const char *common_name,
1631 struct env_set *es)
1633 struct gc_arena gc = gc_new ();
1635 info->lsa->actual = *act; /* Note: skip this line for --force-dest */
1636 setenv_trusted (es, info);
1637 info->connection_established = true;
1639 /* Print connection initiated message, with common name if available */
1641 struct buffer out = alloc_buf_gc (256, &gc);
1642 if (common_name)
1643 buf_printf (&out, "[%s] ", common_name);
1644 buf_printf (&out, "Peer Connection Initiated with %s", print_link_socket_actual (&info->lsa->actual, &gc));
1645 msg (M_INFO, "%s", BSTR (&out));
1648 /* set environmental vars */
1649 setenv_str (es, "common_name", common_name);
1651 /* Process --ipchange plugin */
1652 if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
1654 struct argv argv = argv_new ();
1655 ipchange_fmt (false, &argv, info, &gc);
1656 if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1657 msg (M_WARN, "WARNING: ipchange plugin call failed");
1658 argv_reset (&argv);
1661 /* Process --ipchange option */
1662 if (info->ipchange_command)
1664 struct argv argv = argv_new ();
1665 setenv_str (es, "script_type", "ipchange");
1666 ipchange_fmt (true, &argv, info, &gc);
1667 openvpn_execve_check (&argv, es, S_SCRIPT, "ip-change command failed");
1668 argv_reset (&argv);
1671 gc_free (&gc);
1674 void
1675 link_socket_bad_incoming_addr (struct buffer *buf,
1676 const struct link_socket_info *info,
1677 const struct link_socket_actual *from_addr)
1679 struct gc_arena gc = gc_new ();
1681 msg (D_LINK_ERRORS,
1682 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
1683 print_link_socket_actual (from_addr, &gc),
1684 (int)from_addr->dest.sa.sin_family,
1685 print_sockaddr (&info->lsa->remote, &gc));
1686 buf->len = 0;
1688 gc_free (&gc);
1691 void
1692 link_socket_bad_outgoing_addr (void)
1694 dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
1697 in_addr_t
1698 link_socket_current_remote (const struct link_socket_info *info)
1700 const struct link_socket_addr *lsa = info->lsa;
1702 if (link_socket_actual_defined (&lsa->actual))
1703 return ntohl (lsa->actual.dest.sa.sin_addr.s_addr);
1704 else if (addr_defined (&lsa->remote))
1705 return ntohl (lsa->remote.sa.sin_addr.s_addr);
1706 else
1707 return 0;
1711 * Return a status string describing socket state.
1713 const char *
1714 socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
1716 struct buffer out = alloc_buf_gc (64, gc);
1717 if (s)
1719 if (rwflags & EVENT_READ)
1721 buf_printf (&out, "S%s",
1722 (s->rwflags_debug & EVENT_READ) ? "R" : "r");
1723 #ifdef WIN32
1724 buf_printf (&out, "%s",
1725 overlapped_io_state_ascii (&s->reads));
1726 #endif
1728 if (rwflags & EVENT_WRITE)
1730 buf_printf (&out, "S%s",
1731 (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
1732 #ifdef WIN32
1733 buf_printf (&out, "%s",
1734 overlapped_io_state_ascii (&s->writes));
1735 #endif
1738 else
1740 buf_printf (&out, "S?");
1742 return BSTR (&out);
1746 * Stream buffer functions, used to packetize a TCP
1747 * stream connection.
1750 static inline void
1751 stream_buf_reset (struct stream_buf *sb)
1753 dmsg (D_STREAM_DEBUG, "STREAM: RESET");
1754 sb->residual_fully_formed = false;
1755 sb->buf = sb->buf_init;
1756 buf_reset (&sb->next);
1757 sb->len = -1;
1760 void
1761 stream_buf_init (struct stream_buf *sb,
1762 struct buffer *buf,
1763 const unsigned int sockflags,
1764 const int proto)
1766 sb->buf_init = *buf;
1767 sb->maxlen = sb->buf_init.len;
1768 sb->buf_init.len = 0;
1769 sb->residual = alloc_buf (sb->maxlen);
1770 sb->error = false;
1771 #if PORT_SHARE
1772 sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCPv4_SERVER))
1773 ? PS_ENABLED
1774 : PS_DISABLED;
1775 #endif
1776 stream_buf_reset (sb);
1778 dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
1781 static inline void
1782 stream_buf_set_next (struct stream_buf *sb)
1784 /* set up 'next' for next i/o read */
1785 sb->next = sb->buf;
1786 sb->next.offset = sb->buf.offset + sb->buf.len;
1787 sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
1788 dmsg (D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
1789 sb->buf.offset, sb->buf.len,
1790 sb->next.offset, sb->next.len,
1791 sb->len, sb->maxlen);
1792 ASSERT (sb->next.len > 0);
1793 ASSERT (buf_safe (&sb->buf, sb->next.len));
1796 static inline void
1797 stream_buf_get_final (struct stream_buf *sb, struct buffer *buf)
1799 dmsg (D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
1800 buf_defined (&sb->buf) ? sb->buf.len : -1);
1801 ASSERT (buf_defined (&sb->buf));
1802 *buf = sb->buf;
1805 static inline void
1806 stream_buf_get_next (struct stream_buf *sb, struct buffer *buf)
1808 dmsg (D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
1809 buf_defined (&sb->next) ? sb->next.len : -1);
1810 ASSERT (buf_defined (&sb->next));
1811 *buf = sb->next;
1814 bool
1815 stream_buf_read_setup_dowork (struct link_socket* sock)
1817 if (sock->stream_buf.residual.len && !sock->stream_buf.residual_fully_formed)
1819 ASSERT (buf_copy (&sock->stream_buf.buf, &sock->stream_buf.residual));
1820 ASSERT (buf_init (&sock->stream_buf.residual, 0));
1821 sock->stream_buf.residual_fully_formed = stream_buf_added (&sock->stream_buf, 0);
1822 dmsg (D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
1823 sock->stream_buf.residual_fully_formed ? "YES" : "NO",
1824 sock->stream_buf.residual.len);
1827 if (!sock->stream_buf.residual_fully_formed)
1828 stream_buf_set_next (&sock->stream_buf);
1829 return !sock->stream_buf.residual_fully_formed;
1832 bool
1833 stream_buf_added (struct stream_buf *sb,
1834 int length_added)
1836 dmsg (D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
1837 if (length_added > 0)
1838 sb->buf.len += length_added;
1840 /* if length unknown, see if we can get the length prefix from
1841 the head of the buffer */
1842 if (sb->len < 0 && sb->buf.len >= (int) sizeof (packet_size_type))
1844 packet_size_type net_size;
1846 #if PORT_SHARE
1847 if (sb->port_share_state == PS_ENABLED)
1849 if (!is_openvpn_protocol (&sb->buf))
1851 msg (D_STREAM_ERRORS, "Non-OpenVPN client protocol detected");
1852 sb->port_share_state = PS_FOREIGN;
1853 sb->error = true;
1854 return false;
1856 else
1857 sb->port_share_state = PS_DISABLED;
1859 #endif
1861 ASSERT (buf_read (&sb->buf, &net_size, sizeof (net_size)));
1862 sb->len = ntohps (net_size);
1864 if (sb->len < 1 || sb->len > sb->maxlen)
1866 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 -- [Attemping restart...]", sb->len, sb->maxlen);
1867 stream_buf_reset (sb);
1868 sb->error = true;
1869 return false;
1873 /* is our incoming packet fully read? */
1874 if (sb->len > 0 && sb->buf.len >= sb->len)
1876 /* save any residual data that's part of the next packet */
1877 ASSERT (buf_init (&sb->residual, 0));
1878 if (sb->buf.len > sb->len)
1879 ASSERT (buf_copy_excess (&sb->residual, &sb->buf, sb->len));
1880 dmsg (D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
1881 BLEN (&sb->buf),
1882 BLEN (&sb->residual));
1883 return true;
1885 else
1887 dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
1888 stream_buf_set_next (sb);
1889 return false;
1893 void
1894 stream_buf_close (struct stream_buf* sb)
1896 free_buf (&sb->residual);
1900 * The listen event is a special event whose sole purpose is
1901 * to tell us that there's a new incoming connection on a
1902 * TCP socket, for use in server mode.
1904 event_t
1905 socket_listen_event_handle (struct link_socket *s)
1907 #ifdef WIN32
1908 if (!defined_net_event_win32 (&s->listen_handle))
1909 init_net_event_win32 (&s->listen_handle, FD_ACCEPT, s->sd, 0);
1910 return &s->listen_handle;
1911 #else
1912 return s->sd;
1913 #endif
1917 * Format IP addresses in ascii
1920 const char *
1921 print_sockaddr (const struct openvpn_sockaddr *addr, struct gc_arena *gc)
1923 return print_sockaddr_ex (addr, ":", PS_SHOW_PORT, gc);
1926 const char *
1927 print_sockaddr_ex (const struct openvpn_sockaddr *addr,
1928 const char* separator,
1929 const unsigned int flags,
1930 struct gc_arena *gc)
1932 if (addr)
1934 struct buffer out = alloc_buf_gc (64, gc);
1935 const int port = ntohs (addr->sa.sin_port);
1937 mutex_lock_static (L_INET_NTOA);
1938 if (!(flags & PS_DONT_SHOW_ADDR))
1939 buf_printf (&out, "%s", (addr_defined (addr) ? inet_ntoa (addr->sa.sin_addr) : "[undef]"));
1940 mutex_unlock_static (L_INET_NTOA);
1942 if (((flags & PS_SHOW_PORT) || (addr_defined (addr) && (flags & PS_SHOW_PORT_IF_DEFINED)))
1943 && port)
1945 if (separator)
1946 buf_printf (&out, "%s", separator);
1948 buf_printf (&out, "%d", port);
1950 return BSTR (&out);
1952 else
1953 return "[NULL]";
1956 const char *
1957 print_link_socket_actual (const struct link_socket_actual *act, struct gc_arena *gc)
1959 return print_link_socket_actual_ex (act, ":", PS_SHOW_PORT|PS_SHOW_PKTINFO, gc);
1962 const char *
1963 print_link_socket_actual_ex (const struct link_socket_actual *act,
1964 const char *separator,
1965 const unsigned int flags,
1966 struct gc_arena *gc)
1968 if (act)
1970 struct buffer out = alloc_buf_gc (128, gc);
1971 buf_printf (&out, "%s", print_sockaddr_ex (&act->dest, separator, flags, gc));
1972 #if ENABLE_IP_PKTINFO
1973 if ((flags & PS_SHOW_PKTINFO) && act->pi.ipi_spec_dst.s_addr)
1975 struct openvpn_sockaddr sa;
1976 CLEAR (sa);
1977 sa.sa.sin_addr = act->pi.ipi_spec_dst;
1978 buf_printf (&out, " (via %s)", print_sockaddr_ex (&sa, separator, 0, gc));
1980 #endif
1981 return BSTR (&out);
1983 else
1984 return "[NULL]";
1988 * Convert an in_addr_t in host byte order
1989 * to an ascii dotted quad.
1991 const char *
1992 print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
1994 struct in_addr ia;
1995 struct buffer out = alloc_buf_gc (64, gc);
1997 if (addr || !(flags & IA_EMPTY_IF_UNDEF))
1999 CLEAR (ia);
2000 ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
2002 mutex_lock_static (L_INET_NTOA);
2003 buf_printf (&out, "%s", inet_ntoa (ia));
2004 mutex_unlock_static (L_INET_NTOA);
2006 return BSTR (&out);
2009 /* set environmental variables for ip/port in *addr */
2010 void
2011 setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const bool flags)
2013 char name_buf[256];
2015 if (flags & SA_IP_PORT)
2016 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
2017 else
2018 openvpn_snprintf (name_buf, sizeof (name_buf), "%s", name_prefix);
2020 mutex_lock_static (L_INET_NTOA);
2021 setenv_str (es, name_buf, inet_ntoa (addr->sa.sin_addr));
2022 mutex_unlock_static (L_INET_NTOA);
2024 if ((flags & SA_IP_PORT) && addr->sa.sin_port)
2026 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
2027 setenv_int (es, name_buf, ntohs (addr->sa.sin_port));
2031 void
2032 setenv_in_addr_t (struct env_set *es, const char *name_prefix, in_addr_t addr, const bool flags)
2034 if (addr || !(flags & SA_SET_IF_NONZERO))
2036 struct openvpn_sockaddr si;
2037 CLEAR (si);
2038 si.sa.sin_addr.s_addr = htonl (addr);
2039 setenv_sockaddr (es, name_prefix, &si, flags);
2043 void
2044 setenv_link_socket_actual (struct env_set *es,
2045 const char *name_prefix,
2046 const struct link_socket_actual *act,
2047 const bool flags)
2049 setenv_sockaddr (es, name_prefix, &act->dest, flags);
2053 * Convert protocol names between index and ascii form.
2056 struct proto_names {
2057 const char *short_form;
2058 const char *display_form;
2061 /* Indexed by PROTO_x */
2062 static const struct proto_names proto_names[] = {
2063 {"udp", "UDPv4"},
2064 {"tcp-server", "TCPv4_SERVER"},
2065 {"tcp-client", "TCPv4_CLIENT"},
2066 {"tcp", "TCPv4"}
2070 ascii2proto (const char* proto_name)
2072 int i;
2073 ASSERT (PROTO_N == SIZE (proto_names));
2074 for (i = 0; i < PROTO_N; ++i)
2075 if (!strcmp (proto_name, proto_names[i].short_form))
2076 return i;
2077 return -1;
2080 const char *
2081 proto2ascii (int proto, bool display_form)
2083 ASSERT (PROTO_N == SIZE (proto_names));
2084 if (proto < 0 || proto >= PROTO_N)
2085 return "[unknown protocol]";
2086 else if (display_form)
2087 return proto_names[proto].display_form;
2088 else
2089 return proto_names[proto].short_form;
2092 const char *
2093 proto2ascii_all (struct gc_arena *gc)
2095 struct buffer out = alloc_buf_gc (256, gc);
2096 int i;
2098 ASSERT (PROTO_N == SIZE (proto_names));
2099 for (i = 0; i < PROTO_N; ++i)
2101 if (i)
2102 buf_printf(&out, " ");
2103 buf_printf(&out, "[%s]", proto2ascii(i, false));
2105 return BSTR (&out);
2109 * Given a local proto, return local proto
2110 * if !remote, or compatible remote proto
2111 * if remote.
2113 * This is used for options compatibility
2114 * checking.
2117 proto_remote (int proto, bool remote)
2119 ASSERT (proto >= 0 && proto < PROTO_N);
2120 if (remote)
2122 if (proto == PROTO_TCPv4_SERVER)
2123 return PROTO_TCPv4_CLIENT;
2124 if (proto == PROTO_TCPv4_CLIENT)
2125 return PROTO_TCPv4_SERVER;
2127 return proto;
2131 * Bad incoming address lengths that differ from what
2132 * we expect are considered to be fatal errors.
2134 void
2135 bad_address_length (int actual, int expected)
2137 msg (M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
2138 actual,
2139 expected);
2143 * Socket Read Routines
2147 link_socket_read_tcp (struct link_socket *sock,
2148 struct buffer *buf)
2150 int len = 0;
2152 if (!sock->stream_buf.residual_fully_formed)
2154 #ifdef WIN32
2155 len = socket_finalize (sock->sd, &sock->reads, buf, NULL);
2156 #else
2157 struct buffer frag;
2158 stream_buf_get_next (&sock->stream_buf, &frag);
2159 len = recv (sock->sd, BPTR (&frag), BLEN (&frag), MSG_NOSIGNAL);
2160 #endif
2162 if (!len)
2163 sock->stream_reset = true;
2164 if (len <= 0)
2165 return buf->len = len;
2168 if (sock->stream_buf.residual_fully_formed
2169 || stream_buf_added (&sock->stream_buf, len)) /* packet complete? */
2171 stream_buf_get_final (&sock->stream_buf, buf);
2172 stream_buf_reset (&sock->stream_buf);
2173 return buf->len;
2175 else
2176 return buf->len = 0; /* no error, but packet is still incomplete */
2179 #ifndef WIN32
2181 #if ENABLE_IP_PKTINFO
2183 #pragma pack(1) /* needed to keep structure size consistent for 32 vs. 64-bit architectures */
2184 struct openvpn_pktinfo
2186 struct cmsghdr cmsghdr;
2187 struct in_pktinfo in_pktinfo;
2189 #pragma pack()
2191 static socklen_t
2192 link_socket_read_udp_posix_recvmsg (struct link_socket *sock,
2193 struct buffer *buf,
2194 int maxsize,
2195 struct link_socket_actual *from)
2197 struct iovec iov;
2198 struct openvpn_pktinfo opi;
2199 struct msghdr mesg;
2200 socklen_t fromlen = sizeof (from->dest.sa);
2202 iov.iov_base = BPTR (buf);
2203 iov.iov_len = maxsize;
2204 mesg.msg_iov = &iov;
2205 mesg.msg_iovlen = 1;
2206 mesg.msg_name = &from->dest.sa;
2207 mesg.msg_namelen = fromlen;
2208 mesg.msg_control = &opi;
2209 mesg.msg_controllen = sizeof (opi);
2210 buf->len = recvmsg (sock->sd, &mesg, 0);
2211 if (buf->len >= 0)
2213 struct cmsghdr *cmsg;
2214 fromlen = mesg.msg_namelen;
2215 cmsg = CMSG_FIRSTHDR (&mesg);
2216 if (cmsg != NULL
2217 && CMSG_NXTHDR (&mesg, cmsg) == NULL
2218 && cmsg->cmsg_level == SOL_IP
2219 && cmsg->cmsg_type == IP_PKTINFO
2220 && cmsg->cmsg_len >= sizeof (opi))
2222 struct in_pktinfo *pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
2223 from->pi.ipi_ifindex = pkti->ipi_ifindex;
2224 from->pi.ipi_spec_dst = pkti->ipi_spec_dst;
2227 return fromlen;
2229 #endif
2232 link_socket_read_udp_posix (struct link_socket *sock,
2233 struct buffer *buf,
2234 int maxsize,
2235 struct link_socket_actual *from)
2237 socklen_t fromlen = sizeof (from->dest.sa);
2238 from->dest.sa.sin_addr.s_addr = 0;
2239 ASSERT (buf_safe (buf, maxsize));
2240 #if ENABLE_IP_PKTINFO
2241 if (sock->sockflags & SF_USE_IP_PKTINFO)
2242 fromlen = link_socket_read_udp_posix_recvmsg (sock, buf, maxsize, from);
2243 else
2244 #endif
2245 buf->len = recvfrom (sock->sd, BPTR (buf), maxsize, 0,
2246 (struct sockaddr *) &from->dest.sa, &fromlen);
2247 if (fromlen != sizeof (from->dest.sa))
2248 bad_address_length (fromlen, sizeof (from->dest.sa));
2249 return buf->len;
2252 #endif
2255 * Socket Write Routines
2259 link_socket_write_tcp (struct link_socket *sock,
2260 struct buffer *buf,
2261 struct link_socket_actual *to)
2263 packet_size_type len = BLEN (buf);
2264 dmsg (D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
2265 ASSERT (len <= sock->stream_buf.maxlen);
2266 len = htonps (len);
2267 ASSERT (buf_write_prepend (buf, &len, sizeof (len)));
2268 #ifdef WIN32
2269 return link_socket_write_win32 (sock, buf, to);
2270 #else
2271 return link_socket_write_tcp_posix (sock, buf, to);
2272 #endif
2275 #if ENABLE_IP_PKTINFO
2278 link_socket_write_udp_posix_sendmsg (struct link_socket *sock,
2279 struct buffer *buf,
2280 struct link_socket_actual *to)
2282 struct iovec iov;
2283 struct msghdr mesg;
2284 struct cmsghdr *cmsg;
2285 struct in_pktinfo *pkti;
2286 struct openvpn_pktinfo opi;
2288 iov.iov_base = BPTR (buf);
2289 iov.iov_len = BLEN (buf);
2290 mesg.msg_iov = &iov;
2291 mesg.msg_iovlen = 1;
2292 mesg.msg_name = &to->dest.sa;
2293 mesg.msg_namelen = sizeof (to->dest.sa);
2294 mesg.msg_control = &opi;
2295 mesg.msg_controllen = sizeof (opi);
2296 mesg.msg_flags = 0;
2297 cmsg = CMSG_FIRSTHDR (&mesg);
2298 cmsg->cmsg_len = sizeof (opi);
2299 cmsg->cmsg_level = SOL_IP;
2300 cmsg->cmsg_type = IP_PKTINFO;
2301 pkti = (struct in_pktinfo *) CMSG_DATA (cmsg);
2302 pkti->ipi_ifindex = to->pi.ipi_ifindex;
2303 pkti->ipi_spec_dst = to->pi.ipi_spec_dst;
2304 pkti->ipi_addr.s_addr = 0;
2305 return sendmsg (sock->sd, &mesg, 0);
2308 #endif
2311 * Win32 overlapped socket I/O functions.
2314 #ifdef WIN32
2317 socket_recv_queue (struct link_socket *sock, int maxsize)
2319 if (sock->reads.iostate == IOSTATE_INITIAL)
2321 WSABUF wsabuf[1];
2322 int status;
2324 /* reset buf to its initial state */
2325 if (sock->info.proto == PROTO_UDPv4)
2327 sock->reads.buf = sock->reads.buf_init;
2329 else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
2331 stream_buf_get_next (&sock->stream_buf, &sock->reads.buf);
2333 else
2335 ASSERT (0);
2338 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
2339 wsabuf[0].buf = BPTR (&sock->reads.buf);
2340 wsabuf[0].len = maxsize ? maxsize : BLEN (&sock->reads.buf);
2342 /* check for buffer overflow */
2343 ASSERT (wsabuf[0].len <= BLEN (&sock->reads.buf));
2345 /* the overlapped read will signal this event on I/O completion */
2346 ASSERT (ResetEvent (sock->reads.overlapped.hEvent));
2347 sock->reads.flags = 0;
2349 if (sock->info.proto == PROTO_UDPv4)
2351 sock->reads.addr_defined = true;
2352 sock->reads.addrlen = sizeof (sock->reads.addr);
2353 status = WSARecvFrom(
2354 sock->sd,
2355 wsabuf,
2357 &sock->reads.size,
2358 &sock->reads.flags,
2359 (struct sockaddr *) &sock->reads.addr,
2360 &sock->reads.addrlen,
2361 &sock->reads.overlapped,
2362 NULL);
2364 else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
2366 sock->reads.addr_defined = false;
2367 status = WSARecv(
2368 sock->sd,
2369 wsabuf,
2371 &sock->reads.size,
2372 &sock->reads.flags,
2373 &sock->reads.overlapped,
2374 NULL);
2376 else
2378 status = 0;
2379 ASSERT (0);
2382 if (!status) /* operation completed immediately? */
2384 if (sock->reads.addr_defined && sock->reads.addrlen != sizeof (sock->reads.addr))
2385 bad_address_length (sock->reads.addrlen, sizeof (sock->reads.addr));
2387 sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
2389 /* since we got an immediate return, we must signal the event object ourselves */
2390 ASSERT (SetEvent (sock->reads.overlapped.hEvent));
2391 sock->reads.status = 0;
2393 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
2394 (int) wsabuf[0].len,
2395 (int) sock->reads.size);
2397 else
2399 status = WSAGetLastError ();
2400 if (status == WSA_IO_PENDING) /* operation queued? */
2402 sock->reads.iostate = IOSTATE_QUEUED;
2403 sock->reads.status = status;
2404 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
2405 (int) wsabuf[0].len);
2407 else /* error occurred */
2409 struct gc_arena gc = gc_new ();
2410 ASSERT (SetEvent (sock->reads.overlapped.hEvent));
2411 sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
2412 sock->reads.status = status;
2413 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
2414 (int) wsabuf[0].len,
2415 strerror_win32 (status, &gc));
2416 gc_free (&gc);
2420 return sock->reads.iostate;
2424 socket_send_queue (struct link_socket *sock, struct buffer *buf, const struct link_socket_actual *to)
2426 if (sock->writes.iostate == IOSTATE_INITIAL)
2428 WSABUF wsabuf[1];
2429 int status;
2431 /* make a private copy of buf */
2432 sock->writes.buf = sock->writes.buf_init;
2433 sock->writes.buf.len = 0;
2434 ASSERT (buf_copy (&sock->writes.buf, buf));
2436 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
2437 wsabuf[0].buf = BPTR (&sock->writes.buf);
2438 wsabuf[0].len = BLEN (&sock->writes.buf);
2440 /* the overlapped write will signal this event on I/O completion */
2441 ASSERT (ResetEvent (sock->writes.overlapped.hEvent));
2442 sock->writes.flags = 0;
2444 if (sock->info.proto == PROTO_UDPv4)
2446 /* set destination address for UDP writes */
2447 sock->writes.addr_defined = true;
2448 sock->writes.addr = to->dest.sa;
2449 sock->writes.addrlen = sizeof (sock->writes.addr);
2451 status = WSASendTo(
2452 sock->sd,
2453 wsabuf,
2455 &sock->writes.size,
2456 sock->writes.flags,
2457 (struct sockaddr *) &sock->writes.addr,
2458 sock->writes.addrlen,
2459 &sock->writes.overlapped,
2460 NULL);
2462 else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
2464 /* destination address for TCP writes was established on connection initiation */
2465 sock->writes.addr_defined = false;
2467 status = WSASend(
2468 sock->sd,
2469 wsabuf,
2471 &sock->writes.size,
2472 sock->writes.flags,
2473 &sock->writes.overlapped,
2474 NULL);
2476 else
2478 status = 0;
2479 ASSERT (0);
2482 if (!status) /* operation completed immediately? */
2484 sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
2486 /* since we got an immediate return, we must signal the event object ourselves */
2487 ASSERT (SetEvent (sock->writes.overlapped.hEvent));
2489 sock->writes.status = 0;
2491 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
2492 (int) wsabuf[0].len,
2493 (int) sock->writes.size);
2495 else
2497 status = WSAGetLastError ();
2498 if (status == WSA_IO_PENDING) /* operation queued? */
2500 sock->writes.iostate = IOSTATE_QUEUED;
2501 sock->writes.status = status;
2502 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
2503 (int) wsabuf[0].len);
2505 else /* error occurred */
2507 struct gc_arena gc = gc_new ();
2508 ASSERT (SetEvent (sock->writes.overlapped.hEvent));
2509 sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
2510 sock->writes.status = status;
2512 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
2513 (int) wsabuf[0].len,
2514 strerror_win32 (status, &gc));
2516 gc_free (&gc);
2520 return sock->writes.iostate;
2524 socket_finalize (SOCKET s,
2525 struct overlapped_io *io,
2526 struct buffer *buf,
2527 struct link_socket_actual *from)
2529 int ret = -1;
2530 BOOL status;
2532 switch (io->iostate)
2534 case IOSTATE_QUEUED:
2535 status = WSAGetOverlappedResult(
2537 &io->overlapped,
2538 &io->size,
2539 FALSE,
2540 &io->flags
2542 if (status)
2544 /* successful return for a queued operation */
2545 if (buf)
2546 *buf = io->buf;
2547 ret = io->size;
2548 io->iostate = IOSTATE_INITIAL;
2549 ASSERT (ResetEvent (io->overlapped.hEvent));
2551 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
2553 else
2555 /* error during a queued operation */
2556 ret = -1;
2557 if (WSAGetLastError() != WSA_IO_INCOMPLETE)
2559 /* if no error (i.e. just not finished yet), then DON'T execute this code */
2560 io->iostate = IOSTATE_INITIAL;
2561 ASSERT (ResetEvent (io->overlapped.hEvent));
2562 msg (D_WIN32_IO | M_ERRNO_SOCK, "WIN32 I/O: Socket Completion error");
2565 break;
2567 case IOSTATE_IMMEDIATE_RETURN:
2568 io->iostate = IOSTATE_INITIAL;
2569 ASSERT (ResetEvent (io->overlapped.hEvent));
2570 if (io->status)
2572 /* error return for a non-queued operation */
2573 WSASetLastError (io->status);
2574 ret = -1;
2575 msg (D_WIN32_IO | M_ERRNO_SOCK, "WIN32 I/O: Socket Completion non-queued error");
2577 else
2579 /* successful return for a non-queued operation */
2580 if (buf)
2581 *buf = io->buf;
2582 ret = io->size;
2583 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
2585 break;
2587 case IOSTATE_INITIAL: /* were we called without proper queueing? */
2588 WSASetLastError (WSAEINVAL);
2589 ret = -1;
2590 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
2591 break;
2593 default:
2594 ASSERT (0);
2597 /* return from address if requested */
2598 if (from)
2600 if (ret >= 0 && io->addr_defined)
2602 if (io->addrlen != sizeof (io->addr))
2603 bad_address_length (io->addrlen, sizeof (io->addr));
2604 from->dest.sa = io->addr;
2606 else
2607 CLEAR (from->dest.sa);
2610 if (buf)
2611 buf->len = ret;
2612 return ret;
2615 #endif /* WIN32 */
2618 * Socket event notification
2621 unsigned int
2622 socket_set (struct link_socket *s,
2623 struct event_set *es,
2624 unsigned int rwflags,
2625 void *arg,
2626 unsigned int *persistent)
2628 if (s)
2630 if ((rwflags & EVENT_READ) && !stream_buf_read_setup (s))
2632 ASSERT (!persistent);
2633 rwflags &= ~EVENT_READ;
2636 #ifdef WIN32
2637 if (rwflags & EVENT_READ)
2638 socket_recv_queue (s, 0);
2639 #endif
2641 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
2642 if (!persistent || *persistent != rwflags)
2644 event_ctl (es, socket_event_handle (s), rwflags, arg);
2645 if (persistent)
2646 *persistent = rwflags;
2649 s->rwflags_debug = rwflags;
2651 return rwflags;
2654 void
2655 sd_close (socket_descriptor_t *sd)
2657 if (sd && socket_defined (*sd))
2659 openvpn_close_socket (*sd);
2660 *sd = SOCKET_UNDEFINED;
2664 #if UNIX_SOCK_SUPPORT
2667 * code for unix domain sockets
2670 const char *
2671 sockaddr_unix_name (const struct sockaddr_un *local, const char *null)
2673 if (local && local->sun_family == PF_UNIX)
2674 return local->sun_path;
2675 else
2676 return null;
2679 socket_descriptor_t
2680 create_socket_unix (void)
2682 socket_descriptor_t sd;
2684 if ((sd = socket (PF_UNIX, SOCK_STREAM, 0)) < 0)
2685 msg (M_SOCKERR, "Cannot create unix domain socket");
2686 return sd;
2689 void
2690 socket_bind_unix (socket_descriptor_t sd,
2691 struct sockaddr_un *local,
2692 const char *prefix)
2694 struct gc_arena gc = gc_new ();
2696 #ifdef HAVE_UMASK
2697 const mode_t orig_umask = umask (0);
2698 #endif
2700 if (bind (sd, (struct sockaddr *) local, sizeof (struct sockaddr_un)))
2702 const int errnum = openvpn_errno_socket ();
2703 msg (M_FATAL, "%s: Socket bind[%d] failed on unix domain socket %s: %s",
2704 prefix,
2705 (int)sd,
2706 sockaddr_unix_name (local, "NULL"),
2707 strerror_ts (errnum, &gc));
2710 #ifdef HAVE_UMASK
2711 umask (orig_umask);
2712 #endif
2714 gc_free (&gc);
2717 socket_descriptor_t
2718 socket_accept_unix (socket_descriptor_t sd,
2719 struct sockaddr_un *remote)
2721 socklen_t remote_len = sizeof (struct sockaddr_un);
2722 socket_descriptor_t ret;
2724 CLEAR (*remote);
2725 ret = accept (sd, (struct sockaddr *) remote, &remote_len);
2726 return ret;
2730 socket_connect_unix (socket_descriptor_t sd,
2731 struct sockaddr_un *remote)
2733 int status = connect (sd, (struct sockaddr *) remote, sizeof (struct sockaddr_un));
2734 if (status)
2735 status = openvpn_errno_socket ();
2736 return status;
2739 void
2740 sockaddr_unix_init (struct sockaddr_un *local, const char *path)
2742 local->sun_family = PF_UNIX;
2743 strncpynt (local->sun_path, path, sizeof (local->sun_path));
2746 void
2747 socket_delete_unix (const struct sockaddr_un *local)
2749 const char *name = sockaddr_unix_name (local, NULL);
2750 #ifdef HAVE_UNLINK
2751 if (name && strlen (name))
2752 unlink (name);
2753 #endif
2756 bool
2757 unix_socket_get_peer_uid_gid (const socket_descriptor_t sd, int *uid, int *gid)
2759 #ifdef HAVE_GETPEEREID
2760 uid_t u;
2761 gid_t g;
2762 if (getpeereid (sd, &u, &g) == -1)
2763 return false;
2764 if (uid)
2765 *uid = u;
2766 if (gid)
2767 *gid = g;
2768 return true;
2769 #elif defined(SO_PEERCRED)
2770 struct ucred peercred;
2771 socklen_t so_len = sizeof(peercred);
2772 if (getsockopt(sd, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) == -1)
2773 return false;
2774 if (uid)
2775 *uid = peercred.uid;
2776 if (gid)
2777 *gid = peercred.gid;
2778 return true;
2779 #else
2780 return false;
2781 #endif
2784 #endif