2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
8 * Copyright (C) 2002-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
26 #include "config-win32.h"
43 * Functions related to the translation of DNS names to IP addresses.
47 h_errno_msg(int h_errno_err
)
52 return "[HOST_NOT_FOUND] The specified host is unknown.";
54 return "[NO_DATA] The requested name is valid but does not have an IP address.";
56 return "[NO_RECOVERY] A non-recoverable name server error occurred.";
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.
69 getaddr (unsigned int flags
,
71 int resolve_retry_seconds
,
73 volatile int *signal_received
)
78 int msglevel
= (flags
& GETADDR_FATAL
) ? M_FATAL
: D_RESOLVE_ERRORS
;
80 if (flags
& GETADDR_MSG_VIRT_OUT
)
81 msglevel
|= M_MSG_VIRT_OUT
;
87 if ((flags
& (GETADDR_FATAL_ON_SIGNAL
|GETADDR_WARN_ON_SIGNAL
))
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
);
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
);
119 /* try hostname lookup */
120 h
= gethostbyname (hostname
);
124 get_signal (signal_received
);
125 if (*signal_received
) /* were we interrupted by a signal? */
128 if (*signal_received
== SIGUSR1
) /* ignore SIGUSR1 */
130 msg (level
, "RESOLVE: Ignored SIGUSR1 signal received during DNS resolution attempt");
131 *signal_received
= 0;
142 /* resolve lookup failed, should we
146 if (resolve_retries
> 0)
147 level
= D_RESOLVE_ERRORS
;
152 h_errno_msg (h_errno
));
154 if (--resolve_retries
<= 0)
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
);
166 ia
.s_addr
= *(in_addr_t
*) (h
->h_addr_list
[0]);
170 if (h
->h_addr_list
[1]) /* more than one address returned */
174 /* count address list */
175 while (h
->h_addr_list
[n
])
179 msg (D_RESOLVE_ERRORS
, "RESOLVE: NOTE: %s resolves to %d addresses, choosing one by random",
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 */
194 /* IP address parse succeeded */
200 if (signal_received
&& *signal_received
)
203 if (flags
& GETADDR_FATAL_ON_SIGNAL
)
205 else if (flags
& GETADDR_WARN_ON_SIGNAL
)
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
;
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 */
234 return OIA_HOSTNAME
; /* probably a hostname */
238 update_remote (const char* host
,
239 struct sockaddr_in
*addr
,
244 const in_addr_t new_addr
= getaddr (
250 if (new_addr
&& addr
->sin_addr
.s_addr
!= new_addr
)
252 addr
->sin_addr
.s_addr
= new_addr
;
259 socket_get_sndbuf (int sd
)
261 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_SNDBUF)
266 if (getsockopt (sd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &val
, &len
) == 0
267 && len
== sizeof (val
))
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
);
285 socket_get_rcvbuf (int sd
)
287 #if defined(HAVE_GETSOCKOPT) && defined(SOL_SOCKET) && defined(SO_RCVBUF)
292 if (getsockopt (sd
, SOL_SOCKET
, SO_RCVBUF
, (void *) &val
, &len
) == 0
293 && len
== sizeof (val
))
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
);
313 socket_set_buffers (int fd
, const struct socket_buffer_size
*sbs
)
317 const int sndbuf_old
= socket_get_sndbuf (fd
);
318 const int rcvbuf_old
= socket_get_rcvbuf (fd
);
321 socket_set_sndbuf (fd
, sbs
->sndbuf
);
324 socket_set_rcvbuf (fd
, sbs
->rcvbuf
);
326 msg (D_OSBUF
, "Socket Buffers: R=[%d->%d] S=[%d->%d]",
328 socket_get_rcvbuf (fd
),
330 socket_get_sndbuf (fd
));
335 * Remote list code allows clients to specify a list of
336 * potential remote server addresses.
340 remote_list_next (struct remote_list
*l
)
344 if (l
->no_advance
&& l
->current
>= 0)
346 l
->no_advance
= false;
351 if (++l
->current
>= l
->len
)
354 dmsg (D_REMOTE_LIST
, "REMOTE_LIST len=%d current=%d",
356 for (i
= 0; i
< l
->len
; ++i
)
358 dmsg (D_REMOTE_LIST
, "[%d] %s:%d",
360 l
->array
[i
].hostname
,
368 remote_list_randomize (struct remote_list
*l
)
373 for (i
= 0; i
< l
->len
; ++i
)
375 const int j
= get_random () % l
->len
;
378 struct remote_entry tmp
;
380 l
->array
[i
] = l
->array
[j
];
388 remote_list_host (const struct remote_list
*rl
)
391 return rl
->array
[rl
->current
].hostname
;
397 remote_list_port (const struct remote_list
*rl
)
400 return rl
->array
[rl
->current
].port
;
406 * SOCKET INITALIZATION CODE.
407 * Create a TCP/UDP socket
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 */
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");
427 /* set socket linger options */
429 struct linger linger
;
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");
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");
452 create_socket (struct link_socket
*sock
)
455 if (sock
->info
.proto
== PROTO_UDPv4
)
457 sock
->sd
= create_socket_udp ();
460 if (sock
->socks_proxy
)
461 sock
->ctrl_sd
= create_socket_tcp ();
464 else if (sock
->info
.proto
== PROTO_TCPv4_SERVER
465 || sock
->info
.proto
== PROTO_TCPv4_CLIENT
)
467 sock
->sd
= create_socket_tcp ();
476 * Functions used for establishing a TCP stream connection.
480 socket_do_listen (socket_descriptor_t sd
,
481 const struct sockaddr_in
*local
,
483 bool do_set_nonblock
)
485 struct gc_arena gc
= gc_new ();
488 msg (M_INFO
, "Listening for incoming TCP connection on %s",
489 print_sockaddr (local
, &gc
));
491 msg (M_SOCKERR
, "TCP: listen() failed");
494 /* set socket to non-blocking mode */
502 socket_do_accept (socket_descriptor_t sd
,
503 struct sockaddr_in
*remote
,
506 socklen_t remote_len
= sizeof (*remote
);
507 socket_descriptor_t new_sd
= SOCKET_UNDEFINED
;
509 #ifdef HAVE_GETPEERNAME
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");
521 msg (M_WARN
, "TCP: this OS does not provide the getpeername() function");
525 new_sd
= accept (sd
, (struct sockaddr
*) remote
, &remote_len
);
528 #if 0 /* For debugging only, test the effect of accept() failures */
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
;
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
));
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
,
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);
586 status
= select (sd
+ 1, &reads
, NULL
, NULL
, &tv
);
588 get_signal (signal_received
);
589 if (*signal_received
)
596 msg (D_LINK_ERRORS
| M_ERRNO_SOCK
, "TCP: select() failed");
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
))
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)");
624 if (!nowait
&& openvpn_close_socket (sd
))
625 msg (M_SOCKERR
, "TCP: close socket failed (sd)");
627 tcp_connection_established (remote
);
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
));
648 const int status
= connect (*sd
, (struct sockaddr
*) remote
,
651 get_signal (signal_received
);
652 if (*signal_received
)
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
);
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
));
685 /* For stream protocols, allocate a buffer to build up packet.
686 Called after frame has been finalized. */
689 socket_frame_init (const struct frame
*frame
, struct link_socket
*sock
)
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
;
698 if (link_socket_connection_oriented (sock
))
701 stream_buf_init (&sock
->stream_buf
, &sock
->reads
.buf_init
);
703 alloc_buf_sock_tun (&sock
->stream_buf_data
,
706 FRAME_HEADROOM_MARKER_READ_STREAM
);
707 stream_buf_init (&sock
->stream_buf
, &sock
->stream_buf_data
);
713 * Adjust frame structure based on a Path MTU value given
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
);
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
,
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
));
757 resolve_remote (struct link_socket
*sock
,
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;
778 if (remote_list_len (sock
->remote_list
) > 1 && sock
->resolve_retry_seconds
== RESOLV_RETRY_INFINITE
)
780 flags
= GETADDR_RESOLVE
;
782 flags
|= (GETADDR_TRY_ONCE
| GETADDR_FATAL
);
787 if (sock
->resolve_retry_seconds
)
789 flags
= GETADDR_RESOLVE
;
794 flags
= GETADDR_RESOLVE
| GETADDR_FATAL
| GETADDR_MENTION_RESOLVE_RETRY
;
800 if (sock
->resolve_retry_seconds
)
802 flags
= GETADDR_RESOLVE
| GETADDR_FATAL
;
803 retry
= sock
->resolve_retry_seconds
;
815 sock
->info
.lsa
->remote
.sin_addr
.s_addr
= getaddr (
822 dmsg (D_SOCKET_DEBUG
, "RESOLVE_REMOTE flags=0x%04x phase=%d rrs=%d sig=%d status=%d",
826 signal_received
? *signal_received
: -1,
831 if (*signal_received
)
837 *signal_received
= SIGUSR1
;
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
));
851 *remote_dynamic
= NULL
;
854 sock
->info
.lsa
->actual
= sock
->info
.lsa
->remote
;
856 /* remember that we finished */
857 sock
->did_resolve_remote
= true;
865 link_socket_new (void)
867 struct link_socket
*sock
;
869 ALLOC_OBJ_CLEAR (sock
, struct link_socket
);
870 sock
->sd
= SOCKET_UNDEFINED
;
872 sock
->ctrl_sd
= SOCKET_UNDEFINED
;
877 /* bind socket if necessary */
879 link_socket_init_phase1 (struct link_socket
*sock
,
880 const char *local_host
,
881 struct remote_list
*remote_list
,
885 const struct link_socket
*accept_from
,
886 #ifdef ENABLE_HTTP_PROXY
887 struct http_proxy_info
*http_proxy
,
890 struct socks_proxy_info
*socks_proxy
,
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
,
907 const char *remote_host
;
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
;
925 sock
->socks_proxy
= socks_proxy
;
928 sock
->bind_local
= bind_local
;
930 sock
->resolve_retry_seconds
= resolve_retry_seconds
;
931 sock
->connect_retry_seconds
= connect_retry_seconds
;
932 sock
->mtu_discover_type
= mtu_discover_type
;
935 sock
->gremlin
= gremlin
;
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
;
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
;
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
;
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
;
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;
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? */
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 */
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;
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? */
1065 if (sock
->info
.proto
== PROTO_TCPv4_SERVER
)
1067 socket_listen_accept (sock
->sd
,
1068 &sock
->info
.lsa
->actual
,
1071 &sock
->info
.lsa
->local
,
1073 sock
->inetd
== INETD_NOWAIT
,
1075 ASSERT (!remote_changed
);
1076 if (*signal_received
)
1081 resolve_remote (sock
, 2, &remote_dynamic
, signal_received
);
1083 if (*signal_received
)
1086 /* TCP client/server */
1087 if (sock
->info
.proto
== PROTO_TCPv4_SERVER
)
1091 case LS_MODE_DEFAULT
:
1092 sock
->sd
= socket_listen_accept (sock
->sd
,
1093 &sock
->info
.lsa
->actual
,
1096 &sock
->info
.lsa
->local
,
1101 case LS_MODE_TCP_LISTEN
:
1102 socket_do_listen (sock
->sd
,
1103 &sock
->info
.lsa
->local
,
1107 case LS_MODE_TCP_ACCEPT_FROM
:
1108 sock
->sd
= socket_do_accept (sock
->sd
,
1109 &sock
->info
.lsa
->actual
,
1111 if (!socket_defined (sock
->sd
))
1113 *signal_received
= SIGTERM
;
1116 tcp_connection_established (&sock
->info
.lsa
->actual
);
1122 else if (sock
->info
.proto
== PROTO_TCPv4_CLIENT
)
1124 socket_connect (&sock
->sd
,
1125 &sock
->info
.lsa
->actual
,
1129 sock
->connect_retry_seconds
,
1132 if (*signal_received
)
1137 #ifdef ENABLE_HTTP_PROXY
1138 else if (sock
->http_proxy
)
1140 establish_http_proxy_passthru (sock
->http_proxy
,
1142 sock
->proxy_dest_host
,
1143 sock
->proxy_dest_port
,
1144 &sock
->stream_buf
.residual
,
1149 else if (sock
->socks_proxy
)
1151 establish_socks_proxy_passthru (sock
->socks_proxy
,
1153 sock
->proxy_dest_host
,
1154 sock
->proxy_dest_port
,
1160 else if (sock
->info
.proto
== PROTO_UDPv4
&& sock
->socks_proxy
)
1162 socket_connect (&sock
->ctrl_sd
,
1163 &sock
->info
.lsa
->actual
,
1167 sock
->connect_retry_seconds
,
1170 if (*signal_received
)
1173 establish_socks_proxy_udpassoc (sock
->socks_proxy
,
1175 sock
->sd
, &sock
->socks_relay
,
1178 if (*signal_received
)
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
)
1194 if (*signal_received
)
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
);
1215 if (socket_defined (sock
->ctrl_sd
))
1216 set_cloexec (sock
->ctrl_sd
);
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
);
1227 /* print local address */
1229 msg (M_INFO
, "%s link local: [inetd]", proto2ascii (sock
->info
.proto
, true));
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
));
1242 if (sig_save
&& signal_received
)
1244 if (!*signal_received
)
1245 *signal_received
= sig_save
;
1251 link_socket_close (struct link_socket
*sock
)
1256 const int gremlin
= GREMLIN_CONNECTION_FLOOD_LEVEL (sock
->gremlin
);
1258 const int gremlin
= 0;
1261 if (socket_defined (sock
->sd
))
1264 close_net_event_win32 (&sock
->listen_handle
, sock
->sd
, 0);
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
;
1276 overlapped_io_close (&sock
->reads
);
1277 overlapped_io_close (&sock
->writes
);
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
;
1291 stream_buf_close (&sock
->stream_buf
);
1292 free_buf (&sock
->stream_buf_data
);
1298 /* for stream protocols, allow for packet length prefix */
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
));
1307 setenv_trusted (struct env_set
*es
, const struct link_socket_info
*info
)
1309 setenv_sockaddr (es
, "trusted", &info
->lsa
->actual
, SA_IP_PORT
);
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
,
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
);
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");
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 ();
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
));
1377 link_socket_bad_outgoing_addr (void)
1379 dmsg (D_READ_WRITE
, "TCP/UDP: No outgoing address to send packet");
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
);
1396 * Return a status string describing socket state.
1399 socket_stat (const struct link_socket
*s
, unsigned int rwflags
, struct gc_arena
*gc
)
1401 struct buffer out
= alloc_buf_gc (64, gc
);
1404 if (rwflags
& EVENT_READ
)
1406 buf_printf (&out
, "S%s",
1407 (s
->rwflags_debug
& EVENT_READ
) ? "R" : "r");
1409 buf_printf (&out
, "%s",
1410 overlapped_io_state_ascii (&s
->reads
));
1413 if (rwflags
& EVENT_WRITE
)
1415 buf_printf (&out
, "S%s",
1416 (s
->rwflags_debug
& EVENT_WRITE
) ? "W" : "w");
1418 buf_printf (&out
, "%s",
1419 overlapped_io_state_ascii (&s
->writes
));
1425 buf_printf (&out
, "S?");
1431 * Stream buffer functions, used to packetize a TCP
1432 * stream connection.
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
);
1446 stream_buf_init (struct stream_buf
*sb
,
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
);
1454 stream_buf_reset (sb
);
1456 dmsg (D_STREAM_DEBUG
, "STREAM: INIT maxlen=%d", sb
->maxlen
);
1460 stream_buf_set_next (struct stream_buf
*sb
)
1462 /* set up 'next' for next i/o read */
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
));
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
));
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
));
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
;
1511 stream_buf_added (struct stream_buf
*sb
,
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
);
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",
1544 BLEN (&sb
->residual
));
1549 dmsg (D_STREAM_DEBUG
, "STREAM: ADD returned FALSE (have=%d need=%d)", sb
->buf
.len
, sb
->len
);
1550 stream_buf_set_next (sb
);
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.
1567 socket_listen_event_handle (struct link_socket
*s
)
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
;
1579 * Format IP addresses in ascii
1583 print_sockaddr (const struct sockaddr_in
*addr
, struct gc_arena
*gc
)
1585 return print_sockaddr_ex(addr
, true, ":", gc
);
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
)
1601 buf_printf (&out
, "%s", separator
);
1603 buf_printf (&out
, "%d", port
);
1609 * Convert an in_addr_t in host byte order
1610 * to an ascii dotted quad.
1613 print_in_addr_t (in_addr_t addr
, unsigned int flags
, struct gc_arena
*gc
)
1616 struct buffer out
= alloc_buf_gc (64, gc
);
1618 if (addr
|| !(flags
& IA_EMPTY_IF_UNDEF
))
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
);
1630 /* set environmental variables for ip/port in *addr */
1632 setenv_sockaddr (struct env_set
*es
, const char *name_prefix
, const struct sockaddr_in
*addr
, const bool flags
)
1636 if (flags
& SA_IP_PORT
)
1637 openvpn_snprintf (name_buf
, sizeof (name_buf
), "%s_ip", name_prefix
);
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
));
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
;
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
[] = {
1676 {"tcp-server", "TCPv4_SERVER"},
1677 {"tcp-client", "TCPv4_CLIENT"},
1682 ascii2proto (const char* proto_name
)
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
))
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
;
1701 return proto_names
[proto
].short_form
;
1705 proto2ascii_all (struct gc_arena
*gc
)
1707 struct buffer out
= alloc_buf_gc (256, gc
);
1710 ASSERT (PROTO_N
== SIZE (proto_names
));
1711 for (i
= 0; i
< PROTO_N
; ++i
)
1714 buf_printf(&out
, " ");
1715 buf_printf(&out
, "[%s]", proto2ascii(i
, false));
1721 * Given a local proto, return local proto
1722 * if !remote, or compatible remote proto
1725 * This is used for options compatibility
1729 proto_remote (int proto
, bool remote
)
1731 ASSERT (proto
>= 0 && proto
< PROTO_N
);
1734 if (proto
== PROTO_TCPv4_SERVER
)
1735 return PROTO_TCPv4_CLIENT
;
1736 if (proto
== PROTO_TCPv4_CLIENT
)
1737 return PROTO_TCPv4_SERVER
;
1743 * Bad incoming address lengths that differ from what
1744 * we expect are considered to be fatal errors.
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.",
1755 * Socket Read Routines
1759 link_socket_read_tcp (struct link_socket
*sock
,
1764 if (!sock
->stream_buf
.residual_fully_formed
)
1767 len
= socket_finalize (sock
->sd
, &sock
->reads
, buf
, NULL
);
1770 stream_buf_get_next (&sock
->stream_buf
, &frag
);
1771 len
= recv (sock
->sd
, BPTR (&frag
), BLEN (&frag
), MSG_NOSIGNAL
);
1775 sock
->stream_reset
= true;
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
);
1788 return buf
->len
= 0; /* no error, but packet is still incomplete */
1794 link_socket_read_udp_posix (struct link_socket
*sock
,
1797 struct sockaddr_in
*from
)
1799 socklen_t fromlen
= sizeof (*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
));
1812 * Socket Write Routines
1816 link_socket_write_tcp (struct link_socket
*sock
,
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
);
1824 ASSERT (buf_write_prepend (buf
, &len
, sizeof (len
)));
1826 return link_socket_write_win32 (sock
, buf
, to
);
1828 return link_socket_write_tcp_posix (sock
, buf
, to
);
1833 * Win32 overlapped socket I/O functions.
1839 socket_recv_queue (struct link_socket
*sock
, int maxsize
)
1841 if (sock
->reads
.iostate
== IOSTATE_INITIAL
)
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
);
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(
1881 (struct sockaddr
*) &sock
->reads
.addr
,
1882 &sock
->reads
.addrlen
,
1883 &sock
->reads
.overlapped
,
1886 else if (sock
->info
.proto
== PROTO_TCPv4_CLIENT
|| sock
->info
.proto
== PROTO_TCPv4_SERVER
)
1888 sock
->reads
.addr_defined
= false;
1895 &sock
->reads
.overlapped
,
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
);
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
));
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
)
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
);
1979 (struct sockaddr
*) &sock
->writes
.addr
,
1980 sock
->writes
.addrlen
,
1981 &sock
->writes
.overlapped
,
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;
1995 &sock
->writes
.overlapped
,
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
);
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
));
2042 return sock
->writes
.iostate
;
2048 struct overlapped_io
*io
,
2050 struct sockaddr_in
*from
)
2055 switch (io
->iostate
)
2057 case IOSTATE_QUEUED
:
2058 status
= WSAGetOverlappedResult(
2067 /* successful return for a queued operation */
2071 io
->iostate
= IOSTATE_INITIAL
;
2072 ASSERT (ResetEvent (io
->overlapped
.hEvent
));
2074 dmsg (D_WIN32_IO
, "WIN32 I/O: Socket Completion success [%d]", ret
);
2078 /* error during a queued operation */
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");
2090 case IOSTATE_IMMEDIATE_RETURN
:
2091 io
->iostate
= IOSTATE_INITIAL
;
2092 ASSERT (ResetEvent (io
->overlapped
.hEvent
));
2095 /* error return for a non-queued operation */
2096 WSASetLastError (io
->status
);
2098 msg (D_WIN32_IO
| M_ERRNO_SOCK
, "WIN32 I/O: Socket Completion non-queued error");
2102 /* successful return for a non-queued operation */
2106 dmsg (D_WIN32_IO
, "WIN32 I/O: Socket Completion non-queued success [%d]", ret
);
2110 case IOSTATE_INITIAL
: /* were we called without proper queueing? */
2111 WSASetLastError (WSAEINVAL
);
2113 dmsg (D_WIN32_IO
, "WIN32 I/O: Socket Completion BAD STATE");
2120 /* return from address if requested */
2123 if (ret
>= 0 && io
->addr_defined
)
2125 if (io
->addrlen
!= sizeof (io
->addr
))
2126 bad_address_length (io
->addrlen
, sizeof (io
->addr
));
2141 * Socket event notification
2145 socket_set (struct link_socket
*s
,
2146 struct event_set
*es
,
2147 unsigned int rwflags
,
2149 unsigned int *persistent
)
2153 if ((rwflags
& EVENT_READ
) && !stream_buf_read_setup (s
))
2155 ASSERT (!persistent
);
2156 rwflags
&= ~EVENT_READ
;
2160 if (rwflags
& EVENT_READ
)
2161 socket_recv_queue (s
, 0);
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
);
2169 *persistent
= rwflags
;
2172 s
->rwflags_debug
= rwflags
;