big svn cleanup
[anytun.git] / src / openvpn / socket.c
blobc82471f817360c03f18c0f4cae750d23b686c569
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-2005 OpenVPN Solutions LLC <info@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 #ifdef WIN32
26 #include "config-win32.h"
27 #else
28 #include "config.h"
29 #endif
31 #include "syshead.h"
33 #include "socket.h"
34 #include "fdmisc.h"
35 #include "thread.h"
36 #include "misc.h"
37 #include "gremlin.h"
38 #include "plugin.h"
40 #include "memdbg.h"
43 * Functions related to the translation of DNS names to IP addresses.
46 static const char*
47 h_errno_msg(int h_errno_err)
49 switch (h_errno_err)
51 case HOST_NOT_FOUND:
52 return "[HOST_NOT_FOUND] The specified host is unknown.";
53 case NO_DATA:
54 return "[NO_DATA] The requested name is valid but does not have an IP address.";
55 case NO_RECOVERY:
56 return "[NO_RECOVERY] A non-recoverable name server error occurred.";
57 case TRY_AGAIN:
58 return "[TRY_AGAIN] A temporary error occurred on an authoritative name server.";
60 return "[unknown h_errno value]";
64 * Translate IP addr or hostname to in_addr_t.
65 * If resolve error, try again for
66 * resolve_retry_seconds seconds.
68 in_addr_t
69 getaddr (unsigned int flags,
70 const char *hostname,
71 int resolve_retry_seconds,
72 bool *succeeded,
73 volatile int *signal_received)
75 struct in_addr ia;
76 int status;
77 int sigrec = 0;
78 int msglevel = (flags & GETADDR_FATAL) ? M_FATAL : D_RESOLVE_ERRORS;
80 if (flags & GETADDR_MSG_VIRT_OUT)
81 msglevel |= M_MSG_VIRT_OUT;
83 CLEAR (ia);
84 if (succeeded)
85 *succeeded = false;
87 if ((flags & (GETADDR_FATAL_ON_SIGNAL|GETADDR_WARN_ON_SIGNAL))
88 && !signal_received)
89 signal_received = &sigrec;
91 status = openvpn_inet_aton (hostname, &ia); /* parse ascii IP address */
93 if (status != OIA_IP) /* parse as IP address failed? */
95 const int fail_wait_interval = 5; /* seconds */
96 int resolve_retries = (flags & GETADDR_TRY_ONCE) ? 1 : (resolve_retry_seconds / fail_wait_interval);
97 struct hostent *h;
98 const char *fmt;
99 int level = 0;
101 CLEAR (ia);
103 fmt = "RESOLVE: Cannot resolve host address: %s: %s";
104 if ((flags & GETADDR_MENTION_RESOLVE_RETRY)
105 && !resolve_retry_seconds)
106 fmt = "RESOLVE: Cannot resolve host address: %s: %s (I would have retried this name query if you had specified the --resolv-retry option.)";
108 if (!(flags & GETADDR_RESOLVE) || status == OIA_ERROR)
110 msg (msglevel, "RESOLVE: Cannot parse IP address: %s", hostname);
111 goto done;
115 * Resolve hostname
117 while (true)
119 /* try hostname lookup */
120 h = gethostbyname (hostname);
122 if (signal_received)
124 get_signal (signal_received);
125 if (*signal_received) /* were we interrupted by a signal? */
127 h = NULL;
128 if (*signal_received == SIGUSR1) /* ignore SIGUSR1 */
130 msg (level, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
131 *signal_received = 0;
133 else
134 goto done;
138 /* success? */
139 if (h)
140 break;
142 /* resolve lookup failed, should we
143 continue or fail? */
145 level = msglevel;
146 if (resolve_retries > 0)
147 level = D_RESOLVE_ERRORS;
149 msg (level,
150 fmt,
151 hostname,
152 h_errno_msg (h_errno));
154 if (--resolve_retries <= 0)
155 goto done;
157 openvpn_sleep (fail_wait_interval);
160 if (h->h_addrtype != AF_INET || h->h_length != 4)
162 msg (msglevel, "RESOLVE: Sorry, but we only accept IPv4 DNS names: %s", hostname);
163 goto done;
166 ia.s_addr = *(in_addr_t *) (h->h_addr_list[0]);
168 if (ia.s_addr)
170 if (h->h_addr_list[1]) /* more than one address returned */
172 int n = 0;
174 /* count address list */
175 while (h->h_addr_list[n])
176 ++n;
177 ASSERT (n >= 2);
179 msg (D_RESOLVE_ERRORS, "RESOLVE: NOTE: %s resolves to %d addresses, choosing one by random",
180 hostname,
183 /* choose address randomly, for basic load-balancing capability */
184 ia.s_addr = *(in_addr_t *) (h->h_addr_list[get_random () % n]);
188 /* hostname resolve succeeded */
189 if (succeeded)
190 *succeeded = true;
192 else
194 /* IP address parse succeeded */
195 if (succeeded)
196 *succeeded = true;
199 done:
200 if (signal_received && *signal_received)
202 int level = 0;
203 if (flags & GETADDR_FATAL_ON_SIGNAL)
204 level = M_FATAL;
205 else if (flags & GETADDR_WARN_ON_SIGNAL)
206 level = M_WARN;
207 msg (level, "RESOLVE: signal received during DNS resolution attempt");
210 return (flags & GETADDR_HOST_ORDER) ? ntohl (ia.s_addr) : ia.s_addr;
214 * We do our own inet_aton because the glibc function
215 * isn't very good about error checking.
218 openvpn_inet_aton (const char *dotted_quad, struct in_addr *addr)
220 unsigned int a, b, c, d;
222 CLEAR (*addr);
223 if (sscanf (dotted_quad, "%u.%u.%u.%u", &a, &b, &c, &d) == 4)
225 if (a < 256 && b < 256 && c < 256 && d < 256)
227 addr->s_addr = htonl (a<<24 | b<<16 | c<<8 | d);
228 return OIA_IP; /* good dotted quad */
231 if (string_class (dotted_quad, CC_DIGIT|CC_DOT, 0))
232 return OIA_ERROR; /* probably a badly formatted dotted quad */
233 else
234 return OIA_HOSTNAME; /* probably a hostname */
237 static void
238 update_remote (const char* host,
239 struct sockaddr_in *addr,
240 bool *changed)
242 if (host && addr)
244 const in_addr_t new_addr = getaddr (
245 GETADDR_RESOLVE,
246 host,
248 NULL,
249 NULL);
250 if (new_addr && addr->sin_addr.s_addr != new_addr)
252 addr->sin_addr.s_addr = new_addr;
253 *changed = true;
258 static int
259 socket_get_sndbuf (int sd)
261 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
262 int val;
263 socklen_t len;
265 len = sizeof (val);
266 if (getsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &val, &len) == 0
267 && len == sizeof (val))
268 return val;
269 #endif
270 return 0;
273 static void
274 socket_set_sndbuf (int sd, int size)
276 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
277 if (setsockopt (sd, SOL_SOCKET, SO_SNDBUF, (void *) &size, sizeof (size)) != 0)
279 msg (M_WARN, "NOTE: setsockopt SO_SNDBUF=%d failed", size);
281 #endif
284 static int
285 socket_get_rcvbuf (int sd)
287 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
288 int val;
289 socklen_t len;
291 len = sizeof (val);
292 if (getsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &val, &len) == 0
293 && len == sizeof (val))
294 return val;
295 #endif
296 return 0;
299 static bool
300 socket_set_rcvbuf (int sd, int size)
302 #if defined(HAVE_SETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
303 if (setsockopt (sd, SOL_SOCKET, SO_RCVBUF, (void *) &size, sizeof (size)) != 0)
305 msg (M_WARN, "NOTE: setsockopt SO_RCVBUF=%d failed", size);
306 return false;
308 return true;
309 #endif
312 static void
313 socket_set_buffers (int fd, const struct socket_buffer_size *sbs)
315 if (sbs)
317 const int sndbuf_old = socket_get_sndbuf (fd);
318 const int rcvbuf_old = socket_get_rcvbuf (fd);
320 if (sbs->sndbuf)
321 socket_set_sndbuf (fd, sbs->sndbuf);
323 if (sbs->rcvbuf)
324 socket_set_rcvbuf (fd, sbs->rcvbuf);
326 msg (D_OSBUF, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
327 rcvbuf_old,
328 socket_get_rcvbuf (fd),
329 sndbuf_old,
330 socket_get_sndbuf (fd));
335 * Remote list code allows clients to specify a list of
336 * potential remote server addresses.
339 static void
340 remote_list_next (struct remote_list *l)
342 if (l)
344 if (l->no_advance && l->current >= 0)
346 l->no_advance = false;
348 else
350 int i;
351 if (++l->current >= l->len)
352 l->current = 0;
354 dmsg (D_REMOTE_LIST, "REMOTE_LIST len=%d current=%d",
355 l->len, l->current);
356 for (i = 0; i < l->len; ++i)
358 dmsg (D_REMOTE_LIST, "[%d] %s:%d",
360 l->array[i].hostname,
361 l->array[i].port);
367 void
368 remote_list_randomize (struct remote_list *l)
370 int i;
371 if (l)
373 for (i = 0; i < l->len; ++i)
375 const int j = get_random () % l->len;
376 if (i != j)
378 struct remote_entry tmp;
379 tmp = l->array[i];
380 l->array[i] = l->array[j];
381 l->array[j] = tmp;
387 static const char *
388 remote_list_host (const struct remote_list *rl)
390 if (rl)
391 return rl->array[rl->current].hostname;
392 else
393 return NULL;
396 static int
397 remote_list_port (const struct remote_list *rl)
399 if (rl)
400 return rl->array[rl->current].port;
401 else
402 return 0;
406 * SOCKET INITALIZATION CODE.
407 * Create a TCP/UDP socket
410 socket_descriptor_t
411 create_socket_tcp (void)
413 socket_descriptor_t sd;
415 if ((sd = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
416 msg (M_SOCKERR, "Cannot create TCP socket");
418 /* set SO_REUSEADDR on socket */
420 int on = 1;
421 if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR,
422 (void *) &on, sizeof (on)) < 0)
423 msg (M_SOCKERR, "TCP: Cannot setsockopt SO_REUSEADDR on TCP socket");
426 #if 0
427 /* set socket linger options */
429 struct linger linger;
430 linger.l_onoff = 1;
431 linger.l_linger = 2;
432 if (setsockopt (sd, SOL_SOCKET, SO_LINGER,
433 (void *) &linger, sizeof (linger)) < 0)
434 msg (M_SOCKERR, "TCP: Cannot setsockopt SO_LINGER on TCP socket");
436 #endif
438 return sd;
441 static socket_descriptor_t
442 create_socket_udp (void)
444 socket_descriptor_t sd;
446 if ((sd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
447 msg (M_SOCKERR, "UDP: Cannot create UDP socket");
448 return sd;
451 static void
452 create_socket (struct link_socket *sock)
454 /* create socket */
455 if (sock->info.proto == PROTO_UDPv4)
457 sock->sd = create_socket_udp ();
459 #ifdef ENABLE_SOCKS
460 if (sock->socks_proxy)
461 sock->ctrl_sd = create_socket_tcp ();
462 #endif
464 else if (sock->info.proto == PROTO_TCPv4_SERVER
465 || sock->info.proto == PROTO_TCPv4_CLIENT)
467 sock->sd = create_socket_tcp ();
469 else
471 ASSERT (0);
476 * Functions used for establishing a TCP stream connection.
479 static void
480 socket_do_listen (socket_descriptor_t sd,
481 const struct sockaddr_in *local,
482 bool do_listen,
483 bool do_set_nonblock)
485 struct gc_arena gc = gc_new ();
486 if (do_listen)
488 msg (M_INFO, "Listening for incoming TCP connection on %s",
489 print_sockaddr (local, &gc));
490 if (listen (sd, 1))
491 msg (M_SOCKERR, "TCP: listen() failed");
494 /* set socket to non-blocking mode */
495 if (do_set_nonblock)
496 set_nonblock (sd);
498 gc_free (&gc);
501 socket_descriptor_t
502 socket_do_accept (socket_descriptor_t sd,
503 struct sockaddr_in *remote,
504 const bool nowait)
506 socklen_t remote_len = sizeof (*remote);
507 socket_descriptor_t new_sd = SOCKET_UNDEFINED;
509 #ifdef HAVE_GETPEERNAME
510 if (nowait)
512 new_sd = getpeername (sd, (struct sockaddr *) remote, &remote_len);
514 if (!socket_defined (new_sd))
515 msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: getpeername() failed");
516 else
517 new_sd = sd;
519 #else
520 if (nowait)
521 msg (M_WARN, "TCP: this OS does not provide the getpeername() function");
522 #endif
523 else
525 new_sd = accept (sd, (struct sockaddr *) remote, &remote_len);
528 #if 0 /* For debugging only, test the effect of accept() failures */
530 static int foo = 0;
531 ++foo;
532 if (foo & 1)
533 new_sd = -1;
535 #endif
537 if (!socket_defined (new_sd))
539 msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: accept(%d) failed", sd);
541 else if (remote_len != sizeof (*remote))
543 msg (D_LINK_ERRORS, "TCP: Received strange incoming connection with unknown address length=%d", remote_len);
544 openvpn_close_socket (new_sd);
545 new_sd = SOCKET_UNDEFINED;
547 return new_sd;
550 static void
551 tcp_connection_established (const struct sockaddr_in *remote)
553 struct gc_arena gc = gc_new ();
554 msg (M_INFO, "TCP connection established with %s",
555 print_sockaddr (remote, &gc));
556 gc_free (&gc);
559 static int
560 socket_listen_accept (socket_descriptor_t sd,
561 struct sockaddr_in *remote,
562 const char *remote_dynamic,
563 bool *remote_changed,
564 const struct sockaddr_in *local,
565 bool do_listen,
566 bool nowait,
567 volatile int *signal_received)
569 struct gc_arena gc = gc_new ();
570 struct sockaddr_in remote_verify = *remote;
571 int new_sd = SOCKET_UNDEFINED;
573 socket_do_listen (sd, local, do_listen, true);
575 while (true)
577 int status;
578 fd_set reads;
579 struct timeval tv;
581 FD_ZERO (&reads);
582 FD_SET (sd, &reads);
583 tv.tv_sec = 0;
584 tv.tv_usec = 0;
586 status = select (sd + 1, &reads, NULL, NULL, &tv);
588 get_signal (signal_received);
589 if (*signal_received)
591 gc_free (&gc);
592 return sd;
595 if (status < 0)
596 msg (D_LINK_ERRORS | M_ERRNO_SOCK, "TCP: select() failed");
598 if (status <= 0)
600 openvpn_sleep (1);
601 continue;
604 new_sd = socket_do_accept (sd, remote, nowait);
606 if (socket_defined (new_sd))
608 update_remote (remote_dynamic, &remote_verify, remote_changed);
609 if (addr_defined (&remote_verify)
610 && !addr_match (&remote_verify, remote))
612 msg (M_WARN,
613 "TCP NOTE: Rejected connection attempt from %s due to --remote setting",
614 print_sockaddr (remote, &gc));
615 if (openvpn_close_socket (new_sd))
616 msg (M_SOCKERR, "TCP: close socket failed (new_sd)");
618 else
619 break;
621 openvpn_sleep (1);
624 if (!nowait && openvpn_close_socket (sd))
625 msg (M_SOCKERR, "TCP: close socket failed (sd)");
627 tcp_connection_established (remote);
629 gc_free (&gc);
630 return new_sd;
633 static void
634 socket_connect (socket_descriptor_t *sd,
635 struct sockaddr_in *remote,
636 struct remote_list *remote_list,
637 const char *remote_dynamic,
638 bool *remote_changed,
639 const int connect_retry_seconds,
640 volatile int *signal_received)
642 struct gc_arena gc = gc_new ();
644 msg (M_INFO, "Attempting to establish TCP connection with %s",
645 print_sockaddr (remote, &gc));
646 while (true)
648 const int status = connect (*sd, (struct sockaddr *) remote,
649 sizeof (*remote));
651 get_signal (signal_received);
652 if (*signal_received)
653 goto done;
655 if (!status)
656 break;
658 msg (D_LINK_ERRORS | M_ERRNO_SOCK,
659 "TCP: connect to %s failed, will try again in %d seconds",
660 print_sockaddr (remote, &gc),
661 connect_retry_seconds);
663 openvpn_close_socket (*sd);
664 openvpn_sleep (connect_retry_seconds);
666 if (remote_list)
668 remote_list_next (remote_list);
669 remote_dynamic = remote_list_host (remote_list);
670 remote->sin_port = htons (remote_list_port (remote_list));
671 *remote_changed = true;
674 *sd = create_socket_tcp ();
675 update_remote (remote_dynamic, remote, remote_changed);
678 msg (M_INFO, "TCP connection established with %s",
679 print_sockaddr (remote, &gc));
681 done:
682 gc_free (&gc);
685 /* For stream protocols, allocate a buffer to build up packet.
686 Called after frame has been finalized. */
688 static void
689 socket_frame_init (const struct frame *frame, struct link_socket *sock)
691 #ifdef WIN32
692 overlapped_io_init (&sock->reads, frame, FALSE, false);
693 overlapped_io_init (&sock->writes, frame, TRUE, false);
694 sock->rw_handle.read = sock->reads.overlapped.hEvent;
695 sock->rw_handle.write = sock->writes.overlapped.hEvent;
696 #endif
698 if (link_socket_connection_oriented (sock))
700 #ifdef WIN32
701 stream_buf_init (&sock->stream_buf, &sock->reads.buf_init);
702 #else
703 alloc_buf_sock_tun (&sock->stream_buf_data,
704 frame,
705 false,
706 FRAME_HEADROOM_MARKER_READ_STREAM);
707 stream_buf_init (&sock->stream_buf, &sock->stream_buf_data);
708 #endif
713 * Adjust frame structure based on a Path MTU value given
714 * to us by the OS.
716 void
717 frame_adjust_path_mtu (struct frame *frame, int pmtu, int proto)
719 frame_set_mtu_dynamic (frame, pmtu - datagram_overhead (proto), SET_MTU_UPPER_BOUND);
722 static void
723 resolve_bind_local (struct link_socket *sock)
725 struct gc_arena gc = gc_new ();
727 /* resolve local address if undefined */
728 if (!addr_defined (&sock->info.lsa->local))
730 sock->info.lsa->local.sin_family = AF_INET;
731 sock->info.lsa->local.sin_addr.s_addr =
732 (sock->local_host ? getaddr (GETADDR_RESOLVE | GETADDR_WARN_ON_SIGNAL | GETADDR_FATAL,
733 sock->local_host,
735 NULL,
736 NULL)
737 : htonl (INADDR_ANY));
738 sock->info.lsa->local.sin_port = htons (sock->local_port);
741 /* bind to local address/port */
742 if (sock->bind_local)
744 if (bind (sock->sd, (struct sockaddr *) &sock->info.lsa->local,
745 sizeof (sock->info.lsa->local)))
747 const int errnum = openvpn_errno_socket ();
748 msg (M_FATAL, "TCP/UDP: Socket bind failed on local address %s: %s",
749 print_sockaddr (&sock->info.lsa->local, &gc),
750 strerror_ts (errnum, &gc));
753 gc_free (&gc);
756 static void
757 resolve_remote (struct link_socket *sock,
758 int phase,
759 const char **remote_dynamic,
760 volatile int *signal_received)
762 struct gc_arena gc = gc_new ();
764 if (!sock->did_resolve_remote)
766 /* resolve remote address if undefined */
767 if (!addr_defined (&sock->info.lsa->remote))
769 sock->info.lsa->remote.sin_family = AF_INET;
770 sock->info.lsa->remote.sin_addr.s_addr = 0;
772 if (sock->remote_host)
774 unsigned int flags = 0;
775 int retry = 0;
776 bool status = false;
778 if (remote_list_len (sock->remote_list) > 1 && sock->resolve_retry_seconds == RESOLV_RETRY_INFINITE)
780 flags = GETADDR_RESOLVE;
781 if (phase == 2)
782 flags |= (GETADDR_TRY_ONCE | GETADDR_FATAL);
783 retry = 0;
785 else if (phase == 1)
787 if (sock->resolve_retry_seconds)
789 flags = GETADDR_RESOLVE;
790 retry = 0;
792 else
794 flags = GETADDR_RESOLVE | GETADDR_FATAL | GETADDR_MENTION_RESOLVE_RETRY;
795 retry = 0;
798 else if (phase == 2)
800 if (sock->resolve_retry_seconds)
802 flags = GETADDR_RESOLVE | GETADDR_FATAL;
803 retry = sock->resolve_retry_seconds;
805 else
807 ASSERT (0);
810 else
812 ASSERT (0);
815 sock->info.lsa->remote.sin_addr.s_addr = getaddr (
816 flags,
817 sock->remote_host,
818 retry,
819 &status,
820 signal_received);
822 dmsg (D_SOCKET_DEBUG, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
823 flags,
824 phase,
825 retry,
826 signal_received ? *signal_received : -1,
827 status);
829 if (signal_received)
831 if (*signal_received)
832 goto done;
834 if (!status)
836 if (signal_received)
837 *signal_received = SIGUSR1;
838 goto done;
842 sock->info.lsa->remote.sin_port = htons (sock->remote_port);
845 /* should we re-use previous active remote address? */
846 if (addr_defined (&sock->info.lsa->actual))
848 msg (M_INFO, "TCP/UDP: Preserving recently used remote address: %s",
849 print_sockaddr (&sock->info.lsa->actual, &gc));
850 if (remote_dynamic)
851 *remote_dynamic = NULL;
853 else
854 sock->info.lsa->actual = sock->info.lsa->remote;
856 /* remember that we finished */
857 sock->did_resolve_remote = true;
860 done:
861 gc_free (&gc);
864 struct link_socket *
865 link_socket_new (void)
867 struct link_socket *sock;
869 ALLOC_OBJ_CLEAR (sock, struct link_socket);
870 sock->sd = SOCKET_UNDEFINED;
871 #ifdef ENABLE_SOCKS
872 sock->ctrl_sd = SOCKET_UNDEFINED;
873 #endif
874 return sock;
877 /* bind socket if necessary */
878 void
879 link_socket_init_phase1 (struct link_socket *sock,
880 const char *local_host,
881 struct remote_list *remote_list,
882 int local_port,
883 int proto,
884 int mode,
885 const struct link_socket *accept_from,
886 #ifdef ENABLE_HTTP_PROXY
887 struct http_proxy_info *http_proxy,
888 #endif
889 #ifdef ENABLE_SOCKS
890 struct socks_proxy_info *socks_proxy,
891 #endif
892 #ifdef ENABLE_DEBUG
893 int gremlin,
894 #endif
895 bool bind_local,
896 bool remote_float,
897 int inetd,
898 struct link_socket_addr *lsa,
899 const char *ipchange_command,
900 const struct plugin_list *plugins,
901 int resolve_retry_seconds,
902 int connect_retry_seconds,
903 int mtu_discover_type,
904 int rcvbuf,
905 int sndbuf)
907 const char *remote_host;
908 int remote_port;
910 ASSERT (sock);
912 sock->remote_list = remote_list;
913 remote_list_next (remote_list);
914 remote_host = remote_list_host (remote_list);
915 remote_port = remote_list_port (remote_list);
917 sock->local_host = local_host;
918 sock->local_port = local_port;
920 #ifdef ENABLE_HTTP_PROXY
921 sock->http_proxy = http_proxy;
922 #endif
924 #ifdef ENABLE_SOCKS
925 sock->socks_proxy = socks_proxy;
926 #endif
928 sock->bind_local = bind_local;
929 sock->inetd = inetd;
930 sock->resolve_retry_seconds = resolve_retry_seconds;
931 sock->connect_retry_seconds = connect_retry_seconds;
932 sock->mtu_discover_type = mtu_discover_type;
934 #ifdef ENABLE_DEBUG
935 sock->gremlin = gremlin;
936 #endif
938 sock->socket_buffer_sizes.rcvbuf = rcvbuf;
939 sock->socket_buffer_sizes.sndbuf = sndbuf;
941 sock->info.proto = proto;
942 sock->info.remote_float = remote_float;
943 sock->info.lsa = lsa;
944 sock->info.ipchange_command = ipchange_command;
945 sock->info.plugins = plugins;
947 sock->mode = mode;
948 if (mode == LS_MODE_TCP_ACCEPT_FROM)
950 ASSERT (accept_from);
951 ASSERT (sock->info.proto == PROTO_TCPv4_SERVER);
952 ASSERT (!sock->inetd);
953 sock->sd = accept_from->sd;
956 if (false)
958 #ifdef ENABLE_HTTP_PROXY
959 /* are we running in HTTP proxy mode? */
960 else if (sock->http_proxy)
962 ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT);
963 ASSERT (!sock->inetd);
965 /* the proxy server */
966 sock->remote_host = http_proxy->options.server;
967 sock->remote_port = http_proxy->options.port;
969 /* the OpenVPN server we will use the proxy to connect to */
970 sock->proxy_dest_host = remote_host;
971 sock->proxy_dest_port = remote_port;
973 /* this is needed so that connection retries will go to the proxy server,
974 not the remote OpenVPN address */
975 sock->remote_list = NULL;
977 #endif
978 #ifdef ENABLE_SOCKS
979 /* or in Socks proxy mode? */
980 else if (sock->socks_proxy)
982 ASSERT (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_UDPv4);
983 ASSERT (!sock->inetd);
985 /* the proxy server */
986 sock->remote_host = socks_proxy->server;
987 sock->remote_port = socks_proxy->port;
989 /* the OpenVPN server we will use the proxy to connect to */
990 sock->proxy_dest_host = remote_host;
991 sock->proxy_dest_port = remote_port;
993 /* this is needed so that connection retries will go to the proxy server,
994 not the remote OpenVPN address */
995 sock->remote_list = NULL;
997 #endif
998 else
1000 sock->remote_host = remote_host;
1001 sock->remote_port = remote_port;
1004 /* bind behavior for TCP server vs. client */
1005 if (sock->info.proto == PROTO_TCPv4_SERVER)
1007 if (sock->mode == LS_MODE_TCP_ACCEPT_FROM)
1008 sock->bind_local = false;
1009 else
1010 sock->bind_local = true;
1012 else if (sock->info.proto == PROTO_TCPv4_CLIENT)
1014 sock->bind_local = false;
1017 /* were we started by inetd or xinetd? */
1018 if (sock->inetd)
1020 ASSERT (sock->info.proto != PROTO_TCPv4_CLIENT);
1021 ASSERT (socket_defined (inetd_socket_descriptor));
1022 sock->sd = inetd_socket_descriptor;
1024 else if (mode != LS_MODE_TCP_ACCEPT_FROM)
1026 create_socket (sock);
1027 resolve_bind_local (sock);
1028 resolve_remote (sock, 1, NULL, NULL);
1032 /* finalize socket initialization */
1033 void
1034 link_socket_init_phase2 (struct link_socket *sock,
1035 const struct frame *frame,
1036 volatile int *signal_received)
1038 struct gc_arena gc = gc_new ();
1039 const char *remote_dynamic = NULL;
1040 bool remote_changed = false;
1041 int sig_save = 0;
1043 ASSERT (sock);
1045 if (signal_received && *signal_received)
1047 sig_save = *signal_received;
1048 *signal_received = 0;
1051 /* initialize buffers */
1052 socket_frame_init (frame, sock);
1055 * Pass a remote name to connect/accept so that
1056 * they can test for dynamic IP address changes
1057 * and throw a SIGUSR1 if appropriate.
1059 if (sock->resolve_retry_seconds)
1060 remote_dynamic = sock->remote_host;
1062 /* were we started by inetd or xinetd? */
1063 if (sock->inetd)
1065 if (sock->info.proto == PROTO_TCPv4_SERVER)
1066 sock->sd =
1067 socket_listen_accept (sock->sd,
1068 &sock->info.lsa->actual,
1069 remote_dynamic,
1070 &remote_changed,
1071 &sock->info.lsa->local,
1072 false,
1073 sock->inetd == INETD_NOWAIT,
1074 signal_received);
1075 ASSERT (!remote_changed);
1076 if (*signal_received)
1077 goto done;
1079 else
1081 resolve_remote (sock, 2, &remote_dynamic, signal_received);
1083 if (*signal_received)
1084 goto done;
1086 /* TCP client/server */
1087 if (sock->info.proto == PROTO_TCPv4_SERVER)
1089 switch (sock->mode)
1091 case LS_MODE_DEFAULT:
1092 sock->sd = socket_listen_accept (sock->sd,
1093 &sock->info.lsa->actual,
1094 remote_dynamic,
1095 &remote_changed,
1096 &sock->info.lsa->local,
1097 true,
1098 false,
1099 signal_received);
1100 break;
1101 case LS_MODE_TCP_LISTEN:
1102 socket_do_listen (sock->sd,
1103 &sock->info.lsa->local,
1104 true,
1105 false);
1106 break;
1107 case LS_MODE_TCP_ACCEPT_FROM:
1108 sock->sd = socket_do_accept (sock->sd,
1109 &sock->info.lsa->actual,
1110 false);
1111 if (!socket_defined (sock->sd))
1113 *signal_received = SIGTERM;
1114 goto done;
1116 tcp_connection_established (&sock->info.lsa->actual);
1117 break;
1118 default:
1119 ASSERT (0);
1122 else if (sock->info.proto == PROTO_TCPv4_CLIENT)
1124 socket_connect (&sock->sd,
1125 &sock->info.lsa->actual,
1126 sock->remote_list,
1127 remote_dynamic,
1128 &remote_changed,
1129 sock->connect_retry_seconds,
1130 signal_received);
1132 if (*signal_received)
1133 goto done;
1135 if (false)
1137 #ifdef ENABLE_HTTP_PROXY
1138 else if (sock->http_proxy)
1140 establish_http_proxy_passthru (sock->http_proxy,
1141 sock->sd,
1142 sock->proxy_dest_host,
1143 sock->proxy_dest_port,
1144 &sock->stream_buf.residual,
1145 signal_received);
1147 #endif
1148 #ifdef ENABLE_SOCKS
1149 else if (sock->socks_proxy)
1151 establish_socks_proxy_passthru (sock->socks_proxy,
1152 sock->sd,
1153 sock->proxy_dest_host,
1154 sock->proxy_dest_port,
1155 signal_received);
1157 #endif
1159 #ifdef ENABLE_SOCKS
1160 else if (sock->info.proto == PROTO_UDPv4 && sock->socks_proxy)
1162 socket_connect (&sock->ctrl_sd,
1163 &sock->info.lsa->actual,
1164 NULL,
1165 remote_dynamic,
1166 &remote_changed,
1167 sock->connect_retry_seconds,
1168 signal_received);
1170 if (*signal_received)
1171 goto done;
1173 establish_socks_proxy_udpassoc (sock->socks_proxy,
1174 sock->ctrl_sd,
1175 sock->sd, &sock->socks_relay,
1176 signal_received);
1178 if (*signal_received)
1179 goto done;
1181 sock->remote_host = sock->proxy_dest_host;
1182 sock->remote_port = sock->proxy_dest_port;
1183 sock->did_resolve_remote = false;
1184 sock->info.lsa->actual.sin_addr.s_addr = 0;
1185 sock->info.lsa->remote.sin_addr.s_addr = 0;
1187 resolve_remote (sock, 1, NULL, signal_received);
1189 if (*signal_received)
1190 goto done;
1192 #endif
1194 if (*signal_received)
1195 goto done;
1197 if (remote_changed)
1199 msg (M_INFO, "TCP/UDP: Dynamic remote address changed during TCP connection establishment");
1200 sock->info.lsa->remote.sin_addr.s_addr = sock->info.lsa->actual.sin_addr.s_addr;
1204 /* set socket buffers based on --sndbuf and --rcvbuf options */
1205 socket_set_buffers (sock->sd, &sock->socket_buffer_sizes);
1207 /* set socket to non-blocking mode */
1208 set_nonblock (sock->sd);
1210 /* set socket file descriptor to not pass across execs, so that
1211 scripts don't have access to it */
1212 set_cloexec (sock->sd);
1214 #ifdef ENABLE_SOCKS
1215 if (socket_defined (sock->ctrl_sd))
1216 set_cloexec (sock->ctrl_sd);
1217 #endif
1219 /* set Path MTU discovery options on the socket */
1220 set_mtu_discover_type (sock->sd, sock->mtu_discover_type);
1222 #if EXTENDED_SOCKET_ERROR_CAPABILITY
1223 /* if the OS supports it, enable extended error passing on the socket */
1224 set_sock_extended_error_passing (sock->sd);
1225 #endif
1227 /* print local address */
1228 if (sock->inetd)
1229 msg (M_INFO, "%s link local: [inetd]", proto2ascii (sock->info.proto, true));
1230 else
1231 msg (M_INFO, "%s link local%s: %s",
1232 proto2ascii (sock->info.proto, true),
1233 (sock->bind_local ? " (bound)" : ""),
1234 print_sockaddr_ex (&sock->info.lsa->local, sock->bind_local, ":", &gc));
1236 /* print active remote address */
1237 msg (M_INFO, "%s link remote: %s",
1238 proto2ascii (sock->info.proto, true),
1239 print_sockaddr_ex (&sock->info.lsa->actual, addr_defined (&sock->info.lsa->actual), ":", &gc));
1241 done:
1242 if (sig_save && signal_received)
1244 if (!*signal_received)
1245 *signal_received = sig_save;
1247 gc_free (&gc);
1250 void
1251 link_socket_close (struct link_socket *sock)
1253 if (sock)
1255 #ifdef ENABLE_DEBUG
1256 const int gremlin = GREMLIN_CONNECTION_FLOOD_LEVEL (sock->gremlin);
1257 #else
1258 const int gremlin = 0;
1259 #endif
1261 if (socket_defined (sock->sd))
1263 #ifdef WIN32
1264 close_net_event_win32 (&sock->listen_handle, sock->sd, 0);
1265 #endif
1266 if (!gremlin)
1268 msg (D_CLOSE, "TCP/UDP: Closing socket");
1269 if (openvpn_close_socket (sock->sd))
1270 msg (M_WARN | M_ERRNO_SOCK, "TCP/UDP: Close Socket failed");
1272 sock->sd = SOCKET_UNDEFINED;
1273 #ifdef WIN32
1274 if (!gremlin)
1276 overlapped_io_close (&sock->reads);
1277 overlapped_io_close (&sock->writes);
1279 #endif
1282 #ifdef ENABLE_SOCKS
1283 if (socket_defined (sock->ctrl_sd))
1285 if (openvpn_close_socket (sock->ctrl_sd))
1286 msg (M_WARN | M_ERRNO_SOCK, "TCP/UDP: Close Socket (ctrl_sd) failed");
1287 sock->ctrl_sd = SOCKET_UNDEFINED;
1289 #endif
1291 stream_buf_close (&sock->stream_buf);
1292 free_buf (&sock->stream_buf_data);
1293 if (!gremlin)
1294 free (sock);
1298 /* for stream protocols, allow for packet length prefix */
1299 void
1300 socket_adjust_frame_parameters (struct frame *frame, int proto)
1302 if (link_socket_proto_connection_oriented (proto))
1303 frame_add_to_extra_frame (frame, sizeof (packet_size_type));
1306 void
1307 setenv_trusted (struct env_set *es, const struct link_socket_info *info)
1309 setenv_sockaddr (es, "trusted", &info->lsa->actual, SA_IP_PORT);
1312 void
1313 link_socket_connection_initiated (const struct buffer *buf,
1314 struct link_socket_info *info,
1315 const struct sockaddr_in *addr,
1316 const char *common_name,
1317 struct env_set *es)
1319 struct gc_arena gc = gc_new ();
1321 info->lsa->actual = *addr; /* Note: skip this line for --force-dest */
1322 setenv_trusted (es, info);
1323 info->connection_established = true;
1325 /* Print connection initiated message, with common name if available */
1327 struct buffer out = alloc_buf_gc (256, &gc);
1328 if (common_name)
1329 buf_printf (&out, "[%s] ", common_name);
1330 buf_printf (&out, "Peer Connection Initiated with %s", print_sockaddr (&info->lsa->actual, &gc));
1331 msg (M_INFO, "%s", BSTR (&out));
1334 /* set environmental vars */
1335 setenv_str (es, "common_name", common_name);
1337 /* Process --ipchange plugin */
1338 if (plugin_defined (info->plugins, OPENVPN_PLUGIN_IPCHANGE))
1340 const char *addr_ascii = print_sockaddr_ex (&info->lsa->actual, true, " ", &gc);
1341 if (plugin_call (info->plugins, OPENVPN_PLUGIN_IPCHANGE, addr_ascii, es))
1342 msg (M_WARN, "WARNING: ipchange plugin call failed");
1345 /* Process --ipchange option */
1346 if (info->ipchange_command)
1348 struct buffer out = alloc_buf_gc (256, &gc);
1349 setenv_str (es, "script_type", "ipchange");
1350 buf_printf (&out, "%s %s",
1351 info->ipchange_command,
1352 print_sockaddr_ex (&info->lsa->actual, true, " ", &gc));
1353 system_check (BSTR (&out), es, S_SCRIPT, "ip-change command failed");
1356 gc_free (&gc);
1359 void
1360 link_socket_bad_incoming_addr (struct buffer *buf,
1361 const struct link_socket_info *info,
1362 const struct sockaddr_in *from_addr)
1364 struct gc_arena gc = gc_new ();
1366 msg (D_LINK_ERRORS,
1367 "TCP/UDP: Incoming packet rejected from %s[%d], expected peer address: %s (allow this incoming source address/port by removing --remote or adding --float)",
1368 print_sockaddr (from_addr, &gc),
1369 (int)from_addr->sin_family,
1370 print_sockaddr (&info->lsa->remote, &gc));
1371 buf->len = 0;
1373 gc_free (&gc);
1376 void
1377 link_socket_bad_outgoing_addr (void)
1379 dmsg (D_READ_WRITE, "TCP/UDP: No outgoing address to send packet");
1382 in_addr_t
1383 link_socket_current_remote (const struct link_socket_info *info)
1385 const struct link_socket_addr *lsa = info->lsa;
1387 if (addr_defined (&lsa->actual))
1388 return ntohl (lsa->actual.sin_addr.s_addr);
1389 else if (addr_defined (&lsa->remote))
1390 return ntohl (lsa->remote.sin_addr.s_addr);
1391 else
1392 return 0;
1396 * Return a status string describing socket state.
1398 const char *
1399 socket_stat (const struct link_socket *s, unsigned int rwflags, struct gc_arena *gc)
1401 struct buffer out = alloc_buf_gc (64, gc);
1402 if (s)
1404 if (rwflags & EVENT_READ)
1406 buf_printf (&out, "S%s",
1407 (s->rwflags_debug & EVENT_READ) ? "R" : "r");
1408 #ifdef WIN32
1409 buf_printf (&out, "%s",
1410 overlapped_io_state_ascii (&s->reads));
1411 #endif
1413 if (rwflags & EVENT_WRITE)
1415 buf_printf (&out, "S%s",
1416 (s->rwflags_debug & EVENT_WRITE) ? "W" : "w");
1417 #ifdef WIN32
1418 buf_printf (&out, "%s",
1419 overlapped_io_state_ascii (&s->writes));
1420 #endif
1423 else
1425 buf_printf (&out, "S?");
1427 return BSTR (&out);
1431 * Stream buffer functions, used to packetize a TCP
1432 * stream connection.
1435 static inline void
1436 stream_buf_reset (struct stream_buf *sb)
1438 dmsg (D_STREAM_DEBUG, "STREAM: RESET");
1439 sb->residual_fully_formed = false;
1440 sb->buf = sb->buf_init;
1441 buf_reset (&sb->next);
1442 sb->len = -1;
1445 void
1446 stream_buf_init (struct stream_buf *sb,
1447 struct buffer *buf)
1449 sb->buf_init = *buf;
1450 sb->maxlen = sb->buf_init.len;
1451 sb->buf_init.len = 0;
1452 sb->residual = alloc_buf (sb->maxlen);
1453 sb->error = false;
1454 stream_buf_reset (sb);
1456 dmsg (D_STREAM_DEBUG, "STREAM: INIT maxlen=%d", sb->maxlen);
1459 static inline void
1460 stream_buf_set_next (struct stream_buf *sb)
1462 /* set up 'next' for next i/o read */
1463 sb->next = sb->buf;
1464 sb->next.offset = sb->buf.offset + sb->buf.len;
1465 sb->next.len = (sb->len >= 0 ? sb->len : sb->maxlen) - sb->buf.len;
1466 dmsg (D_STREAM_DEBUG, "STREAM: SET NEXT, buf=[%d,%d] next=[%d,%d] len=%d maxlen=%d",
1467 sb->buf.offset, sb->buf.len,
1468 sb->next.offset, sb->next.len,
1469 sb->len, sb->maxlen);
1470 ASSERT (sb->next.len > 0);
1471 ASSERT (buf_safe (&sb->buf, sb->next.len));
1474 static inline void
1475 stream_buf_get_final (struct stream_buf *sb, struct buffer *buf)
1477 dmsg (D_STREAM_DEBUG, "STREAM: GET FINAL len=%d",
1478 buf_defined (&sb->buf) ? sb->buf.len : -1);
1479 ASSERT (buf_defined (&sb->buf));
1480 *buf = sb->buf;
1483 static inline void
1484 stream_buf_get_next (struct stream_buf *sb, struct buffer *buf)
1486 dmsg (D_STREAM_DEBUG, "STREAM: GET NEXT len=%d",
1487 buf_defined (&sb->next) ? sb->next.len : -1);
1488 ASSERT (buf_defined (&sb->next));
1489 *buf = sb->next;
1492 bool
1493 stream_buf_read_setup_dowork (struct link_socket* sock)
1495 if (sock->stream_buf.residual.len && !sock->stream_buf.residual_fully_formed)
1497 ASSERT (buf_copy (&sock->stream_buf.buf, &sock->stream_buf.residual));
1498 ASSERT (buf_init (&sock->stream_buf.residual, 0));
1499 sock->stream_buf.residual_fully_formed = stream_buf_added (&sock->stream_buf, 0);
1500 dmsg (D_STREAM_DEBUG, "STREAM: RESIDUAL FULLY FORMED [%s], len=%d",
1501 sock->stream_buf.residual_fully_formed ? "YES" : "NO",
1502 sock->stream_buf.residual.len);
1505 if (!sock->stream_buf.residual_fully_formed)
1506 stream_buf_set_next (&sock->stream_buf);
1507 return !sock->stream_buf.residual_fully_formed;
1510 bool
1511 stream_buf_added (struct stream_buf *sb,
1512 int length_added)
1514 dmsg (D_STREAM_DEBUG, "STREAM: ADD length_added=%d", length_added);
1515 if (length_added > 0)
1516 sb->buf.len += length_added;
1518 /* if length unknown, see if we can get the length prefix from
1519 the head of the buffer */
1520 if (sb->len < 0 && sb->buf.len >= (int) sizeof (packet_size_type))
1522 packet_size_type net_size;
1523 ASSERT (buf_read (&sb->buf, &net_size, sizeof (net_size)));
1524 sb->len = ntohps (net_size);
1526 if (sb->len < 1 || sb->len > sb->maxlen)
1528 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);
1529 stream_buf_reset (sb);
1530 sb->error = true;
1531 return false;
1535 /* is our incoming packet fully read? */
1536 if (sb->len > 0 && sb->buf.len >= sb->len)
1538 /* save any residual data that's part of the next packet */
1539 ASSERT (buf_init (&sb->residual, 0));
1540 if (sb->buf.len > sb->len)
1541 ASSERT (buf_copy_excess (&sb->residual, &sb->buf, sb->len));
1542 dmsg (D_STREAM_DEBUG, "STREAM: ADD returned TRUE, buf_len=%d, residual_len=%d",
1543 BLEN (&sb->buf),
1544 BLEN (&sb->residual));
1545 return true;
1547 else
1549 dmsg (D_STREAM_DEBUG, "STREAM: ADD returned FALSE (have=%d need=%d)", sb->buf.len, sb->len);
1550 stream_buf_set_next (sb);
1551 return false;
1555 void
1556 stream_buf_close (struct stream_buf* sb)
1558 free_buf (&sb->residual);
1562 * The listen event is a special event whose sole purpose is
1563 * to tell us that there's a new incoming connection on a
1564 * TCP socket, for use in server mode.
1566 event_t
1567 socket_listen_event_handle (struct link_socket *s)
1569 #ifdef WIN32
1570 if (!defined_net_event_win32 (&s->listen_handle))
1571 init_net_event_win32 (&s->listen_handle, FD_ACCEPT, s->sd, 0);
1572 return &s->listen_handle;
1573 #else
1574 return s->sd;
1575 #endif
1579 * Format IP addresses in ascii
1582 const char *
1583 print_sockaddr (const struct sockaddr_in *addr, struct gc_arena *gc)
1585 return print_sockaddr_ex(addr, true, ":", gc);
1588 const char *
1589 print_sockaddr_ex (const struct sockaddr_in *addr, bool do_port, const char* separator, struct gc_arena *gc)
1591 struct buffer out = alloc_buf_gc (64, gc);
1592 const int port = ntohs (addr->sin_port);
1594 mutex_lock_static (L_INET_NTOA);
1595 buf_printf (&out, "%s", (addr_defined (addr) ? inet_ntoa (addr->sin_addr) : "[undef]"));
1596 mutex_unlock_static (L_INET_NTOA);
1598 if (do_port && port)
1600 if (separator)
1601 buf_printf (&out, "%s", separator);
1603 buf_printf (&out, "%d", port);
1605 return BSTR (&out);
1609 * Convert an in_addr_t in host byte order
1610 * to an ascii dotted quad.
1612 const char *
1613 print_in_addr_t (in_addr_t addr, unsigned int flags, struct gc_arena *gc)
1615 struct in_addr ia;
1616 struct buffer out = alloc_buf_gc (64, gc);
1618 if (addr || !(flags & IA_EMPTY_IF_UNDEF))
1620 CLEAR (ia);
1621 ia.s_addr = (flags & IA_NET_ORDER) ? addr : htonl (addr);
1623 mutex_lock_static (L_INET_NTOA);
1624 buf_printf (&out, "%s", inet_ntoa (ia));
1625 mutex_unlock_static (L_INET_NTOA);
1627 return BSTR (&out);
1630 /* set environmental variables for ip/port in *addr */
1631 void
1632 setenv_sockaddr (struct env_set *es, const char *name_prefix, const struct sockaddr_in *addr, const bool flags)
1634 char name_buf[256];
1636 if (flags & SA_IP_PORT)
1637 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_ip", name_prefix);
1638 else
1639 openvpn_snprintf (name_buf, sizeof (name_buf), "%s", name_prefix);
1641 mutex_lock_static (L_INET_NTOA);
1642 setenv_str (es, name_buf, inet_ntoa (addr->sin_addr));
1643 mutex_unlock_static (L_INET_NTOA);
1645 if ((flags & SA_IP_PORT) && addr->sin_port)
1647 openvpn_snprintf (name_buf, sizeof (name_buf), "%s_port", name_prefix);
1648 setenv_int (es, name_buf, ntohs (addr->sin_port));
1652 void
1653 setenv_in_addr_t (struct env_set *es, const char *name_prefix, in_addr_t addr, const bool flags)
1655 if (addr || !(flags & SA_SET_IF_NONZERO))
1657 struct sockaddr_in si;
1658 CLEAR (si);
1659 si.sin_addr.s_addr = htonl (addr);
1660 setenv_sockaddr (es, name_prefix, &si, flags);
1665 * Convert protocol names between index and ascii form.
1668 struct proto_names {
1669 const char *short_form;
1670 const char *display_form;
1673 /* Indexed by PROTO_x */
1674 static const struct proto_names proto_names[] = {
1675 {"udp", "UDPv4"},
1676 {"tcp-server", "TCPv4_SERVER"},
1677 {"tcp-client", "TCPv4_CLIENT"},
1678 {"tcp", "TCPv4"}
1682 ascii2proto (const char* proto_name)
1684 int i;
1685 ASSERT (PROTO_N == SIZE (proto_names));
1686 for (i = 0; i < PROTO_N; ++i)
1687 if (!strcmp (proto_name, proto_names[i].short_form))
1688 return i;
1689 return -1;
1692 const char *
1693 proto2ascii (int proto, bool display_form)
1695 ASSERT (PROTO_N == SIZE (proto_names));
1696 if (proto < 0 || proto >= PROTO_N)
1697 return "[unknown protocol]";
1698 else if (display_form)
1699 return proto_names[proto].display_form;
1700 else
1701 return proto_names[proto].short_form;
1704 const char *
1705 proto2ascii_all (struct gc_arena *gc)
1707 struct buffer out = alloc_buf_gc (256, gc);
1708 int i;
1710 ASSERT (PROTO_N == SIZE (proto_names));
1711 for (i = 0; i < PROTO_N; ++i)
1713 if (i)
1714 buf_printf(&out, " ");
1715 buf_printf(&out, "[%s]", proto2ascii(i, false));
1717 return BSTR (&out);
1721 * Given a local proto, return local proto
1722 * if !remote, or compatible remote proto
1723 * if remote.
1725 * This is used for options compatibility
1726 * checking.
1729 proto_remote (int proto, bool remote)
1731 ASSERT (proto >= 0 && proto < PROTO_N);
1732 if (remote)
1734 if (proto == PROTO_TCPv4_SERVER)
1735 return PROTO_TCPv4_CLIENT;
1736 if (proto == PROTO_TCPv4_CLIENT)
1737 return PROTO_TCPv4_SERVER;
1739 return proto;
1743 * Bad incoming address lengths that differ from what
1744 * we expect are considered to be fatal errors.
1746 void
1747 bad_address_length (int actual, int expected)
1749 msg (M_FATAL, "ERROR: received strange incoming packet with an address length of %d -- we only accept address lengths of %d.",
1750 actual,
1751 expected);
1755 * Socket Read Routines
1759 link_socket_read_tcp (struct link_socket *sock,
1760 struct buffer *buf)
1762 int len = 0;
1764 if (!sock->stream_buf.residual_fully_formed)
1766 #ifdef WIN32
1767 len = socket_finalize (sock->sd, &sock->reads, buf, NULL);
1768 #else
1769 struct buffer frag;
1770 stream_buf_get_next (&sock->stream_buf, &frag);
1771 len = recv (sock->sd, BPTR (&frag), BLEN (&frag), MSG_NOSIGNAL);
1772 #endif
1774 if (!len)
1775 sock->stream_reset = true;
1776 if (len <= 0)
1777 return buf->len = len;
1780 if (sock->stream_buf.residual_fully_formed
1781 || stream_buf_added (&sock->stream_buf, len)) /* packet complete? */
1783 stream_buf_get_final (&sock->stream_buf, buf);
1784 stream_buf_reset (&sock->stream_buf);
1785 return buf->len;
1787 else
1788 return buf->len = 0; /* no error, but packet is still incomplete */
1791 #ifndef WIN32
1794 link_socket_read_udp_posix (struct link_socket *sock,
1795 struct buffer *buf,
1796 int maxsize,
1797 struct sockaddr_in *from)
1799 socklen_t fromlen = sizeof (*from);
1800 CLEAR (*from);
1801 ASSERT (buf_safe (buf, maxsize));
1802 buf->len = recvfrom (sock->sd, BPTR (buf), maxsize, 0,
1803 (struct sockaddr *) from, &fromlen);
1804 if (fromlen != sizeof (*from))
1805 bad_address_length (fromlen, sizeof (*from));
1806 return buf->len;
1809 #endif
1812 * Socket Write Routines
1816 link_socket_write_tcp (struct link_socket *sock,
1817 struct buffer *buf,
1818 struct sockaddr_in *to)
1820 packet_size_type len = BLEN (buf);
1821 dmsg (D_STREAM_DEBUG, "STREAM: WRITE %d offset=%d", (int)len, buf->offset);
1822 ASSERT (len <= sock->stream_buf.maxlen);
1823 len = htonps (len);
1824 ASSERT (buf_write_prepend (buf, &len, sizeof (len)));
1825 #ifdef WIN32
1826 return link_socket_write_win32 (sock, buf, to);
1827 #else
1828 return link_socket_write_tcp_posix (sock, buf, to);
1829 #endif
1833 * Win32 overlapped socket I/O functions.
1836 #ifdef WIN32
1839 socket_recv_queue (struct link_socket *sock, int maxsize)
1841 if (sock->reads.iostate == IOSTATE_INITIAL)
1843 WSABUF wsabuf[1];
1844 int status;
1846 /* reset buf to its initial state */
1847 if (sock->info.proto == PROTO_UDPv4)
1849 sock->reads.buf = sock->reads.buf_init;
1851 else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
1853 stream_buf_get_next (&sock->stream_buf, &sock->reads.buf);
1855 else
1857 ASSERT (0);
1860 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
1861 wsabuf[0].buf = BPTR (&sock->reads.buf);
1862 wsabuf[0].len = maxsize ? maxsize : BLEN (&sock->reads.buf);
1864 /* check for buffer overflow */
1865 ASSERT (wsabuf[0].len <= BLEN (&sock->reads.buf));
1867 /* the overlapped read will signal this event on I/O completion */
1868 ASSERT (ResetEvent (sock->reads.overlapped.hEvent));
1869 sock->reads.flags = 0;
1871 if (sock->info.proto == PROTO_UDPv4)
1873 sock->reads.addr_defined = true;
1874 sock->reads.addrlen = sizeof (sock->reads.addr);
1875 status = WSARecvFrom(
1876 sock->sd,
1877 wsabuf,
1879 &sock->reads.size,
1880 &sock->reads.flags,
1881 (struct sockaddr *) &sock->reads.addr,
1882 &sock->reads.addrlen,
1883 &sock->reads.overlapped,
1884 NULL);
1886 else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
1888 sock->reads.addr_defined = false;
1889 status = WSARecv(
1890 sock->sd,
1891 wsabuf,
1893 &sock->reads.size,
1894 &sock->reads.flags,
1895 &sock->reads.overlapped,
1896 NULL);
1898 else
1900 status = 0;
1901 ASSERT (0);
1904 if (!status) /* operation completed immediately? */
1906 if (sock->reads.addr_defined && sock->reads.addrlen != sizeof (sock->reads.addr))
1907 bad_address_length (sock->reads.addrlen, sizeof (sock->reads.addr));
1909 sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
1911 /* since we got an immediate return, we must signal the event object ourselves */
1912 ASSERT (SetEvent (sock->reads.overlapped.hEvent));
1913 sock->reads.status = 0;
1915 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive immediate return [%d,%d]",
1916 (int) wsabuf[0].len,
1917 (int) sock->reads.size);
1919 else
1921 status = WSAGetLastError ();
1922 if (status == WSA_IO_PENDING) /* operation queued? */
1924 sock->reads.iostate = IOSTATE_QUEUED;
1925 sock->reads.status = status;
1926 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive queued [%d]",
1927 (int) wsabuf[0].len);
1929 else /* error occurred */
1931 struct gc_arena gc = gc_new ();
1932 ASSERT (SetEvent (sock->reads.overlapped.hEvent));
1933 sock->reads.iostate = IOSTATE_IMMEDIATE_RETURN;
1934 sock->reads.status = status;
1935 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Receive error [%d]: %s",
1936 (int) wsabuf[0].len,
1937 strerror_win32 (status, &gc));
1938 gc_free (&gc);
1942 return sock->reads.iostate;
1946 socket_send_queue (struct link_socket *sock, struct buffer *buf, const struct sockaddr_in *to)
1948 if (sock->writes.iostate == IOSTATE_INITIAL)
1950 WSABUF wsabuf[1];
1951 int status;
1953 /* make a private copy of buf */
1954 sock->writes.buf = sock->writes.buf_init;
1955 sock->writes.buf.len = 0;
1956 ASSERT (buf_copy (&sock->writes.buf, buf));
1958 /* Win32 docs say it's okay to allocate the wsabuf on the stack */
1959 wsabuf[0].buf = BPTR (&sock->writes.buf);
1960 wsabuf[0].len = BLEN (&sock->writes.buf);
1962 /* the overlapped write will signal this event on I/O completion */
1963 ASSERT (ResetEvent (sock->writes.overlapped.hEvent));
1964 sock->writes.flags = 0;
1966 if (sock->info.proto == PROTO_UDPv4)
1968 /* set destination address for UDP writes */
1969 sock->writes.addr_defined = true;
1970 sock->writes.addr = *to;
1971 sock->writes.addrlen = sizeof (sock->writes.addr);
1973 status = WSASendTo(
1974 sock->sd,
1975 wsabuf,
1977 &sock->writes.size,
1978 sock->writes.flags,
1979 (struct sockaddr *) &sock->writes.addr,
1980 sock->writes.addrlen,
1981 &sock->writes.overlapped,
1982 NULL);
1984 else if (sock->info.proto == PROTO_TCPv4_CLIENT || sock->info.proto == PROTO_TCPv4_SERVER)
1986 /* destination address for TCP writes was established on connection initiation */
1987 sock->writes.addr_defined = false;
1989 status = WSASend(
1990 sock->sd,
1991 wsabuf,
1993 &sock->writes.size,
1994 sock->writes.flags,
1995 &sock->writes.overlapped,
1996 NULL);
1998 else
2000 status = 0;
2001 ASSERT (0);
2004 if (!status) /* operation completed immediately? */
2006 sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
2008 /* since we got an immediate return, we must signal the event object ourselves */
2009 ASSERT (SetEvent (sock->writes.overlapped.hEvent));
2011 sock->writes.status = 0;
2013 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send immediate return [%d,%d]",
2014 (int) wsabuf[0].len,
2015 (int) sock->writes.size);
2017 else
2019 status = WSAGetLastError ();
2020 if (status == WSA_IO_PENDING) /* operation queued? */
2022 sock->writes.iostate = IOSTATE_QUEUED;
2023 sock->writes.status = status;
2024 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send queued [%d]",
2025 (int) wsabuf[0].len);
2027 else /* error occurred */
2029 struct gc_arena gc = gc_new ();
2030 ASSERT (SetEvent (sock->writes.overlapped.hEvent));
2031 sock->writes.iostate = IOSTATE_IMMEDIATE_RETURN;
2032 sock->writes.status = status;
2034 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Send error [%d]: %s",
2035 (int) wsabuf[0].len,
2036 strerror_win32 (status, &gc));
2038 gc_free (&gc);
2042 return sock->writes.iostate;
2046 socket_finalize (
2047 SOCKET s,
2048 struct overlapped_io *io,
2049 struct buffer *buf,
2050 struct sockaddr_in *from)
2052 int ret = -1;
2053 BOOL status;
2055 switch (io->iostate)
2057 case IOSTATE_QUEUED:
2058 status = WSAGetOverlappedResult(
2060 &io->overlapped,
2061 &io->size,
2062 FALSE,
2063 &io->flags
2065 if (status)
2067 /* successful return for a queued operation */
2068 if (buf)
2069 *buf = io->buf;
2070 ret = io->size;
2071 io->iostate = IOSTATE_INITIAL;
2072 ASSERT (ResetEvent (io->overlapped.hEvent));
2074 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion success [%d]", ret);
2076 else
2078 /* error during a queued operation */
2079 ret = -1;
2080 if (WSAGetLastError() != WSA_IO_INCOMPLETE)
2082 /* if no error (i.e. just not finished yet), then DON'T execute this code */
2083 io->iostate = IOSTATE_INITIAL;
2084 ASSERT (ResetEvent (io->overlapped.hEvent));
2085 msg (D_WIN32_IO | M_ERRNO_SOCK, "WIN32 I/O: Socket Completion error");
2088 break;
2090 case IOSTATE_IMMEDIATE_RETURN:
2091 io->iostate = IOSTATE_INITIAL;
2092 ASSERT (ResetEvent (io->overlapped.hEvent));
2093 if (io->status)
2095 /* error return for a non-queued operation */
2096 WSASetLastError (io->status);
2097 ret = -1;
2098 msg (D_WIN32_IO | M_ERRNO_SOCK, "WIN32 I/O: Socket Completion non-queued error");
2100 else
2102 /* successful return for a non-queued operation */
2103 if (buf)
2104 *buf = io->buf;
2105 ret = io->size;
2106 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion non-queued success [%d]", ret);
2108 break;
2110 case IOSTATE_INITIAL: /* were we called without proper queueing? */
2111 WSASetLastError (WSAEINVAL);
2112 ret = -1;
2113 dmsg (D_WIN32_IO, "WIN32 I/O: Socket Completion BAD STATE");
2114 break;
2116 default:
2117 ASSERT (0);
2120 /* return from address if requested */
2121 if (from)
2123 if (ret >= 0 && io->addr_defined)
2125 if (io->addrlen != sizeof (io->addr))
2126 bad_address_length (io->addrlen, sizeof (io->addr));
2127 *from = io->addr;
2129 else
2130 CLEAR (*from);
2133 if (buf)
2134 buf->len = ret;
2135 return ret;
2138 #endif /* WIN32 */
2141 * Socket event notification
2144 unsigned int
2145 socket_set (struct link_socket *s,
2146 struct event_set *es,
2147 unsigned int rwflags,
2148 void *arg,
2149 unsigned int *persistent)
2151 if (s)
2153 if ((rwflags & EVENT_READ) && !stream_buf_read_setup (s))
2155 ASSERT (!persistent);
2156 rwflags &= ~EVENT_READ;
2159 #ifdef WIN32
2160 if (rwflags & EVENT_READ)
2161 socket_recv_queue (s, 0);
2162 #endif
2164 /* if persistent is defined, call event_ctl only if rwflags has changed since last call */
2165 if (!persistent || *persistent != rwflags)
2167 event_ctl (es, socket_event_handle (s), rwflags, arg);
2168 if (persistent)
2169 *persistent = rwflags;
2172 s->rwflags_debug = rwflags;
2174 return rwflags;