Column sorting fixes, thanks to Tony550
[tomato.git] / release / src / router / openvpn / socket.c
blob47203985f143f9091097ee3e49065ebc89a59662
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-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
25 #include "syshead.h"
27 #include "socket.h"
28 #include "fdmisc.h"
29 #include "misc.h"
30 #include "gremlin.h"
31 #include "plugin.h"
32 #include "ps.h"
33 #include "manage.h"
34 #include "misc.h"
36 #include "memdbg.h"
38 const int proto_overhead[] = { /* indexed by PROTO_x */
39 IPv4_UDP_HEADER_SIZE,
40 IPv4_TCP_HEADER_SIZE,
41 IPv4_TCP_HEADER_SIZE,
42 IPv4_TCP_HEADER_SIZE
46 * Convert sockflags/getaddr_flags into getaddr_flags
48 static unsigned int
49 sf2gaf(const unsigned int getaddr_flags,
50 const unsigned int sockflags)
52 if (sockflags & SF_HOST_RANDOMIZE)
53 return getaddr_flags | GETADDR_RANDOMIZE;
54 else
55 return getaddr_flags;
59 * Functions related to the translation of DNS names to IP addresses.
62 static const char*
63 h_errno_msg(int h_errno_err)
65 switch (h_errno_err)
67 case HOST_NOT_FOUND:
68 return "[HOST_NOT_FOUND] The specified host is unknown.";
69 case NO_DATA:
70 return "[NO_DATA] The requested name is valid but does not have an IP address.";
71 case NO_RECOVERY:
72 return "[NO_RECOVERY] A non-recoverable name server error occurred.";
73 case TRY_AGAIN:
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.
84 in_addr_t
85 getaddr (unsigned int flags,
86 const char *hostname,
87 int resolve_retry_seconds,
88 bool *succeeded,
89 volatile int *signal_received)
91 return getaddr_multi (flags, hostname, resolve_retry_seconds, succeeded, signal_received, NULL);
94 in_addr_t
95 getaddr_multi (unsigned int flags,
96 const char *hostname,
97 int resolve_retry_seconds,
98 bool *succeeded,
99 volatile int *signal_received,
100 struct resolve_list *reslist)
102 struct in_addr ia;
103 int status;
104 int sigrec = 0;
105 int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
106 struct gc_arena gc = gc_new ();
108 if (reslist)
109 reslist->len = 0;
111 if (flags & GETADDR_RANDOMIZE)
112 hostname = hostname_randomize(hostname, &gc);
114 if (flags & GETADDR_MSG_VIRT_OUT)
115 msglevel |= M_MSG_VIRT_OUT;
117 CLEAR (ia);
118 if (succeeded)
119 *succeeded = false;
121 if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
122 && !signal_received)
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);
131 struct hostent *h;
132 const char *fmt;
133 int level = 0;
135 CLEAR (ia);
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);
145 goto done;
148 #ifdef ENABLE_MANAGEMENT
149 if (flags & GETADDR_UPDATE_MANAGEMENT_STATE)
151 if (management)
152 management_set_state (management,
153 OPENVPN_STATE_RESOLVE,
154 NULL,
155 (in_addr_t)0,
156 (in_addr_t)0);
158 #endif
161 * Resolve hostname
163 while (true)
165 /* try hostname lookup */
166 #if defined(HAVE_RES_INIT)
167 res_init ();
168 #endif
169 h = gethostbyname (hostname);
171 if (signal_received)
173 get_signal (signal_received);
174 if (*signal_received) /* were we interrupted by a signal? */
176 h = NULL;
177 if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
179 msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
180 *signal_received = 0;
182 else
183 goto done;
187 /* success? */
188 if (h)
189 break;
191 /* resolve lookup failed, should we
192 continue or fail? */
194 level = msglevel;
195 if (resolve_retries > 0)
196 level = D_RESOLVE_ERRORS;
198 msg (level,
199 fmt,
200 hostname,
201 h_errno_msg (h_errno));
203 if (--resolve_retries <= 0)
204 goto done;
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);
212 goto done;
215 ia.s_addr = *(in_addr_t *) (h->h_addr_list[0]);
217 if (ia.s_addr)
219 if (h->h_addr_list[1]) /* more than one address returned */
221 int n = 0;
223 /* count address list */
224 while (h->h_addr_list[n])
225 ++n;
226 ASSERT (n >= 2);
228 msg (D_RESOLVE_ERRORS, "RESOLVE: NOTE: %s resolves to %d addresses",
229 hostname,
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]);
238 if (reslist)
240 int i;
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)
245 a = ntohl(a);
246 reslist->data[i] = a;
248 reslist->len = i;
253 /* hostname resolve succeeded */
254 if (succeeded)
255 *succeeded = true;
257 else
259 /* IP address parse succeeded */
260 if (succeeded)
261 *succeeded = true;
264 done:
265 if (signal_received && *signal_received)
267 int level = 0;
268 if (flags & GETADDR_FATAL_ON_SIGNAL)
269 level = M_FATAL;
270 else if (flags & GETADDR_WARN_ON_SIGNAL)
271 level = M_WARN;
272 msg (level, "RESOLVE: signal received during DNS resolution attempt");
275 gc_free (&gc);
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;
288 CLEAR (*addr);
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 */
299 else
300 return OIA_HOSTNAME; /* probably a hostname */
303 bool
304 ip_addr_dotted_quad_safe (const char *dotted_quad)
306 /* verify non-NULL */
307 if (!dotted_quad)
308 return false;
310 /* verify length is within limits */
311 if (strlen (dotted_quad) > 15)
312 return false;
314 /* verify that all chars are either numeric or '.' and that no numeric
315 substring is greater than 3 chars */
317 int nnum = 0;
318 const char *p = dotted_quad;
319 int c;
321 while ((c = *p++))
323 if (c >= '0' && c <= '9')
325 ++nnum;
326 if (nnum > 3)
327 return false;
329 else if (c == '.')
331 nnum = 0;
333 else
334 return false;
338 /* verify that string will convert to IP address */
340 struct in_addr a;
341 return openvpn_inet_aton (dotted_quad, &a) == OIA_IP;
345 static bool
346 dns_addr_safe (const char *addr)
348 if (addr)
350 const size_t len = strlen (addr);
351 return len > 0 && len <= 255 && string_class (addr, CC_ALNUM|CC_DASH|CC_DOT, 0);
353 else
354 return false;
357 bool
358 ip_or_dns_addr_safe (const char *addr, const bool allow_fqdn)
360 if (ip_addr_dotted_quad_safe (addr))
361 return true;
362 else if (allow_fqdn)
363 return dns_addr_safe (addr);
364 else
365 return false;
368 bool
369 mac_addr_safe (const char *mac_addr)
371 /* verify non-NULL */
372 if (!mac_addr)
373 return false;
375 /* verify length is within limits */
376 if (strlen (mac_addr) > 17)
377 return false;
379 /* verify that all chars are either alphanumeric or ':' and that no
380 alphanumeric substring is greater than 2 chars */
382 int nnum = 0;
383 const char *p = mac_addr;
384 int c;
386 while ((c = *p++))
388 if ( (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') )
390 ++nnum;
391 if (nnum > 2)
392 return false;
394 else if (c == ':')
396 nnum = 0;
398 else
399 return false;
403 /* error-checking is left to script invoked in lladdr.c */
404 return true;
407 static void
408 update_remote (const char* host,
409 struct openvpn_sockaddr *addr,
410 bool *changed,
411 const unsigned int sockflags)
413 if (host && addr)
415 const in_addr_t new_addr = getaddr (
416 sf2gaf(GETADDR_RESOLVE|GETADDR_UPDATE_MANAGEMENT_STATE, sockflags),
417 host,
419 NULL,
420 NULL);
421 if (new_addr && addr->sa.sin_addr.s_addr != new_addr)
423 addr->sa.sin_addr.s_addr = new_addr;
424 *changed = true;
429 static int
430 socket_get_sndbuf (int sd)
432 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
433 int val;
434 socklen_t len;
436 len = sizeof (val);
437 if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
438 && len == sizeof (val))
439 return val;
440 #endif
441 return 0;
444 static void
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);
455 #endif
458 static int
459 socket_get_rcvbuf (int sd)
461 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
462 int val;
463 socklen_t len;
465 len = sizeof (val);
466 if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
467 && len == sizeof (val))
468 return val;
469 #endif
470 return 0;
473 static bool
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);
482 return false;
485 return true;
486 #endif
489 static void
490 socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
492 if (sbs)
494 const int sndbuf_old = socket_get_sndbuf (fd);
495 const int rcvbuf_old = socket_get_rcvbuf (fd);
497 if (sbs->sndbuf)
498 socket_set_sndbuf (fd, sbs->sndbuf);
500 if (sbs->rcvbuf)
501 socket_set_rcvbuf (fd, sbs->rcvbuf);
503 msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
504 rcvbuf_old,
505 socket_get_rcvbuf (fd),
506 sndbuf_old,
507 socket_get_sndbuf (fd));
512 * Set other socket options
515 static bool
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);
522 return false;
524 else
526 dmsg (D_OSBUF, "Socket flags: TCP_NODELAY=%d succeeded", state);
527 return true;
529 #else
530 msg (M_WARN, "NOTE: setsockopt TCP_NODELAY=%d failed (No kernel support)", state);
531 return false;
532 #endif
535 static bool
536 socket_set_flags (int sd, unsigned int sockflags)
538 if (sockflags & SF_TCP_NODELAY)
539 return socket_set_tcp_nodelay (sd, 1);
540 else
541 return true;
544 bool
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);
549 else
550 return false;
553 void
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
569 socket_descriptor_t
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 */
580 int on = 1;
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");
585 #endif
587 #if 0
588 /* set socket linger options */
590 struct linger linger;
591 linger.l_onoff = 1;
592 linger.l_linger = 2;
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");
597 #endif
599 return sd;
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)
612 int pad = 1;
613 setsockopt (sd, SOL_IP, IP_PKTINFO, (void*)&pad, sizeof(pad));
615 #endif
616 return sd;
619 static void
620 create_socket (struct link_socket *sock)
622 /* create socket */
623 if (sock->info.proto == PROTO_UDPv4)
625 sock->sd = create_socket_udp (sock->sockflags);
627 #ifdef ENABLE_SOCKS
628 if (sock->socks_proxy)
629 sock->ctrl_sd = create_socket_tcp ();
630 #endif
632 else if (sock->info.proto == PROTO_TCPv4_SERVER
633 || sock->info.proto == PROTO_TCPv4_CLIENT)
635 sock->sd = create_socket_tcp ();
637 else
639 ASSERT (0);
644 * Functions used for establishing a TCP stream connection.
647 static void
648 socket_do_listen (socket_descriptor_t sd,
649 const struct openvpn_sockaddr *local,
650 bool do_listen,
651 bool do_set_nonblock)
653 struct gc_arena gc = gc_new ();
654 if (do_listen)
656 msg (M_INFO, "Listening for incoming TCP connection on %s",
657 print_sockaddr (local, &gc));
658 if (listen (sd, 1))
659 msg (M_SOCKERR, "TCP: listen() failed");
662 /* set socket to non-blocking mode */
663 if (do_set_nonblock)
664 set_nonblock (sd);
666 gc_free (&gc);
669 socket_descriptor_t
670 socket_do_accept (socket_descriptor_t sd,
671 struct link_socket_actual *act,
672 const bool nowait)
674 socklen_t remote_len = sizeof (act->dest.sa);
675 socket_descriptor_t new_sd = SOCKET_UNDEFINED;
677 CLEAR (*act);
679 #ifdef HAVE_GETPEERNAME
680 if (nowait)
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");
686 else
687 new_sd = sd;
689 #else
690 if (nowait)
691 msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
692 #endif
693 else
695 new_sd = accept (sd, (struct sockaddr *) &act->dest.sa, &remote_len);
698 #if 0 /* For debugging only, test the effect of accept() failures */
700 static int foo = 0;
701 ++foo;
702 if (foo & 1)
703 new_sd = -1;
705 #endif
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;
717 return new_sd;
720 static void
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));
726 gc_free (&gc);
729 static int
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,
735 bool do_listen,
736 bool nowait,
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;
744 CLEAR (*act);
745 socket_do_listen (sd, local, do_listen, true);
747 while (true)
749 int status;
750 fd_set reads;
751 struct timeval tv;
753 FD_ZERO (&reads);
754 FD_SET (sd, &reads);
755 tv.tv_sec = 0;
756 tv.tv_usec = 0;
758 status = select (sd + 1, &reads, NULL, NULL, &tv);
760 get_signal (signal_received);
761 if (*signal_received)
763 gc_free (&gc);
764 return sd;
767 if (status < 0)
768 msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: select() failed");
770 if (status <= 0)
772 openvpn_sleep (1);
773 continue;
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))
784 msg (M_WARN,
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)");
790 else
791 break;
793 openvpn_sleep (1);
796 if (!nowait && openvpn_close_socket (sd))
797 msg (M_SOCKERR, "TCP: close socket failed (sd)");
799 tcp_connection_established (act);
801 gc_free (&gc);
802 return new_sd;
805 void
806 socket_bind (socket_descriptor_t sd,
807 struct openvpn_sockaddr *local,
808 const char *prefix)
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",
816 prefix,
817 print_sockaddr (local, &gc),
818 strerror_ts (errnum, &gc));
820 gc_free (&gc);
824 openvpn_connect (socket_descriptor_t sd,
825 struct openvpn_sockaddr *remote,
826 int connect_timeout,
827 volatile int *signal_received)
829 int status = 0;
831 #ifdef CONNECT_NONBLOCK
832 set_nonblock (sd);
833 status = connect (sd, (struct sockaddr *) &remote->sa, sizeof (remote->sa));
834 if (status)
835 status = openvpn_errno_socket ();
836 if (status == EINPROGRESS)
838 while (true)
840 fd_set writes;
841 struct timeval tv;
843 FD_ZERO (&writes);
844 FD_SET (sd, &writes);
845 tv.tv_sec = 0;
846 tv.tv_usec = 0;
848 status = select (sd + 1, NULL, &writes, NULL, &tv);
850 if (signal_received)
852 get_signal (signal_received);
853 if (*signal_received)
855 status = 0;
856 break;
859 if (status < 0)
861 status = openvpn_errno_socket ();
862 break;
864 if (status <= 0)
866 if (--connect_timeout < 0)
868 status = ETIMEDOUT;
869 break;
871 openvpn_sleep (1);
872 continue;
875 /* got it */
877 int val = 0;
878 socklen_t len;
880 len = sizeof (val);
881 if (getsockopt (sd, SOL_SOCKET, SO_ERROR, (void *) &val, &len) == 0
882 && len == sizeof (val))
883 status = val;
884 else
885 status = openvpn_errno_socket ();
886 break;
890 #else
891 status = connect (sd, (struct sockaddr *) &remote->sa, sizeof (remote->sa));
892 if (status)
893 status = openvpn_errno_socket ();
894 #endif
896 return status;
899 void
900 socket_connect (socket_descriptor_t *sd,
901 struct openvpn_sockaddr *local,
902 bool bind_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 ();
914 int retry = 0;
916 #ifdef CONNECT_NONBLOCK
917 msg (M_INFO, "Attempting to establish TCP connection with %s [nonblock]",
918 print_sockaddr (remote, &gc));
919 #else
920 msg (M_INFO, "Attempting to establish TCP connection with %s",
921 print_sockaddr (remote, &gc));
922 #endif
924 while (true)
926 int status;
928 #ifdef ENABLE_MANAGEMENT
929 if (management)
930 management_set_state (management,
931 OPENVPN_STATE_TCP_CONNECT,
932 NULL,
933 (in_addr_t)0,
934 (in_addr_t)0);
935 #endif
937 status = openvpn_connect (*sd, remote, connect_timeout, signal_received);
939 get_signal (signal_received);
940 if (*signal_received)
941 goto done;
943 if (!status)
944 break;
946 msg (D_LINK_ERRORS,
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));
952 gc_reset (&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;
960 goto done;
963 openvpn_sleep (connect_retry_seconds);
965 get_signal (signal_received);
966 if (*signal_received)
967 goto done;
969 *sd = create_socket_tcp ();
970 if (bind_local)
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));
978 done:
979 gc_free (&gc);
982 /* For stream protocols, allocate a buffer to build up packet.
983 Called after frame has been finalized. */
985 static void
986 socket_frame_init (const struct frame *frame, struct link_socket *sock)
988 #ifdef WIN32
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;
993 #endif
995 if (link_socket_connection_oriented (sock))
997 #ifdef WIN32
998 stream_buf_init (&sock->stream_buf,
999 &sock->reads.buf_init,
1000 sock->sockflags,
1001 sock->info.proto);
1002 #else
1003 alloc_buf_sock_tun (&sock->stream_buf_data,
1004 frame,
1005 false,
1006 FRAME_HEADROOM_MARKER_READ_STREAM);
1008 stream_buf_init (&sock->stream_buf,
1009 &sock->stream_buf_data,
1010 sock->sockflags,
1011 sock->info.proto);
1012 #endif
1017 * Adjust frame structure based on a Path MTU value given
1018 * to us by the OS.
1020 void
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);
1026 static void
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,
1037 sock->local_host,
1039 NULL,
1040 NULL)
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)
1048 #ifdef ENABLE_SOCKS
1049 if (sock->socks_proxy && sock->info.proto == PROTO_UDPv4)
1050 socket_bind (sock->ctrl_sd, &sock->info.lsa->local, "SOCKS");
1051 else
1052 #endif
1053 socket_bind (sock->sd, &sock->info.lsa->local, "TCP/UDP");
1055 gc_free (&gc);
1058 static void
1059 resolve_remote (struct link_socket *sock,
1060 int phase,
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);
1077 int retry = 0;
1078 bool status = false;
1080 if (sock->connection_profiles_defined && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
1082 if (phase == 2)
1083 flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
1084 retry = 0;
1086 else if (phase == 1)
1088 if (sock->resolve_retry_seconds)
1090 retry = 0;
1092 else
1094 flags |= (GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY);
1095 retry = 0;
1098 else if (phase == 2)
1100 if (sock->resolve_retry_seconds)
1102 flags |= GETADDR_FATAL;
1103 retry = sock->resolve_retry_seconds;
1105 else
1107 ASSERT (0);
1110 else
1112 ASSERT (0);
1115 sock->info.lsa->remote.sa.sin_addr.s_addr = getaddr (
1116 flags,
1117 sock->remote_host,
1118 retry,
1119 &status,
1120 signal_received);
1122 dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
1123 flags,
1124 phase,
1125 retry,
1126 signal_received ? *signal_received : -1,
1127 status);
1129 if (signal_received)
1131 if (*signal_received)
1132 goto done;
1134 if (!status)
1136 if (signal_received)
1137 *signal_received = SIGUSR1;
1138 goto done;
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));
1150 if (remote_dynamic)
1151 *remote_dynamic = NULL;
1153 else
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;
1163 done:
1164 gc_free (&gc);
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;
1174 #ifdef ENABLE_SOCKS
1175 sock->ctrl_sd = SOCKET_UNDEFINED;
1176 #endif
1177 return sock;
1180 /* bind socket if necessary */
1181 void
1182 link_socket_init_phase1 (struct link_socket *sock,
1183 const bool connection_profiles_defined,
1184 const char *local_host,
1185 int local_port,
1186 const char *remote_host,
1187 int remote_port,
1188 int proto,
1189 int mode,
1190 const struct link_socket *accept_from,
1191 #ifdef ENABLE_HTTP_PROXY
1192 struct http_proxy_info *http_proxy,
1193 #endif
1194 #ifdef ENABLE_SOCKS
1195 struct socks_proxy_info *socks_proxy,
1196 #endif
1197 #ifdef ENABLE_DEBUG
1198 int gremlin,
1199 #endif
1200 bool bind_local,
1201 bool remote_float,
1202 int inetd,
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,
1211 int rcvbuf,
1212 int sndbuf,
1213 unsigned int sockflags)
1215 ASSERT (sock);
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;
1226 #endif
1228 #ifdef ENABLE_SOCKS
1229 sock->socks_proxy = socks_proxy;
1230 #endif
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;
1240 #ifdef ENABLE_DEBUG
1241 sock->gremlin = gremlin;
1242 #endif
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;
1255 sock->mode = mode;
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;
1264 if (false)
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;
1281 #endif
1282 #ifdef ENABLE_SOCKS
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;
1297 #endif
1298 else
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;
1309 else
1310 sock->bind_local = true;
1313 /* were we started by inetd or xinetd? */
1314 if (sock->inetd)
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);
1332 /* finalize socket initialization */
1333 void
1334 link_socket_init_phase2 (struct link_socket *sock,
1335 const struct frame *frame,
1336 volatile int *signal_received)
1338 struct gc_arena gc = gc_new ();
1339 const char *remote_dynamic = NULL;
1340 bool remote_changed = false;
1341 int sig_save = 0;
1343 ASSERT (sock);
1345 if (signal_received && *signal_received)
1347 sig_save = *signal_received;
1348 *signal_received = 0;
1351 /* initialize buffers */
1352 socket_frame_init (frame, sock);
1355 * Pass a remote name to connect/accept so that
1356 * they can test for dynamic IP address changes
1357 * and throw a SIGUSR1 if appropriate.
1359 if (sock->resolve_retry_seconds)
1360 remote_dynamic = sock->remote_host;
1362 /* were we started by inetd or xinetd? */
1363 if (sock->inetd)
1365 if (sock->info.proto == PROTO_TCPv4_SERVER)
1366 sock->sd =
1367 socket_listen_accept (sock->sd,
1368 &sock->info.lsa->actual,
1369 remote_dynamic,
1370 &remote_changed,
1371 &sock->info.lsa->local,
1372 false,
1373 sock->inetd == INETD_NOWAIT,
1374 signal_received);
1375 ASSERT (!remote_changed);
1376 if (*signal_received)
1377 goto done;
1379 else
1381 resolve_remote (sock, 2, &remote_dynamic, signal_received);
1383 if (*signal_received)
1384 goto done;
1386 /* TCP client/server */
1387 if (sock->info.proto == PROTO_TCPv4_SERVER)
1389 switch (sock->mode)
1391 case LS_MODE_DEFAULT:
1392 sock->sd = socket_listen_accept (sock->sd,
1393 &sock->info.lsa->actual,
1394 remote_dynamic,
1395 &remote_changed,
1396 &sock->info.lsa->local,
1397 true,
1398 false,
1399 signal_received);
1400 break;
1401 case LS_MODE_TCP_LISTEN:
1402 socket_do_listen (sock->sd,
1403 &sock->info.lsa->local,
1404 true,
1405 false);
1406 break;
1407 case LS_MODE_TCP_ACCEPT_FROM:
1408 sock->sd = socket_do_accept (sock->sd,
1409 &sock->info.lsa->actual,
1410 false);
1411 if (!socket_defined (sock->sd))
1413 *signal_received = SIGTERM;
1414 goto done;
1416 tcp_connection_established (&sock->info.lsa->actual);
1417 break;
1418 default:
1419 ASSERT (0);
1422 else if (sock->info.proto == PROTO_TCPv4_CLIENT)
1425 #ifdef GENERAL_PROXY_SUPPORT
1426 bool proxy_retry = false;
1427 #else
1428 const bool proxy_retry = false;
1429 #endif
1430 do {
1431 socket_connect (&sock->sd,
1432 &sock->info.lsa->local,
1433 sock->bind_local,
1434 &sock->info.lsa->actual.dest,
1435 sock->connection_profiles_defined,
1436 remote_dynamic,
1437 &remote_changed,
1438 sock->connect_retry_seconds,
1439 sock->connect_timeout,
1440 sock->connect_retry_max,
1441 sock->sockflags,
1442 signal_received);
1444 if (*signal_received)
1445 goto done;
1447 if (false)
1449 #ifdef ENABLE_HTTP_PROXY
1450 else if (sock->http_proxy)
1452 proxy_retry = establish_http_proxy_passthru (sock->http_proxy,
1453 sock->sd,
1454 sock->proxy_dest_host,
1455 sock->proxy_dest_port,
1456 &sock->stream_buf.residual,
1457 signal_received);
1459 #endif
1460 #ifdef ENABLE_SOCKS
1461 else if (sock->socks_proxy)
1463 establish_socks_proxy_passthru (sock->socks_proxy,
1464 sock->sd,
1465 sock->proxy_dest_host,
1466 sock->proxy_dest_port,
1467 signal_received);
1469 #endif
1470 if (proxy_retry)
1472 openvpn_close_socket (sock->sd);
1473 sock->sd = create_socket_tcp ();
1475 } while (proxy_retry);
1477 #ifdef ENABLE_SOCKS
1478 else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
1480 socket_connect (&sock->ctrl_sd,
1481 &sock->info.lsa->local,
1482 sock->bind_local,
1483 &sock->info.lsa->actual.dest,
1484 sock->connection_profiles_defined,
1485 remote_dynamic,
1486 &remote_changed,
1487 sock->connect_retry_seconds,
1488 sock->connect_timeout,
1489 sock->connect_retry_max,
1490 sock->sockflags,
1491 signal_received);
1493 if (*signal_received)
1494 goto done;
1496 establish_socks_proxy_udpassoc (sock->socks_proxy,
1497 sock->ctrl_sd,
1498 sock->sd,
1499 &sock->socks_relay.dest,
1500 signal_received);
1502 if (*signal_received)
1503 goto done;
1505 sock->remote_host = sock->proxy_dest_host;
1506 sock->remote_port = sock->proxy_dest_port;
1507 sock->did_resolve_remote = false;
1509 sock->info.lsa->actual.dest.sa.sin_addr.s_addr = 0;
1510 sock->info.lsa->remote.sa.sin_addr.s_addr = 0;
1512 resolve_remote (sock, 1, NULL, signal_received);
1514 if (*signal_received)
1515 goto done;
1517 #endif
1519 if (*signal_received)
1520 goto done;
1522 if (remote_changed)
1524 msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
1525 sock->info.lsa->remote.sa.sin_addr.s_addr = sock->info.lsa->actual.dest.sa.sin_addr.s_addr;
1529 /* set misc socket parameters */
1530 socket_set_flags (sock->sd, sock->sockflags);
1532 /* set socket to non-blocking mode */
1533 set_nonblock (sock->sd);
1535 /* set socket file descriptor to not pass across execs, so that
1536 scripts don't have access to it */
1537 set_cloexec (sock->sd);
1539 #ifdef ENABLE_SOCKS
1540 if (socket_defined (sock->ctrl_sd))
1541 set_cloexec (sock->ctrl_sd);
1542 #endif
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);
1550 #endif
1552 /* print local address */
1553 if (sock->inetd)
1554 msg (M_INFO, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
1555 else
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,
1565 ":",
1566 PS_SHOW_PORT_IF_DEFINED,
1567 &gc));
1569 done:
1570 if (sig_save && signal_received)
1572 if (!*signal_received)
1573 *signal_received = sig_save;
1575 gc_free (&gc);
1578 void
1579 link_socket_close (struct link_socket *sock)
1581 if (sock)
1583 #ifdef ENABLE_DEBUG
1584 const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
1585 #else
1586 const int gremlin = 0;
1587 #endif
1589 if (socket_defined (sock->sd))
1591 #ifdef WIN32
1592 close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
1593 #endif
1594 if (!gremlin)
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;
1601 #ifdef WIN32
1602 if (!gremlin)
1604 overlapped_io_close (&sock->reads);
1605 overlapped_io_close (&sock->writes);
1607 #endif
1610 #ifdef ENABLE_SOCKS
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;
1617 #endif
1619 stream_buf_close (&sock->stream_buf);
1620 free_buf (&sock->stream_buf_data);
1621 if (!gremlin)
1622 free (sock);
1626 /* for stream protocols, allow for packet length prefix */
1627 void
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));
1634 void
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);
1640 static void
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);
1645 if (include_cmd)
1646 argv_printf (argv, "%sc %s %s",
1647 info->ipchange_command,
1649 port);
1650 else
1651 argv_printf (argv, "%s %s",
1653 port);
1656 void
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,
1661 struct env_set *es)
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);
1672 if (common_name)
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");
1688 argv_reset (&argv);
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");
1698 argv_reset (&argv);
1701 gc_free (&gc);
1704 void
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 ();
1711 msg (D_LINK_ERRORS,
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));
1716 buf->len = 0;
1718 gc_free (&gc);
1721 void
1722 link_socket_bad_outgoing_addr (void)
1724 dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
1727 in_addr_t
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);
1736 else
1737 return 0;
1741 * Return a status string describing socket state.
1743 const char *
1744 socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
1746 struct buffer out = alloc_buf_gc (64, gc);
1747 if (s)
1749 if (rwflags & EVENT_READ)
1751 buf_printf (&out, "S%s",
1752 (s->rwflags_debug & EVENT_READ) ? "R" : "r");
1753 #ifdef WIN32
1754 buf_printf (&out, "%s",
1755 overlapped_io_state_ascii (&s->reads));
1756 #endif
1758 if (rwflags & EVENT_WRITE)
1760 buf_printf (&out, "S%s",
1761 (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
1762 #ifdef WIN32
1763 buf_printf (&out, "%s",
1764 overlapped_io_state_ascii (&s->writes));
1765 #endif
1768 else
1770 buf_printf (&out, "S?");
1772 return BSTR (&out);
1776 * Stream buffer functions, used to packetize a TCP
1777 * stream connection.
1780 static inline void
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);
1787 sb->len = -1;
1790 void
1791 stream_buf_init (struct stream_buf *sb,
1792 struct buffer *buf,
1793 const unsigned int sockflags,
1794 const int proto)
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);
1800 sb->error = false;
1801 #if PORT_SHARE
1802 sb->port_share_state = ((sockflags & SF_PORT_SHARE) && (proto == PROTO_TCPv4_SERVER))
1803 ? PS_ENABLED
1804 : PS_DISABLED;
1805 #endif
1806 stream_buf_reset (sb);
1808 dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
1811 static inline void
1812 stream_buf_set_next (struct stream_buf *sb)
1814 /* set up 'next' for next i/o read */
1815 sb->next = sb->buf;
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));
1826 static inline void
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));
1832 *buf = sb->buf;
1835 static inline void
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));
1841 *buf = sb->next;
1844 bool
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;
1862 bool
1863 stream_buf_added (struct stream_buf *sb,
1864 int length_added)
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;
1876 #if PORT_SHARE
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;
1883 sb->error = true;
1884 return false;
1886 else
1887 sb->port_share_state = PS_DISABLED;
1889 #endif
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);
1898 sb->error = true;
1899 return false;
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",
1911 BLEN (&sb->buf),
1912 BLEN (&sb->residual));
1913 return true;
1915 else
1917 dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
1918 stream_buf_set_next (sb);
1919 return false;
1923 void
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.
1934 event_t
1935 socket_listen_event_handle (struct link_socket *s)
1937 #ifdef WIN32
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;
1941 #else
1942 return s->sd;
1943 #endif
1947 * Format IP addresses in ascii
1950 const char *
1951 print_sockaddr (const struct openvpn_sockaddr *addr, struct gc_arena *gc)
1953 return print_sockaddr_ex (addr, ":", PS_SHOW_PORT, gc);
1956 const char *
1957 print_sockaddr_ex (const struct openvpn_sockaddr *addr,
1958 const char* separator,
1959 const unsigned int flags,
1960 struct gc_arena *gc)
1962 if (addr)
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)))
1971 && port)
1973 if (separator)
1974 buf_printf (&out, "%s", separator);
1976 buf_printf (&out, "%d", port);
1978 return BSTR (&out);
1980 else
1981 return "[NULL]";
1984 const char *
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);
1990 const char *
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)
1996 if (act)
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;
2004 CLEAR (sa);
2005 sa.sa.sin_addr = act->pi.ipi_spec_dst;
2006 buf_printf (&out, " (via %s)", print_sockaddr_ex (&sa, separator, 0, gc));
2008 #endif
2009 return BSTR (&out);
2011 else
2012 return "[NULL]";
2016 * Convert an in_addr_t in host byte order
2017 * to an ascii dotted quad.
2019 const char *
2020 print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
2022 struct in_addr ia;
2023 struct buffer out = alloc_buf_gc (64, gc);
2025 if (addr || !(flags & IA_EMPTY_IF_UNDEF))
2027 CLEAR (ia);
2028 ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
2030 buf_printf (&out, "%s", inet_ntoa (ia));
2032 return BSTR (&out);
2035 /* set environmental variables for ip/port in *addr */
2036 void
2037 setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct openvpn_sockaddr *addr, const bool flags)
2039 char name_buf[256];
2041 if (flags & SA_IP_PORT)
2042 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
2043 else
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));
2055 void
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;
2061 CLEAR (si);
2062 si.sa.sin_addr.s_addr = htonl (addr);
2063 setenv_sockaddr (es, name_prefix, &si, flags);
2067 void
2068 setenv_link_socket_actual (struct env_set *es,
2069 const char *name_prefix,
2070 const struct link_socket_actual *act,
2071 const bool flags)
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[] = {
2087 {"udp", "UDPv4"},
2088 {"tcp-server", "TCPv4_SERVER"},
2089 {"tcp-client", "TCPv4_CLIENT"},
2090 {"tcp", "TCPv4"}
2094 ascii2proto (const char* proto_name)
2096 int i;
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))
2100 return i;
2101 return -1;
2104 const char *
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;
2112 else
2113 return proto_names[proto].short_form;
2116 const char *
2117 proto2ascii_all (struct gc_arena *gc)
2119 struct buffer out = alloc_buf_gc (256, gc);
2120 int i;
2122 ASSERT (PROTO_N == SIZE (proto_names));
2123 for (i = 0; i < PROTO_N; ++i)
2125 if (i)
2126 buf_printf(&out, " ");
2127 buf_printf(&out, "[%s]", proto2ascii(i, false));
2129 return BSTR (&out);
2133 * Given a local proto, return local proto
2134 * if !remote, or compatible remote proto
2135 * if remote.
2137 * This is used for options compatibility
2138 * checking.
2141 proto_remote (int proto, bool remote)
2143 ASSERT (proto >= 0 && proto < PROTO_N);
2144 if (remote)
2146 if (proto == PROTO_TCPv4_SERVER)
2147 return PROTO_TCPv4_CLIENT;
2148 if (proto == PROTO_TCPv4_CLIENT)
2149 return PROTO_TCPv4_SERVER;
2151 return proto;
2155 * Bad incoming address lengths that differ from what
2156 * we expect are considered to be fatal errors.
2158 void
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.",
2162 actual,
2163 expected);
2167 * Socket Read Routines
2171 link_socket_read_tcp (struct link_socket *sock,
2172 struct buffer *buf)
2174 int len = 0;
2176 if (!sock->stream_buf.residual_fully_formed)
2178 #ifdef WIN32
2179 len = socket_finalize (sock->sd, &sock->reads, buf, NULL);
2180 #else
2181 struct buffer frag;
2182 stream_buf_get_next (&sock->stream_buf, &frag);
2183 len = recv (sock->sd, BPTR (&frag), BLEN (&frag), MSG_NOSIGNAL);
2184 #endif
2186 if (!len)
2187 sock->stream_reset = true;
2188 if (len <= 0)
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);
2197 return buf->len;
2199 else
2200 return buf->len = 0; /* no error, but packet is still incomplete */
2203 #ifndef WIN32
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;
2213 #pragma pack()
2215 static socklen_t
2216 link_socket_read_udp_posix_recvmsg (struct link_socket *sock,
2217 struct buffer *buf,
2218 int maxsize,
2219 struct link_socket_actual *from)
2221 struct iovec iov;
2222 struct openvpn_pktinfo opi;
2223 struct msghdr mesg;
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);
2235 if (buf->len >= 0)
2237 struct cmsghdr *cmsg;
2238 fromlen = mesg.msg_namelen;
2239 cmsg = CMSG_FIRSTHDR (&mesg);
2240 if (cmsg != NULL
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;
2251 return fromlen;
2253 #endif
2256 link_socket_read_udp_posix (struct link_socket *sock,
2257 struct buffer *buf,
2258 int maxsize,
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);
2267 else
2268 #endif
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));
2273 return buf->len;
2276 #endif
2279 * Socket Write Routines
2283 link_socket_write_tcp (struct link_socket *sock,
2284 struct buffer *buf,
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);
2290 len = htonps (len);
2291 ASSERT (buf_write_prepend (buf, &len, sizeof (len)));
2292 #ifdef WIN32
2293 return link_socket_write_win32 (sock, buf, to);
2294 #else
2295 return link_socket_write_tcp_posix (sock, buf, to);
2296 #endif
2299 #if ENABLE_IP_PKTINFO
2302 link_socket_write_udp_posix_sendmsg (struct link_socket *sock,
2303 struct buffer *buf,
2304 struct link_socket_actual *to)
2306 struct iovec iov;
2307 struct msghdr mesg;
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);
2320 mesg.msg_flags = 0;
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);
2332 #endif
2335 * Win32 overlapped socket I/O functions.
2338 #ifdef WIN32
2341 socket_recv_queue (struct link_socket *sock, int maxsize)
2343 if (sock->reads.iostate == IOSTATE_INITIAL)
2345 WSABUF wsabuf[1];
2346 int status;
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);
2357 else
2359 ASSERT (0);
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(
2378 sock->sd,
2379 wsabuf,
2381 &sock->reads.size,
2382 &sock->reads.flags,
2383 (struct sockaddr *) &sock->reads.addr,
2384 &sock->reads.addrlen,
2385 &sock->reads.overlapped,
2386 NULL);
2388 else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
2390 sock->reads.addr_defined = false;
2391 status = WSARecv(
2392 sock->sd,
2393 wsabuf,
2395 &sock->reads.size,
2396 &sock->reads.flags,
2397 &sock->reads.overlapped,
2398 NULL);
2400 else
2402 status = 0;
2403 ASSERT (0);
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);
2421 else
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));
2440 gc_free (&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)
2452 WSABUF wsabuf[1];
2453 int status;
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);
2475 status = WSASendTo(
2476 sock->sd,
2477 wsabuf,
2479 &sock->writes.size,
2480 sock->writes.flags,
2481 (struct sockaddr *) &sock->writes.addr,
2482 sock->writes.addrlen,
2483 &sock->writes.overlapped,
2484 NULL);
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;
2491 status = WSASend(
2492 sock->sd,
2493 wsabuf,
2495 &sock->writes.size,
2496 sock->writes.flags,
2497 &sock->writes.overlapped,
2498 NULL);
2500 else
2502 status = 0;
2503 ASSERT (0);
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);
2519 else
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));
2540 gc_free (&gc);
2544 return sock->writes.iostate;
2548 socket_finalize (SOCKET s,
2549 struct overlapped_io *io,
2550 struct buffer *buf,
2551 struct link_socket_actual *from)
2553 int ret = -1;
2554 BOOL status;
2556 switch (io->iostate)
2558 case IOSTATE_QUEUED:
2559 status = WSAGetOverlappedResult(
2561 &io->overlapped,
2562 &io->size,
2563 FALSE,
2564 &io->flags
2566 if (status)
2568 /* successful return for a queued operation */
2569 if (buf)
2570 *buf = io->buf;
2571 ret = io->size;
2572 io->iostate = IOSTATE_INITIAL;
2573 ASSERT (ResetEvent (io->overlapped.hEvent));
2575 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
2577 else
2579 /* error during a queued operation */
2580 ret = -1;
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");
2589 break;
2591 case IOSTATE_IMMEDIATE_RETURN:
2592 io->iostate = IOSTATE_INITIAL;
2593 ASSERT (ResetEvent (io->overlapped.hEvent));
2594 if (io->status)
2596 /* error return for a non-queued operation */
2597 WSASetLastError (io->status);
2598 ret = -1;
2599 msg (D_WIN32_IO | M_ERRNO_SOCK, "WIN32 I/O: Socket Completion non-queued error");
2601 else
2603 /* successful return for a non-queued operation */
2604 if (buf)
2605 *buf = io->buf;
2606 ret = io->size;
2607 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
2609 break;
2611 case IOSTATE_INITIAL: /* were we called without proper queueing? */
2612 WSASetLastError (WSAEINVAL);
2613 ret = -1;
2614 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
2615 break;
2617 default:
2618 ASSERT (0);
2621 /* return from address if requested */
2622 if (from)
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;
2630 else
2631 CLEAR (from->dest.sa);
2634 if (buf)
2635 buf->len = ret;
2636 return ret;
2639 #endif /* WIN32 */
2642 * Socket event notification
2645 unsigned int
2646 socket_set (struct link_socket *s,
2647 struct event_set *es,
2648 unsigned int rwflags,
2649 void *arg,
2650 unsigned int *persistent)
2652 if (s)
2654 if ((rwflags & EVENT_READ) && !stream_buf_read_setup (s))
2656 ASSERT (!persistent);
2657 rwflags &= ~EVENT_READ;
2660 #ifdef WIN32
2661 if (rwflags & EVENT_READ)
2662 socket_recv_queue (s, 0);
2663 #endif
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);
2669 if (persistent)
2670 *persistent = rwflags;
2673 s->rwflags_debug = rwflags;
2675 return rwflags;
2678 void
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
2694 const char *
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;
2699 else
2700 return null;
2703 socket_descriptor_t
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");
2710 return sd;
2713 void
2714 socket_bind_unix (socket_descriptor_t sd,
2715 struct sockaddr_un *local,
2716 const char *prefix)
2718 struct gc_arena gc = gc_new ();
2720 #ifdef HAVE_UMASK
2721 const mode_t orig_umask = umask (0);
2722 #endif
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",
2728 prefix,
2729 (int)sd,
2730 sockaddr_unix_name (local, "NULL"),
2731 strerror_ts (errnum, &gc));
2734 #ifdef HAVE_UMASK
2735 umask (orig_umask);
2736 #endif
2738 gc_free (&gc);
2741 socket_descriptor_t
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;
2748 CLEAR (*remote);
2749 ret = accept (sd, (struct sockaddr *) remote, &remote_len);
2750 return ret;
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));
2758 if (status)
2759 status = openvpn_errno_socket ();
2760 return status;
2763 void
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));
2770 void
2771 socket_delete_unix (const struct sockaddr_un *local)
2773 const char *name = sockaddr_unix_name (local, NULL);
2774 #ifdef HAVE_UNLINK
2775 if (name && strlen (name))
2776 unlink (name);
2777 #endif
2780 bool
2781 unix_socket_get_peer_uid_gid (const socket_descriptor_t sd, int *uid, int *gid)
2783 #ifdef HAVE_GETPEEREID
2784 uid_t u;
2785 gid_t g;
2786 if (getpeereid (sd, &u, &g) == -1)
2787 return false;
2788 if (uid)
2789 *uid = u;
2790 if (gid)
2791 *gid = g;
2792 return true;
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)
2797 return false;
2798 if (uid)
2799 *uid = peercred.uid;
2800 if (gid)
2801 *gid = peercred.gid;
2802 return true;
2803 #else
2804 return false;
2805 #endif
2808 #endif